Skip to content

Improve py_image layering - #324

Merged
nlopezgi merged 2 commits into
bazelbuild:masterfrom
scele:improve_layers
Oct 3, 2018
Merged

nlopezgi merged 2 commits into
bazelbuild:masterfrom
scele:improve_layers

Conversation

@scele

@scele scele commented Feb 16, 2018 •

Copy link
Copy Markdown
Contributor

Consider the following more complex python image that uses the pip requirement feature of rules_python:

load("@pip_deps//:requirements.bzl", "requirement")

py_library(
    name = "py_image_library_with_external_deps",
    srcs = ["py_image_library.py"],
    deps = [requirement("tensorflow")],
)

py_library(
    name = "py_image_library",
    srcs = ["py_image_library.py"],
    deps = [":py_image_library_with_external_deps"],
)

py_image(
    name = "py_image_complex",
    srcs = ["py_image.py"],
    layers = [
        ":py_image_library_with_external_deps",
        ":py_image_library",
    ],
    main = "py_image.py",
)

Currently, it will produce the following layers:

301M bazel-bin/testdata/py_image_complex.0-layer.tar
301M bazel-bin/testdata/py_image_complex.1-layer.tar
 15M bazel-bin/testdata/py_image_complex-layer.tar

This change improves the layering by fixing the following issues:

  1. The middle layer does not detect that all tensorflow files were already added by the first layer.

  2. The last layer is 15MB in size due to the huge symlink forest. Create a separate symlink layer for each dependency layer to avoid bloating the top layer, while still keeping the dependency layers image agnostic.

  3. Getting "tensorflow" to its own layer requires the author of the "py_image" rule to know that libraries transitively depend on "tensorflow". This is not great, since library authors may addand remove dependencies without remembering to update the "layers" list. To counter this, add a new py_layer rule that can be used to select from transitive dependencies and group them to layers, without explicitly naming the transitive dependencies like "tensorflow".

With these improvements, the above example can be rewritten as:

load("@pip_deps//:requirements.bzl", "requirement")

py_library(
    name = "py_image_library_with_external_deps",
    srcs = ["py_image_library.py"],
    deps = [requirement("tensorflow")],
)

py_library(
    name = "py_image_library",
    srcs = ["py_image_library.py"],
    deps = [":py_image_library_with_external_deps"],
)

py_layer(
    name = "external_deps",
    deps = [":py_image_library"],
    filter = "@",
)

py_image(
    name = "py_image_complex",
    srcs = ["py_image.py"],
    layers = [
        ":external_deps",
        ":py_image_library",
    ],
    main = "py_image.py",
)

This will yield the following layer structure:

310M bazel-bin/testdata/py_image_complex.0-layer.tar           (agnostic)
 15M bazel-bin/testdata/py_image_complex.0-symlinks-layer.tar  (non-agnostic)
 10K bazel-bin/testdata/py_image_complex.1-layer.tar           (agnostic)
 10K bazel-bin/testdata/py_image_complex.1-symlinks-layer.tar  (non-agnostic)
 20K bazel-bin/testdata/py_image_complex-layer.tar             (non-agnostic)

@bazel-io

Copy link
Copy Markdown
Member

Can one of the admins verify this patch?

@mirandaconrado mirandaconrado left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Awesome!

Comment thread container/image.bzl Outdated
file_map = file_map or {}
files = files or ctx.files.files
empty_files = empty_files or ctx.attr.empty_files
empty_files = empty_files or {f: f for f in ctx.attr.empty_files}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why do we need to change this from a list to dictionary? The only uses seem to be in calling _build_layer, which isn't changed in this PR so I imagine it doesn't care, and in creating transient_emptyfiles, which could be done with the list directly. Am I missing something?
Also, if this change is indeed necessary, we should probably update the documentation of this function to reflect the new type.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I used to pass relative paths in the dict value. But now I reshuffled things and found out it's not needed, so I removed this confusing thing.

@scele
scele force-pushed the improve_layers branch 5 times, most recently from 316084c to 5d1b9c6 Compare February 19, 2018 11:30
@scele

scele commented Feb 23, 2018

Copy link
Copy Markdown
Contributor Author

@mattmoor would you have time to take a look?

@mattmoor mattmoor left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the PR. There are a bunch of subtle trade-offs to different strategies for bucketing things into layers that I am constantly grappling with. @hsyed actually brought this exact pattern up in the context of Java a while back (it would be good to confirm this works for his case).

