-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathcloudrun.bzl
More file actions
510 lines (474 loc) · 18.4 KB
/
Copy pathcloudrun.bzl
File metadata and controls
510 lines (474 loc) · 18.4 KB
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
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
# Copyright 2026 The rules_gitops Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
load("//gitops:provider.bzl", "GitopsArtifactsInfo", "GitopsPushInfo")
load("//push_oci:push_oci.bzl", "push_oci")
load("//skylib:push_alias.bzl", "pushed_image_alias")
load("//skylib:runfile.bzl", "get_runfile_path")
load("//skylib:stamp.bzl", "stamp")
load(
"//skylib/kustomize:kustomize.bzl",
"imagePushStatements",
"kustomize",
)
def _image_pushes(name_suffix, images, image_registry, image_repository, image_digest_tag, tags = []):
image_pushes = []
def process_image(image_label, image_alias = None):
rule_name_parts = [image_label, image_registry, image_repository]
rule_name_parts = [p for p in rule_name_parts if p]
rule_name = "_".join(rule_name_parts)
rule_name = rule_name.replace("/", "_").replace(":", "_").replace("@", "_").replace(".", "_")
rule_name = rule_name.strip("_")
if not native.existing_rule(rule_name + name_suffix):
push_oci(
name = rule_name + name_suffix,
image = image_label, # buildifier: disable=uninitialized
image_digest_tag = image_digest_tag,
registry = image_registry,
repository = image_repository,
tags = tags,
visibility = ["//visibility:public"],
)
if not image_alias:
return rule_name + name_suffix
if not native.existing_rule(rule_name + "_alias_" + name_suffix):
pushed_image_alias(
name = rule_name + "_alias_" + name_suffix,
alias = image_alias,
pushed_image = rule_name + name_suffix,
tags = tags,
visibility = ["//visibility:public"],
)
return rule_name + "_alias_" + name_suffix
if type(images) == "dict":
for image_alias in images:
image = images[image_alias]
push = process_image(image, image_alias)
image_pushes.append(push)
else:
for image in images:
push = process_image(image)
image_pushes.append(push)
return image_pushes
def _gcloud_run_impl(ctx):
files = [] + ctx.files.srcs
yq_bin = ctx.toolchains["@yq.bzl//yq/toolchain:type"].yqinfo.bin
files.append(yq_bin)
statements = ""
transitive = None
transitive_runfiles = []
project = ctx.attr.project
if "{" in ctx.attr.project:
project = stamp(ctx, project, files, ctx.label.name + ".project-name", True)
region = ctx.attr.region
if "{" in ctx.attr.region:
region = stamp(ctx, region, files, ctx.label.name + ".region-name", True)
command = ctx.attr.command
push = ctx.attr.push
files += [ctx.executable._template_engine, ctx.file._info_file]
if push:
pushes = [obj[GitopsArtifactsInfo].image_pushes for obj in ctx.attr.srcs]
trans_img_pushes = depset(transitive = pushes).to_list()
trans_img_pushes = [push for push in trans_img_pushes if push.files_to_run.executable]
statements += "\n".join([
"# {}\n".format(exe[GitopsPushInfo].image_label) +
"echo pushing {}".format(exe[GitopsPushInfo].repository if GitopsPushInfo in exe else "")
for exe in trans_img_pushes
]) + "\n"
statements += "\n".join([
"async \"%s\"" % get_runfile_path(ctx, exe.files_to_run.executable)
for exe in trans_img_pushes
]) + "\nwaitpids\n"
files += [obj.files_to_run.executable for obj in trans_img_pushes]
transitive = depset(transitive = [obj.default_runfiles.files for obj in trans_img_pushes])
transitive_runfiles += [exe[DefaultInfo].default_runfiles for exe in trans_img_pushes]
for inattr in ctx.attr.srcs:
for infile in inattr.files.to_list():
if command == "replace":
statements += "{template_engine} --template={infile} --variable=PROJECT=\"$PROJECT\" --variable=REGION=\"$REGION\" --stamp_info_file={info_file} | gcloud run services replace - --project=\"$PROJECT\" --region=\"$REGION\"\n".format(
infile = get_runfile_path(ctx, infile),
template_engine = get_runfile_path(ctx, ctx.executable._template_engine),
info_file = get_runfile_path(ctx, ctx.file._info_file),
)
elif command == "delete":
statements += ("SERVICES=$({yq_bin_path} 'select(.kind == \"Service\") | .metadata.name' {infile})\n" +
"if [ -z \"$SERVICES\" ] || [ \"$SERVICES\" = \"null\" ]; then\n" +
" echo \"Error: Failed to extract any service names from manifest {infile}\" >&2\n" +
" exit 1\n" +
"fi\n" +
"for SERVICE in $SERVICES; do\n" +
" gcloud run services delete \"$SERVICE\" --project=\"$PROJECT\" --region=\"$REGION\"\n" +
"done\n").format(
yq_bin_path = get_runfile_path(ctx, yq_bin),
infile = get_runfile_path(ctx, infile),
)
else:
fail("Unsupported command: %s" % command)
ctx.actions.expand_template(
template = ctx.file._template,
substitutions = {
"%{project}": project,
"%{region}": region,
"%{statements}": statements,
},
output = ctx.outputs.executable,
)
runfiles = ctx.runfiles(files = files, transitive_files = transitive)
runfiles = runfiles.merge_all(transitive_runfiles)
return [
DefaultInfo(runfiles = runfiles),
]
gcloud_run = rule(
attrs = {
"srcs": attr.label_list(providers = (GitopsArtifactsInfo,)),
"project": attr.string(mandatory = True),
"region": attr.string(mandatory = True),
"command": attr.string(default = "replace"),
"push": attr.bool(default = True),
"_build_user_value": attr.label(
default = Label("//skylib:build_user_value.txt"),
allow_single_file = True,
),
"_info_file": attr.label(
default = Label("//skylib:more_stable_status.txt"),
allow_single_file = True,
),
"_stamper": attr.label(
default = Label("//stamper:stamper"),
cfg = "exec",
executable = True,
allow_files = True,
),
"_template": attr.label(
default = Label("//gitops:cloudrun.sh.tpl"),
allow_single_file = True,
),
"_template_engine": attr.label(
default = Label("//templating:fast_template_engine"),
executable = True,
cfg = "exec",
),
},
executable = True,
implementation = _gcloud_run_impl,
toolchains = ["@yq.bzl//yq/toolchain:type"],
)
def _remove_prefix(s, prefix):
return s[len(prefix):] if s.startswith(prefix) else s
def _remove_prefixes(s, prefixes):
for prefix in prefixes:
s = _remove_prefix(s, prefix)
return s
def _cloudrun_gitops_impl(ctx):
region = ctx.attr.region
project = ctx.attr.project
strip_prefixes = ctx.attr.strip_prefixes
files = []
push_statements, files, pushes_runfiles = imagePushStatements(ctx, ctx.attr.srcs, files)
statements = """if [ "$PERFORM_PUSH" == "1" ]; then
{}
fi
""".format(push_statements)
if "{" in region:
fail("unable to gitops region with placeholders %s" % region)
if "{" in project:
fail("unable to gitops project with placeholders %s" % project)
for inattr in ctx.attr.srcs:
for infile in inattr.files.to_list():
statements += ("echo $TARGET_DIR/{gitops_path}/{project}/{region}/{file}\n" +
"mkdir -p $TARGET_DIR/{gitops_path}/{project}/{region}\n" +
"echo '# GENERATED BY {rulename} -> {gitopsrulename}' > $TARGET_DIR/{gitops_path}/{project}/{region}/{file}\n" +
"{template_engine} --template={infile} --variable=PROJECT={project} --variable=REGION={region} --stamp_info_file={info_file} >> $TARGET_DIR/{gitops_path}/{project}/{region}/{file}\n").format(
infile = get_runfile_path(ctx, infile),
rulename = inattr.label,
gitopsrulename = ctx.label,
project = project,
gitops_path = ctx.attr.gitops_path,
region = region,
file = _remove_prefixes(infile.path.split("/")[-1], strip_prefixes),
template_engine = get_runfile_path(ctx, ctx.executable._template_engine),
info_file = get_runfile_path(ctx, ctx.file._info_file),
)
ctx.actions.expand_template(
template = ctx.file._template,
substitutions = {
"%{deployment_branch}": ctx.attr.deployment_branch,
"%{statements}": statements,
},
output = ctx.outputs.executable,
)
runfiles = files + ctx.files.srcs + [ctx.executable._template_engine, ctx.file._info_file]
transitive = depset(transitive = [obj.default_runfiles.files for obj in ctx.attr.srcs])
rf = ctx.runfiles(files = runfiles, transitive_files = transitive)
for dep_rf in pushes_runfiles:
rf = rf.merge(dep_rf)
return [
DefaultInfo(runfiles = rf),
GitopsArtifactsInfo(
image_pushes = depset(transitive = [obj[GitopsArtifactsInfo].image_pushes for obj in ctx.attr.srcs]),
deployment_branch = ctx.attr.deployment_branch,
),
]
cloudrun_gitops = rule(
attrs = {
"srcs": attr.label_list(providers = (GitopsArtifactsInfo,)),
"project": attr.string(mandatory = True),
"region": attr.string(mandatory = True),
"deployment_branch": attr.string(),
"gitops_path": attr.string(),
"release_branch_prefix": attr.string(),
"strip_prefixes": attr.string_list(),
"_info_file": attr.label(
default = Label("//skylib:more_stable_status.txt"),
allow_single_file = True,
),
"_template_engine": attr.label(
default = Label("//templating:fast_template_engine"),
executable = True,
cfg = "exec",
),
"_template": attr.label(
default = Label("//skylib:k8s_gitops.sh.tpl"),
allow_single_file = True,
),
},
executable = True,
implementation = _cloudrun_gitops_impl,
)
def _cloudrun_show_impl(ctx):
script_content = """#!/usr/bin/env bash
set -e
function guess_runfiles() {
if [ -d "${BASH_SOURCE[0]}.runfiles" ]; then
# Runfiles are adjacent to the current script.
echo "$( cd "${BASH_SOURCE[0]}.runfiles" && pwd )"
else
# The current script is within some other script's runfiles.
mydir="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
echo $mydir | sed -e 's|\\(.*\\.runfiles\\)/.*|\\1|'
fi
}
RUNFILES=${RUNFILES:-$(guess_runfiles)}
"""
outputs = []
script_template = "{template_engine} --template={infile} --variable=PROJECT={project} --variable=REGION={region} --stamp_info_file={info_file}\n"
for dep in ctx.attr.src.files.to_list():
outputs.append(script_template.format(
infile = get_runfile_path(ctx, dep),
template_engine = get_runfile_path(ctx, ctx.executable._template_engine),
project = ctx.attr.project,
region = ctx.attr.region,
info_file = get_runfile_path(ctx, ctx.file._info_file),
))
script_content += "echo '---'\n".join(outputs)
ctx.actions.write(ctx.outputs.executable, script_content, is_executable = True)
return [
DefaultInfo(runfiles = ctx.runfiles(files = [ctx.executable._template_engine, ctx.file._info_file] + ctx.files.src)),
]
cloudrun_show = rule(
implementation = _cloudrun_show_impl,
attrs = {
"src": attr.label(
doc = "Input file.",
mandatory = True,
),
"project": attr.string(
mandatory = True,
),
"region": attr.string(
mandatory = True,
),
"_info_file": attr.label(
default = Label("//skylib:more_stable_status.txt"),
allow_single_file = True,
),
"_template_engine": attr.label(
default = Label("//templating:fast_template_engine"),
executable = True,
cfg = "exec",
),
},
executable = True,
)
def cloudrun_deploy(
name,
project = None,
region = None,
manifests = None,
name_prefix = None,
name_suffix = None,
patches = None,
image_name_patches = {},
image_tag_patches = {},
substitutions = {},
configurations = [],
common_labels = {},
common_annotations = {},
openapi_path = "@rules_gitops//skylib:run_schema.json",
deps = [],
deps_aliases = {},
images = [],
image_digest_tag = False,
image_registry = "gcr.io",
image_repository = None,
gitops = True,
gitops_path = "cloud",
deployment_branch = None,
release_branch_prefix = "main",
start_tag = "{{",
end_tag = "}}",
tags = [],
visibility = None):
if not manifests:
manifests = native.glob(["*.yaml", "*.yaml.tpl"])
for reservedname in ["PROJECT", "REGION"]:
if substitutions.get(reservedname):
fail("do not put %s in substitutions parameter of cloudrun_deploy. It will be added autimatically" % reservedname)
substitutions = dict(substitutions)
substitutions["PROJECT"] = project
substitutions["REGION"] = region
if not gitops:
image_pushes = _image_pushes(
name_suffix = "-mynamespace.push",
images = images,
image_registry = image_registry + "/mynamespace",
image_repository = image_repository,
image_digest_tag = image_digest_tag,
tags = tags,
)
kustomize(
name = name,
namespace = project,
images = image_pushes,
manifests = manifests,
substitutions = substitutions,
deps = deps,
deps_aliases = deps_aliases,
start_tag = start_tag,
end_tag = end_tag,
name_prefix = name_prefix,
name_suffix = name_suffix,
configurations = configurations,
common_labels = common_labels,
common_annotations = common_annotations,
patches = patches,
image_name_patches = image_name_patches,
image_tag_patches = image_tag_patches,
openapi_path = openapi_path,
tags = tags,
visibility = visibility,
)
gcloud_run(
name = name + ".apply",
srcs = [name],
project = project,
region = region,
command = "replace",
tags = tags,
visibility = visibility,
)
gcloud_run(
name = name + ".delete",
srcs = [name],
command = "delete",
project = project,
region = region,
push = False,
tags = tags,
visibility = visibility,
)
cloudrun_show(
name = name + ".show",
src = name,
project = project,
region = region,
tags = tags,
visibility = visibility,
)
else:
if not region:
fail("region must be defined for gitops cloudrun_deploy")
if not project:
fail("project must be defined for gitops cloudrun_deploy")
image_pushes = _image_pushes(
name_suffix = ".push",
images = images,
image_registry = image_registry,
image_repository = image_repository,
image_digest_tag = image_digest_tag,
tags = tags,
)
kustomize(
name = name,
namespace = project,
images = image_pushes,
manifests = manifests,
visibility = visibility,
substitutions = substitutions,
deps = deps,
deps_aliases = deps_aliases,
start_tag = start_tag,
end_tag = end_tag,
name_prefix = name_prefix,
name_suffix = name_suffix,
configurations = configurations,
common_labels = common_labels,
common_annotations = common_annotations,
patches = patches,
image_name_patches = image_name_patches,
image_tag_patches = image_tag_patches,
openapi_path = openapi_path,
tags = tags,
)
gcloud_run(
name = name + ".apply",
srcs = [name],
project = project,
region = region,
command = "replace",
tags = tags,
visibility = visibility,
)
gcloud_run(
name = name + ".delete",
srcs = [name],
command = "delete",
project = project,
region = region,
push = False,
tags = tags,
visibility = visibility,
)
cloudrun_gitops(
name = name + ".gitops",
srcs = [name],
project = project,
region = region,
gitops_path = gitops_path,
strip_prefixes = [
project + "-",
region + "-",
],
deployment_branch = deployment_branch,
release_branch_prefix = release_branch_prefix,
tags = tags,
visibility = ["//visibility:public"],
)
cloudrun_show(
name = name + ".show",
src = name,
project = project,
region = region,
tags = tags,
visibility = visibility,
)