Skip to content

Networking

This page shows how clocks reach Connect. It also shows how to set up the load balancer in front of it. It covers listeners and endpoints, sharing a port by path, adding a port, keeping the clock’s address, IP lists and health checks.

Listeners and endpoints are runtime setup. They are kept in the database and changed through the admin API or hourctl apply. Only the exposed ports are deploy configuration.

PieceWhat it is
listenerWhere traffic arrives. It is one of two types. http binds an address and port: listen = "0.0.0.0:8080". mqtt connects out to a broker and subscribes: broker = "mqtts://host". Device listeners speak plain HTTP, because that is what most clocks speak.
endpointWhere a set of devices is served. Traffic on this listener under this path (or MQTT topic) uses this package, these options and these sinks. It is in one group. Paths and topics may capture segments: /site/{site}, clocks/{device}/events. An MQTT endpoint may name a reply_topic.
Terminal window
hourctl listener add public --http 0.0.0.0:8080
hourctl endpoint add office --listener public --path /office --package zk-push@3.4 --option timezone=America/Chicago
hourctl listener add broker --mqtt mqtts://broker.example.com --username houradvantage --broker-password <PW> --window 20
hourctl endpoint add cloud --listener broker --topic "clocks/{device}/events" --reply-topic "clocks/{device}/commands" --package brightlink-cloud

An mqtt listener states its broker’s window. The window is how many messages the broker hands it at once before it has acknowledged any. You set it with --window, 1 to 65535.

The window is not a setting of the listener’s own to invent. Copy it from the broker. In Mosquitto it is max_inflight_messages, 20 unless changed. Other brokers call it the receive window or receive maximum they give a client.

The listener holds no more unacknowledged messages than that. So the broker’s window is the limit on what any one device, or all of them together, can have waiting. A listener with no window is refused.

Connect does not tell the broker its window. The broker’s setting is what counts, and the number stated here has to match it.

Acme's clocks path /acme Globex's clocks path /globex Balancer port 8080 any instance Listener :8080 /acme [email protected] /globex its own package longest prefix
Any number of endpoints share one port by path. The balancer may send a clock's requests to any instance. Every instance has the same listeners and endpoints.

A stopped listener (hourctl listener stop) stays stopped across restarts. A stopped endpoint answers its devices 503.

Every instance subscribes to an MQTT listener’s topics in one shared subscription. So the broker must support shared subscriptions (operations).

MQTT covers how MQTT messages are acknowledged, held or set aside. It also covers what that asks of the broker, the listener’s ack_wait_secs, and per-device credentials and ACLs.

A tenant’s MQTT listeners reach public brokers only, unless the install lists more in tenant_destinations (where a tenant’s setup reaches).

Security covers keeping strangers from acting as your devices. That means keys, new_devices, paths, IP lists and broker ACLs.

Listeners and endpoints change at run time on every instance at once. Which ports reach the instances from outside is written in the deploy files. That means the balancer’s frontends, a Kubernetes Service’s ports and firewall rules. They are written port by port, so the list says exactly what is open.

The reference deployments expose one HTTP device port, 8080. They are Docker Compose (HAProxy) and Kubernetes (a Service of type LoadBalancer).

MQTT listeners connect out to their broker, so Connect exposes nothing for them. The broker’s port (1883, or 8883 for TLS) belongs to the broker’s deployment.

Any number of endpoints, of any packages, can share one HTTP listener. A request goes to the endpoint whose path is the longest prefix of its own.

  • Literal segments match regardless of case.
  • {name} segments match anything and are captured.

Among endpoints whose paths are as long, the more specific one wins, whatever order they were added in. The segments are compared from the left. At the first place two differ, a literal beats a {name}. For example, /a/b goes before /a/{x}, and /a/{x} goes before /{y}/b.

A path no endpoint has gets a bare 404.

So most changes are a new endpoint on the existing port, with nothing to change on the balancer. Examples are a new site, a new vendor or a new package version.

Choose paths this way:

  • One segment deep for each endpoint, saying what it is for: /office, /warehouse, /site/{site}.
  • Give every endpoint a prefix of its own. A vendor’s own paths, such as ZK PUSH’s /iclock/..., follow the endpoint’s prefix.
  • A {name} segment and a literal at the same depth under one prefix (/site/{site} and /site/main) is allowed. /site/main takes its own requests and /site/{site} takes the rest.

Two endpoints of one listener with the same shape are refused. That means the same path, or the same pattern (/site/{a} and /site/{b}). An endpoint with no path next to others is refused too, because it takes the whole listener.

MQTT topics are chosen the same way, matching the whole topic. The exception is that a topic’s literal segments match exactly. C/x/up is not served by an endpoint on c/x/up.

