@mark1russell7/harness 0.16.17 → 0.16.18

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -246,6 +246,11 @@ console.log(used.cpu?.total, used.network?.tx.bytes, used.memory.peak, reader.se
246
246
  - Docker removes the cgroup of a client when its program ends. After that, a `read()` throws, and each reading of a series has null for the values of the cgroup.
247
247
  - The traffic of a client is the traffic of the namespace that the clients of the lab share.
248
248
  - **The parse is in TypeScript.** The reader writes the text of each file in one JSON line. `resourceReadingOf` reads that line with `cpuStatOf`, `memoryStatOf`, `cpuMaxOf`, `networkOf`, `cgroupNumber`, `cgroupLimit` and `cgroupKeyed`.
249
+ - **The readings of a cell** (from 0.16.16). A cell can measure the cost of its target in each run, with `runCell`:
250
+ - `Cell.clientLimits` gives the limits of the client in each run, for example other CPUs than the target.
251
+ - `Cell.resources` starts a reader of the target in each run, with these options. The reader stops at the end of the run.
252
+ - Each run then keeps `Run.resources`. It has a reading when the client is ready and before it sends (`start`). It also has a reading after the run ended (`end`), and the series of the reader.
253
+ - `environmentProblems` names each problem of the limits of the target and of the client, before a lab opens.
249
254
 
250
255
  ## The subjects
251
256
 
@@ -1,6 +1,209 @@
1
1
  import { Quantity } from "@mark1russell7/quantity";
2
2
  import { Profile, Schedule, ScheduleOptions } from "@mark1russell7/rigor-chaos";
3
3
  import { KernelRecord } from "@mark1russell7/prober";
4
+ /**
5
+ * The resources that one container of a lab used. A reader in a sidecar reads the files of the
6
+ * cgroup of the container and the devices of its network namespace (`RESOURCES_PROGRAM`). It
7
+ * writes the text of each file in one JSON line, with a stamp on CLOCK_MONOTONIC. This module reads
8
+ * each file from that line, and it gives the change between two readings.
9
+ *
10
+ * A file that the reader cannot read gives null: no read. It does not give a zero.
11
+ */
12
+ /** This name is the event of a line of the reader. */
13
+ declare const RESOURCES_EVENT = "resources";
14
+ /** This path is the reader of the resources, in the image of the harness. */
15
+ declare const RESOURCES_PROGRAM = "/opt/harness/resources";
16
+ /** These are the counters of `cpu.stat` of a cgroup. Each time is in microseconds, as the kernel gives it. */
17
+ interface ResourceCpu {
18
+ /** This time is `usage_usec`: the CPU time of the tasks of the cgroup. */
19
+ readonly usage: number;
20
+ /** This time is `user_usec`: the part of the usage in user mode. */
21
+ readonly user: number;
22
+ /** This time is `system_usec`: the part of the usage in the kernel. */
23
+ readonly system: number;
24
+ /** This count is `nr_periods`: the periods of the CPU limit. It is null in a cgroup with no `cpu` controller. */
25
+ readonly periods: number | null;
26
+ /** This count is `nr_throttled`: the periods in which the limit stopped the cgroup. */
27
+ readonly throttled: number | null;
28
+ /** This time is `throttled_usec`: how long the limit stopped the cgroup. */
29
+ readonly throttledTime: number | null;
30
+ }
31
+ /** These are the amounts of memory of a cgroup, in bytes. Each one is null when its file or its key gave no read. */
32
+ interface ResourceMemory {
33
+ /** This amount is `memory.current`: the memory that the cgroup holds at this time. */
34
+ readonly current: number | null;
35
+ /** This amount is `memory.peak`: the highest `memory.current` of the cgroup. A kernel before Linux 5.19 has no such file. */
36
+ readonly peak: number | null;
37
+ /** This amount is `anon` of `memory.stat`: the anonymous memory, for example the heap of a program. */
38
+ readonly anon: number | null;
39
+ /** This amount is `file` of `memory.stat`: the page cache. */
40
+ readonly file: number | null;
41
+ /** This amount is `kernel` of `memory.stat`. Where the kernel has no such key, it is `kernel_stack` and `slab`. */
42
+ readonly kernel: number | null;
43
+ /** This amount is `sock` of `memory.stat`: the buffers of the sockets. */
44
+ readonly sock: number | null;
45
+ /** These are the counts of `memory.events`, for example `max` and `oom_kill`. */
46
+ readonly events: Readonly<Record<string, number>> | null;
47
+ }
48
+ /** These are the bytes and the packets of one direction of a device. */
49
+ interface ResourceTraffic {
50
+ readonly bytes: number;
51
+ readonly packets: number;
52
+ }
53
+ /** These are the counters of one device of a network namespace: what it received (`rx`) and what it sent (`tx`). */
54
+ interface ResourceDevice {
55
+ readonly name: string;
56
+ readonly rx: ResourceTraffic;
57
+ readonly tx: ResourceTraffic;
58
+ }
59
+ /** These are the counters of the devices of a network namespace, without `lo`, and their sums. */
60
+ interface ResourceNetwork {
61
+ /** These are the devices, in the order of their names. */
62
+ readonly devices: readonly ResourceDevice[];
63
+ readonly rx: ResourceTraffic;
64
+ readonly tx: ResourceTraffic;
65
+ }
66
+ /** These are the limits of a cgroup, as the kernel prints them. Each one is null when its file gave no read. */
67
+ interface ResourceLimits {
68
+ /** This limit is `cpu.max`: the CPU time of each period in microseconds, or `max` for no limit. */
69
+ readonly cpu: {
70
+ readonly quota: number | "max";
71
+ readonly period: number;
72
+ } | null;
73
+ /** This limit is `memory.max` in bytes, or `max` for no limit. */
74
+ readonly memory: number | "max" | null;
75
+ /** This list is `cpuset.cpus.effective`: the CPUs of the cgroup, for example `0-3`. */
76
+ readonly cpuset: string | null;
77
+ }
78
+ /** A resource reading is the resources of one container at one moment. */
79
+ interface ResourceReading {
80
+ /** This stamp is the time on CLOCK_MONOTONIC before the first file, in nanoseconds. The reader reads `cpu.stat` first. */
81
+ readonly t0: number;
82
+ /** This stamp is the time on CLOCK_MONOTONIC after the last file, in nanoseconds. */
83
+ readonly t1: number;
84
+ /** This folder is the cgroup of the container, as the reader found it. */
85
+ readonly cgroup: string;
86
+ readonly cpu: ResourceCpu | null;
87
+ readonly memory: ResourceMemory;
88
+ /** This count is `pids.current`: the tasks of the cgroup. */
89
+ readonly pids: number | null;
90
+ readonly network: ResourceNetwork | null;
91
+ readonly limits: ResourceLimits;
92
+ }
93
+ /**
94
+ * A resource change is what a container used between two readings. A part is null when a file of
95
+ * it gave no read in one of the readings, or when a counter of it went down. `resets` names each
96
+ * counter that went down, because a negative use has no meaning.
97
+ */
98
+ interface ResourceChange {
99
+ /** This time is the time between the first stamps of the two readings. */
100
+ readonly elapsed: Quantity;
101
+ readonly cpu: {
102
+ readonly total: Quantity;
103
+ readonly user: Quantity;
104
+ readonly system: Quantity;
105
+ /** This time is how long the CPU limit stopped the cgroup. It is null in a cgroup with no `cpu` controller. */
106
+ readonly throttled: Quantity | null;
107
+ /** This count is the periods of the CPU limit. */
108
+ readonly periods: number | null;
109
+ /** This count is the periods in which the limit stopped the cgroup. */
110
+ readonly throttledPeriods: number | null;
111
+ } | null;
112
+ readonly memory: {
113
+ /** This amount is `memory.current` at the second reading, in bytes. */
114
+ readonly last: number | null;
115
+ /** This amount is `memory.peak` at the second reading, in bytes: the highest usage of the cgroup from its start. */
116
+ readonly peak: number | null;
117
+ /** This choice says that the peak rose between the two readings. The peak is then the peak of that time. */
118
+ readonly peakBetween: boolean | null;
119
+ };
120
+ /** This part is the traffic of each device and the sums. A device that came after the first reading counts from 0. */
121
+ readonly network: ResourceNetwork | null;
122
+ /** These are the counters that went down, for example `cpu.usage` after a restart of the container. */
123
+ readonly resets: readonly string[];
124
+ }
125
+ /** These are the options of a reader of the resources of a container. */
126
+ interface ResourceOptions {
127
+ /** This time is the period of a series, for example 1 s. Without it, the reader has no series. */
128
+ readonly period?: Quantity;
129
+ /** This list is the CPUs that the kernel puts the reader on, for example the CPUs of the client. Without it, the reader has no such limit. */
130
+ readonly cpuset?: string;
131
+ }
132
+ /**
133
+ * A resource reader reads the resources of one container from a sidecar. The sidecar is in the
134
+ * network namespace of the container and in the cgroup namespace of the host. It is not in the
135
+ * cgroup of the container, thus its own CPU time and memory are not in the readings.
136
+ */
137
+ interface ResourceReader {
138
+ /** These are the readings of the series, as they arrive. A reader with no period has none. */
139
+ readonly series: readonly ResourceReading[];
140
+ /**
141
+ * This method gives one reading at this moment. The stamps of the reading are the times of the
142
+ * read in the VM, thus the latency of the call is not in them.
143
+ */
144
+ read(): Promise<ResourceReading>;
145
+ /** This method stops the sidecar. The series keeps its readings. */
146
+ stop(): Promise<void>;
147
+ }
148
+ /** These are the fields of the `HostConfig` of the Docker API that hold the limits of a container. */
149
+ interface HostLimits {
150
+ /** This count is the CPU quota, in units of 1e-9 CPUs. */
151
+ NanoCpus?: number;
152
+ /** This list is the CPUs that the kernel puts the container on. */
153
+ CpusetCpus?: string;
154
+ /** This amount is the memory limit, in bytes. */
155
+ Memory?: number;
156
+ /** This amount is the limit of the memory and the swap together, in bytes. It is equal to `Memory`, thus the container has no swap. */
157
+ MemorySwap?: number;
158
+ }
159
+ /** This function gives the problems of the limits of a container, each as a sentence. Limits with no problem give an empty list. */
160
+ declare const limitsProblems: (limits: ContainerLimits) => string[];
161
+ /**
162
+ * This function gives the limits of a container as Docker takes them: the CPU quota, the CPUs and
163
+ * the memory, with no swap. It throws for limits that have a problem (`limitsProblems`).
164
+ */
165
+ declare const hostLimitsOf: (limits: ContainerLimits) => HostLimits;
166
+ /**
167
+ * This function gives the argv of the reader: one reading, or a series with a period. Each folder
168
+ * is a place where the cgroup of the container can be. The reader takes the first one that is there.
169
+ */
170
+ declare const resourceArgs: (dirs: readonly string[], period?: Quantity) => string[];
171
+ /** This function gives the count of a file of a cgroup that holds one count, as `memory.current` does. Another text gives null. */
172
+ declare const cgroupNumber: (text: string) => number | null;
173
+ /** This function gives a limit of a cgroup, as `memory.max` prints it: its count, or `max` for no limit. Another text gives null. */
174
+ declare const cgroupLimit: (text: string) => number | "max" | null;
175
+ /**
176
+ * This function gives the counts of a flat keyed file of a cgroup: one key and one count on each
177
+ * line. `cpu.stat` and `memory.stat` are such files. It skips each other line.
178
+ */
179
+ declare const cgroupKeyed: (text: string) => Readonly<Record<string, number>>;
180
+ /** This function reads `cpu.stat`. It gives null for a text with no usage. */
181
+ declare const cpuStatOf: (text: string) => ResourceCpu | null;
182
+ /** This function reads `memory.stat`: the amounts of `anon`, `file`, `kernel` and `sock`, each null without its key. */
183
+ declare const memoryStatOf: (text: string) => Pick<ResourceMemory, "anon" | "file" | "kernel" | "sock">;
184
+ /** This function reads `cpu.max`: the quota and the period, as `50000 100000` or `max 100000`. Another text gives null. */
185
+ declare const cpuMaxOf: (text: string) => ResourceLimits["cpu"];
186
+ /**
187
+ * This function reads `/proc/net/dev`: the bytes and the packets of each device, without `lo`. It
188
+ * gives null for a text that is not that file, and for a line of a device that it cannot read.
189
+ */
190
+ declare const networkOf: (text: string) => ResourceNetwork | null;
191
+ /**
192
+ * This function gives the reading of one line of the reader (`RESOURCES_EVENT`). It gives null for
193
+ * another line, and for a line with no stamps.
194
+ */
195
+ declare const resourceReadingOf: (line: ProbeEvent) => ResourceReading | null;
196
+ /**
197
+ * This function gives the reading of the output of one read of the reader. It throws for a text
198
+ * that is not a line of a reading.
199
+ */
200
+ declare const resourceReadingIn: (output: string) => ResourceReading;
201
+ /**
202
+ * This function gives what a container used between two readings. It gives its CPU time, the time
203
+ * that its CPU limit stopped it, the traffic of each device, and its last memory. A counter that
204
+ * went down is in `resets`, and its part is null. It throws when the second reading is the earlier one.
205
+ */
206
+ declare const resourceChange: (before: ResourceReading, after: ResourceReading) => ResourceChange;
4
207
  /**
5
208
  * A fault is a failure that the harness injects, by the name of its manifestation. Each name is
6
209
  * the last segment of the identifier of the manifestation in the corpus:
@@ -1541,6 +1744,18 @@ interface Cell {
1541
1744
  * the container starts, and then it makes the file `/tmp/cgroup` in it.
1542
1745
  */
1543
1746
  readonly cgroup?: Readonly<Record<string, string>>;
1747
+ /**
1748
+ * These are the limits of the container of the client in each run: its CPU quota, its CPUs and its
1749
+ * memory. A measurement of the cost of a target puts the client on other CPUs than the target.
1750
+ * Without them, the client has no limit.
1751
+ */
1752
+ readonly clientLimits?: ContainerLimits;
1753
+ /**
1754
+ * These options start a reader of the resources of the target in each run (`Lab.resources`). The
1755
+ * run then keeps a reading when its client is ready, a reading at its end, and the series of the
1756
+ * reader (`Run.resources`). Without them, a run reads no resources.
1757
+ */
1758
+ readonly resources?: ResourceOptions;
1544
1759
  readonly prediction: Prediction;
1545
1760
  /** This side is the side whose detection the cell measures. Without it, the side is the client. */
1546
1761
  readonly observer?: Observer;
@@ -1764,6 +1979,19 @@ interface Run {
1764
1979
  readonly schedule?: Schedule;
1765
1980
  /** These schedules are the ones that the streams of the client `load` had. */
1766
1981
  readonly streams?: readonly RunStream[];
1982
+ /** These are the readings of the resources of the target in a run of a cell with `Cell.resources`. */
1983
+ readonly resources?: RunResources;
1984
+ }
1985
+ /**
1986
+ * These are the readings of the resources of the target in one run. The two readings bracket the
1987
+ * work of the run. The reading `start` comes after the client is ready and before it sends. The
1988
+ * reading `end` comes after the run ended. `resourceChange(start, end)` gives what the target used.
1989
+ */
1990
+ interface RunResources {
1991
+ readonly start: ResourceReading;
1992
+ readonly end: ResourceReading;
1993
+ /** These are the readings of the series of the reader, from its start to its stop. A reader with no period has none. */
1994
+ readonly series: readonly ResourceReading[];
1767
1995
  }
1768
1996
  /** A run route is one change of a route at a leaf of a fabric, on the monotonic clock. */
1769
1997
  interface RunRoute {
@@ -1895,4 +2123,4 @@ interface RunTopology {
1895
2123
  };
1896
2124
  }>>;
1897
2125
  }