re: symlinks

The requirement of the symlinks is an artifact of us using the Bazel entrypoint, which expects the runfiles tree set up a certain way. Java doesn't use this entrypoint, and it can elide the symlinks by simply inlining the resolved path into the classpath.

re: my ideal world

In my perfect world, I'd have a layer per dependency that excludes transitive dependencies (similar to what you have), and frankly layers=[] is a hack to approximate that with some poor heuristics to turn these into layers. One potential avenue towards this is using "Aspects", but I haven't had an opportunity to explore this. I've tried to explain some of the original rationale in the comments below.

re: allowing multiple heuristics

I am open to other heuristics, and have been debating if/how to allow them for some time. I think my preference in this case would be to replace external_layer = True with a layering_strategy = "a-descriptive-strategy-name". WDYT?

Comment thread container/image_test.py Resolved
Comment thread container/image.bzl Outdated
unzipped_layers = parent_parts.get("unzipped_layer", []) + [unzipped_layer]
diff_ids = parent_parts.get("diff_id", []) + [diff_id]
transient_files = parent_parts.get("transient_files", depset()) + [f for f in file_map]
transient_emptyfiles = parent_parts.get("transient_emptyfiles", depset()) + empty_files

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do you mean transitive?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes!

Comment thread python/image.bzl Outdated
})

def py_image(name, base=None, deps=[], layers=[], **kwargs):
def py_image(name, base=None, deps=[], layers=[], external_layer=False, **kwargs):

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This new kwarg isn't documented below.

Comment thread testdata/py_image_complex.py Outdated
@@ -0,0 +1,22 @@
# Copyright 2017 The Bazel Authors. All rights reserved.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: 2018 :)

Comment thread python/image.bzl Outdated
base = base or DEFAULT_BASE

# Add a separate layer for external deps, usually they don't change very often.
if external_layer:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Making this a single layer will significantly hurt performance when a small dependency is added, changed, or removed. It also creates an interesting combinatorial problem for cross-image dependency sharing.

I agree that this is a 10-20% case, not an 80-90% case.

For rules_python, I wonder if simply using:

py_image(
    name = "foo",
    ...
    layers = all_requirements,
)

Would get you what you want? Maybe, maybe not because IIRC it's intentionally dumb about deduplicating across deps (to keep them agnostic of the binary context).

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The issue with layers = all_requirements is that the requirements.txt file in the repo might contain a LOT of pip packages, while only some of them are used in the py_image that is being built. I wouldn't want to include the useless packages to the image, and I wouldn't want the built image to change just because somebody adds an unrelated pip package to the requirements.txt.

