-
Notifications
You must be signed in to change notification settings - Fork 916
/
run.ts
346 lines (310 loc) · 9.53 KB
/
run.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
import { Client } from "../apiv2";
import { FirebaseError } from "../error";
import { runOrigin } from "../api";
import * as proto from "./proto";
import * as iam from "./iam";
import { backoff } from "../throttler/throttler";
import { logger } from "../logger";
const API_VERSION = "v1";
const client = new Client({
urlPrefix: runOrigin(),
auth: true,
apiVersion: API_VERSION,
});
export const LOCATION_LABEL = "cloud.googleapis.com/location";
// Unfortuantely, Omit<> doesn't allow supbath, so it's hard to have a reasonable API that
// declares all mandatory fields as mandatory and then accepts an Omit<> for update types.
export interface ObjectMetadata {
name: string;
// Must be the project ID or project number
namespace: string;
labels?: Record<string, string>;
// Not supported in Cloud Run:
generate_name?: string;
deletionGracePeriodSeconds?: number;
finalizers?: string[];
clusterName?: string;
// Output only:
selfLink?: string;
uid?: string;
resourceVersion?: string;
generation?: number;
createTime?: string;
// Onput only; not supported by Cloud Run
ownerReference?: unknown;
deleteTime?: string;
}
export interface Addressable {
url: string;
}
export interface Condition {
type: string;
status: string;
reason: string;
message: string;
lastTransitionTime: string;
severity: "Error" | "Warning" | "Info";
}
export interface ServiceSpec {
template: RevisionTemplate;
traffic: TrafficTarget[];
}
// All fields in ServiceStatus are output only so we will assume
// that an input Service will just Omit<"status">
export interface ServiceStatus {
observedGeneration: number;
conditions: Condition[];
latestReadyRevisionName: string;
latestCreatedRevisionName: string;
traffic: TrafficTarget[];
url: string;
address: Addressable;
}
export interface Service {
apiVersion: "serving.knative.dev/v1";
kind: "Service";
metadata: ObjectMetadata;
spec: ServiceSpec;
status?: ServiceStatus;
}
export interface Container {
image: string;
ports: Array<{ name: string; containerPort: number }>;
env: Record<string, string>;
resources: {
limits: {
cpu: string;
memory: string;
};
};
}
export interface RevisionSpec {
containerConcurrency?: number | null;
containers: Container[];
}
export interface RevisionTemplate {
metadata: Partial<ObjectMetadata>;
spec: RevisionSpec;
}
export interface TrafficTarget {
configurationName?: string;
// RevisionName can be used to target a specific revision,
// or customers can set latestRevision = true
revisionName?: string;
latestRevision?: boolean;
percent?: number; // optional when tagged
tag?: string;
// Output only:
// Displayed when TrafficTarget is part of a status and forbidden
// when TrafficTarget is part of spec.
url?: string;
}
export interface IamPolicy {
version?: number;
bindings?: iam.Binding[];
auditConfigs?: Record<string, unknown>[];
etag?: string;
}
export interface GCPIds {
serviceId: string;
region: string;
projectNumber: string;
}
/**
* Gets the standard project/location/id tuple from the K8S style resource.
*/
export function gcpIds(service: Pick<Service, "metadata">): GCPIds {
return {
serviceId: service.metadata.name,
projectNumber: service.metadata.namespace,
region: service.metadata.labels?.[LOCATION_LABEL] || "unknown-region",
};
}
/**
* Gets a service with a given name.
*/
export async function getService(name: string): Promise<Service> {
try {
const response = await client.get<Service>(name);
return response.body;
} catch (err: any) {
throw new FirebaseError(`Failed to fetch Run service ${name}`, {
original: err,
status: err?.context?.response?.statusCode,
});
}
}
/**
* Update a service and wait for changes to replicate.
*/
export async function updateService(name: string, service: Service): Promise<Service> {
delete service.status;
service = await exports.replaceService(name, service);
// Now we need to wait for reconciliation or we might delete the docker
// image while the service is still rolling out a new revision.
let retry = 0;
while (!exports.serviceIsResolved(service)) {
await backoff(retry, 2, 30);
retry = retry + 1;
service = await exports.getService(name);
}
return service;
}
/**
* Returns whether a service is resolved (all transitions have completed).
*/
export function serviceIsResolved(service: Service): boolean {
if (service.status?.observedGeneration !== service.metadata.generation) {
logger.debug(
`Service ${service.metadata.name} is not resolved because` +
`observed generation ${service.status?.observedGeneration} does not ` +
`match spec generation ${service.metadata.generation}`,
);
return false;
}
const readyCondition = service.status?.conditions?.find((condition) => {
return condition.type === "Ready";
});
if (readyCondition?.status === "Unknown") {
logger.debug(
`Waiting for service ${service.metadata.name} to be ready. ` +
`Status is ${JSON.stringify(service.status?.conditions)}`,
);
return false;
} else if (readyCondition?.status === "True") {
return true;
}
logger.debug(
`Service ${service.metadata.name} has unexpected ready status ${JSON.stringify(
readyCondition,
)}. It may have failed rollout.`,
);
throw new FirebaseError(
`Unexpected Status ${readyCondition?.status} for service ${service.metadata.name}`,
);
}
/**
* Replaces a service spec. Prefer updateService to block on replication.
*/
export async function replaceService(name: string, service: Service): Promise<Service> {
try {
const response = await client.put<Service, Service>(name, service);
return response.body;
} catch (err: any) {
throw new FirebaseError(`Failed to replace Run service ${name}`, {
original: err,
status: err?.context?.response?.statusCode,
});
}
}
/**
* Sets the IAM policy of a Service
* @param name Fully qualified name of the Service.
* @param policy The [policy](https://cloud.google.com/run/docs/reference/rest/v1/projects.locations.services/setIamPolicy) to set.
*/
export async function setIamPolicy(
name: string,
policy: iam.Policy,
httpClient: Client = client,
): Promise<void> {
// Cloud Run has an atypical REST binding for SetIamPolicy. Instead of making the body a policy and
// the update mask a query parameter (e.g. Cloud Functions v1) the request body is the literal
// proto.
interface Request {
policy: iam.Policy;
updateMask: string;
}
try {
await httpClient.post<Request, IamPolicy>(`${name}:setIamPolicy`, {
policy,
updateMask: proto.fieldMasks(policy).join(","),
});
} catch (err: any) {
throw new FirebaseError(`Failed to set the IAM Policy on the Service ${name}`, {
original: err,
status: err?.context?.response?.statusCode,
});
}
}
/**
* Gets IAM policy for a service.
*/
export async function getIamPolicy(
serviceName: string,
httpClient: Client = client,
): Promise<IamPolicy> {
try {
const response = await httpClient.get<IamPolicy>(`${serviceName}:getIamPolicy`);
return response.body;
} catch (err: any) {
throw new FirebaseError(`Failed to get the IAM Policy on the Service ${serviceName}`, {
original: err,
});
}
}
/**
* Gets the current IAM policy for the run service and overrides the invoker role with the supplied invoker members
* @param projectId id of the project
* @param serviceName cloud run service
* @param invoker an array of invoker strings
* @throws {@link FirebaseError} on an empty invoker, when the IAM Polciy fails to be grabbed or set
*/
export async function setInvokerCreate(
projectId: string,
serviceName: string,
invoker: string[],
httpClient: Client = client, // for unit testing
) {
if (invoker.length === 0) {
throw new FirebaseError("Invoker cannot be an empty array");
}
const invokerMembers = proto.getInvokerMembers(invoker, projectId);
const invokerRole = "roles/run.invoker";
const bindings = [{ role: invokerRole, members: invokerMembers }];
const policy: iam.Policy = {
bindings: bindings,
etag: "",
version: 3,
};
await setIamPolicy(serviceName, policy, httpClient);
}
/**
* Gets the current IAM policy for the run service and overrides the invoker role with the supplied invoker members
* @param projectId id of the project
* @param serviceName cloud run service
* @param invoker an array of invoker strings
* @throws {@link FirebaseError} on an empty invoker, when the IAM Polciy fails to be grabbed or set
*/
export async function setInvokerUpdate(
projectId: string,
serviceName: string,
invoker: string[],
httpClient: Client = client, // for unit testing
) {
if (invoker.length === 0) {
throw new FirebaseError("Invoker cannot be an empty array");
}
const invokerMembers = proto.getInvokerMembers(invoker, projectId);
const invokerRole = "roles/run.invoker";
const currentPolicy = await getIamPolicy(serviceName, httpClient);
const currentInvokerBinding = currentPolicy.bindings?.find(
(binding) => binding.role === invokerRole,
);
if (
currentInvokerBinding &&
JSON.stringify(currentInvokerBinding.members.sort()) === JSON.stringify(invokerMembers.sort())
) {
return;
}
const bindings = (currentPolicy.bindings || []).filter((binding) => binding.role !== invokerRole);
bindings.push({
role: invokerRole,
members: invokerMembers,
});
const policy: iam.Policy = {
bindings: bindings,
etag: currentPolicy.etag || "",
version: 3,
};
await setIamPolicy(serviceName, policy, httpClient);
}