Skip to content

Instantly share code, notes, and snippets.

@gzm0
Created February 17, 2023 08:01
Show Gist options
  • Save gzm0/3c4056115574a4503821924f78c3101f to your computer and use it in GitHub Desktop.
Save gzm0/3c4056115574a4503821924f78c3101f to your computer and use it in GitHub Desktop.
"""Rules to run docker-compose.yml files
They require Compose V2 (as part of the docker CLI).
Simply install via the docker repositories:
```
$ sudo apt-get install docker-compose-plugin
```
"""
load("@io_bazel_rules_docker//container:providers.bzl", "ImageInfo")
load("@io_bazel_rules_docker//skylib:docker.bzl", "docker_path")
def _preprocess_dc(ctx):
# Write image-info.json containing the label -> file mappings.
image_info_file = ctx.actions.declare_file("image-info.json")
image_info = {
str(image.label): image[ImageInfo].container_parts["config_digest"].path
for image in ctx.attr.deps
}
ctx.actions.write(image_info_file, json.encode(image_info))
# Inputs for the processor.
inputs = [ctx.file.src, image_info_file] + [
image[ImageInfo].container_parts["config_digest"]
for image in ctx.attr.deps
]
new_dc = ctx.actions.declare_file("docker-compose.gen.yml")
ctx.actions.run(
inputs = inputs,
outputs = [new_dc],
arguments = [
"--input",
ctx.file.src.path,
"--imageInfo",
image_info_file.path,
"--output",
new_dc.path,
],
env = {"BAZEL_BINDIR": "."},
executable = ctx.executable._dc_processor,
)
return new_dc
def _docker_compose_up(ctx, dc_file):
docker_toolchain = ctx.toolchains["@io_bazel_rules_docker//toolchains/docker:toolchain_type"].info
executable = ctx.actions.declare_file("run-dc.sh")
# First, load all the images into the local docker.
cmds = [
"./%s --norun" % image.files_to_run.executable.short_path
for image in ctx.attr.deps
]
# Then, actually run `docker compose`.
cmds.append("%s compose --file %s up " % (docker_path(docker_toolchain), dc_file.short_path))
ctx.actions.write(
content = "#!/bin/sh\n" + " && ".join(cmds),
output = executable,
is_executable = True,
)
return executable
def _docker_compose_impl(ctx):
new_dc = _preprocess_dc(ctx)
executable = _docker_compose_up(ctx, new_dc)
image_runfiles = [
image.default_runfiles
for image in ctx.attr.deps
]
runfiles = ctx.runfiles(files = [new_dc]).merge_all(image_runfiles)
return DefaultInfo(
executable = executable,
runfiles = runfiles,
)
docker_compose = rule(
attrs = {
"deps": attr.label_list(
providers = [ImageInfo],
doc = "Container images required by this docker-compose file",
),
"src": attr.label(
allow_single_file = [".yml"],
doc = "The docker compose file",
),
"_dc_processor": attr.label(
default = "//bzl/src:dc-processor",
executable = True,
cfg = "exec",
),
},
executable = True,
implementation = _docker_compose_impl,
toolchains = ["@io_bazel_rules_docker//toolchains/docker:toolchain_type"],
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment