129 points · by todsacerdoti · 2y ago · 84 comments
Why the people who implement these tools, who presumably are very accomplished programmers, cannot 1) see they are implementing something that is already well known and/or 2) implement it with standard semantics, is baffling to me.
Kids, just say NORWAY to devops.
sh / bash / zsh scripts are just fragile and that's the inconvenient truth. People who devised the shell interpreters had good intentions but ultimately their creations grew to a scope 1000x bigger than they intended, hence all the "do X but if Y flag is set then do Z... unless flag A is also set in which case do Y and part of Z".
It's horrendous and I seriously don't get what's so difficult in just coding these scripts in a programming language that provides single statically linked binaries (like Golang) and just distribute it with your images -- or run them in CI/CD and have init containers and never include them in the images in the first place.
Inertia, of course. But I'll be actively working against it until I retire.
It takes longer to develop (for sufficiently small scripts), it's harder to verify, it's harder to debug, it requires a build step and it's a lot more effort to modify it in-place. The process for calling other programs is also extremely streamlined, making it perfect for integration tasks like CI/CD pipelines.
Some of these issues don't exist when using an interpreted language like Python instead, but this comes with its own problems. Shell is pretty universal, well-known and is, for sufficiently small problems, the quickest solution.
Obviously, but at one point I sat down and tried to estimate how much time I wasted on using `set -euo pipefail` in my scripts and still having to chase after silent failures. I might be biased at this point but it still seemed quite a lot.
For a lot of one-off tasks shell scripting is 90% superior (unless you are super comfy with Golang) because it takes literal minutes to write and then iterate on it. Sure. But my threshold for when to reach for a proper program has been getting lower and lower lately because I very quickly arrive at a point where I need typing, better error-handling, retries and a few others.
Not everyone's case, surely. It seems my journey was more along the lines of "I was using shell scripting much more than I had to and I am making a partial comeback to proper programs".
- Debugging. I can prefix any shell script with "bash -x" and I'll get an step-by-step output of every command executed, including the arguments. I can copy-paste any part of script into interactive shell so I can run it over and over until I get things right.
- Error reporting: as long as you use shell's best practices, shell script automatically stops at a first error, and in most case there will be a clear error message printed. In golang, this is all manual, and it is pretty easy to ignore errors. (python really helps here)
(note your library seems even worse than that: not only it starts with go's error reporting handicap, you also designed it so "we just won't see any output from this program if the server returns an error response.", _and_ you actively mix stdout and stderr... this basically means any programs using your library will be nightmare to debug)
- Performance: "sort" is an external process, but it is designed to be able to sort even the data which does not fit into memory (it has spill-to-disk code). "grep" actually uses extreme optimization and things like Boyer-Moore algorithm - does your code do that?
(that said, shell scripts rapidly become unreadable after some complexity threshold.. my personal rule is "if you ever feel tempted to create common library of shell functions, it means your script become too complicated and it's time to rewrite it in real language ASAP". But until you hit that complexity limit, the shell scripts are very nice)
I agree shell scripts are still more convenient for iteration but as you pointed out in your last paragraph, most of mine crossed the complexity threshold and it's now more worth it to me to invest in a proper program than to keep stumbling on poorly documented edge cases in bash/zsh.
And I again agree with your criticisms of the Golang library (worthy of filling a few issues in their GitHub repo btw, if you have the time), it's just that my stance there is: sure it will hurt replacing shell scripts but we should start getting to it. Being stuck in this local maxima is limiting.
You can also employ DSLs (domain specific languages). Plain ones or my favorite ones - as subset/SDK of generic purpose languages.
I really, really hate to be "that one guy" (c) Rachel Kroll, but... if you're about to use a large, old, complicated piece of software, the chances are very good that its developers have mental models about what is good software, and what is good documentation, and what is self-evident and what is not, that are very, very different from yours, especially if you're a programmer and the piece of software is aimed at the sysadmins/ops/devops — so yes, read the whole docs. The things are not what you would hope they are.
Recent example I hit was a Gitlab pipeline. "When: always" setting for after_script does not mean the command will be executed always. Only if main section finished with either success or failure. If it is terminated by timeout or manually - no, script is not executed.
Thanks to reading the whole docs an hour a day I avoided a bug that happens once a year and takes whole 30 minutes of debugging.
"Correct practices" in a nutshell.
Docker documents its bugs, calls them the intended behavior, and then blames users for not reading about the bug in the documentation.
Recently it turned out that docker-compose.yaml was helpfully exposing our DB to our local LAN (which is an entire company that has nothing to do with our dev work), despite restricting all in and out traffic to our tailnet with UFW.
I know it's a known issue, it comes up here every now and then, we kept it in mind and even talked about it. But as soon as someone uses an "expose" in a docker-compose.yaml, you're f-ed.
Sure, you should keep the containers talking within the docker network, but we are kind of distributed in our org (across a series of NUCs).
I find it annoying that is has come to this. Now considering Podman, or VMs (to use a host firewall around the virtual stuff).
> Sure, you should keep the containers talking within the docker network, but we are kind of distributed in our org (across a series of NUCs).
I don’t think I understand this, are you saying that you want the ports exposed to some devices on your network but not others?
Not terribly unusual, but I wasn't aware of it - so yeah, wouldn't hurt if the docs for ARG mentioned it.
Maybe submitting a PR for an addition to the docs would help more people than writing a blog post about it?
There's a third type of documentation: Documentation that describes behavior that is contrary to the mental model. This documentation is useless to a user, as there is no reason to seek it out. The benefit to a developer is that they can document bugs instead of fixing them, and blame the users for it.
One of my more tongue-in-cheek maxims is that too much documentation is worse than too little. With too much documentation the information might be there, but you aren't able to find it. The outcome is the same, but with too much documentation you've just wasted an hour failing.
It's slightly tongue-in-cheek because you can push the amount of documentation pretty far, but you have to think about how to organise it and how users will get the required information when and if they need it.
Compare these two similar functions:
https://hexdocs.pm/elixir/1.12/Enum.html#map/2
https://modules.vlang.io/maps.html#to_array
One has beautiful clear examples of what 99% of people are going to want to do. The other is some kind of secret language people must decipher, especially if they are new to the language. "What is 'm'? What is 'I'?"
Docker can improve!
I want this one arg in multiple stages, so I'll declare it above everything is the chain of thought.
The issue here is that docker evolved rather rapidly and in a “let a thousand flowers bloom” sort of manner. And because of that you have these subtle but confusing differences between behaviors that aren’t really all that consistent.
A good example of this is how the shell is handled from layer to layer(sorta this) or even how CMD and ENTRYPOINT behave (or don’t).
If the spec has allowances for behaviors like this generating warnings would be the best possible outcome (eg referencing a variable that theoretically isn’t set). Maybe certain runtime / runc / build envs complain but the author didn’t see the complaint.
There is an unofficial bash “strict mode”, overlooked and undervalued:
set -euo pipefail
Just use it everywhere and use shellcheck for scripts.
Somebody did something the straightforward way which worked. A solution is given on a better way, but that also has a problem that somebody else didn't know about.
Bash let's you do anything and have it kind of work but you never know how many footguns you're setting up for yourself.
In my "real world" usage, I've found "bash strict mode" incredibly useful, especially when scripting things that others will be modifying. It just avoids all of the "somebody forgot an error check", "there's a typo in a variable name", etc., type errors. And pouring through logs to figure out what actually went wrong in CI/CD is brutal.
Looking at the examples:
- I don't generally do arithmetic in bash, that's a sign of "time to change language" - Also generally use `if ...; then ...; fi` instead of `test ... && ...`
If you do the advanced type of scripting that somebody who writes a Bash FAQ does, I'm sure `set -e` can be annoying. But once you learn a couple simple idioms y(covered on the original "bash strict mode" page) you don't have to know much more to have fairly robust scripts. And future maintainers will thank you for it!
Perl has “use warnings ‘uninitialized’” for the same reason.
It sounds like this feature would be worth considering for the Dockerfile spec.
https://github.com/containers/buildah/blob/main/examples/lig...
Since Dockerfile is a rather limited and (IMHO) poorly executed re-implementation of a shell script, why not use shell directly? Not even bash with coreutils is necessary: even posix sh with busybox can do much more than Dockerfile, and you can use something else (like Python) and take it very far indeed.
Things I've run into:
* Cannot compose together. Suppose I have three packages, A/B/C. I would like to build each package in an image, and also build an image with all three packages installed. I cannot extract functionality into a subroutine. Instead, I need to make a separate build script, add it to the image, and run it in the build.
* Easy to have unintentional image bloat. The obvious way to install a package in a debian-based container is with `RUN apt-get update` followed by `RUN apt-get install FOO`. However, this causes the `/var/lib/apt/lists` directory to be included in the downloaded images, even if `RUN rm -rf /var/lib/apt/lists/` is included in the Dockerfile. In order to avoid bloating the image, the all three steps of update/install/rm must be in a single RUN command.
Cannot mark commands as order-independent. If I am installing N different packages* Cannot do a dry run. There is no command that will tell you if an image is up-to-date with the current Dockerfile, and what stages must be rebuilt to bring it up to date.
* Must be sequestered away in a subdirectory. Anything that is in the directory of the dockerfile is treated as part of the build context, and is copied to the docker server. Having a Dockerfile in a top-level source directory will cause all docker commands to grind to a halt. (Gee, if only there were an explicit ADD command indicating which files are actually needed.)
* Must NOT be sequestered away in a subdirectory. The dockerfile may only add files to the image if they are contained in the dockerfile's directory.
* No support for symlinks. Symlinks are the obvious way to avoid the contradiction in the previous two bullet points, but are not allowed. Instead, you must re-structure your entire project based on whether docker requires a file. (The documented reason for this is that the target of a symlink can change. If applied consistently, I might accept this reasoning, but the ADD command can download from a URL. Pretending that symlinks are somehow less consistent than a remote resource is ridiculous.)
* Requires periodic cleanup. A failed build command results in a container left in an exited state. This occurs even if the build occurred in a command that explicitly tries to avoid leaving containers running. (e.g. "docker run --rm", where the image must be built before running.)
In other words you can use this code to catch this error:
ARG DEBVER="10"
ARG CAPVER="7.8"
FROM debian:${DEBVER}
RUN <<EOF
set -eu
printf "DEB=${DEBVER}\nCAP=${CAPVER}\n"
EOF
This code fails with expected error.https://www.docker.com/blog/introduction-to-heredocs-in-dock...
It would still be possible to accidentally reference uninitialized environment variables in contexts other than RUN though. Having those be treated as errors would be useful.
SHELL ["/bin/sh", "-o", "nounset", "-c"]
RUN printf "DEB=${DEBVER}\nCAP=${CAPVER}\n"Better defaults and/or an easier way to change the defaults would be good!
The previous commenter is right -- it's all very well to say "just read all the docs" or "it's consistent with the way other tools work", but sometimes both the docs and the tools can be made less error-prone for users.
Environment variables can be useful. The first version of some code can be oblivious to environment variables and the second version can use them for feature flags. Because it is entirely optional to provide these, the second version of the code can be deployed to the first version’s infrastructure, and the first version will happily ignore environment variables set in the second version’s infrastructure.
As a tool for incrementally moving heterogeneous parts of a system forward without needing atomic leaps, the use of environment variables as optional flags is very useful.
I just wouldn’t even start from there. Instead I configure everything in code, in one repo, with all new deployments appearing as new clusters where the only thing they have in common is that they take production traffic. This kind of production infra is very useful but there are downsides for sure. It makes database schema changes, for example, something between very hard and anathema to execute.
[0] https://json5.org/ [1] https://www.youtube.com/watch?v=SxdOUGdseq4
With this out of the way: Dockerfile as a concept, i.e. a minimalist (in simple cases) way to declaratively configure a container is great. The execution of this concept is, on the other hand, awful. The behavior of gotchas like the one OP described isn't the reason for the awfulness, rather, it comes from the inconsistent-by-default builds. That is, Dockerfile is not a full description of the contents of the built image. To know what will go into the image, you also need to consider the state of the entire world (because you can download things from the Internet during build, execute code with unpredictable side effects etc.)
FROM ubuntu:20.04
ARG foo
ENV foo $foo
CMD ["/bin/sh", "-c", "echo $foo"]In a multistage build, they are only valid in the image that declared them (ie. they do not magically pass over to any other image).
I can see an argument for variables declared within one stage being inaccessible in another stage, as the FROM keyword starts a new sibling stage. However, they are still children of the outer scope, should have access to variables in the outer scope. That they do not is rather unexpected.
But that's how it feels to me.
It's mostly because my mental image of multistage builds is different, I see them as a way to make the final image smaller by throwing away everything from the previous image.
So it does make sense to me that ARG values are thrown away after a new FROM instruction and if you need them, you need to declare them again.
These two guides have led me to this view, I blame the author! ;) They're excellent BTW, I've revisited them a lot.
https://vsupalov.com/docker-arg-env-variable-guide/#arg-and-...
https://vsupalov.com/build-docker-image-clone-private-repo-s...
And apologies on my side, as I worded it a bit strongly. I agree with pretty much everything in your post, except for the implication that it would be magic. To me, the expected behavior is to follow lexical scoping, just like the vast majority of languages from the past several decades.
> So it does make sense to me that ARG values are thrown away after a new FROM instruction and if you need them, you need to declare them again.
True, and I'd expect an ARG from a previous stage to be undefined when in the next stage. Each ARG belongs to the scope in which it is declared, and a new scope is entered with each FROM statement. However, ARG statements prior to the first FROM statement don't fit into that model. They are before any FROM statement, so they can't belong to any FROM statement.
There's a design decision on whether statements before the first FROM statement are a parent scope, or whether they are unrelated scopes, to the scope used for each stage. They feel like they should be a parent scope, because these ARG definitions can be used in a FROM statement, and so it keeps surprising me when they are instead treated as unrelated scopes.