@celljs/ta-gateway 4.15.2 → 4.17.0
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.en.md +5 -2
- package/README.md +5 -2
- package/esm/node/command-sandbox.d.ts +1 -0
- package/esm/node/command-sandbox.js +10 -1
- package/esm/node/docker-engine.d.ts +10 -1
- package/esm/node/docker-engine.js +18 -1
- package/esm/node/docker-sandbox.d.ts +13 -1
- package/esm/node/docker-sandbox.js +35 -2
- package/esm/node/egress-proxy.d.ts +98 -0
- package/esm/node/egress-proxy.js +428 -0
- package/esm/node/environments.d.ts +5 -0
- package/esm/node/environments.js +7 -3
- package/esm/node/gateway-cli.js +12 -5
- package/esm/node/gateway-exec.d.ts +19 -0
- package/esm/node/gateway-exec.js +65 -0
- package/esm/node/gateway-policy.d.ts +7 -1
- package/esm/node/gateway-policy.js +12 -2
- package/esm/node/gateway-quotas.d.ts +15 -2
- package/esm/node/gateway-quotas.js +51 -3
- package/esm/node/gateway-server.d.ts +43 -1
- package/esm/node/gateway-server.js +179 -10
- package/esm/node/gateway-service-util.d.ts +41 -0
- package/esm/node/gateway-service-util.js +178 -0
- package/esm/node/gateway-service.d.ts +13 -41
- package/esm/node/gateway-service.js +41 -176
- package/esm/node/gateway-socket.d.ts +1 -1
- package/esm/node/gateway-socket.js +1 -1
- package/esm/node/index.d.ts +4 -0
- package/esm/node/index.js +4 -0
- package/esm/node/kubernetes-api.d.ts +35 -0
- package/esm/node/kubernetes-api.js +115 -0
- package/esm/node/kubernetes-sandbox.d.ts +198 -0
- package/esm/node/kubernetes-sandbox.js +279 -0
- package/esm/node/local-sandbox.d.ts +1 -0
- package/esm/node/local-sandbox.js +2 -1
- package/esm/node/model-proxy.d.ts +105 -0
- package/esm/node/model-proxy.js +435 -0
- package/esm/node/sandbox-provider.d.ts +17 -0
- package/esm/node/sandbox-provider.js +2 -1
- package/esm/node/tenant-store.d.ts +22 -0
- package/esm/node/tenant-store.js +25 -0
- package/lib/node/command-sandbox.d.ts +1 -0
- package/lib/node/command-sandbox.js +10 -1
- package/lib/node/docker-engine.d.ts +10 -1
- package/lib/node/docker-engine.js +18 -1
- package/lib/node/docker-sandbox.d.ts +13 -1
- package/lib/node/docker-sandbox.js +35 -2
- package/lib/node/egress-proxy.d.ts +99 -0
- package/lib/node/egress-proxy.js +433 -0
- package/lib/node/environments.d.ts +5 -0
- package/lib/node/environments.js +7 -3
- package/lib/node/gateway-cli.js +12 -5
- package/lib/node/gateway-exec.d.ts +20 -0
- package/lib/node/gateway-exec.js +69 -0
- package/lib/node/gateway-policy.d.ts +7 -1
- package/lib/node/gateway-policy.js +12 -2
- package/lib/node/gateway-quotas.d.ts +15 -2
- package/lib/node/gateway-quotas.js +51 -3
- package/lib/node/gateway-server.d.ts +43 -1
- package/lib/node/gateway-server.js +177 -8
- package/lib/node/gateway-service-util.d.ts +42 -0
- package/lib/node/gateway-service-util.js +182 -0
- package/lib/node/gateway-service.d.ts +13 -41
- package/lib/node/gateway-service.js +63 -199
- package/lib/node/gateway-socket.d.ts +1 -1
- package/lib/node/gateway-socket.js +10 -10
- package/lib/node/index.d.ts +4 -0
- package/lib/node/index.js +4 -0
- package/lib/node/kubernetes-api.d.ts +36 -0
- package/lib/node/kubernetes-api.js +120 -0
- package/lib/node/kubernetes-sandbox.d.ts +199 -0
- package/lib/node/kubernetes-sandbox.js +283 -0
- package/lib/node/local-sandbox.d.ts +1 -0
- package/lib/node/local-sandbox.js +2 -1
- package/lib/node/model-proxy.d.ts +106 -0
- package/lib/node/model-proxy.js +440 -0
- package/lib/node/sandbox-provider.d.ts +17 -0
- package/lib/node/sandbox-provider.js +2 -1
- package/lib/node/tenant-store.d.ts +22 -0
- package/lib/node/tenant-store.js +25 -0
- package/package.json +4 -4
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
import { readFileSync } from 'node:fs';
|
|
2
|
+
import { request as httpRequest } from 'node:http';
|
|
3
|
+
import { request as httpsRequest } from 'node:https';
|
|
4
|
+
/** Where a pod finds the API of its cluster: its service account's token, CA and namespace. */
|
|
5
|
+
const ACCOUNT = '/var/run/secrets/kubernetes.io/serviceaccount';
|
|
6
|
+
export class KubernetesError extends Error {
|
|
7
|
+
constructor(status, message) {
|
|
8
|
+
super(message);
|
|
9
|
+
this.status = status;
|
|
10
|
+
}
|
|
11
|
+
}
|
|
12
|
+
/**
|
|
13
|
+
* The API of a cluster over HTTPS, without a client library: what a provider of sandboxes needs is a few
|
|
14
|
+
* resources by their paths.
|
|
15
|
+
*/
|
|
16
|
+
export class KubernetesApi {
|
|
17
|
+
/** In a pod of the cluster: its service account, and the namespace it runs in. */
|
|
18
|
+
static inCluster(env = process.env, read = (path) => readFileSync(path, 'utf8')) {
|
|
19
|
+
var _a;
|
|
20
|
+
const host = env.KUBERNETES_SERVICE_HOST;
|
|
21
|
+
if (!host) {
|
|
22
|
+
throw new Error('Not in a pod of Kubernetes (no KUBERNETES_SERVICE_HOST): give "server" and "token" of the cluster.');
|
|
23
|
+
}
|
|
24
|
+
const port = (_a = env.KUBERNETES_SERVICE_PORT) !== null && _a !== void 0 ? _a : '443';
|
|
25
|
+
return {
|
|
26
|
+
server: `https://${host.includes(':') ? `[${host}]` : host}:${port}`,
|
|
27
|
+
token: read(`${ACCOUNT}/token`).trim(),
|
|
28
|
+
ca: read(`${ACCOUNT}/ca.crt`),
|
|
29
|
+
namespace: read(`${ACCOUNT}/namespace`).trim(),
|
|
30
|
+
};
|
|
31
|
+
}
|
|
32
|
+
constructor(options) {
|
|
33
|
+
this.options = options;
|
|
34
|
+
}
|
|
35
|
+
async call(method, path, body, type = 'application/json') {
|
|
36
|
+
const text = await this.send(method, path, body === undefined ? undefined : JSON.stringify(body), type);
|
|
37
|
+
return (text ? JSON.parse(text) : undefined);
|
|
38
|
+
}
|
|
39
|
+
text(path) {
|
|
40
|
+
return this.send('GET', path);
|
|
41
|
+
}
|
|
42
|
+
send(method, path, body, type) {
|
|
43
|
+
const url = new URL(path, this.options.server);
|
|
44
|
+
const options = {
|
|
45
|
+
method,
|
|
46
|
+
headers: {
|
|
47
|
+
accept: 'application/json, */*',
|
|
48
|
+
...(this.options.token ? { authorization: `Bearer ${this.options.token}` } : {}),
|
|
49
|
+
...(body !== undefined ? { 'content-type': type !== null && type !== void 0 ? type : 'application/json', 'content-length': Buffer.byteLength(body) } : {}),
|
|
50
|
+
},
|
|
51
|
+
...(this.options.ca ? { ca: this.options.ca } : {}),
|
|
52
|
+
timeout: 30000,
|
|
53
|
+
};
|
|
54
|
+
const send = url.protocol === 'https:' ? httpsRequest : httpRequest;
|
|
55
|
+
return new Promise((resolve, reject) => {
|
|
56
|
+
const request = send(url, options, response => {
|
|
57
|
+
const chunks = [];
|
|
58
|
+
response.on('data', chunk => chunks.push(chunk));
|
|
59
|
+
response.on('end', () => {
|
|
60
|
+
var _a, _b;
|
|
61
|
+
const text = Buffer.concat(chunks).toString('utf8');
|
|
62
|
+
const status = (_a = response.statusCode) !== null && _a !== void 0 ? _a : 0;
|
|
63
|
+
if (status >= 200 && status < 300) {
|
|
64
|
+
resolve(text);
|
|
65
|
+
return;
|
|
66
|
+
}
|
|
67
|
+
let message = text.slice(0, 300);
|
|
68
|
+
try {
|
|
69
|
+
message = (_b = JSON.parse(text).message) !== null && _b !== void 0 ? _b : message;
|
|
70
|
+
}
|
|
71
|
+
catch (_c) {
|
|
72
|
+
// Not JSON.
|
|
73
|
+
}
|
|
74
|
+
reject(new KubernetesError(status, `${method} ${url.pathname}: ${status} ${message}`));
|
|
75
|
+
});
|
|
76
|
+
response.on('error', reject);
|
|
77
|
+
});
|
|
78
|
+
request.on('timeout', () => request.destroy(new Error(`${method} ${url.pathname}: no answer in time`)));
|
|
79
|
+
request.on('error', reject);
|
|
80
|
+
request.end(body);
|
|
81
|
+
});
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
export var KubernetesUtil;
|
|
85
|
+
(function (KubernetesUtil) {
|
|
86
|
+
/** A quantity of Kubernetes (`4Gi`, `500M`, `250m`, `123456n`) as a number of its unit (bytes, CPUs). */
|
|
87
|
+
function quantity(value) {
|
|
88
|
+
if (typeof value === 'number') {
|
|
89
|
+
return value;
|
|
90
|
+
}
|
|
91
|
+
const match = /^([0-9.]+)([a-zA-Z]*)$/.exec(String(value !== null && value !== void 0 ? value : '').trim());
|
|
92
|
+
if (!match) {
|
|
93
|
+
return undefined;
|
|
94
|
+
}
|
|
95
|
+
const scale = {
|
|
96
|
+
'': 1,
|
|
97
|
+
n: 1e-9,
|
|
98
|
+
u: 1e-6,
|
|
99
|
+
m: 1e-3,
|
|
100
|
+
k: 1e3,
|
|
101
|
+
K: 1e3,
|
|
102
|
+
M: 1e6,
|
|
103
|
+
G: 1e9,
|
|
104
|
+
T: 1e12,
|
|
105
|
+
Ki: 2 ** 10,
|
|
106
|
+
Mi: 2 ** 20,
|
|
107
|
+
Gi: 2 ** 30,
|
|
108
|
+
Ti: 2 ** 40,
|
|
109
|
+
};
|
|
110
|
+
const factor = scale[match[2]];
|
|
111
|
+
return factor === undefined ? undefined : Number(match[1]) * factor;
|
|
112
|
+
}
|
|
113
|
+
KubernetesUtil.quantity = quantity;
|
|
114
|
+
})(KubernetesUtil || (KubernetesUtil = {}));
|
|
115
|
+
//# sourceMappingURL=kubernetes-api.js.map
|
|
@@ -0,0 +1,198 @@
|
|
|
1
|
+
import { KubernetesApi, type KubernetesCalls } from './kubernetes-api.js';
|
|
2
|
+
import { type SandboxEndpoint, type SandboxProvider, type SandboxProviderConfig, type SandboxState, type SandboxTenant, type SandboxUsage } from './sandbox-provider.js';
|
|
3
|
+
export interface KubernetesSandboxOptions {
|
|
4
|
+
image: string;
|
|
5
|
+
imagePullPolicy?: string;
|
|
6
|
+
namespace: string;
|
|
7
|
+
/** Each sandbox at most: a quantity of memory (`4Gi`), CPUs. */
|
|
8
|
+
memory: string;
|
|
9
|
+
cpus: number;
|
|
10
|
+
/** The volume of its home: its size, and the class of storage (the cluster's default without one). */
|
|
11
|
+
storage: string;
|
|
12
|
+
storageClass?: string;
|
|
13
|
+
/** gVisor, Kata: the isolation of the cluster's choice, a RuntimeClass. */
|
|
14
|
+
runtimeClass?: string;
|
|
15
|
+
/** Names of the Sandbox and its Secret: `<prefix><tenant>`. */
|
|
16
|
+
prefix: string;
|
|
17
|
+
/** More of the environment of every sandbox. */
|
|
18
|
+
env: Record<string, string>;
|
|
19
|
+
nodeSelector?: Record<string, string>;
|
|
20
|
+
imagePullSecrets?: string[];
|
|
21
|
+
/** The domain of the cluster's services, for the address of a sandbox. */
|
|
22
|
+
clusterDomain: string;
|
|
23
|
+
}
|
|
24
|
+
/** What the API answers of a Sandbox, as far as the provider reads it. */
|
|
25
|
+
interface SandboxObject {
|
|
26
|
+
metadata: {
|
|
27
|
+
name: string;
|
|
28
|
+
uid?: string;
|
|
29
|
+
annotations?: Record<string, string>;
|
|
30
|
+
};
|
|
31
|
+
spec: {
|
|
32
|
+
operatingMode?: 'Running' | 'Suspended';
|
|
33
|
+
};
|
|
34
|
+
status?: {
|
|
35
|
+
serviceFQDN?: string;
|
|
36
|
+
conditions?: {
|
|
37
|
+
type: string;
|
|
38
|
+
status: string;
|
|
39
|
+
reason?: string;
|
|
40
|
+
message?: string;
|
|
41
|
+
}[];
|
|
42
|
+
};
|
|
43
|
+
}
|
|
44
|
+
export declare namespace KubernetesSandboxUtil {
|
|
45
|
+
/** The annotation of a Sandbox and its pod that tells the environment the gateway gave it (as `cell.ta.env` of docker). */
|
|
46
|
+
const ENV_ANNOTATION = "cell.ta/env";
|
|
47
|
+
const COMPONENT = "ta-sandbox";
|
|
48
|
+
function options(config: SandboxProviderConfig, inCluster?: () => {
|
|
49
|
+
namespace: string;
|
|
50
|
+
}): KubernetesSandboxOptions;
|
|
51
|
+
/** The API: `server` and `token` (`$NAME`: of the gateway's environment) of the configuration, else the pod's own. */
|
|
52
|
+
function api(config: SandboxProviderConfig, env?: Record<string, string | undefined>): KubernetesApi;
|
|
53
|
+
function ready(sandbox: SandboxObject | undefined): boolean;
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* `kubernetes`: a Sandbox of kubernetes-sigs/agent-sandbox per tenant (docs/design/ta-deploy.md 6): a pod of ta serve,
|
|
57
|
+
* its home in a volume of its own that stays while it is suspended, a headless Service for a stable address. Stopping
|
|
58
|
+
* suspends it (the pod goes, the volume stays); its token and the environment of the gateway are in a Secret of its
|
|
59
|
+
* own, not in the Sandbox, which more people may read.
|
|
60
|
+
*/
|
|
61
|
+
export declare class KubernetesSandbox implements SandboxProvider {
|
|
62
|
+
readonly id: string;
|
|
63
|
+
protected readonly options: KubernetesSandboxOptions;
|
|
64
|
+
readonly type = "kubernetes";
|
|
65
|
+
readonly name: string;
|
|
66
|
+
readonly gatewayUrl?: string;
|
|
67
|
+
/** A first pull of the image and a volume to bind take longer than a container. */
|
|
68
|
+
readonly readyTimeoutMs: number;
|
|
69
|
+
protected readonly api: KubernetesCalls;
|
|
70
|
+
constructor(id: string, config: SandboxProviderConfig, api?: KubernetesCalls, options?: KubernetesSandboxOptions);
|
|
71
|
+
start(tenant: SandboxTenant): Promise<SandboxEndpoint>;
|
|
72
|
+
stop(tenant: SandboxTenant): Promise<void>;
|
|
73
|
+
state(tenant: SandboxTenant): Promise<SandboxState>;
|
|
74
|
+
/** From metrics.k8s.io, when the cluster has metrics-server. */
|
|
75
|
+
usage(tenant: SandboxTenant): Promise<SandboxUsage | undefined>;
|
|
76
|
+
logs(tenant: SandboxTenant, lines: number): Promise<string>;
|
|
77
|
+
/** The Sandbox of a tenant, as the API is given it. */
|
|
78
|
+
manifest(tenant: SandboxTenant): {
|
|
79
|
+
apiVersion: string;
|
|
80
|
+
kind: string;
|
|
81
|
+
metadata: {
|
|
82
|
+
name: string;
|
|
83
|
+
labels: {
|
|
84
|
+
'app.kubernetes.io/name': string;
|
|
85
|
+
'app.kubernetes.io/component': string;
|
|
86
|
+
'cell.ta/tenant': string;
|
|
87
|
+
};
|
|
88
|
+
annotations: {
|
|
89
|
+
"cell.ta/env": string;
|
|
90
|
+
'cell.ta/account': string;
|
|
91
|
+
};
|
|
92
|
+
};
|
|
93
|
+
spec: {
|
|
94
|
+
operatingMode: string;
|
|
95
|
+
service: boolean;
|
|
96
|
+
failedPodPolicy: string;
|
|
97
|
+
podTemplate: {
|
|
98
|
+
metadata: {
|
|
99
|
+
labels: {
|
|
100
|
+
'app.kubernetes.io/name': string;
|
|
101
|
+
'app.kubernetes.io/component': string;
|
|
102
|
+
'cell.ta/tenant': string;
|
|
103
|
+
};
|
|
104
|
+
annotations: {
|
|
105
|
+
"cell.ta/env": string;
|
|
106
|
+
};
|
|
107
|
+
};
|
|
108
|
+
spec: {
|
|
109
|
+
automountServiceAccountToken: boolean;
|
|
110
|
+
enableServiceLinks: boolean;
|
|
111
|
+
hostname: string;
|
|
112
|
+
securityContext: {
|
|
113
|
+
runAsUser: number;
|
|
114
|
+
runAsGroup: number;
|
|
115
|
+
fsGroup: number;
|
|
116
|
+
seccompProfile: {
|
|
117
|
+
type: string;
|
|
118
|
+
};
|
|
119
|
+
};
|
|
120
|
+
runtimeClassName?: string | undefined;
|
|
121
|
+
nodeSelector?: Record<string, string> | undefined;
|
|
122
|
+
imagePullSecrets?: {
|
|
123
|
+
name: string;
|
|
124
|
+
}[] | undefined;
|
|
125
|
+
containers: {
|
|
126
|
+
name: string;
|
|
127
|
+
image: string;
|
|
128
|
+
imagePullPolicy?: string | undefined;
|
|
129
|
+
workingDir: string;
|
|
130
|
+
command: string[];
|
|
131
|
+
envFrom: {
|
|
132
|
+
secretRef: {
|
|
133
|
+
name: string;
|
|
134
|
+
};
|
|
135
|
+
}[];
|
|
136
|
+
ports: {
|
|
137
|
+
name: string;
|
|
138
|
+
containerPort: number;
|
|
139
|
+
}[];
|
|
140
|
+
resources: {
|
|
141
|
+
limits: {
|
|
142
|
+
memory: string;
|
|
143
|
+
cpu: string;
|
|
144
|
+
};
|
|
145
|
+
requests: {
|
|
146
|
+
memory: string;
|
|
147
|
+
cpu: string;
|
|
148
|
+
};
|
|
149
|
+
};
|
|
150
|
+
securityContext: {
|
|
151
|
+
capabilities: {
|
|
152
|
+
drop: string[];
|
|
153
|
+
};
|
|
154
|
+
};
|
|
155
|
+
readinessProbe: {
|
|
156
|
+
httpGet: {
|
|
157
|
+
path: string;
|
|
158
|
+
port: number;
|
|
159
|
+
};
|
|
160
|
+
periodSeconds: number;
|
|
161
|
+
failureThreshold: number;
|
|
162
|
+
};
|
|
163
|
+
volumeMounts: {
|
|
164
|
+
name: string;
|
|
165
|
+
mountPath: string;
|
|
166
|
+
}[];
|
|
167
|
+
}[];
|
|
168
|
+
};
|
|
169
|
+
};
|
|
170
|
+
volumeClaimTemplates: {
|
|
171
|
+
metadata: {
|
|
172
|
+
name: string;
|
|
173
|
+
labels: {
|
|
174
|
+
'app.kubernetes.io/name': string;
|
|
175
|
+
'app.kubernetes.io/component': string;
|
|
176
|
+
'cell.ta/tenant': string;
|
|
177
|
+
};
|
|
178
|
+
};
|
|
179
|
+
spec: {
|
|
180
|
+
accessModes: string[];
|
|
181
|
+
resources: {
|
|
182
|
+
requests: {
|
|
183
|
+
storage: string;
|
|
184
|
+
};
|
|
185
|
+
};
|
|
186
|
+
storageClassName?: string | undefined;
|
|
187
|
+
};
|
|
188
|
+
}[];
|
|
189
|
+
};
|
|
190
|
+
};
|
|
191
|
+
/** Its token and the environment of the gateway, owned by its Sandbox, which takes it along when it goes. */
|
|
192
|
+
protected putSecret(tenant: SandboxTenant, sandbox: SandboxObject): Promise<void>;
|
|
193
|
+
protected deletePod(name: string): Promise<void>;
|
|
194
|
+
protected read(name: string): Promise<SandboxObject | undefined>;
|
|
195
|
+
protected path(name?: string): string;
|
|
196
|
+
protected resourceName(tenant: SandboxTenant): string;
|
|
197
|
+
}
|
|
198
|
+
export {};
|
|
@@ -0,0 +1,279 @@
|
|
|
1
|
+
import { readFileSync } from 'node:fs';
|
|
2
|
+
import { DockerSandboxUtil } from './docker-sandbox.js';
|
|
3
|
+
import { KubernetesApi, KubernetesError, KubernetesUtil } from './kubernetes-api.js';
|
|
4
|
+
import { SandboxConfigError, SandboxProviders, } from './sandbox-provider.js';
|
|
5
|
+
/** The resources of kubernetes-sigs/agent-sandbox the provider makes. */
|
|
6
|
+
const GROUP = '/apis/agents.x-k8s.io/v1beta1';
|
|
7
|
+
/** The port of ta serve in the image (its Dockerfile). */
|
|
8
|
+
const PORT = 4100;
|
|
9
|
+
export var KubernetesSandboxUtil;
|
|
10
|
+
(function (KubernetesSandboxUtil) {
|
|
11
|
+
/** The annotation of a Sandbox and its pod that tells the environment the gateway gave it (as `cell.ta.env` of docker). */
|
|
12
|
+
KubernetesSandboxUtil.ENV_ANNOTATION = 'cell.ta/env';
|
|
13
|
+
KubernetesSandboxUtil.COMPONENT = 'ta-sandbox';
|
|
14
|
+
function options(config, inCluster) {
|
|
15
|
+
var _a, _b, _c, _d, _e;
|
|
16
|
+
const text = (key, fallback) => SandboxProviders.string(config, key, fallback);
|
|
17
|
+
const cpus = (_a = config.cpus) !== null && _a !== void 0 ? _a : 2;
|
|
18
|
+
if (typeof cpus !== 'number' || cpus <= 0) {
|
|
19
|
+
throw new SandboxConfigError('"cpus" of a provider of the type kubernetes is a number above 0.');
|
|
20
|
+
}
|
|
21
|
+
const memory = String((_b = config.memory) !== null && _b !== void 0 ? _b : '4Gi');
|
|
22
|
+
const storage = String((_c = config.storage) !== null && _c !== void 0 ? _c : '10Gi');
|
|
23
|
+
for (const [key, value] of [
|
|
24
|
+
['memory', memory],
|
|
25
|
+
['storage', storage],
|
|
26
|
+
]) {
|
|
27
|
+
if (!KubernetesUtil.quantity(value)) {
|
|
28
|
+
throw new SandboxConfigError(`"${key}" of a provider of the type kubernetes is a quantity such as 4Gi.`);
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
const strings = (key) => {
|
|
32
|
+
const value = config[key];
|
|
33
|
+
if (value !== undefined && (!Array.isArray(value) || value.some(item => typeof item !== 'string'))) {
|
|
34
|
+
throw new SandboxConfigError(`"${key}" of a provider of the type kubernetes is a list of strings.`);
|
|
35
|
+
}
|
|
36
|
+
return value;
|
|
37
|
+
};
|
|
38
|
+
const selector = config.nodeSelector;
|
|
39
|
+
if (selector !== undefined &&
|
|
40
|
+
(typeof selector !== 'object' || Array.isArray(selector) || Object.values(selector).some(item => typeof item !== 'string'))) {
|
|
41
|
+
throw new SandboxConfigError('"nodeSelector" of a provider of the type kubernetes is an object of strings.');
|
|
42
|
+
}
|
|
43
|
+
const prefix = text('prefix', 'ta-');
|
|
44
|
+
if (!/^[a-z][a-z0-9-]{0,20}$/.test(prefix)) {
|
|
45
|
+
throw new SandboxConfigError('"prefix" of a provider of the type kubernetes starts with a letter: lower-case letters, digits and -.');
|
|
46
|
+
}
|
|
47
|
+
return {
|
|
48
|
+
image: text('image', 'ta:latest'),
|
|
49
|
+
imagePullPolicy: text('imagePullPolicy'),
|
|
50
|
+
namespace: (_e = (_d = text('namespace')) !== null && _d !== void 0 ? _d : inCluster === null || inCluster === void 0 ? void 0 : inCluster().namespace) !== null && _e !== void 0 ? _e : 'default',
|
|
51
|
+
memory,
|
|
52
|
+
cpus,
|
|
53
|
+
storage,
|
|
54
|
+
storageClass: text('storageClass'),
|
|
55
|
+
runtimeClass: text('runtimeClass'),
|
|
56
|
+
prefix,
|
|
57
|
+
env: SandboxProviders.env(config),
|
|
58
|
+
nodeSelector: selector,
|
|
59
|
+
imagePullSecrets: strings('imagePullSecrets'),
|
|
60
|
+
clusterDomain: text('clusterDomain', 'cluster.local'),
|
|
61
|
+
};
|
|
62
|
+
}
|
|
63
|
+
KubernetesSandboxUtil.options = options;
|
|
64
|
+
/** The API: `server` and `token` (`$NAME`: of the gateway's environment) of the configuration, else the pod's own. */
|
|
65
|
+
function api(config, env = process.env) {
|
|
66
|
+
const server = SandboxProviders.string(config, 'server');
|
|
67
|
+
if (!server) {
|
|
68
|
+
return new KubernetesApi(KubernetesApi.inCluster(env));
|
|
69
|
+
}
|
|
70
|
+
const given = SandboxProviders.string(config, 'token');
|
|
71
|
+
const token = (given === null || given === void 0 ? void 0 : given.startsWith('$')) ? env[given.slice(1).replace(/^\{|\}$/g, '')] : given;
|
|
72
|
+
const caFile = SandboxProviders.string(config, 'caFile');
|
|
73
|
+
return new KubernetesApi({ server, token, ...(caFile ? { ca: readFileSync(caFile, 'utf8') } : {}) });
|
|
74
|
+
}
|
|
75
|
+
KubernetesSandboxUtil.api = api;
|
|
76
|
+
function ready(sandbox) {
|
|
77
|
+
var _a, _b;
|
|
78
|
+
var _c;
|
|
79
|
+
return (_c = (_b = (_a = sandbox === null || sandbox === void 0 ? void 0 : sandbox.status) === null || _a === void 0 ? void 0 : _a.conditions) === null || _b === void 0 ? void 0 : _b.some(condition => condition.type === 'Ready' && condition.status === 'True')) !== null && _c !== void 0 ? _c : false;
|
|
80
|
+
}
|
|
81
|
+
KubernetesSandboxUtil.ready = ready;
|
|
82
|
+
})(KubernetesSandboxUtil || (KubernetesSandboxUtil = {}));
|
|
83
|
+
/**
|
|
84
|
+
* `kubernetes`: a Sandbox of kubernetes-sigs/agent-sandbox per tenant (docs/design/ta-deploy.md 6): a pod of ta serve,
|
|
85
|
+
* its home in a volume of its own that stays while it is suspended, a headless Service for a stable address. Stopping
|
|
86
|
+
* suspends it (the pod goes, the volume stays); its token and the environment of the gateway are in a Secret of its
|
|
87
|
+
* own, not in the Sandbox, which more people may read.
|
|
88
|
+
*/
|
|
89
|
+
export class KubernetesSandbox {
|
|
90
|
+
constructor(id, config, api, options = KubernetesSandboxUtil.options(config, () => KubernetesApi.inCluster())) {
|
|
91
|
+
this.id = id;
|
|
92
|
+
this.options = options;
|
|
93
|
+
this.type = 'kubernetes';
|
|
94
|
+
/** A first pull of the image and a volume to bind take longer than a container. */
|
|
95
|
+
this.readyTimeoutMs = 5 * 60 * 1000;
|
|
96
|
+
this.name = SandboxProviders.string(config, 'name', 'Kubernetes');
|
|
97
|
+
this.gatewayUrl = SandboxProviders.string(config, 'gatewayUrl');
|
|
98
|
+
this.api = api !== null && api !== void 0 ? api : KubernetesSandboxUtil.api(config);
|
|
99
|
+
}
|
|
100
|
+
async start(tenant) {
|
|
101
|
+
var _a;
|
|
102
|
+
const name = this.resourceName(tenant);
|
|
103
|
+
const hash = DockerSandboxUtil.envHash(tenant.env);
|
|
104
|
+
let sandbox = await this.read(name);
|
|
105
|
+
if (!sandbox) {
|
|
106
|
+
sandbox = await this.api.call('POST', this.path(), this.manifest(tenant));
|
|
107
|
+
await this.putSecret(tenant, sandbox);
|
|
108
|
+
}
|
|
109
|
+
else {
|
|
110
|
+
await this.putSecret(tenant, sandbox);
|
|
111
|
+
const changed = ((_a = sandbox.metadata.annotations) === null || _a === void 0 ? void 0 : _a[KubernetesSandboxUtil.ENV_ANNOTATION]) !== hash;
|
|
112
|
+
if (changed || sandbox.spec.operatingMode === 'Suspended') {
|
|
113
|
+
// Its pod is made from the template when it starts: the one with another environment goes, the volume stays.
|
|
114
|
+
const { metadata, spec } = this.manifest(tenant);
|
|
115
|
+
await this.api.call('PATCH', this.path(name), { metadata: { annotations: metadata.annotations }, spec }, 'application/merge-patch+json');
|
|
116
|
+
if (changed && sandbox.spec.operatingMode !== 'Suspended') {
|
|
117
|
+
await this.deletePod(name);
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
return { url: `http://${name}.${this.options.namespace}.svc.${this.options.clusterDomain}:${PORT}`, token: tenant.token };
|
|
122
|
+
}
|
|
123
|
+
async stop(tenant) {
|
|
124
|
+
const name = this.resourceName(tenant);
|
|
125
|
+
if (await this.read(name)) {
|
|
126
|
+
await this.api.call('PATCH', this.path(name), { spec: { operatingMode: 'Suspended' } }, 'application/merge-patch+json');
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
async state(tenant) {
|
|
130
|
+
const sandbox = await this.read(this.resourceName(tenant));
|
|
131
|
+
return !sandbox ? 'missing' : sandbox.spec.operatingMode === 'Suspended' ? 'stopped' : 'running';
|
|
132
|
+
}
|
|
133
|
+
/** From metrics.k8s.io, when the cluster has metrics-server. */
|
|
134
|
+
async usage(tenant) {
|
|
135
|
+
var _a, _b;
|
|
136
|
+
const name = this.resourceName(tenant);
|
|
137
|
+
const metrics = await this.api
|
|
138
|
+
.call('GET', `/apis/metrics.k8s.io/v1beta1/namespaces/${this.options.namespace}/pods/${name}`)
|
|
139
|
+
.catch(() => undefined);
|
|
140
|
+
const usage = (_b = (_a = metrics === null || metrics === void 0 ? void 0 : metrics.containers) === null || _a === void 0 ? void 0 : _a.find(container => container.name === 'ta')) === null || _b === void 0 ? void 0 : _b.usage;
|
|
141
|
+
if (!usage) {
|
|
142
|
+
return undefined;
|
|
143
|
+
}
|
|
144
|
+
const cpu = KubernetesUtil.quantity(usage.cpu);
|
|
145
|
+
return {
|
|
146
|
+
cpu: cpu === undefined ? undefined : Math.round(cpu * 1000) / 10,
|
|
147
|
+
memory: KubernetesUtil.quantity(usage.memory),
|
|
148
|
+
memoryLimit: KubernetesUtil.quantity(this.options.memory),
|
|
149
|
+
};
|
|
150
|
+
}
|
|
151
|
+
logs(tenant, lines) {
|
|
152
|
+
const name = this.resourceName(tenant);
|
|
153
|
+
return this.api
|
|
154
|
+
.text(`/api/v1/namespaces/${this.options.namespace}/pods/${name}/log?container=ta&tailLines=${Math.max(1, Math.floor(lines))}`)
|
|
155
|
+
.catch(error => (error instanceof KubernetesError && error.status === 404 ? '' : Promise.reject(error)));
|
|
156
|
+
}
|
|
157
|
+
/** The Sandbox of a tenant, as the API is given it. */
|
|
158
|
+
manifest(tenant) {
|
|
159
|
+
var _a;
|
|
160
|
+
const name = this.resourceName(tenant);
|
|
161
|
+
const hash = DockerSandboxUtil.envHash(tenant.env);
|
|
162
|
+
const labels = { 'app.kubernetes.io/name': 'ta', 'app.kubernetes.io/component': KubernetesSandboxUtil.COMPONENT, 'cell.ta/tenant': tenant.id };
|
|
163
|
+
const options = this.options;
|
|
164
|
+
return {
|
|
165
|
+
apiVersion: 'agents.x-k8s.io/v1beta1',
|
|
166
|
+
kind: 'Sandbox',
|
|
167
|
+
metadata: { name, labels, annotations: { [KubernetesSandboxUtil.ENV_ANNOTATION]: hash, 'cell.ta/account': tenant.account } },
|
|
168
|
+
spec: {
|
|
169
|
+
operatingMode: 'Running',
|
|
170
|
+
service: true,
|
|
171
|
+
failedPodPolicy: 'Recreate',
|
|
172
|
+
podTemplate: {
|
|
173
|
+
metadata: { labels, annotations: { [KubernetesSandboxUtil.ENV_ANNOTATION]: hash } },
|
|
174
|
+
spec: {
|
|
175
|
+
// Nothing of the cluster's API in a sandbox, nor the addresses of its services.
|
|
176
|
+
automountServiceAccountToken: false,
|
|
177
|
+
enableServiceLinks: false,
|
|
178
|
+
// What the Ta of the tenant tells its clients its machine is.
|
|
179
|
+
hostname: DockerSandboxUtil.hostname(tenant.account),
|
|
180
|
+
securityContext: { runAsUser: 1000, runAsGroup: 1000, fsGroup: 1000, seccompProfile: { type: 'RuntimeDefault' } },
|
|
181
|
+
...(options.runtimeClass ? { runtimeClassName: options.runtimeClass } : {}),
|
|
182
|
+
...(options.nodeSelector ? { nodeSelector: options.nodeSelector } : {}),
|
|
183
|
+
...(((_a = options.imagePullSecrets) === null || _a === void 0 ? void 0 : _a.length) ? { imagePullSecrets: options.imagePullSecrets.map(secret => ({ name: secret })) } : {}),
|
|
184
|
+
containers: [
|
|
185
|
+
{
|
|
186
|
+
name: 'ta',
|
|
187
|
+
image: options.image,
|
|
188
|
+
...(options.imagePullPolicy ? { imagePullPolicy: options.imagePullPolicy } : {}),
|
|
189
|
+
// A new volume is empty: the workspace the image has is made in it, by its user (the
|
|
190
|
+
// runtime would make the image's WORKDIR in the volume as root).
|
|
191
|
+
workingDir: '/home/ta',
|
|
192
|
+
command: [
|
|
193
|
+
'tini',
|
|
194
|
+
'--',
|
|
195
|
+
'sh',
|
|
196
|
+
'-c',
|
|
197
|
+
`mkdir -p /home/ta/workspace && cd /home/ta/workspace && exec ta serve --host 0.0.0.0 --port ${PORT}`,
|
|
198
|
+
],
|
|
199
|
+
envFrom: [{ secretRef: { name } }],
|
|
200
|
+
ports: [{ name: 'ta', containerPort: PORT }],
|
|
201
|
+
resources: {
|
|
202
|
+
limits: { memory: options.memory, cpu: String(options.cpus) },
|
|
203
|
+
requests: { memory: '256Mi', cpu: '100m' },
|
|
204
|
+
},
|
|
205
|
+
// A tenant is root in its sandbox (sudo), as in docker: without raw sockets it cannot forge packets.
|
|
206
|
+
securityContext: { capabilities: { drop: ['NET_RAW'] } },
|
|
207
|
+
readinessProbe: { httpGet: { path: '/', port: PORT }, periodSeconds: 5, failureThreshold: 3 },
|
|
208
|
+
volumeMounts: [{ name: 'home', mountPath: '/home/ta' }],
|
|
209
|
+
},
|
|
210
|
+
],
|
|
211
|
+
},
|
|
212
|
+
},
|
|
213
|
+
volumeClaimTemplates: [
|
|
214
|
+
{
|
|
215
|
+
metadata: { name: 'home', labels },
|
|
216
|
+
spec: {
|
|
217
|
+
accessModes: ['ReadWriteOnce'],
|
|
218
|
+
resources: { requests: { storage: options.storage } },
|
|
219
|
+
...(options.storageClass ? { storageClassName: options.storageClass } : {}),
|
|
220
|
+
},
|
|
221
|
+
},
|
|
222
|
+
],
|
|
223
|
+
},
|
|
224
|
+
};
|
|
225
|
+
}
|
|
226
|
+
/** Its token and the environment of the gateway, owned by its Sandbox, which takes it along when it goes. */
|
|
227
|
+
async putSecret(tenant, sandbox) {
|
|
228
|
+
const name = this.resourceName(tenant);
|
|
229
|
+
const env = { ...this.options.env, ...tenant.env, TA_SERVE_TOKEN: tenant.token };
|
|
230
|
+
const secret = {
|
|
231
|
+
apiVersion: 'v1',
|
|
232
|
+
kind: 'Secret',
|
|
233
|
+
metadata: {
|
|
234
|
+
name,
|
|
235
|
+
labels: { 'app.kubernetes.io/name': 'ta', 'app.kubernetes.io/component': KubernetesSandboxUtil.COMPONENT, 'cell.ta/tenant': tenant.id },
|
|
236
|
+
...(sandbox.metadata.uid
|
|
237
|
+
? { ownerReferences: [{ apiVersion: 'agents.x-k8s.io/v1beta1', kind: 'Sandbox', name, uid: sandbox.metadata.uid }] }
|
|
238
|
+
: {}),
|
|
239
|
+
},
|
|
240
|
+
type: 'Opaque',
|
|
241
|
+
stringData: env,
|
|
242
|
+
};
|
|
243
|
+
const path = `/api/v1/namespaces/${this.options.namespace}/secrets`;
|
|
244
|
+
try {
|
|
245
|
+
await this.api.call('PUT', `${path}/${name}`, secret);
|
|
246
|
+
}
|
|
247
|
+
catch (error) {
|
|
248
|
+
if (!(error instanceof KubernetesError && error.status === 404)) {
|
|
249
|
+
throw error;
|
|
250
|
+
}
|
|
251
|
+
await this.api.call('POST', path, secret);
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
async deletePod(name) {
|
|
255
|
+
await this.api.call('DELETE', `/api/v1/namespaces/${this.options.namespace}/pods/${name}`).catch(error => {
|
|
256
|
+
if (!(error instanceof KubernetesError && error.status === 404)) {
|
|
257
|
+
throw error;
|
|
258
|
+
}
|
|
259
|
+
});
|
|
260
|
+
}
|
|
261
|
+
async read(name) {
|
|
262
|
+
try {
|
|
263
|
+
return await this.api.call('GET', this.path(name));
|
|
264
|
+
}
|
|
265
|
+
catch (error) {
|
|
266
|
+
if (error instanceof KubernetesError && error.status === 404) {
|
|
267
|
+
return undefined;
|
|
268
|
+
}
|
|
269
|
+
throw error;
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
path(name) {
|
|
273
|
+
return `${GROUP}/namespaces/${this.options.namespace}/sandboxes${name ? `/${name}` : ''}`;
|
|
274
|
+
}
|
|
275
|
+
resourceName(tenant) {
|
|
276
|
+
return `${this.options.prefix}${tenant.id}`;
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
//# sourceMappingURL=kubernetes-sandbox.js.map
|
|
@@ -19,6 +19,7 @@ export declare class LocalSandbox implements SandboxProvider {
|
|
|
19
19
|
protected readonly context: SandboxContext;
|
|
20
20
|
readonly type = "local";
|
|
21
21
|
readonly name: string;
|
|
22
|
+
readonly gatewayUrl?: string;
|
|
22
23
|
protected readonly running: Map<string, {
|
|
23
24
|
child: ChildProcess;
|
|
24
25
|
url: string;
|
|
@@ -42,6 +42,7 @@ export class LocalSandbox {
|
|
|
42
42
|
/** Kept past a stop, so that the console shows why one ended. */
|
|
43
43
|
this.output = new Map();
|
|
44
44
|
this.name = SandboxProviders.string(config, 'name', 'Local');
|
|
45
|
+
this.gatewayUrl = SandboxProviders.string(config, 'gatewayUrl');
|
|
45
46
|
}
|
|
46
47
|
async start(tenant) {
|
|
47
48
|
var _a, _b;
|
|
@@ -58,7 +59,7 @@ export class LocalSandbox {
|
|
|
58
59
|
const [command, ...args] = this.context.taCommand;
|
|
59
60
|
const child = spawn(command, [...args, 'serve', '--port', String(port)], {
|
|
60
61
|
cwd,
|
|
61
|
-
env: { ...process.env, TA_CODING_AGENT_DIR: agentDir, TA_SERVE_TOKEN: tenant.token, CELL_SERVER__HOST: '127.0.0.1' },
|
|
62
|
+
env: { ...process.env, ...tenant.env, TA_CODING_AGENT_DIR: agentDir, TA_SERVE_TOKEN: tenant.token, CELL_SERVER__HOST: '127.0.0.1' },
|
|
62
63
|
stdio: ['ignore', 'pipe', 'pipe'],
|
|
63
64
|
});
|
|
64
65
|
const tail = new LineTail();
|