2018-02-05 21:05:59 +00:00
package dockerfile // import "github.com/docker/docker/builder/dockerfile"
2014-08-05 20:17:40 +00:00
2014-08-07 05:56:44 +00:00
// This file contains the dispatchers for each command. Note that
// `nullDispatch` is not actually a command, but support for commands we parse
// but do nothing with.
//
// See evaluator.go for a higher level discussion of the whole evaluator
// package.
2014-08-05 20:17:40 +00:00
import (
2017-05-12 19:00:55 +00:00
"bytes"
2022-10-26 16:13:17 +00:00
"context"
2014-08-05 20:17:40 +00:00
"fmt"
2015-05-05 15:39:37 +00:00
"runtime"
2014-11-12 08:22:08 +00:00
"sort"
2014-08-05 20:17:40 +00:00
"strings"
2014-08-05 22:41:09 +00:00
2018-06-26 07:39:25 +00:00
"github.com/containerd/containerd/platforms"
2015-12-31 13:57:58 +00:00
"github.com/docker/docker/api"
2016-09-06 18:18:12 +00:00
"github.com/docker/docker/api/types/strslice"
2017-05-05 22:52:11 +00:00
"github.com/docker/docker/builder"
2018-01-11 19:53:06 +00:00
"github.com/docker/docker/errdefs"
2017-05-14 18:18:48 +00:00
"github.com/docker/docker/image"
2017-04-13 22:44:36 +00:00
"github.com/docker/docker/pkg/jsonmessage"
2017-05-18 00:08:01 +00:00
"github.com/docker/docker/pkg/system"
2015-12-18 17:58:48 +00:00
"github.com/docker/go-connections/nat"
2018-06-02 16:46:53 +00:00
"github.com/moby/buildkit/frontend/dockerfile/instructions"
"github.com/moby/buildkit/frontend/dockerfile/parser"
"github.com/moby/buildkit/frontend/dockerfile/shell"
2021-07-09 22:11:57 +00:00
"github.com/moby/sys/signal"
2023-05-08 09:57:52 +00:00
ocispec "github.com/opencontainers/image-spec/specs-go/v1"
2017-03-15 22:28:06 +00:00
"github.com/pkg/errors"
2014-08-05 20:17:40 +00:00
)
2014-08-07 05:56:44 +00:00
// ENV foo bar
//
// Sets the environment variable foo to bar, also makes interpolation
// in the dockerfile available from the next statement on via ${foo}.
2022-10-26 16:13:17 +00:00
func dispatchEnv ( ctx context . Context , d dispatchRequest , c * instructions . EnvCommand ) error {
2017-05-22 15:21:17 +00:00
runConfig := d . state . runConfig
2017-04-04 16:28:59 +00:00
commitMessage := bytes . NewBufferString ( "ENV" )
2017-05-22 15:21:17 +00:00
for _ , e := range c . Env {
name := e . Key
newVar := e . String ( )
2016-08-01 16:38:05 +00:00
2017-04-04 16:28:59 +00:00
commitMessage . WriteString ( " " + newVar )
2014-09-26 02:28:24 +00:00
gotOne := false
2017-04-26 21:45:16 +00:00
for i , envVar := range runConfig . Env {
2022-10-31 16:09:57 +00:00
compareFrom , _ , _ := strings . Cut ( envVar , "=" )
2018-01-30 23:58:21 +00:00
if shell . EqualEnvKeys ( compareFrom , name ) {
2017-04-26 21:45:16 +00:00
runConfig . Env [ i ] = newVar
2014-09-26 02:28:24 +00:00
gotOne = true
break
}
2014-08-13 10:07:41 +00:00
}
2014-09-26 02:28:24 +00:00
if ! gotOne {
2017-04-26 21:45:16 +00:00
runConfig . Env = append ( runConfig . Env , newVar )
2014-09-26 02:28:24 +00:00
}
2014-08-13 10:07:41 +00:00
}
2022-10-26 16:13:17 +00:00
return d . builder . commit ( ctx , d . state , commitMessage . String ( ) )
2014-08-05 20:17:40 +00:00
}
2014-08-07 05:56:44 +00:00
// MAINTAINER some text <maybe@an.email.address>
//
// Sets the maintainer metadata.
2022-10-26 16:13:17 +00:00
func dispatchMaintainer ( ctx context . Context , d dispatchRequest , c * instructions . MaintainerCommand ) error {
2017-05-22 15:21:17 +00:00
d . state . maintainer = c . Maintainer
2022-10-26 16:13:17 +00:00
return d . builder . commit ( ctx , d . state , "MAINTAINER " + c . Maintainer )
2014-08-05 20:17:40 +00:00
}
2015-02-17 15:20:06 +00:00
// LABEL some json data describing the image
//
// Sets the Label variable foo to bar,
2022-10-26 16:13:17 +00:00
func dispatchLabel ( ctx context . Context , d dispatchRequest , c * instructions . LabelCommand ) error {
2017-05-22 15:21:17 +00:00
if d . state . runConfig . Labels == nil {
d . state . runConfig . Labels = make ( map [ string ] string )
2015-05-05 21:27:42 +00:00
}
2015-02-17 15:20:06 +00:00
commitStr := "LABEL"
2017-05-22 15:21:17 +00:00
for _ , v := range c . Labels {
d . state . runConfig . Labels [ v . Key ] = v . Value
commitStr += " " + v . String ( )
2015-02-17 15:20:06 +00:00
}
2022-10-26 16:13:17 +00:00
return d . builder . commit ( ctx , d . state , commitStr )
2015-02-17 15:20:06 +00:00
}
2014-08-07 05:56:44 +00:00
// ADD foo /path
//
2018-07-02 23:51:07 +00:00
// Add the file 'foo' to '/path'. Tarball and Remote URL (http, https) handling
2014-08-07 05:56:44 +00:00
// exist here. If you do not wish to have this automatic handling, use COPY.
2022-10-26 16:13:17 +00:00
func dispatchAdd ( ctx context . Context , d dispatchRequest , c * instructions . AddCommand ) error {
builder: produce error when using unsupported Dockerfile option
With the promotion of the experimental Dockerfile syntax to "stable", the Dockerfile
syntax now includes some options that are supported by BuildKit, but not (yet)
supported in the classic builder.
As a result, parsing a Dockerfile may succeed, but any flag that's known to BuildKit,
but not supported by the classic builder is silently ignored;
$ mkdir buildkit_flags && cd buildkit_flags
$ touch foo.txt
For example, `RUN --mount`:
DOCKER_BUILDKIT=0 docker build --no-cache -f- . <<EOF
FROM busybox
RUN --mount=type=cache,target=/foo echo hello
EOF
Sending build context to Docker daemon 2.095kB
Step 1/2 : FROM busybox
---> 219ee5171f80
Step 2/2 : RUN --mount=type=cache,target=/foo echo hello
---> Running in 022fdb856bc8
hello
Removing intermediate container 022fdb856bc8
---> e9f0988844d1
Successfully built e9f0988844d1
Or `COPY --chmod` (same for `ADD --chmod`):
DOCKER_BUILDKIT=0 docker build --no-cache -f- . <<EOF
FROM busybox
COPY --chmod=0777 /foo.txt /foo.txt
EOF
Sending build context to Docker daemon 2.095kB
Step 1/2 : FROM busybox
---> 219ee5171f80
Step 2/2 : COPY --chmod=0777 /foo.txt /foo.txt
---> 8b7117932a2a
Successfully built 8b7117932a2a
Note that unknown flags still produce and error, for example, the below fails because `--hello` is an unknown flag;
DOCKER_BUILDKIT=0 docker build -<<EOF
FROM busybox
RUN --hello echo hello
EOF
Sending build context to Docker daemon 2.048kB
Error response from daemon: dockerfile parse error line 2: Unknown flag: hello
With this patch applied
----------------------------
With this patch applied, flags that are known in the Dockerfile spec, but are not
supported by the classic builder, produce an error, which includes a link to the
documentation how to enable BuildKit:
DOCKER_BUILDKIT=0 docker build --no-cache -f- . <<EOF
FROM busybox
RUN --mount=type=cache,target=/foo echo hello
EOF
Sending build context to Docker daemon 2.048kB
Step 1/2 : FROM busybox
---> b97242f89c8a
Step 2/2 : RUN --mount=type=cache,target=/foo echo hello
the --mount option requires BuildKit. Refer to https://docs.docker.com/go/buildkit/ to learn how to build images with BuildKit enabled
DOCKER_BUILDKIT=0 docker build --no-cache -f- . <<EOF
FROM busybox
COPY --chmod=0777 /foo.txt /foo.txt
EOF
Sending build context to Docker daemon 2.095kB
Step 1/2 : FROM busybox
---> b97242f89c8a
Step 2/2 : COPY --chmod=0777 /foo.txt /foo.txt
the --chmod option requires BuildKit. Refer to https://docs.docker.com/go/buildkit/ to learn how to build images with BuildKit enabled
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2021-01-21 12:25:18 +00:00
if c . Chmod != "" {
return errors . New ( "the --chmod option requires BuildKit. Refer to https://docs.docker.com/go/buildkit/ to learn how to build images with BuildKit enabled" )
}
2017-05-22 15:21:17 +00:00
downloader := newRemoteSourceDownloader ( d . builder . Output , d . builder . Stdout )
copier := copierFromDispatchRequest ( d , downloader , nil )
2017-05-07 18:37:46 +00:00
defer copier . Cleanup ( )
2017-05-22 15:21:17 +00:00
copyInstruction , err := copier . createCopyInstruction ( c . SourcesAndDest , "ADD" )
2017-05-07 18:37:46 +00:00
if err != nil {
return err
}
2017-05-22 15:21:17 +00:00
copyInstruction . chownStr = c . Chown
2017-05-07 18:37:46 +00:00
copyInstruction . allowLocalDecompression = true
2022-10-26 16:13:17 +00:00
return d . builder . performCopy ( ctx , d , copyInstruction )
2014-08-05 20:17:40 +00:00
}
2014-08-07 05:56:44 +00:00
// COPY foo /path
//
// Same as 'ADD' but without the tar and remote url handling.
2022-10-26 16:13:17 +00:00
func dispatchCopy ( ctx context . Context , d dispatchRequest , c * instructions . CopyCommand ) error {
builder: produce error when using unsupported Dockerfile option
With the promotion of the experimental Dockerfile syntax to "stable", the Dockerfile
syntax now includes some options that are supported by BuildKit, but not (yet)
supported in the classic builder.
As a result, parsing a Dockerfile may succeed, but any flag that's known to BuildKit,
but not supported by the classic builder is silently ignored;
$ mkdir buildkit_flags && cd buildkit_flags
$ touch foo.txt
For example, `RUN --mount`:
DOCKER_BUILDKIT=0 docker build --no-cache -f- . <<EOF
FROM busybox
RUN --mount=type=cache,target=/foo echo hello
EOF
Sending build context to Docker daemon 2.095kB
Step 1/2 : FROM busybox
---> 219ee5171f80
Step 2/2 : RUN --mount=type=cache,target=/foo echo hello
---> Running in 022fdb856bc8
hello
Removing intermediate container 022fdb856bc8
---> e9f0988844d1
Successfully built e9f0988844d1
Or `COPY --chmod` (same for `ADD --chmod`):
DOCKER_BUILDKIT=0 docker build --no-cache -f- . <<EOF
FROM busybox
COPY --chmod=0777 /foo.txt /foo.txt
EOF
Sending build context to Docker daemon 2.095kB
Step 1/2 : FROM busybox
---> 219ee5171f80
Step 2/2 : COPY --chmod=0777 /foo.txt /foo.txt
---> 8b7117932a2a
Successfully built 8b7117932a2a
Note that unknown flags still produce and error, for example, the below fails because `--hello` is an unknown flag;
DOCKER_BUILDKIT=0 docker build -<<EOF
FROM busybox
RUN --hello echo hello
EOF
Sending build context to Docker daemon 2.048kB
Error response from daemon: dockerfile parse error line 2: Unknown flag: hello
With this patch applied
----------------------------
With this patch applied, flags that are known in the Dockerfile spec, but are not
supported by the classic builder, produce an error, which includes a link to the
documentation how to enable BuildKit:
DOCKER_BUILDKIT=0 docker build --no-cache -f- . <<EOF
FROM busybox
RUN --mount=type=cache,target=/foo echo hello
EOF
Sending build context to Docker daemon 2.048kB
Step 1/2 : FROM busybox
---> b97242f89c8a
Step 2/2 : RUN --mount=type=cache,target=/foo echo hello
the --mount option requires BuildKit. Refer to https://docs.docker.com/go/buildkit/ to learn how to build images with BuildKit enabled
DOCKER_BUILDKIT=0 docker build --no-cache -f- . <<EOF
FROM busybox
COPY --chmod=0777 /foo.txt /foo.txt
EOF
Sending build context to Docker daemon 2.095kB
Step 1/2 : FROM busybox
---> b97242f89c8a
Step 2/2 : COPY --chmod=0777 /foo.txt /foo.txt
the --chmod option requires BuildKit. Refer to https://docs.docker.com/go/buildkit/ to learn how to build images with BuildKit enabled
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2021-01-21 12:25:18 +00:00
if c . Chmod != "" {
return errors . New ( "the --chmod option requires BuildKit. Refer to https://docs.docker.com/go/buildkit/ to learn how to build images with BuildKit enabled" )
}
2017-05-22 15:21:17 +00:00
var im * imageMount
var err error
if c . From != "" {
2022-10-28 11:40:06 +00:00
im , err = d . getImageMount ( ctx , c . From )
2017-05-22 15:21:17 +00:00
if err != nil {
return errors . Wrapf ( err , "invalid from flag value %s" , c . From )
}
2017-03-15 22:28:06 +00:00
}
2017-05-22 15:21:17 +00:00
copier := copierFromDispatchRequest ( d , errOnSourceDownload , im )
2017-05-07 18:37:46 +00:00
defer copier . Cleanup ( )
2017-05-22 15:21:17 +00:00
copyInstruction , err := copier . createCopyInstruction ( c . SourcesAndDest , "COPY" )
2017-05-07 18:37:46 +00:00
if err != nil {
return err
}
2017-05-22 15:21:17 +00:00
copyInstruction . chownStr = c . Chown
2018-12-18 21:30:08 +00:00
if c . From != "" && copyInstruction . chownStr == "" {
copyInstruction . preserveOwnership = true
}
2022-10-26 16:13:17 +00:00
return d . builder . performCopy ( ctx , d , copyInstruction )
2014-08-05 20:17:40 +00:00
}
2014-08-05 22:41:09 +00:00
2022-10-28 11:40:06 +00:00
func ( d * dispatchRequest ) getImageMount ( ctx context . Context , imageRefOrID string ) ( * imageMount , error ) {
2017-05-22 15:21:17 +00:00
if imageRefOrID == "" {
2017-05-05 22:52:11 +00:00
// TODO: this could return the source in the default case as well?
2017-03-28 01:36:28 +00:00
return nil , nil
}
2017-05-05 22:52:11 +00:00
2017-06-20 00:15:23 +00:00
var localOnly bool
2017-05-22 15:21:17 +00:00
stage , err := d . stages . get ( imageRefOrID )
2017-05-05 22:52:11 +00:00
if err != nil {
return nil , err
}
if stage != nil {
2017-05-22 15:21:17 +00:00
imageRefOrID = stage . Image
2017-06-20 00:15:23 +00:00
localOnly = true
2017-03-28 01:36:28 +00:00
}
2022-10-28 11:40:06 +00:00
return d . builder . imageSources . Get ( ctx , imageRefOrID , localOnly , d . builder . platform )
2017-03-28 01:36:28 +00:00
}
2017-10-03 22:34:33 +00:00
// FROM [--platform=platform] imagename[:tag | @digest] [AS build-stage-name]
2022-10-26 16:13:17 +00:00
func initializeStage ( ctx context . Context , d dispatchRequest , cmd * instructions . Stage ) error {
err := d . builder . imageProber . Reset ( ctx )
if err != nil {
return err
}
2018-06-26 07:39:25 +00:00
2023-05-08 09:57:52 +00:00
var platform * ocispec . Platform
2018-06-26 18:30:19 +00:00
if v := cmd . Platform ; v != "" {
2018-06-26 21:49:33 +00:00
v , err := d . getExpandedString ( d . shlex , v )
if err != nil {
return errors . Wrapf ( err , "failed to process arguments for platform %s" , v )
}
2018-06-26 18:30:19 +00:00
p , err := platforms . Parse ( v )
if err != nil {
return errors . Wrapf ( err , "failed to parse platform %s" , v )
}
2018-06-26 21:49:33 +00:00
platform = & p
2018-06-26 18:30:19 +00:00
}
2018-06-26 21:49:33 +00:00
2022-10-28 11:40:06 +00:00
image , err := d . getFromImage ( ctx , d . shlex , cmd . BaseName , platform )
2017-02-24 22:19:45 +00:00
if err != nil {
return err
}
2017-05-22 15:21:17 +00:00
state := d . state
2017-11-20 16:33:20 +00:00
if err := state . beginStage ( cmd . Name , image ) ; err != nil {
return err
}
2017-05-22 15:21:17 +00:00
if len ( state . runConfig . OnBuild ) > 0 {
triggers := state . runConfig . OnBuild
state . runConfig . OnBuild = nil
2022-10-26 16:13:17 +00:00
return dispatchTriggeredOnBuild ( ctx , d , triggers )
2017-05-05 17:05:25 +00:00
}
2017-05-22 15:21:17 +00:00
return nil
2017-03-28 00:51:42 +00:00
}
2016-01-04 03:45:06 +00:00
2022-10-26 16:13:17 +00:00
func dispatchTriggeredOnBuild ( ctx context . Context , d dispatchRequest , triggers [ ] string ) error {
2017-05-22 15:21:17 +00:00
fmt . Fprintf ( d . builder . Stdout , "# Executing %d build trigger" , len ( triggers ) )
if len ( triggers ) > 1 {
fmt . Fprint ( d . builder . Stdout , "s" )
}
fmt . Fprintln ( d . builder . Stdout )
for _ , trigger := range triggers {
d . state . updateRunConfig ( )
ast , err := parser . Parse ( strings . NewReader ( trigger ) )
if err != nil {
return err
}
if len ( ast . AST . Children ) != 1 {
return errors . New ( "onbuild trigger should be a single expression" )
}
cmd , err := instructions . ParseCommand ( ast . AST . Children [ 0 ] )
if err != nil {
2022-03-18 15:01:18 +00:00
var uiErr * instructions . UnknownInstructionError
2020-06-15 05:28:06 +00:00
if errors . As ( err , & uiErr ) {
2017-05-22 15:21:17 +00:00
buildsFailed . WithValues ( metricsUnknownInstructionError ) . Inc ( )
}
return err
}
2022-10-26 16:13:17 +00:00
err = dispatch ( ctx , d , cmd )
2017-05-22 15:21:17 +00:00
if err != nil {
return err
2017-03-28 00:51:42 +00:00
}
}
2017-05-22 15:21:17 +00:00
return nil
2017-03-28 00:51:42 +00:00
}
2018-06-26 21:49:33 +00:00
func ( d * dispatchRequest ) getExpandedString ( shlex * shell . Lex , str string ) ( string , error ) {
2017-03-28 00:51:42 +00:00
substitutionArgs := [ ] string { }
2017-05-22 15:21:17 +00:00
for key , value := range d . state . buildArgs . GetAllMeta ( ) {
2017-03-28 00:51:42 +00:00
substitutionArgs = append ( substitutionArgs , key + "=" + value )
}
2018-06-26 21:49:33 +00:00
name , err := shlex . ProcessWord ( str , substitutionArgs )
2017-03-28 00:51:42 +00:00
if err != nil {
2017-05-22 15:21:17 +00:00
return "" , err
2017-03-20 17:28:21 +00:00
}
2017-05-22 15:21:17 +00:00
return name , nil
}
2017-10-04 21:26:56 +00:00
2023-05-08 09:57:52 +00:00
func ( d * dispatchRequest ) getImageOrStage ( ctx context . Context , name string , platform * ocispec . Platform ) ( builder . Image , error ) {
2017-06-20 00:15:23 +00:00
var localOnly bool
2017-05-22 15:21:17 +00:00
if im , ok := d . stages . getByName ( name ) ; ok {
name = im . Image
2017-06-20 00:15:23 +00:00
localOnly = true
2017-03-23 01:36:08 +00:00
}
2016-01-04 03:45:06 +00:00
2018-06-26 21:49:33 +00:00
if platform == nil {
2018-07-03 02:31:05 +00:00
platform = d . builder . platform
2018-06-26 21:49:33 +00:00
}
2017-10-04 21:26:56 +00:00
2022-01-25 11:23:05 +00:00
// Windows cannot support a container with no base image.
2017-03-28 00:51:42 +00:00
if name == api . NoBaseImageSpecifier {
2022-01-25 11:23:05 +00:00
// Windows supports scratch. What is not supported is running containers from it.
if runtime . GOOS == "windows" {
return nil , errors . New ( "Windows does not support FROM scratch" )
2018-06-26 21:49:33 +00:00
}
// TODO: scratch should not have an os. It should be nil image.
2022-01-25 11:23:05 +00:00
imageImage := & image . Image { }
if platform != nil {
imageImage . OS = platform . OS
} else {
imageImage . OS = runtime . GOOS
2017-03-28 00:51:42 +00:00
}
2017-08-08 19:43:48 +00:00
return builder . Image ( imageImage ) , nil
2017-03-28 00:51:42 +00:00
}
2022-10-28 11:40:06 +00:00
imageMount , err := d . builder . imageSources . Get ( ctx , name , localOnly , platform )
2017-03-28 01:36:28 +00:00
if err != nil {
return nil , err
}
2017-05-05 22:52:11 +00:00
return imageMount . Image ( ) , nil
2014-08-05 22:41:09 +00:00
}
2022-10-28 11:40:06 +00:00
2023-05-08 09:57:52 +00:00
func ( d * dispatchRequest ) getFromImage ( ctx context . Context , shlex * shell . Lex , basename string , platform * ocispec . Platform ) ( builder . Image , error ) {
2018-07-05 00:23:15 +00:00
name , err := d . getExpandedString ( shlex , basename )
2017-05-22 15:21:17 +00:00
if err != nil {
return nil , err
2017-05-05 17:05:25 +00:00
}
2018-07-05 00:23:15 +00:00
// Empty string is interpreted to FROM scratch by images.GetImageAndReleasableLayer,
// so validate expanded result is not empty.
if name == "" {
return nil , errors . Errorf ( "base name (%s) should not be blank" , basename )
}
2022-10-28 11:40:06 +00:00
return d . getImageOrStage ( ctx , name , platform )
2017-05-05 17:05:25 +00:00
}
2022-10-26 16:13:17 +00:00
func dispatchOnbuild ( ctx context . Context , d dispatchRequest , c * instructions . OnbuildCommand ) error {
2017-05-22 15:21:17 +00:00
d . state . runConfig . OnBuild = append ( d . state . runConfig . OnBuild , c . Expression )
2022-10-26 16:13:17 +00:00
return d . builder . commit ( ctx , d . state , "ONBUILD " + c . Expression )
2014-08-05 22:41:09 +00:00
}
2014-08-07 05:56:44 +00:00
// WORKDIR /tmp
//
// Set the working directory for future RUN/CMD/etc statements.
2022-10-26 16:13:17 +00:00
func dispatchWorkdir ( ctx context . Context , d dispatchRequest , c * instructions . WorkdirCommand ) error {
2017-05-22 15:21:17 +00:00
runConfig := d . state . runConfig
var err error
2018-02-05 22:41:45 +00:00
runConfig . WorkingDir , err = normalizeWorkdir ( d . state . operatingSystem , runConfig . WorkingDir , c . Path )
2016-05-03 01:33:59 +00:00
if err != nil {
return err
2014-08-05 22:41:09 +00:00
}
2014-12-12 18:32:11 +00:00
2016-11-16 23:02:27 +00:00
// For performance reasons, we explicitly do a create/mkdir now
// This avoids having an unnecessary expensive mount/unmount calls
// (on Windows in particular) during each container create.
// Prior to 1.13, the mkdir was deferred and not executed at this step.
2017-05-22 15:21:17 +00:00
if d . builder . disableCommit {
2016-11-16 23:02:27 +00:00
// Don't call back into the daemon if we're going through docker commit --change "WORKDIR /foo".
// We've already updated the runConfig and that's enough.
return nil
}
2016-11-28 23:44:10 +00:00
2017-04-26 21:45:16 +00:00
comment := "WORKDIR " + runConfig . WorkingDir
2018-02-05 22:41:45 +00:00
runConfigWithCommentCmd := copyRunConfig ( runConfig , withCmdCommentString ( comment , d . state . operatingSystem ) )
2018-06-01 07:21:29 +00:00
2022-10-26 16:13:17 +00:00
containerID , err := d . builder . probeAndCreate ( ctx , d . state , runConfigWithCommentCmd )
2017-04-13 22:44:36 +00:00
if err != nil || containerID == "" {
2016-11-28 23:44:10 +00:00
return err
}
2018-06-01 07:21:29 +00:00
2017-05-22 15:21:17 +00:00
if err := d . builder . docker . ContainerCreateWorkdir ( containerID ) ; err != nil {
2016-11-16 23:02:27 +00:00
return err
}
2016-10-29 02:24:37 +00:00
2023-01-12 14:14:12 +00:00
return d . builder . commitContainer ( ctx , d . state , containerID , runConfigWithCommentCmd )
2017-05-22 15:21:17 +00:00
}
2014-08-07 05:56:44 +00:00
// RUN some command yo
//
// run a command and commit the image. Args are automatically prepended with
2016-05-03 20:56:59 +00:00
// the current SHELL which defaults to 'sh -c' under linux or 'cmd /S /C' under
// Windows, in the event there is only one argument The difference in processing:
2014-08-07 05:56:44 +00:00
//
2017-06-20 22:08:58 +00:00
// RUN echo hi # sh -c echo hi (Linux and LCOW)
2015-05-05 15:39:37 +00:00
// RUN echo hi # cmd /S /C echo hi (Windows)
2014-08-07 05:56:44 +00:00
// RUN [ "echo", "hi" ] # echo hi
2022-10-26 16:13:17 +00:00
func dispatchRun ( ctx context . Context , d dispatchRequest , c * instructions . RunCommand ) error {
2017-11-20 16:33:20 +00:00
if ! system . IsOSSupported ( d . state . operatingSystem ) {
return system . ErrNotSupportedOperatingSystem
}
builder: produce error when using unsupported Dockerfile option
With the promotion of the experimental Dockerfile syntax to "stable", the Dockerfile
syntax now includes some options that are supported by BuildKit, but not (yet)
supported in the classic builder.
As a result, parsing a Dockerfile may succeed, but any flag that's known to BuildKit,
but not supported by the classic builder is silently ignored;
$ mkdir buildkit_flags && cd buildkit_flags
$ touch foo.txt
For example, `RUN --mount`:
DOCKER_BUILDKIT=0 docker build --no-cache -f- . <<EOF
FROM busybox
RUN --mount=type=cache,target=/foo echo hello
EOF
Sending build context to Docker daemon 2.095kB
Step 1/2 : FROM busybox
---> 219ee5171f80
Step 2/2 : RUN --mount=type=cache,target=/foo echo hello
---> Running in 022fdb856bc8
hello
Removing intermediate container 022fdb856bc8
---> e9f0988844d1
Successfully built e9f0988844d1
Or `COPY --chmod` (same for `ADD --chmod`):
DOCKER_BUILDKIT=0 docker build --no-cache -f- . <<EOF
FROM busybox
COPY --chmod=0777 /foo.txt /foo.txt
EOF
Sending build context to Docker daemon 2.095kB
Step 1/2 : FROM busybox
---> 219ee5171f80
Step 2/2 : COPY --chmod=0777 /foo.txt /foo.txt
---> 8b7117932a2a
Successfully built 8b7117932a2a
Note that unknown flags still produce and error, for example, the below fails because `--hello` is an unknown flag;
DOCKER_BUILDKIT=0 docker build -<<EOF
FROM busybox
RUN --hello echo hello
EOF
Sending build context to Docker daemon 2.048kB
Error response from daemon: dockerfile parse error line 2: Unknown flag: hello
With this patch applied
----------------------------
With this patch applied, flags that are known in the Dockerfile spec, but are not
supported by the classic builder, produce an error, which includes a link to the
documentation how to enable BuildKit:
DOCKER_BUILDKIT=0 docker build --no-cache -f- . <<EOF
FROM busybox
RUN --mount=type=cache,target=/foo echo hello
EOF
Sending build context to Docker daemon 2.048kB
Step 1/2 : FROM busybox
---> b97242f89c8a
Step 2/2 : RUN --mount=type=cache,target=/foo echo hello
the --mount option requires BuildKit. Refer to https://docs.docker.com/go/buildkit/ to learn how to build images with BuildKit enabled
DOCKER_BUILDKIT=0 docker build --no-cache -f- . <<EOF
FROM busybox
COPY --chmod=0777 /foo.txt /foo.txt
EOF
Sending build context to Docker daemon 2.095kB
Step 1/2 : FROM busybox
---> b97242f89c8a
Step 2/2 : COPY --chmod=0777 /foo.txt /foo.txt
the --chmod option requires BuildKit. Refer to https://docs.docker.com/go/buildkit/ to learn how to build images with BuildKit enabled
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2021-01-21 12:25:18 +00:00
if len ( c . FlagsUsed ) > 0 {
// classic builder RUN currently does not support any flags, so fail on the first one
return errors . Errorf ( "the --%s option requires BuildKit. Refer to https://docs.docker.com/go/buildkit/ to learn how to build images with BuildKit enabled" , c . FlagsUsed [ 0 ] )
}
2017-05-22 15:21:17 +00:00
stateRunConfig := d . state . runConfig
Windows: (WCOW) Generate OCI spec that remote runtime can escape
Signed-off-by: John Howard <jhoward@microsoft.com>
Also fixes https://github.com/moby/moby/issues/22874
This commit is a pre-requisite to moving moby/moby on Windows to using
Containerd for its runtime.
The reason for this is that the interface between moby and containerd
for the runtime is an OCI spec which must be unambigious.
It is the responsibility of the runtime (runhcs in the case of
containerd on Windows) to ensure that arguments are escaped prior
to calling into HCS and onwards to the Win32 CreateProcess call.
Previously, the builder was always escaping arguments which has
led to several bugs in moby. Because the local runtime in
libcontainerd had context of whether or not arguments were escaped,
it was possible to hack around in daemon/oci_windows.go with
knowledge of the context of the call (from builder or not).
With a remote runtime, this is not possible as there's rightly
no context of the caller passed across in the OCI spec. Put another
way, as I put above, the OCI spec must be unambigious.
The other previous limitation (which leads to various subtle bugs)
is that moby is coded entirely from a Linux-centric point of view.
Unfortunately, Windows != Linux. Windows CreateProcess uses a
command line, not an array of arguments. And it has very specific
rules about how to escape a command line. Some interesting reading
links about this are:
https://blogs.msdn.microsoft.com/twistylittlepassagesallalike/2011/04/23/everyone-quotes-command-line-arguments-the-wrong-way/
https://stackoverflow.com/questions/31838469/how-do-i-convert-argv-to-lpcommandline-parameter-of-createprocess
https://docs.microsoft.com/en-us/cpp/cpp/parsing-cpp-command-line-arguments?view=vs-2017
For this reason, the OCI spec has recently been updated to cater
for more natural syntax by including a CommandLine option in
Process.
What does this commit do?
Primary objective is to ensure that the built OCI spec is unambigious.
It changes the builder so that `ArgsEscaped` as commited in a
layer is only controlled by the use of CMD or ENTRYPOINT.
Subsequently, when calling in to create a container from the builder,
if follows a different path to both `docker run` and `docker create`
using the added `ContainerCreateIgnoreImagesArgsEscaped`. This allows
a RUN from the builder to control how to escape in the OCI spec.
It changes the builder so that when shell form is used for RUN,
CMD or ENTRYPOINT, it builds (for WCOW) a more natural command line
using the original as put by the user in the dockerfile, not
the parsed version as a set of args which loses fidelity.
This command line is put into args[0] and `ArgsEscaped` is set
to true for CMD or ENTRYPOINT. A RUN statement does not commit
`ArgsEscaped` to the commited layer regardless or whether shell
or exec form were used.
2019-01-18 00:03:29 +00:00
cmdFromArgs , argsEscaped := resolveCmdLine ( c . ShellDependantCmdLine , stateRunConfig , d . state . operatingSystem , c . Name ( ) , c . String ( ) )
2017-05-22 15:21:17 +00:00
buildArgs := d . state . buildArgs . FilterAllowed ( stateRunConfig . Env )
2014-08-05 22:41:09 +00:00
2017-04-21 19:08:11 +00:00
saveCmd := cmdFromArgs
if len ( buildArgs ) > 0 {
2017-05-22 15:21:17 +00:00
saveCmd = prependEnvOnCmd ( d . state . buildArgs , buildArgs , cmdFromArgs )
2016-01-05 16:48:09 +00:00
}
2017-04-26 21:45:16 +00:00
runConfigForCacheProbe := copyRunConfig ( stateRunConfig ,
2017-04-25 16:21:43 +00:00
withCmd ( saveCmd ) ,
Windows: (WCOW) Generate OCI spec that remote runtime can escape
Signed-off-by: John Howard <jhoward@microsoft.com>
Also fixes https://github.com/moby/moby/issues/22874
This commit is a pre-requisite to moving moby/moby on Windows to using
Containerd for its runtime.
The reason for this is that the interface between moby and containerd
for the runtime is an OCI spec which must be unambigious.
It is the responsibility of the runtime (runhcs in the case of
containerd on Windows) to ensure that arguments are escaped prior
to calling into HCS and onwards to the Win32 CreateProcess call.
Previously, the builder was always escaping arguments which has
led to several bugs in moby. Because the local runtime in
libcontainerd had context of whether or not arguments were escaped,
it was possible to hack around in daemon/oci_windows.go with
knowledge of the context of the call (from builder or not).
With a remote runtime, this is not possible as there's rightly
no context of the caller passed across in the OCI spec. Put another
way, as I put above, the OCI spec must be unambigious.
The other previous limitation (which leads to various subtle bugs)
is that moby is coded entirely from a Linux-centric point of view.
Unfortunately, Windows != Linux. Windows CreateProcess uses a
command line, not an array of arguments. And it has very specific
rules about how to escape a command line. Some interesting reading
links about this are:
https://blogs.msdn.microsoft.com/twistylittlepassagesallalike/2011/04/23/everyone-quotes-command-line-arguments-the-wrong-way/
https://stackoverflow.com/questions/31838469/how-do-i-convert-argv-to-lpcommandline-parameter-of-createprocess
https://docs.microsoft.com/en-us/cpp/cpp/parsing-cpp-command-line-arguments?view=vs-2017
For this reason, the OCI spec has recently been updated to cater
for more natural syntax by including a CommandLine option in
Process.
What does this commit do?
Primary objective is to ensure that the built OCI spec is unambigious.
It changes the builder so that `ArgsEscaped` as commited in a
layer is only controlled by the use of CMD or ENTRYPOINT.
Subsequently, when calling in to create a container from the builder,
if follows a different path to both `docker run` and `docker create`
using the added `ContainerCreateIgnoreImagesArgsEscaped`. This allows
a RUN from the builder to control how to escape in the OCI spec.
It changes the builder so that when shell form is used for RUN,
CMD or ENTRYPOINT, it builds (for WCOW) a more natural command line
using the original as put by the user in the dockerfile, not
the parsed version as a set of args which loses fidelity.
This command line is put into args[0] and `ArgsEscaped` is set
to true for CMD or ENTRYPOINT. A RUN statement does not commit
`ArgsEscaped` to the commited layer regardless or whether shell
or exec form were used.
2019-01-18 00:03:29 +00:00
withArgsEscaped ( argsEscaped ) ,
2017-04-25 16:21:43 +00:00
withEntrypointOverride ( saveCmd , nil ) )
2018-06-01 07:21:29 +00:00
if hit , err := d . builder . probeCache ( d . state , runConfigForCacheProbe ) ; err != nil || hit {
2014-08-05 22:41:09 +00:00
return err
}
2017-04-26 21:45:16 +00:00
runConfig := copyRunConfig ( stateRunConfig ,
2017-04-21 19:08:11 +00:00
withCmd ( cmdFromArgs ) ,
Windows: (WCOW) Generate OCI spec that remote runtime can escape
Signed-off-by: John Howard <jhoward@microsoft.com>
Also fixes https://github.com/moby/moby/issues/22874
This commit is a pre-requisite to moving moby/moby on Windows to using
Containerd for its runtime.
The reason for this is that the interface between moby and containerd
for the runtime is an OCI spec which must be unambigious.
It is the responsibility of the runtime (runhcs in the case of
containerd on Windows) to ensure that arguments are escaped prior
to calling into HCS and onwards to the Win32 CreateProcess call.
Previously, the builder was always escaping arguments which has
led to several bugs in moby. Because the local runtime in
libcontainerd had context of whether or not arguments were escaped,
it was possible to hack around in daemon/oci_windows.go with
knowledge of the context of the call (from builder or not).
With a remote runtime, this is not possible as there's rightly
no context of the caller passed across in the OCI spec. Put another
way, as I put above, the OCI spec must be unambigious.
The other previous limitation (which leads to various subtle bugs)
is that moby is coded entirely from a Linux-centric point of view.
Unfortunately, Windows != Linux. Windows CreateProcess uses a
command line, not an array of arguments. And it has very specific
rules about how to escape a command line. Some interesting reading
links about this are:
https://blogs.msdn.microsoft.com/twistylittlepassagesallalike/2011/04/23/everyone-quotes-command-line-arguments-the-wrong-way/
https://stackoverflow.com/questions/31838469/how-do-i-convert-argv-to-lpcommandline-parameter-of-createprocess
https://docs.microsoft.com/en-us/cpp/cpp/parsing-cpp-command-line-arguments?view=vs-2017
For this reason, the OCI spec has recently been updated to cater
for more natural syntax by including a CommandLine option in
Process.
What does this commit do?
Primary objective is to ensure that the built OCI spec is unambigious.
It changes the builder so that `ArgsEscaped` as commited in a
layer is only controlled by the use of CMD or ENTRYPOINT.
Subsequently, when calling in to create a container from the builder,
if follows a different path to both `docker run` and `docker create`
using the added `ContainerCreateIgnoreImagesArgsEscaped`. This allows
a RUN from the builder to control how to escape in the OCI spec.
It changes the builder so that when shell form is used for RUN,
CMD or ENTRYPOINT, it builds (for WCOW) a more natural command line
using the original as put by the user in the dockerfile, not
the parsed version as a set of args which loses fidelity.
This command line is put into args[0] and `ArgsEscaped` is set
to true for CMD or ENTRYPOINT. A RUN statement does not commit
`ArgsEscaped` to the commited layer regardless or whether shell
or exec form were used.
2019-01-18 00:03:29 +00:00
withArgsEscaped ( argsEscaped ) ,
2017-04-26 21:45:16 +00:00
withEnv ( append ( stateRunConfig . Env , buildArgs ... ) ) ,
2018-07-08 00:36:50 +00:00
withEntrypointOverride ( saveCmd , strslice . StrSlice { "" } ) ,
withoutHealthcheck ( ) )
2017-04-21 19:08:11 +00:00
2022-10-26 16:13:17 +00:00
cID , err := d . builder . create ( ctx , runConfig )
2014-08-05 22:41:09 +00:00
if err != nil {
return err
}
2018-06-01 07:21:29 +00:00
2022-10-28 11:40:06 +00:00
if err := d . builder . containerManager . Run ( ctx , cID , d . builder . Stdout , d . builder . Stderr ) ; err != nil {
2017-04-13 22:44:36 +00:00
if err , ok := err . ( * statusCodeError ) ; ok {
// TODO: change error type, because jsonmessage.JSONError assumes HTTP
Windows: Pass back system errors on container exit
Signed-off-by: John Howard <jhoward@microsoft.com>
While debugging #32838, it was found (https://github.com/moby/moby/issues/32838#issuecomment-356005845) that the utility VM in some circumstances was crashing. Unfortunately, this was silently thrown away, and as far as the build step (also applies to docker run) was concerned, the exit code was zero and the error was thrown away. Windows containers operate differently to containers on Linux, and there can be legitimate system errors during container shutdown after the init process exits. This PR handles this and passes the error all the way back to the client, and correctly causes a build step running a container which hits a system error to fail, rather than blindly trying to keep going, assuming all is good, and get a subsequent failure on a commit.
With this change, assuming an error occurs, here's an example of a failure which previous was reported as a commit error:
```
The command 'powershell -Command $ErrorActionPreference = 'Stop'; $ProgressPreference = 'SilentlyContinue'; Install-WindowsFeature -Name Web-App-Dev ; Install-WindowsFeature -Name ADLDS; Install-WindowsFeature -Name Web-Mgmt-Compat; Install-WindowsFeature -Name Web-Mgmt-Service; Install-WindowsFeature -Name Web-Metabase; Install-WindowsFeature -Name Web-Lgcy-Scripting; Install-WindowsFeature -Name Web-WMI; Install-WindowsFeature -Name Web-WHC; Install-WindowsFeature -Name Web-Scripting-Tools; Install-WindowsFeature -Name Web-Net-Ext45; Install-WindowsFeature -Name Web-ASP; Install-WindowsFeature -Name Web-ISAPI-Ext; Install-WindowsFeature -Name Web-ISAPI-Filter; Install-WindowsFeature -Name Web-Default-Doc; Install-WindowsFeature -Name Web-Dir-Browsing; Install-WindowsFeature -Name Web-Http-Errors; Install-WindowsFeature -Name Web-Static-Content; Install-WindowsFeature -Name Web-Http-Redirect; Install-WindowsFeature -Name Web-DAV-Publishing; Install-WindowsFeature -Name Web-Health; Install-WindowsFeature -Name Web-Http-Logging; Install-WindowsFeature -Name Web-Custom-Logging; Install-WindowsFeature -Name Web-Log-Libraries; Install-WindowsFeature -Name Web-Request-Monitor; Install-WindowsFeature -Name Web-Http-Tracing; Install-WindowsFeature -Name Web-Stat-Compression; Install-WindowsFeature -Name Web-Dyn-Compression; Install-WindowsFeature -Name Web-Security; Install-WindowsFeature -Name Web-Windows-Auth; Install-WindowsFeature -Name Web-Basic-Auth; Install-WindowsFeature -Name Web-Url-Auth; Install-WindowsFeature -Name Web-WebSockets; Install-WindowsFeature -Name Web-AppInit; Install-WindowsFeature -Name NET-WCF-HTTP-Activation45; Install-WindowsFeature -Name NET-WCF-Pipe-Activation45; Install-WindowsFeature -Name NET-WCF-TCP-Activation45;' returned a non-zero code: 4294967295: container shutdown failed: container ba9c65054d42d4830fb25ef55e4ab3287550345aa1a2bb265df4e5bfcd79c78a encountered an error during WaitTimeout: failure in a Windows system call: The compute system exited unexpectedly. (0xc0370106)
```
Without this change, it would be incorrectly reported such as in this comment: https://github.com/moby/moby/issues/32838#issuecomment-309621097
```
Step 3/8 : ADD buildtools C:/buildtools
re-exec error: exit status 1: output: time="2017-06-20T11:37:38+10:00" level=error msg="hcsshim::ImportLayer failed in Win32: The system cannot find the path specified. (0x3) layerId=\\\\?\\C:\\ProgramData\\docker\\windowsfilter\\b41d28c95f98368b73fc192cb9205700e21
6691495c1f9ac79b9b04ec4923ea2 flavour=1 folder=C:\\Windows\\TEMP\\hcs232661915"
hcsshim::ImportLayer failed in Win32: The system cannot find the path specified. (0x3) layerId=\\?\C:\ProgramData\docker\windowsfilter\b41d28c95f98368b73fc192cb9205700e216691495c1f9ac79b9b04ec4923ea2 flavour=1 folder=C:\Windows\TEMP\hcs232661915
```
2018-01-09 19:46:29 +00:00
msg := fmt . Sprintf (
"The command '%s' returned a non-zero code: %d" ,
strings . Join ( runConfig . Cmd , " " ) , err . StatusCode ( ) )
if err . Error ( ) != "" {
msg = fmt . Sprintf ( "%s: %s" , msg , err . Error ( ) )
}
2017-04-13 22:44:36 +00:00
return & jsonmessage . JSONError {
Windows: Pass back system errors on container exit
Signed-off-by: John Howard <jhoward@microsoft.com>
While debugging #32838, it was found (https://github.com/moby/moby/issues/32838#issuecomment-356005845) that the utility VM in some circumstances was crashing. Unfortunately, this was silently thrown away, and as far as the build step (also applies to docker run) was concerned, the exit code was zero and the error was thrown away. Windows containers operate differently to containers on Linux, and there can be legitimate system errors during container shutdown after the init process exits. This PR handles this and passes the error all the way back to the client, and correctly causes a build step running a container which hits a system error to fail, rather than blindly trying to keep going, assuming all is good, and get a subsequent failure on a commit.
With this change, assuming an error occurs, here's an example of a failure which previous was reported as a commit error:
```
The command 'powershell -Command $ErrorActionPreference = 'Stop'; $ProgressPreference = 'SilentlyContinue'; Install-WindowsFeature -Name Web-App-Dev ; Install-WindowsFeature -Name ADLDS; Install-WindowsFeature -Name Web-Mgmt-Compat; Install-WindowsFeature -Name Web-Mgmt-Service; Install-WindowsFeature -Name Web-Metabase; Install-WindowsFeature -Name Web-Lgcy-Scripting; Install-WindowsFeature -Name Web-WMI; Install-WindowsFeature -Name Web-WHC; Install-WindowsFeature -Name Web-Scripting-Tools; Install-WindowsFeature -Name Web-Net-Ext45; Install-WindowsFeature -Name Web-ASP; Install-WindowsFeature -Name Web-ISAPI-Ext; Install-WindowsFeature -Name Web-ISAPI-Filter; Install-WindowsFeature -Name Web-Default-Doc; Install-WindowsFeature -Name Web-Dir-Browsing; Install-WindowsFeature -Name Web-Http-Errors; Install-WindowsFeature -Name Web-Static-Content; Install-WindowsFeature -Name Web-Http-Redirect; Install-WindowsFeature -Name Web-DAV-Publishing; Install-WindowsFeature -Name Web-Health; Install-WindowsFeature -Name Web-Http-Logging; Install-WindowsFeature -Name Web-Custom-Logging; Install-WindowsFeature -Name Web-Log-Libraries; Install-WindowsFeature -Name Web-Request-Monitor; Install-WindowsFeature -Name Web-Http-Tracing; Install-WindowsFeature -Name Web-Stat-Compression; Install-WindowsFeature -Name Web-Dyn-Compression; Install-WindowsFeature -Name Web-Security; Install-WindowsFeature -Name Web-Windows-Auth; Install-WindowsFeature -Name Web-Basic-Auth; Install-WindowsFeature -Name Web-Url-Auth; Install-WindowsFeature -Name Web-WebSockets; Install-WindowsFeature -Name Web-AppInit; Install-WindowsFeature -Name NET-WCF-HTTP-Activation45; Install-WindowsFeature -Name NET-WCF-Pipe-Activation45; Install-WindowsFeature -Name NET-WCF-TCP-Activation45;' returned a non-zero code: 4294967295: container shutdown failed: container ba9c65054d42d4830fb25ef55e4ab3287550345aa1a2bb265df4e5bfcd79c78a encountered an error during WaitTimeout: failure in a Windows system call: The compute system exited unexpectedly. (0xc0370106)
```
Without this change, it would be incorrectly reported such as in this comment: https://github.com/moby/moby/issues/32838#issuecomment-309621097
```
Step 3/8 : ADD buildtools C:/buildtools
re-exec error: exit status 1: output: time="2017-06-20T11:37:38+10:00" level=error msg="hcsshim::ImportLayer failed in Win32: The system cannot find the path specified. (0x3) layerId=\\\\?\\C:\\ProgramData\\docker\\windowsfilter\\b41d28c95f98368b73fc192cb9205700e21
6691495c1f9ac79b9b04ec4923ea2 flavour=1 folder=C:\\Windows\\TEMP\\hcs232661915"
hcsshim::ImportLayer failed in Win32: The system cannot find the path specified. (0x3) layerId=\\?\C:\ProgramData\docker\windowsfilter\b41d28c95f98368b73fc192cb9205700e216691495c1f9ac79b9b04ec4923ea2 flavour=1 folder=C:\Windows\TEMP\hcs232661915
```
2018-01-09 19:46:29 +00:00
Message : msg ,
Code : err . StatusCode ( ) ,
2017-04-13 22:44:36 +00:00
}
}
2014-08-05 22:41:09 +00:00
return err
}
2014-11-14 18:59:14 +00:00
Windows: (WCOW) Generate OCI spec that remote runtime can escape
Signed-off-by: John Howard <jhoward@microsoft.com>
Also fixes https://github.com/moby/moby/issues/22874
This commit is a pre-requisite to moving moby/moby on Windows to using
Containerd for its runtime.
The reason for this is that the interface between moby and containerd
for the runtime is an OCI spec which must be unambigious.
It is the responsibility of the runtime (runhcs in the case of
containerd on Windows) to ensure that arguments are escaped prior
to calling into HCS and onwards to the Win32 CreateProcess call.
Previously, the builder was always escaping arguments which has
led to several bugs in moby. Because the local runtime in
libcontainerd had context of whether or not arguments were escaped,
it was possible to hack around in daemon/oci_windows.go with
knowledge of the context of the call (from builder or not).
With a remote runtime, this is not possible as there's rightly
no context of the caller passed across in the OCI spec. Put another
way, as I put above, the OCI spec must be unambigious.
The other previous limitation (which leads to various subtle bugs)
is that moby is coded entirely from a Linux-centric point of view.
Unfortunately, Windows != Linux. Windows CreateProcess uses a
command line, not an array of arguments. And it has very specific
rules about how to escape a command line. Some interesting reading
links about this are:
https://blogs.msdn.microsoft.com/twistylittlepassagesallalike/2011/04/23/everyone-quotes-command-line-arguments-the-wrong-way/
https://stackoverflow.com/questions/31838469/how-do-i-convert-argv-to-lpcommandline-parameter-of-createprocess
https://docs.microsoft.com/en-us/cpp/cpp/parsing-cpp-command-line-arguments?view=vs-2017
For this reason, the OCI spec has recently been updated to cater
for more natural syntax by including a CommandLine option in
Process.
What does this commit do?
Primary objective is to ensure that the built OCI spec is unambigious.
It changes the builder so that `ArgsEscaped` as commited in a
layer is only controlled by the use of CMD or ENTRYPOINT.
Subsequently, when calling in to create a container from the builder,
if follows a different path to both `docker run` and `docker create`
using the added `ContainerCreateIgnoreImagesArgsEscaped`. This allows
a RUN from the builder to control how to escape in the OCI spec.
It changes the builder so that when shell form is used for RUN,
CMD or ENTRYPOINT, it builds (for WCOW) a more natural command line
using the original as put by the user in the dockerfile, not
the parsed version as a set of args which loses fidelity.
This command line is put into args[0] and `ArgsEscaped` is set
to true for CMD or ENTRYPOINT. A RUN statement does not commit
`ArgsEscaped` to the commited layer regardless or whether shell
or exec form were used.
2019-01-18 00:03:29 +00:00
// Don't persist the argsEscaped value in the committed image. Use the original
// from previous build steps (only CMD and ENTRYPOINT persist this).
if d . state . operatingSystem == "windows" {
runConfigForCacheProbe . ArgsEscaped = stateRunConfig . ArgsEscaped
}
2023-01-12 14:14:12 +00:00
return d . builder . commitContainer ( ctx , d . state , cID , runConfigForCacheProbe )
2014-08-05 22:41:09 +00:00
}
2017-04-21 19:08:11 +00:00
// Derive the command to use for probeCache() and to commit in this container.
// Note that we only do this if there are any build-time env vars. Also, we
// use the special argument "|#" at the start of the args array. This will
// avoid conflicts with any RUN command since commands can not
// start with | (vertical bar). The "#" (number of build envs) is there to
// help ensure proper cache matches. We don't want a RUN command
// that starts with "foo=abc" to be considered part of a build-time env var.
//
// remove any unreferenced built-in args from the environment variables.
// These args are transparent so resulting image should be the same regardless
// of the value.
2018-05-07 17:49:13 +00:00
func prependEnvOnCmd ( buildArgs * BuildArgs , buildArgVars [ ] string , cmd strslice . StrSlice ) strslice . StrSlice {
2022-10-31 16:09:57 +00:00
tmpBuildEnv := make ( [ ] string , 0 , len ( buildArgVars ) )
2017-04-28 16:49:50 +00:00
for _ , env := range buildArgVars {
2022-10-31 16:09:57 +00:00
key , _ , _ := strings . Cut ( env , "=" )
2017-05-09 15:25:33 +00:00
if buildArgs . IsReferencedOrNotBuiltin ( key ) {
2017-04-28 16:49:50 +00:00
tmpBuildEnv = append ( tmpBuildEnv , env )
}
}
sort . Strings ( tmpBuildEnv )
tmpEnv := append ( [ ] string { fmt . Sprintf ( "|%d" , len ( tmpBuildEnv ) ) } , tmpBuildEnv ... )
2022-10-31 16:09:57 +00:00
return append ( tmpEnv , cmd ... )
2017-04-28 16:49:50 +00:00
}
2014-08-07 05:56:44 +00:00
// CMD foo
//
// Set the default command to run in the container (which may be empty).
// Argument handling is the same as RUN.
2022-10-26 16:13:17 +00:00
func dispatchCmd ( ctx context . Context , d dispatchRequest , c * instructions . CmdCommand ) error {
2017-05-22 15:21:17 +00:00
runConfig := d . state . runConfig
Windows: (WCOW) Generate OCI spec that remote runtime can escape
Signed-off-by: John Howard <jhoward@microsoft.com>
Also fixes https://github.com/moby/moby/issues/22874
This commit is a pre-requisite to moving moby/moby on Windows to using
Containerd for its runtime.
The reason for this is that the interface between moby and containerd
for the runtime is an OCI spec which must be unambigious.
It is the responsibility of the runtime (runhcs in the case of
containerd on Windows) to ensure that arguments are escaped prior
to calling into HCS and onwards to the Win32 CreateProcess call.
Previously, the builder was always escaping arguments which has
led to several bugs in moby. Because the local runtime in
libcontainerd had context of whether or not arguments were escaped,
it was possible to hack around in daemon/oci_windows.go with
knowledge of the context of the call (from builder or not).
With a remote runtime, this is not possible as there's rightly
no context of the caller passed across in the OCI spec. Put another
way, as I put above, the OCI spec must be unambigious.
The other previous limitation (which leads to various subtle bugs)
is that moby is coded entirely from a Linux-centric point of view.
Unfortunately, Windows != Linux. Windows CreateProcess uses a
command line, not an array of arguments. And it has very specific
rules about how to escape a command line. Some interesting reading
links about this are:
https://blogs.msdn.microsoft.com/twistylittlepassagesallalike/2011/04/23/everyone-quotes-command-line-arguments-the-wrong-way/
https://stackoverflow.com/questions/31838469/how-do-i-convert-argv-to-lpcommandline-parameter-of-createprocess
https://docs.microsoft.com/en-us/cpp/cpp/parsing-cpp-command-line-arguments?view=vs-2017
For this reason, the OCI spec has recently been updated to cater
for more natural syntax by including a CommandLine option in
Process.
What does this commit do?
Primary objective is to ensure that the built OCI spec is unambigious.
It changes the builder so that `ArgsEscaped` as commited in a
layer is only controlled by the use of CMD or ENTRYPOINT.
Subsequently, when calling in to create a container from the builder,
if follows a different path to both `docker run` and `docker create`
using the added `ContainerCreateIgnoreImagesArgsEscaped`. This allows
a RUN from the builder to control how to escape in the OCI spec.
It changes the builder so that when shell form is used for RUN,
CMD or ENTRYPOINT, it builds (for WCOW) a more natural command line
using the original as put by the user in the dockerfile, not
the parsed version as a set of args which loses fidelity.
This command line is put into args[0] and `ArgsEscaped` is set
to true for CMD or ENTRYPOINT. A RUN statement does not commit
`ArgsEscaped` to the commited layer regardless or whether shell
or exec form were used.
2019-01-18 00:03:29 +00:00
cmd , argsEscaped := resolveCmdLine ( c . ShellDependantCmdLine , runConfig , d . state . operatingSystem , c . Name ( ) , c . String ( ) )
// We warn here as Windows shell processing operates differently to Linux.
// Linux: /bin/sh -c "echo hello" world --> hello
// Windows: cmd /s /c "echo hello" world --> hello world
if d . state . operatingSystem == "windows" &&
len ( runConfig . Entrypoint ) > 0 &&
d . state . runConfig . ArgsEscaped != argsEscaped {
fmt . Fprintf ( d . builder . Stderr , " ---> [Warning] Shell-form ENTRYPOINT and exec-form CMD may have unexpected results\n" )
}
2017-05-22 15:21:17 +00:00
runConfig . Cmd = cmd
Windows: (WCOW) Generate OCI spec that remote runtime can escape
Signed-off-by: John Howard <jhoward@microsoft.com>
Also fixes https://github.com/moby/moby/issues/22874
This commit is a pre-requisite to moving moby/moby on Windows to using
Containerd for its runtime.
The reason for this is that the interface between moby and containerd
for the runtime is an OCI spec which must be unambigious.
It is the responsibility of the runtime (runhcs in the case of
containerd on Windows) to ensure that arguments are escaped prior
to calling into HCS and onwards to the Win32 CreateProcess call.
Previously, the builder was always escaping arguments which has
led to several bugs in moby. Because the local runtime in
libcontainerd had context of whether or not arguments were escaped,
it was possible to hack around in daemon/oci_windows.go with
knowledge of the context of the call (from builder or not).
With a remote runtime, this is not possible as there's rightly
no context of the caller passed across in the OCI spec. Put another
way, as I put above, the OCI spec must be unambigious.
The other previous limitation (which leads to various subtle bugs)
is that moby is coded entirely from a Linux-centric point of view.
Unfortunately, Windows != Linux. Windows CreateProcess uses a
command line, not an array of arguments. And it has very specific
rules about how to escape a command line. Some interesting reading
links about this are:
https://blogs.msdn.microsoft.com/twistylittlepassagesallalike/2011/04/23/everyone-quotes-command-line-arguments-the-wrong-way/
https://stackoverflow.com/questions/31838469/how-do-i-convert-argv-to-lpcommandline-parameter-of-createprocess
https://docs.microsoft.com/en-us/cpp/cpp/parsing-cpp-command-line-arguments?view=vs-2017
For this reason, the OCI spec has recently been updated to cater
for more natural syntax by including a CommandLine option in
Process.
What does this commit do?
Primary objective is to ensure that the built OCI spec is unambigious.
It changes the builder so that `ArgsEscaped` as commited in a
layer is only controlled by the use of CMD or ENTRYPOINT.
Subsequently, when calling in to create a container from the builder,
if follows a different path to both `docker run` and `docker create`
using the added `ContainerCreateIgnoreImagesArgsEscaped`. This allows
a RUN from the builder to control how to escape in the OCI spec.
It changes the builder so that when shell form is used for RUN,
CMD or ENTRYPOINT, it builds (for WCOW) a more natural command line
using the original as put by the user in the dockerfile, not
the parsed version as a set of args which loses fidelity.
This command line is put into args[0] and `ArgsEscaped` is set
to true for CMD or ENTRYPOINT. A RUN statement does not commit
`ArgsEscaped` to the commited layer regardless or whether shell
or exec form were used.
2019-01-18 00:03:29 +00:00
runConfig . ArgsEscaped = argsEscaped
2015-04-11 00:05:21 +00:00
2022-10-26 16:13:17 +00:00
if err := d . builder . commit ( ctx , d . state , fmt . Sprintf ( "CMD %q" , cmd ) ) ; err != nil {
2014-08-05 22:41:09 +00:00
return err
}
2017-05-22 15:21:17 +00:00
if len ( c . ShellDependantCmdLine . CmdLine ) != 0 {
d . state . cmdSet = true
2014-08-30 11:34:09 +00:00
}
2014-08-05 22:41:09 +00:00
return nil
}
2016-04-18 09:48:13 +00:00
// HEALTHCHECK foo
//
// Set the default healthcheck command to run in the container (which may be empty).
// Argument handling is the same as RUN.
2022-10-26 16:13:17 +00:00
func dispatchHealthcheck ( ctx context . Context , d dispatchRequest , c * instructions . HealthCheckCommand ) error {
2017-05-22 15:21:17 +00:00
runConfig := d . state . runConfig
if runConfig . Healthcheck != nil {
oldCmd := runConfig . Healthcheck . Test
if len ( oldCmd ) > 0 && oldCmd [ 0 ] != "NONE" {
fmt . Fprintf ( d . builder . Stdout , "Note: overriding previous HEALTHCHECK: %v\n" , oldCmd )
2016-04-18 09:48:13 +00:00
}
}
2017-05-22 15:21:17 +00:00
runConfig . Healthcheck = c . Health
2022-10-26 16:13:17 +00:00
return d . builder . commit ( ctx , d . state , fmt . Sprintf ( "HEALTHCHECK %q" , runConfig . Healthcheck ) )
2016-04-18 09:48:13 +00:00
}
2014-08-07 05:56:44 +00:00
// ENTRYPOINT /usr/sbin/nginx
//
2016-05-03 20:56:59 +00:00
// Set the entrypoint to /usr/sbin/nginx. Will accept the CMD as the arguments
// to /usr/sbin/nginx. Uses the default shell if not in JSON format.
2014-08-07 05:56:44 +00:00
//
2017-04-11 18:34:05 +00:00
// Handles command processing similar to CMD and RUN, only req.runConfig.Entrypoint
2017-04-13 18:37:32 +00:00
// is initialized at newBuilder time instead of through argument parsing.
2022-10-26 16:13:17 +00:00
func dispatchEntrypoint ( ctx context . Context , d dispatchRequest , c * instructions . EntrypointCommand ) error {
2017-05-22 15:21:17 +00:00
runConfig := d . state . runConfig
Windows: (WCOW) Generate OCI spec that remote runtime can escape
Signed-off-by: John Howard <jhoward@microsoft.com>
Also fixes https://github.com/moby/moby/issues/22874
This commit is a pre-requisite to moving moby/moby on Windows to using
Containerd for its runtime.
The reason for this is that the interface between moby and containerd
for the runtime is an OCI spec which must be unambigious.
It is the responsibility of the runtime (runhcs in the case of
containerd on Windows) to ensure that arguments are escaped prior
to calling into HCS and onwards to the Win32 CreateProcess call.
Previously, the builder was always escaping arguments which has
led to several bugs in moby. Because the local runtime in
libcontainerd had context of whether or not arguments were escaped,
it was possible to hack around in daemon/oci_windows.go with
knowledge of the context of the call (from builder or not).
With a remote runtime, this is not possible as there's rightly
no context of the caller passed across in the OCI spec. Put another
way, as I put above, the OCI spec must be unambigious.
The other previous limitation (which leads to various subtle bugs)
is that moby is coded entirely from a Linux-centric point of view.
Unfortunately, Windows != Linux. Windows CreateProcess uses a
command line, not an array of arguments. And it has very specific
rules about how to escape a command line. Some interesting reading
links about this are:
https://blogs.msdn.microsoft.com/twistylittlepassagesallalike/2011/04/23/everyone-quotes-command-line-arguments-the-wrong-way/
https://stackoverflow.com/questions/31838469/how-do-i-convert-argv-to-lpcommandline-parameter-of-createprocess
https://docs.microsoft.com/en-us/cpp/cpp/parsing-cpp-command-line-arguments?view=vs-2017
For this reason, the OCI spec has recently been updated to cater
for more natural syntax by including a CommandLine option in
Process.
What does this commit do?
Primary objective is to ensure that the built OCI spec is unambigious.
It changes the builder so that `ArgsEscaped` as commited in a
layer is only controlled by the use of CMD or ENTRYPOINT.
Subsequently, when calling in to create a container from the builder,
if follows a different path to both `docker run` and `docker create`
using the added `ContainerCreateIgnoreImagesArgsEscaped`. This allows
a RUN from the builder to control how to escape in the OCI spec.
It changes the builder so that when shell form is used for RUN,
CMD or ENTRYPOINT, it builds (for WCOW) a more natural command line
using the original as put by the user in the dockerfile, not
the parsed version as a set of args which loses fidelity.
This command line is put into args[0] and `ArgsEscaped` is set
to true for CMD or ENTRYPOINT. A RUN statement does not commit
`ArgsEscaped` to the commited layer regardless or whether shell
or exec form were used.
2019-01-18 00:03:29 +00:00
cmd , argsEscaped := resolveCmdLine ( c . ShellDependantCmdLine , runConfig , d . state . operatingSystem , c . Name ( ) , c . String ( ) )
// This warning is a little more complex than in dispatchCmd(), as the Windows base images (similar
// universally to almost every Linux image out there) have a single .Cmd field populated so that
// `docker run --rm image` starts the default shell which would typically be sh on Linux,
// or cmd on Windows. The catch to this is that if a dockerfile had `CMD ["c:\\windows\\system32\\cmd.exe"]`,
// we wouldn't be able to tell the difference. However, that would be highly unlikely, and besides, this
// is only trying to give a helpful warning of possibly unexpected results.
if d . state . operatingSystem == "windows" &&
d . state . runConfig . ArgsEscaped != argsEscaped &&
( ( len ( runConfig . Cmd ) == 1 && strings . ToLower ( runConfig . Cmd [ 0 ] ) != ` c:\windows\system32\cmd.exe ` && len ( runConfig . Shell ) == 0 ) || ( len ( runConfig . Cmd ) > 1 ) ) {
fmt . Fprintf ( d . builder . Stderr , " ---> [Warning] Shell-form CMD and exec-form ENTRYPOINT may have unexpected results\n" )
}
2017-05-22 15:21:17 +00:00
runConfig . Entrypoint = cmd
Windows: (WCOW) Generate OCI spec that remote runtime can escape
Signed-off-by: John Howard <jhoward@microsoft.com>
Also fixes https://github.com/moby/moby/issues/22874
This commit is a pre-requisite to moving moby/moby on Windows to using
Containerd for its runtime.
The reason for this is that the interface between moby and containerd
for the runtime is an OCI spec which must be unambigious.
It is the responsibility of the runtime (runhcs in the case of
containerd on Windows) to ensure that arguments are escaped prior
to calling into HCS and onwards to the Win32 CreateProcess call.
Previously, the builder was always escaping arguments which has
led to several bugs in moby. Because the local runtime in
libcontainerd had context of whether or not arguments were escaped,
it was possible to hack around in daemon/oci_windows.go with
knowledge of the context of the call (from builder or not).
With a remote runtime, this is not possible as there's rightly
no context of the caller passed across in the OCI spec. Put another
way, as I put above, the OCI spec must be unambigious.
The other previous limitation (which leads to various subtle bugs)
is that moby is coded entirely from a Linux-centric point of view.
Unfortunately, Windows != Linux. Windows CreateProcess uses a
command line, not an array of arguments. And it has very specific
rules about how to escape a command line. Some interesting reading
links about this are:
https://blogs.msdn.microsoft.com/twistylittlepassagesallalike/2011/04/23/everyone-quotes-command-line-arguments-the-wrong-way/
https://stackoverflow.com/questions/31838469/how-do-i-convert-argv-to-lpcommandline-parameter-of-createprocess
https://docs.microsoft.com/en-us/cpp/cpp/parsing-cpp-command-line-arguments?view=vs-2017
For this reason, the OCI spec has recently been updated to cater
for more natural syntax by including a CommandLine option in
Process.
What does this commit do?
Primary objective is to ensure that the built OCI spec is unambigious.
It changes the builder so that `ArgsEscaped` as commited in a
layer is only controlled by the use of CMD or ENTRYPOINT.
Subsequently, when calling in to create a container from the builder,
if follows a different path to both `docker run` and `docker create`
using the added `ContainerCreateIgnoreImagesArgsEscaped`. This allows
a RUN from the builder to control how to escape in the OCI spec.
It changes the builder so that when shell form is used for RUN,
CMD or ENTRYPOINT, it builds (for WCOW) a more natural command line
using the original as put by the user in the dockerfile, not
the parsed version as a set of args which loses fidelity.
This command line is put into args[0] and `ArgsEscaped` is set
to true for CMD or ENTRYPOINT. A RUN statement does not commit
`ArgsEscaped` to the commited layer regardless or whether shell
or exec form were used.
2019-01-18 00:03:29 +00:00
runConfig . ArgsEscaped = argsEscaped
2017-05-22 15:21:17 +00:00
if ! d . state . cmdSet {
2017-04-26 21:45:16 +00:00
runConfig . Cmd = nil
2014-08-05 22:41:09 +00:00
}
2014-08-13 10:07:41 +00:00
2022-10-26 16:13:17 +00:00
return d . builder . commit ( ctx , d . state , fmt . Sprintf ( "ENTRYPOINT %q" , runConfig . Entrypoint ) )
2014-08-05 22:41:09 +00:00
}
2014-08-07 05:56:44 +00:00
// EXPOSE 6667/tcp 7000/tcp
//
// Expose ports for links and port mappings. This all ends up in
2017-04-11 18:34:05 +00:00
// req.runConfig.ExposedPorts for runconfig.
2022-10-26 16:13:17 +00:00
func dispatchExpose ( ctx context . Context , d dispatchRequest , c * instructions . ExposeCommand , envs [ ] string ) error {
2017-05-22 15:21:17 +00:00
// custom multi word expansion
// expose $FOO with FOO="80 443" is expanded as EXPOSE [80,443]. This is the only command supporting word to words expansion
// so the word processing has been de-generalized
ports := [ ] string { }
for _ , p := range c . Ports {
ps , err := d . shlex . ProcessWords ( p , envs )
if err != nil {
return err
}
ports = append ( ports , ps ... )
2015-02-04 17:34:25 +00:00
}
2017-05-22 15:21:17 +00:00
c . Ports = ports
2015-02-04 17:34:25 +00:00
2017-05-22 15:21:17 +00:00
ps , _ , err := nat . ParsePortSpecs ( ports )
if err != nil {
2015-05-05 21:27:42 +00:00
return err
}
2017-05-22 15:21:17 +00:00
if d . state . runConfig . ExposedPorts == nil {
d . state . runConfig . ExposedPorts = make ( nat . PortSet )
2014-08-05 22:41:09 +00:00
}
2017-05-22 15:21:17 +00:00
for p := range ps {
d . state . runConfig . ExposedPorts [ p ] = struct { } { }
2014-08-05 22:41:09 +00:00
}
2022-10-26 16:13:17 +00:00
return d . builder . commit ( ctx , d . state , "EXPOSE " + strings . Join ( c . Ports , " " ) )
2014-08-05 22:41:09 +00:00
}
2014-08-07 05:56:44 +00:00
// USER foo
//
// Set the user to 'foo' for future commands and when running the
// ENTRYPOINT/CMD at container run time.
2022-10-26 16:13:17 +00:00
func dispatchUser ( ctx context . Context , d dispatchRequest , c * instructions . UserCommand ) error {
2017-05-22 15:21:17 +00:00
d . state . runConfig . User = c . User
2022-10-26 16:13:17 +00:00
return d . builder . commit ( ctx , d . state , fmt . Sprintf ( "USER %v" , c . User ) )
2014-08-05 22:41:09 +00:00
}
2014-08-07 05:56:44 +00:00
// VOLUME /foo
//
2014-09-11 13:27:51 +00:00
// Expose the volume /foo for use. Will also accept the JSON array form.
2022-10-26 16:13:17 +00:00
func dispatchVolume ( ctx context . Context , d dispatchRequest , c * instructions . VolumeCommand ) error {
2017-05-22 15:21:17 +00:00
if d . state . runConfig . Volumes == nil {
d . state . runConfig . Volumes = map [ string ] struct { } { }
2015-05-05 21:27:42 +00:00
}
2017-05-22 15:21:17 +00:00
for _ , v := range c . Volumes {
2015-03-21 04:39:49 +00:00
if v == "" {
2016-12-25 06:37:31 +00:00
return errors . New ( "VOLUME specified can not be an empty string" )
2015-03-21 04:39:49 +00:00
}
2017-05-22 15:21:17 +00:00
d . state . runConfig . Volumes [ v ] = struct { } { }
2014-08-05 22:41:09 +00:00
}
2022-10-26 16:13:17 +00:00
return d . builder . commit ( ctx , d . state , fmt . Sprintf ( "VOLUME %v" , c . Volumes ) )
2014-08-05 22:41:09 +00:00
}
2015-08-18 17:30:44 +00:00
// STOPSIGNAL signal
//
// Set the signal that will be used to kill the container.
2022-10-26 16:13:17 +00:00
func dispatchStopSignal ( ctx context . Context , d dispatchRequest , c * instructions . StopSignalCommand ) error {
2017-05-22 15:21:17 +00:00
_ , err := signal . ParseSignal ( c . Signal )
2015-08-18 17:30:44 +00:00
if err != nil {
2017-11-29 04:09:37 +00:00
return errdefs . InvalidParameter ( err )
2015-08-18 17:30:44 +00:00
}
2017-05-22 15:21:17 +00:00
d . state . runConfig . StopSignal = c . Signal
2022-10-26 16:13:17 +00:00
return d . builder . commit ( ctx , d . state , fmt . Sprintf ( "STOPSIGNAL %v" , c . Signal ) )
2015-08-18 17:30:44 +00:00
}
2014-11-14 18:59:14 +00:00
// ARG name[=value]
//
// Adds the variable foo to the trusted list of variables that can be passed
2017-02-16 15:56:53 +00:00
// to builder using the --build-arg flag for expansion/substitution or passing to 'run'.
2014-11-14 18:59:14 +00:00
// Dockerfile author may optionally set a default value of this variable.
2022-10-26 16:13:17 +00:00
func dispatchArg ( ctx context . Context , d dispatchRequest , c * instructions . ArgCommand ) error {
2020-11-13 02:14:57 +00:00
var commitStr strings . Builder
commitStr . WriteString ( "ARG " )
for i , arg := range c . Args {
if i > 0 {
commitStr . WriteString ( " " )
}
commitStr . WriteString ( arg . Key )
if arg . Value != nil {
commitStr . WriteString ( "=" )
commitStr . WriteString ( * arg . Value )
}
d . state . buildArgs . AddArg ( arg . Key , arg . Value )
2014-11-14 18:59:14 +00:00
}
2022-10-26 16:13:17 +00:00
return d . builder . commit ( ctx , d . state , commitStr . String ( ) )
2014-11-14 18:59:14 +00:00
}
Remove static errors from errors package.
Moving all strings to the errors package wasn't a good idea after all.
Our custom implementation of Go errors predates everything that's nice
and good about working with errors in Go. Take as an example what we
have to do to get an error message:
```go
func GetErrorMessage(err error) string {
switch err.(type) {
case errcode.Error:
e, _ := err.(errcode.Error)
return e.Message
case errcode.ErrorCode:
ec, _ := err.(errcode.ErrorCode)
return ec.Message()
default:
return err.Error()
}
}
```
This goes against every good practice for Go development. The language already provides a simple, intuitive and standard way to get error messages, that is calling the `Error()` method from an error. Reinventing the error interface is a mistake.
Our custom implementation also makes very hard to reason about errors, another nice thing about Go. I found several (>10) error declarations that we don't use anywhere. This is a clear sign about how little we know about the errors we return. I also found several error usages where the number of arguments was different than the parameters declared in the error, another clear example of how difficult is to reason about errors.
Moreover, our custom implementation didn't really make easier for people to return custom HTTP status code depending on the errors. Again, it's hard to reason about when to set custom codes and how. Take an example what we have to do to extract the message and status code from an error before returning a response from the API:
```go
switch err.(type) {
case errcode.ErrorCode:
daError, _ := err.(errcode.ErrorCode)
statusCode = daError.Descriptor().HTTPStatusCode
errMsg = daError.Message()
case errcode.Error:
// For reference, if you're looking for a particular error
// then you can do something like :
// import ( derr "github.com/docker/docker/errors" )
// if daError.ErrorCode() == derr.ErrorCodeNoSuchContainer { ... }
daError, _ := err.(errcode.Error)
statusCode = daError.ErrorCode().Descriptor().HTTPStatusCode
errMsg = daError.Message
default:
// This part of will be removed once we've
// converted everything over to use the errcode package
// FIXME: this is brittle and should not be necessary.
// If we need to differentiate between different possible error types,
// we should create appropriate error types with clearly defined meaning
errStr := strings.ToLower(err.Error())
for keyword, status := range map[string]int{
"not found": http.StatusNotFound,
"no such": http.StatusNotFound,
"bad parameter": http.StatusBadRequest,
"conflict": http.StatusConflict,
"impossible": http.StatusNotAcceptable,
"wrong login/password": http.StatusUnauthorized,
"hasn't been activated": http.StatusForbidden,
} {
if strings.Contains(errStr, keyword) {
statusCode = status
break
}
}
}
```
You can notice two things in that code:
1. We have to explain how errors work, because our implementation goes against how easy to use Go errors are.
2. At no moment we arrived to remove that `switch` statement that was the original reason to use our custom implementation.
This change removes all our status errors from the errors package and puts them back in their specific contexts.
IT puts the messages back with their contexts. That way, we know right away when errors used and how to generate their messages.
It uses custom interfaces to reason about errors. Errors that need to response with a custom status code MUST implementent this simple interface:
```go
type errorWithStatus interface {
HTTPErrorStatusCode() int
}
```
This interface is very straightforward to implement. It also preserves Go errors real behavior, getting the message is as simple as using the `Error()` method.
I included helper functions to generate errors that use custom status code in `errors/errors.go`.
By doing this, we remove the hard dependency we have eeverywhere to our custom errors package. Yes, you can use it as a helper to generate error, but it's still very easy to generate errors without it.
Please, read this fantastic blog post about errors in Go: http://dave.cheney.net/2014/12/24/inspecting-errors
Signed-off-by: David Calavera <david.calavera@gmail.com>
2016-02-25 15:53:35 +00:00
2016-05-03 20:56:59 +00:00
// SHELL powershell -command
//
// Set the non-default shell to use.
2022-10-26 16:13:17 +00:00
func dispatchShell ( ctx context . Context , d dispatchRequest , c * instructions . ShellCommand ) error {
2017-05-22 15:21:17 +00:00
d . state . runConfig . Shell = c . Shell
2022-10-26 16:13:17 +00:00
return d . builder . commit ( ctx , d . state , fmt . Sprintf ( "SHELL %v" , d . state . runConfig . Shell ) )
Remove static errors from errors package.
Moving all strings to the errors package wasn't a good idea after all.
Our custom implementation of Go errors predates everything that's nice
and good about working with errors in Go. Take as an example what we
have to do to get an error message:
```go
func GetErrorMessage(err error) string {
switch err.(type) {
case errcode.Error:
e, _ := err.(errcode.Error)
return e.Message
case errcode.ErrorCode:
ec, _ := err.(errcode.ErrorCode)
return ec.Message()
default:
return err.Error()
}
}
```
This goes against every good practice for Go development. The language already provides a simple, intuitive and standard way to get error messages, that is calling the `Error()` method from an error. Reinventing the error interface is a mistake.
Our custom implementation also makes very hard to reason about errors, another nice thing about Go. I found several (>10) error declarations that we don't use anywhere. This is a clear sign about how little we know about the errors we return. I also found several error usages where the number of arguments was different than the parameters declared in the error, another clear example of how difficult is to reason about errors.
Moreover, our custom implementation didn't really make easier for people to return custom HTTP status code depending on the errors. Again, it's hard to reason about when to set custom codes and how. Take an example what we have to do to extract the message and status code from an error before returning a response from the API:
```go
switch err.(type) {
case errcode.ErrorCode:
daError, _ := err.(errcode.ErrorCode)
statusCode = daError.Descriptor().HTTPStatusCode
errMsg = daError.Message()
case errcode.Error:
// For reference, if you're looking for a particular error
// then you can do something like :
// import ( derr "github.com/docker/docker/errors" )
// if daError.ErrorCode() == derr.ErrorCodeNoSuchContainer { ... }
daError, _ := err.(errcode.Error)
statusCode = daError.ErrorCode().Descriptor().HTTPStatusCode
errMsg = daError.Message
default:
// This part of will be removed once we've
// converted everything over to use the errcode package
// FIXME: this is brittle and should not be necessary.
// If we need to differentiate between different possible error types,
// we should create appropriate error types with clearly defined meaning
errStr := strings.ToLower(err.Error())
for keyword, status := range map[string]int{
"not found": http.StatusNotFound,
"no such": http.StatusNotFound,
"bad parameter": http.StatusBadRequest,
"conflict": http.StatusConflict,
"impossible": http.StatusNotAcceptable,
"wrong login/password": http.StatusUnauthorized,
"hasn't been activated": http.StatusForbidden,
} {
if strings.Contains(errStr, keyword) {
statusCode = status
break
}
}
}
```
You can notice two things in that code:
1. We have to explain how errors work, because our implementation goes against how easy to use Go errors are.
2. At no moment we arrived to remove that `switch` statement that was the original reason to use our custom implementation.
This change removes all our status errors from the errors package and puts them back in their specific contexts.
IT puts the messages back with their contexts. That way, we know right away when errors used and how to generate their messages.
It uses custom interfaces to reason about errors. Errors that need to response with a custom status code MUST implementent this simple interface:
```go
type errorWithStatus interface {
HTTPErrorStatusCode() int
}
```
This interface is very straightforward to implement. It also preserves Go errors real behavior, getting the message is as simple as using the `Error()` method.
I included helper functions to generate errors that use custom status code in `errors/errors.go`.
By doing this, we remove the hard dependency we have eeverywhere to our custom errors package. Yes, you can use it as a helper to generate error, but it's still very easy to generate errors without it.
Please, read this fantastic blog post about errors in Go: http://dave.cheney.net/2014/12/24/inspecting-errors
Signed-off-by: David Calavera <david.calavera@gmail.com>
2016-02-25 15:53:35 +00:00
}