1898
- export { MiddleboxEvent as $, HopEvent as A, RunGroup as At, KernelRecord as B, Stage as Bt, Fault as C, RequestPrediction as Ct, GroupPrediction as D, RunBackup as Dt, GroupPlace as E, Run as Et, HttpProbe as F, RunTopology as Ft, LoadPrediction as G, Toxic as Gt, LineMatch as H, Subject as Ht, ImageSource as I, SentinelEvent as It, MemoryOomPrediction as J, isHopPlace as Jt, LoadStream as K, WsProbe as Kt, Jitter as L, SentinelStage as Lt, HopSignal as M, RunPause as Mt, HopWrite as N, RunRoute as Nt, GroupRole as O, RunDrill as Ot, HostSysctl as P, RunStream as Pt, MemoryThrottlePrediction as Q, Kafka as R, Shipped as Rt, FabricManifest as S, Replies as St, Group as T, RttRange as Tt, LoadBand as U, Target as Ut, LineCount as V, StageBand as Vt, LoadPlan as W, Topology as Wt, MemoryPrediction as X, MemoryOomTask as Y, latestEndOf as Yt, MemoryStep as Z, DriverStep as _, Reconnects as _t, ClientCapability as a, PauseBand as at, EgressPrediction as b, ReplicaSet as bt, ClusterClientAt as c, PortsPrediction as ct, ContainerLimits as d, ProxyHop as dt, MiddleboxExpectation as et, CountBand as f, ProxyTime as ft, DriverBand as g, QueuePrediction as gt, DrillRoom as h, QueueEnd as ht, Client as i, Pair as it, HopPlace as j, RunPart as jt, Hop as k, RunFabric as kt, ClusterStage as l, Prediction as lt, Drill as m, QueueConnection as mt, CLIENT_CAPABILITIES as n, Observer as nt, ClientImage as o, PausePrediction as ot, DeliveryPrediction as p, QueueBand as pt, MemoryLimits as q, environmentProblems as qt, Cell as r, Outcomes as rt, Cluster as s, PinnedImage as st, BuildImage as t, MiddleboxForm as tt, ConntrackPrediction as u, ProbeEvent as ut, EgressBurst as v, Recovers as vt, FaultPlace as w, RouterHop as wt, Fabric as x, ReplicaSetStage as xt, EgressPacketLaw as y, Reference as yt, KafkaPause as z, ShippedImage as zt };
2126
+ export { MiddleboxEvent as $, RESOURCES_PROGRAM as $t, HopEvent as A, RunGroup as At, KernelRecord as B, ShippedImage as Bt, Fault as C, RequestPrediction as Ct, GroupPrediction as D, RunBackup as Dt, GroupPlace as E, Run as Et, HttpProbe as F, RunStream as Ft, LoadPrediction as G, Topology as Gt, LineMatch as H, StageBand as Ht, ImageSource as I, RunTopology as It, MemoryOomPrediction as J, environmentProblems as Jt, LoadStream as K, Toxic as Kt, Jitter as L, SentinelEvent as Lt, HopSignal as M, RunPause as Mt, HopWrite as N, RunResources as Nt, GroupRole as O, RunDrill as Ot, HostSysctl as P, RunRoute as Pt, MemoryThrottlePrediction as Q, RESOURCES_EVENT as Qt, Kafka as R, SentinelStage as Rt, FabricManifest as S, resourceReadingOf as Sn, Replies as St, Group as T, RttRange as Tt, LoadBand as U, Subject as Ut, LineCount as V, Stage as Vt, LoadPlan as W, Target as Wt, MemoryPrediction as X, latestEndOf as Xt, MemoryOomTask as Y, isHopPlace as Yt, MemoryStep as Z, HostLimits as Zt, DriverStep as _, memoryStatOf as _n, Reconnects as _t, ClientCapability as a, ResourceNetwork as an, PauseBand as at, EgressPrediction as b, resourceChange as bn, ReplicaSet as bt, ClusterClientAt as c, ResourceReading as cn, PortsPrediction as ct, ContainerLimits as d, cgroupLimit as dn, ProxyHop as dt, ResourceChange as en, MiddleboxExpectation as et, CountBand as f, cgroupNumber as fn, ProxyTime as ft, DriverBand as g, limitsProblems as gn, QueuePrediction as gt, DrillRoom as h, hostLimitsOf as hn, QueueEnd as ht, Client as i, ResourceMemory as in, Pair as it, HopPlace as j, RunPart as jt, Hop as k, RunFabric as kt, ClusterStage as l, ResourceTraffic as ln, Prediction as lt, Drill as m, cpuStatOf as mn, QueueConnection as mt, CLIENT_CAPABILITIES as n, ResourceDevice as nn, Observer as nt, ClientImage as o, ResourceOptions as on, PausePrediction as ot, DeliveryPrediction as p, cpuMaxOf as pn, QueueBand as pt, MemoryLimits as q, WsProbe as qt, Cell as r, ResourceLimits as rn, Outcomes as rt, Cluster as s, ResourceReader as sn, PinnedImage as st, BuildImage as t, ResourceCpu as tn, MiddleboxForm as tt, ConntrackPrediction as u, cgroupKeyed as un, ProbeEvent as ut, EgressBurst as v, networkOf as vn, Recovers as vt, FaultPlace as w, RouterHop as wt, Fabric as x, resourceReadingIn as xn, ReplicaSetStage as xt, EgressPacketLaw as y, resourceArgs as yn, Reference as yt, KafkaPause as z, Shipped as zt };
@@ -1,4 +1,4 @@
1
- import { valueIn } from "@mark1russell7/quantity";
1
+ import { quantity, valueIn } from "@mark1russell7/quantity";
2
2
  import { setTimeout } from "node:timers/promises";