Sometimes clocks cannot be told apart by URL. Then give them a second port: a listener of its own, exposed as below. This applies to firmware that takes a host and port but no path. It also applies to two vendors’ clocks that use the same paths and cannot be given a prefix.

  1. Add the listener at run time:

    Terminal window
    hourctl listener add branch --http 0.0.0.0:8081

    When no other listener uses the port, the answer carries a Warning header. hourctl prints it. It reads: “port 8081 is one no listener of this setup used before: a load balancer or a published port that clocks reach it by needs it too (…)”.

    A port is never shared between tenants. So each tenant’s listener needs a port of its own, and each tenant with HTTP devices needs its own published port.

  2. Print the balancer snippet from the listeners in the database, so nothing has to be typed twice:

    Terminal window
    hourctl export lb haproxy
  3. Expose the port in the deploy files and on the balancer.

To remove a port, do the same in reverse: take it off the balancer, then remove the listener.

hourctl export lb <format>Prints
haproxyA frontend and a backend per port (fe_http_<port>, be_http_<port>). It has balance roundrobin, option forwardfor, option httpchk with GET /api/ready, and check port 9090.
nginxFor the http block: an upstream and a server per port, with X-Forwarded-For and X-Request-Id set.
k8sA Service of type LoadBalancer, one port entry per device port, externalTrafficPolicy: Local
composeA ports: list for the balancer’s service

Each port is listed once, however many listeners use it. Stopped listeners keep their port, so starting one again needs no balancer change. A listener bound to a loopback address is left out, because a balancer cannot reach it. MQTT listeners are left out too, each with a comment line saying so.

The health checks use the port of the admin URL hourctl was given (--admin, HOURADVANTAGE_ADMIN_URL), or 9090.

The server lines are placeholders (TEST-NET addresses). List the instances, or let the balancer find them in DNS. The compose setup’s haproxy.cfg does this with server-template.

The command prints configuration, not data, so it refuses --json. hourctl listeners --json has the data.

Any balancer that balances TCP or HTTP across the instances works. Nothing is sticky: any instance handles any request. Round robin is the default everywhere.

  • HAProxy: deploy/compose/haproxy.cfg, or hourctl export lb haproxy. Check health on the admin port. Use check port 9090 on the server lines and http-check send meth GET uri /api/ready.
  • nginx: hourctl export lb nginx, inside http { }. Use the http proxy. A stream (TCP) proxy hides the clock’s address, unless it passes it on with proxy_protocol on and the listener’s proxy_protocol = true (below). Open-source nginx checks passively only (max_fails). NGINX Plus can probe /api/ready on the admin port (health_check port=9090 uri=/api/ready).
  • Kubernetes: a Service of type LoadBalancer with one port per device port and externalTrafficPolicy: Local (hourctl export lb k8s). The pods’ readinessProbe on /api/ready takes starting and draining pods out of its endpoints. The cloud balancer checks the nodes (healthCheckNodePort).
  • AWS: a Network Load Balancer passes TCP through with the client’s address. That holds for instance targets. For IP targets, turn on the target group’s preserve_client_ip.enabled. Use one listener and target group per device port. Give it an HTTP health check on /api/ready, port 9090 (the target group’s health check port override). An Application Load Balancer works too, with the same health check. It sends X-Forwarded-For, so set trusted_proxies to its subnets.
  • Google Cloud: the passthrough Network Load Balancer keeps the client’s address. Give its backend service an HTTP health check on port 9090, path /api/ready. The proxy balancers (Application Load Balancer) send X-Forwarded-For. Trust the source ranges Google documents for the balancer type.
  • Azure: Azure Load Balancer passes TCP through with the client’s address. Use a load balancing rule per device port, and an HTTP health probe on port 9090, path /api/ready. Application Gateway sends X-Forwarded-For with the client’s port appended (192.0.2.7:51234). Connect reads that as the address. Trust the Application Gateway’s subnet.

Cloud health checks cannot send Host: localhost, and need not. An admin API that listens beyond loopback (as it must, to be checked) has a login and accepts any host name. /api/ready needs no login.

Connect records each clock’s address from the connection. It reads the address from X-Forwarded-For instead when the connection comes from one of trusted_proxies on a listener without the PROXY protocol.

X-Forwarded-For is read right to left. It skips trusted hops and goes no further than the first untrusted one. So a value the client sent cannot pass for the clock’s. A request whose deciding hop is not an address is answered 400.

Keep the clock’s address in one of three ways:

  • An HTTP balancer that sets X-Forwarded-For (HAProxy option forwardfor, nginx proxy_set_header X-Forwarded-For, cloud application balancers). Set trusted_proxies to the balancer’s addresses. Use hourctl settings set trusted_proxies=10.0.0.0/8, or put trusted_proxies = ["10.0.0.0/8"] at the top of a file for hourctl apply.
  • A passthrough L4 balancer that keeps the source address. On Kubernetes, use externalTrafficPolicy: Local. The default, Cluster, hides the address behind a node’s address. Leave trusted_proxies empty.
  • The PROXY protocol (v1 or v2). TCP balancers use it to pass the address ahead of the request. Those are AWS NLB, HAProxy send-proxy/send-proxy-v2, and nginx stream proxy_protocol on. Set proxy_protocol = true on the listener and trusted_proxies to the balancer’s addresses (below).

