skip to content
==> include/mesh/nic.h <==
1/* @ajax/mesh-nic: the machine's network interfaces' counters (net.rs, "Network I/O").
2 *
3 * Read once a second: Linux /proc/net/dev, macOS the routing sysctl's 64-bit
4 * if_data64. Each OS counter is extended to a monotonic u64 (a narrower one
5 * that went down wrapped; a 64-bit one that went down was reset), and a total
6 * sums every physical interface (mesh-abi NET_VIRTUAL prefixes left out) that
7 * never goes down. NIC records (NI_*) are what the host block publishes. */
8#ifndef MESH_NIC_H
9#define MESH_NIC_H
10
11#include "mesh/abi/host_nics.h"
12
13#include <stdbool.h>
14#include <stddef.h>
15#include <stdint.h>
16
17#define MESH_NIC_NAME_MAX 64
18
19/* The NIC counters in NI_* order: rx/tx bytes, packets, errors, drops. */
20extern const size_t MESH_NIC_COUNTERS[8];
21
22/* One interface's raw counters as the OS reports them, and each counter's width in bits. */
23typedef struct {
24    char name[MESH_NIC_NAME_MAX];
25    uint64_t v[8];
26    uint32_t bits[8];
27} mesh_nic_raw;
28
29/* A raw counter extended to a monotonic u64. */
30typedef struct {
31    uint64_t last, value;
32} mesh_nic_ext;
33
34mesh_nic_ext mesh_nic_ext_new(uint64_t raw);
35/* Advances by the delta to raw; returns it. */
36uint64_t mesh_nic_ext_update(mesh_nic_ext *e, uint64_t raw, uint32_t bits);
37
38/* `/proc/net/dev`'s text: 0 and *out (free it), or -1 and *err (free it). */
39int mesh_nic_parse_proc_net_dev(const char *text, mesh_nic_raw **out, size_t *n, char **err);
40/* This machine's interfaces now. */
41int mesh_nic_read(mesh_nic_raw **out, size_t *n, char **err);
42/* The interface holding local address `ip` (IPv4 or IPv6 text): 0 and name, or -1 and *err. */
43int mesh_nic_iface_of(const char *ip, char name[MESH_NIC_NAME_MAX], char **err);
44
45/* An interface's extended counters now (one sample's answer). */
46typedef struct {
47    char name[MESH_NIC_NAME_MAX];
48    uint64_t v[8];
49} mesh_nic_now;
50
51typedef struct {
52    char name[MESH_NIC_NAME_MAX];
53    mesh_nic_ext e[8];
54} mesh_nic_entry_;
55
56/* The sampler's state: each interface's extended counters, and the total. */
57typedef struct {
58    mesh_nic_entry_ *ext;
59    size_t n;
60    uint64_t total[8];
61    uint32_t counted;
62} mesh_nics;
63
64/* One sample: updates every interface; *now (free it) lists each by name, in raw's order. */
65void mesh_nics_sample(mesh_nics *s, const mesh_nic_raw *raw, size_t n, mesh_nic_now **now, size_t *nnow);
66const uint64_t *mesh_nic_lookup(const mesh_nic_now *now, size_t n, const char *name);
67void mesh_nics_free(mesh_nics *s);
68
69/* A NIC record's bytes (MESH_NIC_BYTES): the name (at most 15 bytes), the counters, links, count. */
70void mesh_nic_record(uint8_t out[MESH_NIC_BYTES], const char *name, const uint64_t v[8], uint32_t links, uint32_t count);
71
72#endif