3
3
  import { createHash } from "node:crypto";
4
4
  import { execFile } from "node:child_process";
@@ -9,6 +9,337 @@ import { createRequire } from "node:module";
9
9
  import { fileURLToPath } from "node:url";
10
10
  import { isDeepStrictEqual } from "node:util";
11
11
  import semver from "semver";
12
+ // src/resources.ts
13
+ /**
14
+ * The resources that one container of a lab used. A reader in a sidecar reads the files of the
15
+ * cgroup of the container and the devices of its network namespace (`RESOURCES_PROGRAM`). It
16
+ * writes the text of each file in one JSON line, with a stamp on CLOCK_MONOTONIC. This module reads
17
+ * each file from that line, and it gives the change between two readings.
18
+ *
19
+ * A file that the reader cannot read gives null: no read. It does not give a zero.
20
+ */
21
+ /** This name is the event of a line of the reader. */
22
+ const RESOURCES_EVENT = "resources";
23
+ /** This path is the reader of the resources, in the image of the harness. */
24
+ const RESOURCES_PROGRAM = "/opt/harness/resources";
25
+ /** This count is the smallest CPU limit that Docker takes, in CPUs. */
26
+ const LEAST_CPUS = .01;
27
+ /** This amount is the smallest memory limit that Docker takes, in bytes: 6 MiB. */
28
+ const LEAST_MEMORY = 6291456;
29
+ /** This function gives the bytes of a memory limit, or null for an amount that is not a count of bytes. */
30
+ const bytesOf = (memory) => {
31
+ try {
32
+ const bytes = Math.round(valueIn(memory, "B"));
33
+ return Number.isSafeInteger(bytes) ? bytes : null;
34
+ } catch {
35
+ return null;
36
+ }
37
+ };
38
+ /** This function tells that a text is a list of CPUs, as `cpuset.cpus` takes it: `0`, `2-3` or `0,2`. */
39
+ const isCpuList = (text) => /^\d+(-\d+)?(,\d+(-\d+)?)*$/.test(text) && text.split(",").every((range) => {
40
+ const [first, last] = range.split("-").map(Number);
41
+ return last === void 0 || first <= last;
42
+ });
43
+ /** This function gives the problems of the limits of a container, each as a sentence. Limits with no problem give an empty list. */
44
+ const limitsProblems = (limits) => {
45
+ const problems = [];
46
+ const { cpus, cpuset, memory } = limits;
47
+ if (cpus !== void 0 && !(Number.isFinite(cpus) && cpus >= LEAST_CPUS)) problems.push(`cpus is ${cpus}: Docker takes ${LEAST_CPUS} CPUs or more`);
48
+ if (cpuset !== void 0 && !isCpuList(cpuset)) problems.push(`cpuset is "${cpuset}": write a list of CPUs, for example 0, 2-3 or 0,2`);
49
+ if (memory !== void 0) {
50
+ const bytes = bytesOf(memory);
51
+ if (bytes === null) problems.push(`memory is ${memory.value} ${memory.unit}: write an amount of data, for example 512 MiB`);
52
+ else if (bytes < LEAST_MEMORY) problems.push(`memory is ${bytes} B: Docker takes 6 MiB or more`);
53
+ }
54
+ return problems;
55
+ };
56
+ /**
57
+ * This function gives the limits of a container as Docker takes them: the CPU quota, the CPUs and
58
+ * the memory, with no swap. It throws for limits that have a problem (`limitsProblems`).
59
+ */
60
+ const hostLimitsOf = (limits) => {
61
+ const problems = limitsProblems(limits);
62
+ if (problems.length > 0) throw new RangeError(`the limits of a container: ${problems.join("; ")}`);
63
+ const bytes = limits.memory === void 0 ? null : bytesOf(limits.memory);
64
+ return {
65
+ ...limits.cpus === void 0 ? {} : { NanoCpus: Math.round(limits.cpus * 1e9) },
66
+ ...limits.cpuset === void 0 ? {} : { CpusetCpus: limits.cpuset },
67
+ ...bytes === null ? {} : {
68
+ Memory: bytes,
69
+ MemorySwap: bytes
70
+ }
71
+ };
72
+ };
73
+ /**
74
+ * This function gives the argv of the reader: one reading, or a series with a period. Each folder
75
+ * is a place where the cgroup of the container can be. The reader takes the first one that is there.
76
+ */
77
+ const resourceArgs = (dirs, period) => {
78
+ if (period === void 0) return [
79
+ RESOURCES_PROGRAM,
80
+ "read",
81
+ ...dirs
82
+ ];
83
+ const ms = Math.round(valueIn(period, "ms"));
84
+ if (!(ms >= 1)) throw new RangeError(`resourceArgs: the period of a series is ${ms} ms, and the reader takes 1 ms or more`);
85
+ return [
86
+ RESOURCES_PROGRAM,
87
+ "watch",
88
+ "--period-ms",
89
+ String(ms),
90
+ ...dirs
91
+ ];
92
+ };
93
+ /** This function gives a count from its digits, or null for another text and for a count that a number cannot hold. */
94
+ const countOf = (text) => {
95
+ if (text === void 0 || !/^\d+$/.test(text)) return null;
96
+ const count = Number(text);
97
+ return Number.isSafeInteger(count) ? count : null;
98
+ };
99
+ /** This function gives the count of a file of a cgroup that holds one count, as `memory.current` does. Another text gives null. */
100
+ const cgroupNumber = (text) => countOf(text.trim());
101
+ /** This function gives a limit of a cgroup, as `memory.max` prints it: its count, or `max` for no limit. Another text gives null. */
102
+ const cgroupLimit = (text) => text.trim() === "max" ? "max" : cgroupNumber(text);
103
+ /**
104
+ * This function gives the counts of a flat keyed file of a cgroup: one key and one count on each
105
+ * line. `cpu.stat` and `memory.stat` are such files. It skips each other line.
106
+ */
107
+ const cgroupKeyed = (text) => Object.fromEntries(text.split("\n").flatMap((line) => {
108
+ const parts = line.trim().split(/\s+/);
109
+ const count = parts.length === 2 ? countOf(parts[1]) : null;
110
+ return count === null ? [] : [[parts[0], count]];
111
+ }));
112
+ /** This function gives one count of a flat keyed file, or null for a key that the file does not have. */
113
+ const keyOf = (counts, key) => Object.hasOwn(counts, key) ? counts[key] : null;
114
+ /** This function reads `cpu.stat`. It gives null for a text with no usage. */
115
+ const cpuStatOf = (text) => {
116
+ const counts = cgroupKeyed(text);
117
+ const [usage, user, system] = [
118
+ keyOf(counts, "usage_usec"),
119
+ keyOf(counts, "user_usec"),
120
+ keyOf(counts, "system_usec")
121
+ ];
122
+ if (usage === null || user === null || system === null) return null;
123
+ return {
124
+ usage,
125
+ user,
126
+ system,
127
+ periods: keyOf(counts, "nr_periods"),
128
+ throttled: keyOf(counts, "nr_throttled"),
129
+ throttledTime: keyOf(counts, "throttled_usec")
130
+ };
131
+ };
132
+ /** This function reads `memory.stat`: the amounts of `anon`, `file`, `kernel` and `sock`, each null without its key. */
133
+ const memoryStatOf = (text) => {
134
+ const counts = cgroupKeyed(text);
135
+ const [stack, slab] = [keyOf(counts, "kernel_stack"), keyOf(counts, "slab")];
136
+ return {
137
+ anon: keyOf(counts, "anon"),
138
+ file: keyOf(counts, "file"),
139
+ kernel: keyOf(counts, "kernel") ?? (stack === null || slab === null ? null : stack + slab),
140
+ sock: keyOf(counts, "sock")
141
+ };
142
+ };
143
+ /** This function reads `cpu.max`: the quota and the period, as `50000 100000` or `max 100000`. Another text gives null. */
144
+ const cpuMaxOf = (text) => {
145
+ const parts = text.trim().split(/\s+/);
146
+ const quota = parts[0] === "max" ? "max" : countOf(parts[0]);
147
+ const period = countOf(parts[1]);
148
+ return parts.length !== 2 || quota === null || period === null ? null : {
149
+ quota,
150
+ period
151
+ };
152
+ };
153
+ const NO_TRAFFIC = {
154
+ bytes: 0,
155
+ packets: 0
156
+ };
157
+ const sumOf = (devices, side) => devices.reduce((sum, device) => ({
158
+ bytes: sum.bytes + device[side].bytes,
159
+ packets: sum.packets + device[side].packets
160
+ }), NO_TRAFFIC);
161
+ /** This function gives the network of some devices: the devices in the order of their names, and their sums. */
162
+ const networkWith = (devices) => {
163
+ const sorted = [...devices].sort((one, other) => one.name < other.name ? -1 : one.name > other.name ? 1 : 0);
164
+ return {
165
+ devices: sorted,
166
+ rx: sumOf(sorted, "rx"),
167
+ tx: sumOf(sorted, "tx")
168
+ };
169
+ };
170
+ /**
171
+ * This function reads `/proc/net/dev`: the bytes and the packets of each device, without `lo`. It
172
+ * gives null for a text that is not that file, and for a line of a device that it cannot read.
173
+ */
174
+ const networkOf = (text) => {
175
+ if (!text.includes("|bytes")) return null;
176
+ const devices = [];
177
+ for (const line of text.split("\n")) {
178
+ const colon = line.lastIndexOf(":");
179
+ if (colon < 0) continue;
180
+ const name = line.slice(0, colon).trim();
181
+ const counts = line.slice(colon + 1).trim().split(/\s+/).map(countOf);
182
+ if (name === "" || counts.length < 16 || counts.includes(null)) return null;
183
+ if (name === "lo") continue;
184
+ devices.push({
185
+ name,
186
+ rx: {
187
+ bytes: counts[0],
188
+ packets: counts[1]
189
+ },
190
+ tx: {
191
+ bytes: counts[8],
192
+ packets: counts[9]
193
+ }
194
+ });
195
+ }
196
+ return networkWith(devices);
197
+ };
198
+ /** This function gives the text of one file of a line of the reader, or null for no read. */
199
+ const textOf$1 = (files, name) => {
200
+ if (typeof files !== "object" || files === null || !Object.hasOwn(files, name)) return null;
201
+ const text = files[name];
202
+ return typeof text === "string" ? text : null;
203
+ };
204
+ /** This function reads a text with `read`, and gives null for no text. */
205
+ const readWith = (text, read) => text === null ? null : read(text);
206
+ /**
207
+ * This function gives the reading of one line of the reader (`RESOURCES_EVENT`). It gives null for
208
+ * another line, and for a line with no stamps.
209
+ */
210
+ const resourceReadingOf = (line) => {
211
+ const { t, t1, cgroup, files, net } = line;
212
+ if (line.ev !== "resources" || typeof t !== "number" || typeof t1 !== "number" || typeof cgroup !== "string") return null;
213
+ const file = (name) => textOf$1(files, name);
214
+ const stat = readWith(file("memory.stat"), memoryStatOf) ?? {
215
+ anon: null,
216
+ file: null,
217
+ kernel: null,
218
+ sock: null
219
+ };
220
+ const cpuset = file("cpuset.cpus.effective")?.trim();
221
+ return {
222
+ t0: t,
223
+ t1,
224
+ cgroup,
225
+ cpu: readWith(file("cpu.stat"), cpuStatOf),
226
+ memory: {
227
+ current: readWith(file("memory.current"), cgroupNumber),
228
+ peak: readWith(file("memory.peak"), cgroupNumber),
229
+ ...stat,
230
+ events: readWith(file("memory.events"), cgroupKeyed)
231
+ },
232
+ pids: readWith(file("pids.current"), cgroupNumber),
233
+ network: typeof net === "string" ? networkOf(net) : null,
234
+ limits: {
235
+ cpu: readWith(file("cpu.max"), cpuMaxOf),
236
+ memory: readWith(file("memory.max"), cgroupLimit),
237
+ cpuset: cpuset === void 0 || cpuset === "" ? null : cpuset
238
+ }
239
+ };
240
+ };
241
+ /**
242
+ * This function gives the reading of the output of one read of the reader. It throws for a text
243
+ * that is not a line of a reading.
244
+ */
245
+ const resourceReadingIn = (output) => {
246
+ let line = null;
247
+ try {
248
+ line = JSON.parse(output);
249
+ } catch {}
250
+ const reading = typeof line === "object" && line !== null && typeof line.ev === "string" ? resourceReadingOf(line) : null;
251
+ if (reading === null) throw new Error(`the reader of the resources gave no reading: ${output.slice(0, 200)}`);
252
+ return reading;
253
+ };
254
+ /** This function gives a time from its microseconds. */
255
+ const fromMicroseconds = (time) => quantity(time / 1e6, "s");
256
+ /**
257
+ * This function gives what a container used between two readings. It gives its CPU time, the time
258
+ * that its CPU limit stopped it, the traffic of each device, and its last memory. A counter that
259
+ * went down is in `resets`, and its part is null. It throws when the second reading is the earlier one.
260
+ */
261
+ const resourceChange = (before, after) => {
262
+ if (after.t0 < before.t0) throw new RangeError(`resourceChange: the second reading is ${before.t0 - after.t0} ns before the first`);
263
+ const resets = [];
264
+ /** This function gives the rise of a counter. It gives null for a counter that went down, and names it. */
265
+ const rise = (name, from, to) => {
266
+ if (to >= from) return to - from;
267
+ resets.push(name);
268
+ return null;
269
+ };
270
+ /** This function gives the rise of a counter that can have no read. */
271
+ const riseOf = (name, from, to) => from === null || to === null ? null : rise(name, from, to);
272
+ const same = before.cgroup === after.cgroup;
273
+ if (!same) resets.push("cgroup");
274
+ const cpu = (() => {
275
+ if (!same || before.cpu === null || after.cpu === null) return null;
276
+ const [total, user, system] = [
277
+ rise("cpu.usage", before.cpu.usage, after.cpu.usage),
278
+ rise("cpu.user", before.cpu.user, after.cpu.user),
279
+ rise("cpu.system", before.cpu.system, after.cpu.system)
280
+ ];
281
+ const periods = riseOf("cpu.periods", before.cpu.periods, after.cpu.periods);
282
+ const throttledPeriods = riseOf("cpu.throttled", before.cpu.throttled, after.cpu.throttled);
283
+ const throttled = riseOf("cpu.throttledTime", before.cpu.throttledTime, after.cpu.throttledTime);
284
+ if (total === null || user === null || system === null) return null;
285
+ return {
286
+ total: fromMicroseconds(total),
287
+ user: fromMicroseconds(user),
288
+ system: fromMicroseconds(system),
289
+ throttled: throttled === null ? null : fromMicroseconds(throttled),
290
+ periods,
291
+ throttledPeriods
292
+ };
293
+ })();
294
+ const network = (() => {
295
+ if (before.network === null || after.network === null) return null;
296
+ const earlier = new Map(before.network.devices.map((device) => [device.name, device]));
297
+ const devices = [];
298
+ let whole = true;
299
+ for (const device of after.network.devices) {
300
+ const from = earlier.get(device.name) ?? {
301
+ name: device.name,
302
+ rx: NO_TRAFFIC,
303
+ tx: NO_TRAFFIC
304
+ };
305
+ earlier.delete(device.name);
306
+ const each = ["rx", "tx"].map((side) => ({
307
+ bytes: rise(`network.${device.name}.${side}.bytes`, from[side].bytes, device[side].bytes),
308
+ packets: rise(`network.${device.name}.${side}.packets`, from[side].packets, device[side].packets)
309
+ }));
310
+ const [rx, tx] = [each[0], each[1]];
311
+ if (rx.bytes === null || rx.packets === null || tx.bytes === null || tx.packets === null) whole = false;
312
+ else devices.push({
313
+ name: device.name,
314
+ rx: {
315
+ bytes: rx.bytes,
316
+ packets: rx.packets
317
+ },
318
+ tx: {
319
+ bytes: tx.bytes,
320
+ packets: tx.packets
321
+ }
322
+ });
323
+ }
324
+ for (const name of earlier.keys()) {
325
+ resets.push(`network.${name}`);
326
+ whole = false;
327
+ }
328
+ return whole ? networkWith(devices) : null;
329
+ })();
330
+ const [peakBefore, peakAfter] = [before.memory.peak, after.memory.peak];
331
+ return {
332
+ elapsed: quantity((after.t0 - before.t0) / 1e9, "s"),
333
+ cpu,
334
+ memory: {
335
+ last: after.memory.current,
336
+ peak: peakAfter,
337
+ peakBetween: !same || peakBefore === null || peakAfter === null ? null : peakAfter > peakBefore
338
+ },
339
+ network,
340
+ resets
341
+ };
342
+ };
12
343
  // src/cell.ts