A listener with proxy_protocol = true expects every connection to start with a PROXY header, v1 or v2. It takes the address in the header as the client’s. That address is used in the device record, the IP lists and the wire capture.

  • The header is taken only from a connection whose own address is in trusted_proxies. Any other connection is closed unanswered. Settings with such a listener and no trusted_proxies are refused.
  • A connection without the header, with a broken one, or whose header does not arrive in time is closed unanswered. It is counted in houradvantage_http_connection_errors_total{kind="proxy_protocol"}.
  • A v2 LOCAL header (a balancer’s health check) or v1 UNKNOWN keeps the connection’s own address.
  • On such a listener X-Forwarded-For is never read, even from inside trusted_proxies. Past a TCP balancer, that header is whatever the client wrote.
  • A listener without the switch never looks for a header, so no client can claim an address by sending one.

Turn it on only for a listener nothing but the balancer can reach. Turn it on at the balancer at the same time. A balancer that does not send the header gets every connection closed. Changing the switch restarts that listener, so its port closes for a moment.

Listeners and endpoints take allow_from and deny_from. These are lists of addresses or CIDR ranges. They are matched against the client’s address as resolved above.

[[listener]]
id = "public"
type = "http"
listen = "0.0.0.0:8080"
deny_from = ["203.0.113.0/24"]
[[endpoint]]
id = "acme"
listener = "public"
path = "/acme"
package = "zk-push"
allow_from = ["198.51.100.0/24", "2001:db8:acme::/48"]
  • The listener’s lists are checked first, for every request. A request refused there gets 403, even on a path no endpoint has. Then the endpoint’s lists are checked. A request must pass both.
  • deny_from wins over allow_from. With allow_from set, every address it does not name is refused. With neither, everyone is let in.
  • A refused request gets a bare 403 before its body is read. The package never sees it, no device is registered and nothing goes in the traffic log. Refusals are logged (warn) at most once a minute per address. They are counted in houradvantage_ip_refused_total{listener}.
  • Behind an HTTP proxy, set trusted_proxies, or the lists see the proxy’s own address.
  • Changes take effect on every instance without restarting the listener.
  • MQTT listeners and their endpoints refuse IP lists. Connect connects out to the broker and never sees a device’s address. Use the broker’s ACLs.

Several customers (or sites, or vendors) can share a port. Each is on endpoints of its own, with its own package, sinks, new-device policy, IP lists and group, so their people never mix. To keep them apart completely, give each a tenant.

  • By path prefix, on a shared port, for devices whose server URL can take a path. Put /acme and /globex on one listener, each an endpoint of its own, even of different packages or versions. The prefix is taken off before the package sees the request. For example, a ZK PUSH clock pointed at http://gw:8080/acme sends /acme/iclock/cdata. The package sees /iclock/cdata.
  • By port, for devices that take a host and port but no path: a listener of its own with one endpoint and no path.
  • Both at once: prefixed endpoints on one listener and a no-path endpoint on another.

An endpoint is chosen by listener and path (or topic) only, never by the device’s identity.

Always check health on the admin port with GET /api/ready, never on the device port. A device port answers 404 to a probe that matches no endpoint. That says nothing about whether the instance takes work.

Use round robin (balance roundrobin) or whatever the balancer does. Any instance handles any request, and a clock’s requests may go to every instance in turn. The live views gather what every instance sees (operations).

GET /api/ready needs no login and answers from memory. It answers 200 while the instance takes work. It answers 503 with the reasons ({"ready": false, "config_version": 41, "why": [...], "database": true}) in these cases:

  • while it starts;
  • while it drains;
  • while an HTTP listener (not stopped by hand) does not have its port;
  • when it has fallen behind the config version and cannot catch up.

Readiness never depends on the database. The database is shared, so a lost one would take every instance out of the balancer at once. Clocks would then be turned away by the balancer.

Instead, during a database outage every instance stays ready and answers idle polls. It answers what needs the database (uploads, punches, new devices) with 503 “not stored”. Clocks keep the data and send it again. It is stored once the database is back.

database in the body of /api/ready, GET /api/instance and houradvantage_database_up report the database separately. MQTT listeners do not count toward readiness, since whether the broker answers is the same for every instance.

An instance told to stop keeps serving for 6 seconds while /api/ready answers 503. The balancer must mark it down within that time. The compose setup takes 3 checks, about 4 seconds. The stop timeout must be longer.

For a slower balancer, delay the stop signal. On Kubernetes, use a preStop sleep (20 seconds in the Kubernetes setup, with a 45-second grace period).

A cloud balancer in front of VMs takes check interval times unhealthy threshold to notice. An AWS target group checking every 10 seconds with 2 failures takes up to 20 seconds. Take the instance out of the balancer first. Deregister it, which also lets requests under way finish. Wait that long, then stop it.

Have the balancer give each request an id in X-Request-Id and log it. The compose HAProxy does, and hourctl export lb nginx sets nginx’s $request_id. Connect puts it on its log lines about the message (request_id) and sends it back.

Retrying a failed or empty response on another instance is safe. An upload is stored before it is answered, and a repeated record has the same event id.