Comment thread README.md Outdated
```

You can also put all external dependencies to a separate layer at the bottom,
by setting `external_layer=True`.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This isn't specific to py_image, and isn't really "fine layering". Perhaps add a new example illustrating how to do this grouping all external deps?

@fahhem

fahhem commented Mar 8, 2018

Copy link
Copy Markdown
Contributor

@scele, this PR seems very useful! Do you want help getting it updated for the review and merge conflicts? I'd love to see this get in

@scele

scele commented Mar 8, 2018

Copy link
Copy Markdown
Contributor Author

Sorry for letting this sit for so long.. Thanks for your thoughtful review @mattmoor !

re: my ideal world

I like the idea of putting every pip dep to its own layer. I worry about the 127 layer limit that docker apparently has (at least for some FS drivers), and it's also documented as a limitation of ECR. The code I'm building the image for has > 60 pip packages already today, and it won't be going down. Also, docker push and pull seem to be slower for high number of layers, even if none of the layers changed (I haven't measured this though).

I think my preference in this case would be to replace external_layer = True with a layering_strategy = "a-descriptive-strategy-name". WDYT?

Sounds good! Perhaps layering_strategy='group_external|default'?

I also wonder if we could expose equivalent functionality in a more flexible manner by building on top of the new container_layer. Something like:

container_layer(
    name = "layer_1_external",
    files = ":lib_A_that_depends_on_pip_set_A",
    external_only = True,
)
container_layer(
    name = "layer_1",
    files = ":lib_A_that_depends_on_pip_set_A",
)
container_layer(
    name = "layer_2_external",
    files = ":lib_B_that_depends_on_pip_set_B",
    external_only = True,
)
container_layer(
    name = "layer_2",
    files = ":lib_B_that_depends_on_pip_set_B",
)
py_image(
    name = "app",
    src = "app.py",
    layers = [
        ":layer_1_external", # pip set A
        ":layer_1",          # source of lib A
        ":layer_2_external", # pip set B-A
        ":layer_2",          # source of lib B
    ],
)

@scele

scele commented Mar 8, 2018

Copy link
Copy Markdown
Contributor Author

Thanks also @fahhem for rebasing! :)

@scele

scele commented Mar 14, 2018

Copy link
Copy Markdown
Contributor Author

@mattmoor I uploaded a new version that tries to make layering even more flexible (see the updated cover letter of this PR and the updated README.md). I also took the liberty to reduce code duplication by merging "dep_layer" and "app_layer" into a single rule since they already were very similar.

What do you think?

@scele

scele commented Apr 2, 2018

Copy link
Copy Markdown
Contributor Author

@mattmoor would you have time to comment on the revised proposal?

@nlopezgi

Copy link
Copy Markdown
Contributor

Hi @scele sorry for the long time to respond to this PR, we have been transitioning the team owning these rules and some PRs fell through the cracks in the meantime. Is this work still needed? If so could you try to resolve conflicts and let me know when this is ready again for me to take a look? Again, apologies for the delay.

@scele
scele force-pushed the improve_layers branch 3 times, most recently from 03c6e7c to 63385c3 Compare September 20, 2018 08:17
@scele

scele commented Sep 20, 2018

Copy link
Copy Markdown
Contributor Author

@nlopezgi rebased, ready for your review!

@nlopezgi

Copy link
Copy Markdown
Contributor

Thanks again for sending this PR. Kicked off tests and started reviewing this today. Will take some time to do a full review but will try to get back with, at least, some comments by EoW.
To followup on some comments from above,

Sounds good! Perhaps layering_strategy='group_external|default'?

I do think it would be useful to have the alternative of still using the default layering strategy, but to be 100% honest I'm not sure if the effort to support both is worth it (do you have opinions on if this change in layering strategy could negatively impact other use cases?)

I also wonder if we could expose equivalent functionality in a more flexible manner by building on top of the new container_layer.

I think that is worth exploring more. The container_layer was added after all these xx_images rules and leveraging it would be interesting. Do you think this is something that replaces/improves what you currently have in this PR or is this follow up improvements that you think could be made after this PR?

@scele

scele commented Sep 27, 2018

Copy link
Copy Markdown
Contributor Author

Yeah, I realize this MR can be quite a bit to digest.. :)

I do think it would be useful to have the alternative of still using the default layering strategy, but to be 100% honest I'm not sure if the effort to support both is worth it (do you have opinions on if this change in layering strategy could negatively impact other use cases?)

The only change in behavior (for users who don't explicitly start using the new py_layer primitive) is as follows: If user has py_image or py3_image rules that use the layers attribute, each such layer will generate two container layers: one agnostic with the real files, and one symlink layer that links the files in the right places under runfiles.

It's done by these lines:

    for index, dep in enumerate(layers):
        base = app_layer(name = "%s_%d" % (name, index), base = base, dep = dep)
        base = app_layer(name = "%s_%d-symlinks" % (name, index), base = base, dep = dep, binary = binary)

(I added these lines also to rust, go, d and cc images for consistency, but all of those also emit a warning print that says "xxx_image does not benefit from layers=[]" so we could also drop the symlink layer from those if you'd like. The java rules appear to benefit from explicit layering, but I'm not changing any behavior there.)

So, I think your question about supporting the old "default layering strategy" could be rephrased as "should we still support generating python images where symlinks are not separated to their own container layers?" The easiest way to support that would be to expose some new attribute like py_image(..., squash_symlinks=True) but exposing a hacky thing like that might be premature.. Perhaps we could see if people report any drawbacks of the new scheme, and then see how to best address those specific issues?

I think that is worth exploring more. The container_layer was added after all these xx_images rules and leveraging it would be interesting. Do you think this is something that replaces/improves what you currently have in this PR or is this follow up improvements that you think could be made after this PR?

The last version of this PR already exposes py_layer which allows quite flexible layer partitioning as shown in README (the original version of this PR had external_layer boolean attribute to py_image, and Matt suggested renaming it to layering_strategy, but I abandoned both of these ideas in favor of the more flexible py_layer). However py_layer does not build on container_layer, and I'm not sure how that could even be leveraged.. For example, container_layer is dumb in the sense that it always adds all input files to the layer tarball, while the py_image(layers=[...]) (which py_layer integrates to) only adds files if they are not already present on the previous layers.

So, I think there is some discrepancy between container_layer and the layers passed to lang_image rules. This MR does not solve the discrepancy, but I hope that it doesn't make it worse either.

Comment thread WORKSPACE Resolved
Comment thread container/image_test.py Resolved
Comment thread lang/image.bzl Resolved
@scele

scele commented Sep 29, 2018

Copy link
Copy Markdown
Contributor Author

Fixed WORKSPACE, typo, and replied about layer sharing.

@nlopezgi nlopezgi left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

One minor nit about location of Providers, but this looks good to submit. Could you please update the branch one final time and let me know about the Providers nit and I will approve and merge.
Thanks!

Comment thread lang/image.bzl Outdated
_get_layers = "get_from_target",
)

FilterAspectInfo = provider(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do you think these should be in container/providers.bzl?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes! Done.

Consider the following more complex python image that uses the pip
requirement feature of rules_python:

    load("@pip_deps//:requirements.bzl", "requirement")

    py_library(
        name = "py_image_library_with_external_deps",
        srcs = ["py_image_library.py"],
        deps = [requirement("tensorflow")],
    )

    py_library(
        name = "py_image_library",
        srcs = ["py_image_library.py"],
        deps = [":py_image_library_with_external_deps"],
    )

    py_image(
        name = "py_image_complex",
        srcs = ["py_image.py"],
        layers = [
            ":py_image_library_with_external_deps",
            ":py_image_library",
        ],
        main = "py_image.py",
    )

Currently, it will produce the following layers:

   301M bazel-bin/testdata/py_image_complex.0-layer.tar
   301M bazel-bin/testdata/py_image_complex.1-layer.tar
    15M bazel-bin/testdata/py_image_complex-layer.tar

This change improves the layering by fixing the following issues:

   1. The middle layer does not detect that all tensorflow files
      were already added by the first layer.

   2. The last layer is 15MB in size due to the huge symlink forest.
      Create a separate symlink layer for each dependency layer to
      avoid bloating the top layer, while still keeping the dependency
      layers image agnostic.

   3. Getting "tensorflow" to its own layer requires the author of the
      "py_image" rule to know that libraries transitively depend on
      "tensorflow".  This is not great, since library authors may add
      and remove dependencies without remembering to update the "layers"
      list.  To counter this, add a new py_layer rule that can be used
      to select from transitive dependencies and group them to layers,
      without explicitly naming the transitive dependencies like
      "tensorflow".

With these improvements, the above example can be rewritten as:

    load("@pip_deps//:requirements.bzl", "requirement")

    py_library(
        name = "py_image_library_with_external_deps",
        srcs = ["py_image_library.py"],
        deps = [requirement("tensorflow")],
    )

    py_library(
        name = "py_image_library",
        srcs = ["py_image_library.py"],
        deps = [":py_image_library_with_external_deps"],
    )

    py_layer(
        name = "external_deps",
        deps = [":py_image_library"],
        filter = "@",
    )

    py_image(
        name = "py_image_complex",
        srcs = ["py_image.py"],
        layers = [
            ":external_deps",
            ":py_image_library",
        ],
        main = "py_image.py",
    )

This will yield the following layer structure:

   310M bazel-bin/testdata/py_image_complex.0-layer.tar           (agnostic)
    15M bazel-bin/testdata/py_image_complex.0-symlinks-layer.tar  (non-agnostic)
    10K bazel-bin/testdata/py_image_complex.1-layer.tar           (agnostic)
    10K bazel-bin/testdata/py_image_complex.1-symlinks-layer.tar  (non-agnostic)
    20K bazel-bin/testdata/py_image_complex-layer.tar             (non-agnostic)
@scele

scele commented Oct 2, 2018

Copy link
Copy Markdown
Contributor Author

Moved providers, and rebased on top of master. I also squashed the review fixes to the main commit (if that was a mistake, the unsquashed and unrebased changes are still in my improve_layers_before_rebase branch).

@nlopezgi nlopezgi left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks again for all the work on this PR. Will approve and merge once all tests pass.

Comment thread container/image_test.py Resolved
@nlopezgi
nlopezgi merged commit c9065d1 into bazelbuild:master Oct 3, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

7 participants