13
344
  /** These are the capabilities that a client image can get. */
14
345
  const CLIENT_CAPABILITIES = [
@@ -24,7 +355,11 @@ const isHopPlace = (place) => typeof place === "object" && "hop" in place;
24
355
  * host. Thus a cell with sysctls of the host operates one environment at a time. Otherwise, a lab
25
356
  * reads the value of a different lab as its value before, and the restore does not give back the host.
26
357
  */
27
- const environmentProblems = (cell) => (cell.hostSysctls?.length ?? 0) > 0 && (cell.concurrency ?? 1) > 1 ? [`${cell.name}: a cell with sysctls of the host operates one environment at a time, not ${cell.concurrency}`] : [];
358
+ const environmentProblems = (cell) => [
359
+ ...(cell.hostSysctls?.length ?? 0) > 0 && (cell.concurrency ?? 1) > 1 ? [`${cell.name}: a cell with sysctls of the host operates one environment at a time, not ${cell.concurrency}`] : [],
360
+ ...cell.target.limits === void 0 ? [] : limitsProblems(cell.target.limits).map((problem) => `${cell.name}: the target: ${problem}`),
361
+ ...cell.clientLimits === void 0 ? [] : limitsProblems(cell.clientLimits).map((problem) => `${cell.name}: the client: ${problem}`)
362
+ ];
28
363
  /**
29
364
  * This function tells if the request of a client goes before the fault of its cell. That is so for a
30
365
  * hop event that comes while the request is in flight (`HopEvent.inFlight`). Then a request after the fault is void.
@@ -754,6 +1089,6 @@ const grpcClientImage = () => imageOf(shipped("grpc"));
754
1089
  const targetSourceOf = (target) => target.subject ?? target.image;
755
1090
  /** This function gives the image that a target operates: the image of its subject, or its stock image. */
756
1091
  const targetImageOf = (target) => imageOf(targetSourceOf(target));
757
- export { targetSourceOf as A, versionsOf as B, programOf as C, subjectClient as D, sources as E, goVersions as F, requestFirst as G, environmentProblems as H, jarVersions as I, locksOf as L, unpinnedBases as M, LOCK_NAMES as N, subjectProblems as O, cargoVersions as P, npmDrift as R, planOf as S, shippedSource as T, isHopPlace as U, CLIENT_CAPABILITIES as V, latestEndOf as W, kafkaClientImage as _, SHIPPED_NAMES as a, nodeHttpImage as b, buildRecordOf as c, harnessImage as d, harnessVersion as f, inContext as g, imageProblems as h, SHIPPED_CLIENTS as i, unlockedManifests as j, targetImageOf as k, goHttpImage as l, imageOf as m, PINNED as n, amqpClientImage as o, hikariClientImage as p, REPOSITORY as r, basesOf as s, CLIENT_NAMES as t, grpcClientImage as u, mongoClientImage as v, routerImage as w, pgClientImage as x, nodeClientImage as y, npmVersions as z };
1092
+ export { hostLimitsOf as $, targetSourceOf as A, versionsOf as B, programOf as C, subjectClient as D, sources as E, goVersions as F, requestFirst as G, environmentProblems as H, jarVersions as I, cgroupKeyed as J, RESOURCES_EVENT as K, locksOf as L, unpinnedBases as M, LOCK_NAMES as N, subjectProblems as O, cargoVersions as P, cpuStatOf as Q, npmDrift as R, planOf as S, shippedSource as T, isHopPlace as U, CLIENT_CAPABILITIES as V, latestEndOf as W, cgroupNumber as X, cgroupLimit as Y, cpuMaxOf as Z, kafkaClientImage as _, SHIPPED_NAMES as a, resourceReadingIn as at, nodeHttpImage as b, buildRecordOf as c, harnessImage as d, limitsProblems as et, harnessVersion as f, inContext as g, imageProblems as h, SHIPPED_CLIENTS as i, resourceChange as it, unlockedManifests as j, targetImageOf as k, goHttpImage as l, imageOf as m, PINNED as n, networkOf as nt, amqpClientImage as o, resourceReadingOf as ot, hikariClientImage as p, RESOURCES_PROGRAM as q, REPOSITORY as r, resourceArgs as rt, basesOf as s, CLIENT_NAMES as t, memoryStatOf as tt, grpcClientImage as u, mongoClientImage as v, routerImage as w, pgClientImage as x, nodeClientImage as y, npmVersions as z };
758
1093
 
759
- //# sourceMappingURL=image-BE9H5gIv.js.map
1094
+ //# sourceMappingURL=image-CjrmLPA7.js.map