From 9ce3c4d37af66f8814d25d1a2fa1edd8ea8539a3 Mon Sep 17 00:00:00 2001 From: Vito Caputo Date: Mon, 2 Mar 2015 19:10:01 -0800 Subject: [PATCH 1/4] rkt: support passing arguments to apps on the cli `rkt run` and `rkt prepare` can now receive arguments on the commandline which get appended to the default exec arguments of the preceding app image. Examples: Append --foo=bar to the second aci in a two aci invocation: `rkt run bar.aci foo.aci -- --foo=bar` Append options to both acis: `rkt run bar.aci -- --foobar --- foo.aci -- --woot` or if preparing: `rkt prepare bar.aci -- --foobar --- foo.aci -- --woot` Also lays groundwork for general support of CRM overrides, though only argument appending has been plumbed to the rkt commandline. Fixes #564 Conflicts: stage0/run.go --- rkt/prepare.go | 25 +++++++++++++--- rkt/run.go | 65 +++++++++++++++++++++++++++++++++++----- stage0/run.go | 22 ++++++++------ stage1/init/container.go | 33 ++++++++++++-------- 4 files changed, 113 insertions(+), 32 deletions(-) diff --git a/rkt/prepare.go b/rkt/prepare.go index c644296..651a475 100644 --- a/rkt/prepare.go +++ b/rkt/prepare.go @@ -30,9 +30,13 @@ var ( cmdPrepare = &Command{ Name: "prepare", Summary: "Prepare to run image(s) in an application container in rocket", - Usage: "[--volume name,type=host...] [--quiet] IMAGE...", + Usage: "[--volume name,type=host...] [--quiet] IMAGE [-- image-args...[---]]...", Description: `Image should be a string referencing an image; either a hash, local file on disk, or URL. -They will be checked in that order and the first match will be used.`, +They will be checked in that order and the first match will be used. + +An "--" may be used to inhibit rkt prepare's parsing of subsequent arguments, +which will instead be appended to the preceding image app's exec arguments. +End the image arguments with a lone "---" to resume argument parsing.`, Run: runPrepare, } flagQuiet bool @@ -54,7 +58,14 @@ func runPrepare(args []string) (exit int) { return 1 } } - if len(args) < 1 { + + appArgs, images, err := parseAppArgs(args) + if err != nil { + stderr("prepare: error parsing app image arguments") + return 1 + } + + if len(images) < 1 { stderr("prepare: Must provide at least one image") return 1 } @@ -80,12 +91,17 @@ func runPrepare(args []string) (exit int) { return 1 } - imgs, err := findImages(args, ds, ks) + imgs, err := findImages(images, ds, ks) if err != nil { stderr("%v", err) return 1 } + if len(imgs) != len(appArgs) { + stderr("Unexpected mismatch of app args and app images") + return 1 + } + c, err := newContainer() if err != nil { stderr("prepare: error creating new container: %v", err) @@ -99,6 +115,7 @@ func runPrepare(args []string) (exit int) { }, Stage1Image: *s1img, Images: imgs, + ExecAppends: appArgs, Volumes: []types.Volume(flagVolumes), } diff --git a/rkt/run.go b/rkt/run.go index 800c96f..d736814 100644 --- a/rkt/run.go +++ b/rkt/run.go @@ -40,9 +40,13 @@ var ( cmdRun = &Command{ Name: "run", Summary: "Run image(s) in an application container in rocket", - Usage: "[--volume name,type=host...] IMAGE...", + Usage: "[--volume name,type=host...] IMAGE [-- image-args...[---]]...", Description: `IMAGE should be a string referencing an image; either a hash, local file on disk, or URL. -They will be checked in that order and the first match will be used.`, +They will be checked in that order and the first match will be used. + +An "--" may be used to inhibit rkt run's parsing of subsequent arguments, +which will instead be appended to the preceding image app's exec arguments. +End the image arguments with a lone "---" to resume argument parsing.`, Run: runRun, } ) @@ -127,11 +131,41 @@ func findImage(img string, ds *cas.Store, ks *keystore.Keystore, discover bool) return h, nil } -func runRun(args []string) (exit int) { - if len(args) < 1 { - stderr("run: Must provide at least one image") - return 1 +// parseAppArgs looks through the remaining arguments for support of per-app argument lists delimited with "--" and "---" +func parseAppArgs(args []string) ([][]string, []string, error) { + // valid args here may either be: + // not-"--"; an image specifier + // "--"; image arguments begin + // "---"; conclude image arguments + appArgs := make([][]string, 0) + images := make([]string, 0) + inAppArgs := false + for _, a := range args { + if inAppArgs { + if a == "---" { + // conclude this app's args + inAppArgs = false + } else { + // keep appending to this app's args + appArgs[len(appArgs)-1] = append(appArgs[len(appArgs)-1], a) + } + } else { + if a == "--" { + // begin app's args, TODO(vc): this could be made more strict/police if deemed necessary + inAppArgs = true + } else { + // this is something else, append it to images + // TODO(vc): for now these basically have to be images, but it should be possible to reenter cmdRun.flags.Parse() + images = append(images, a) + appArgs = append(appArgs, make([]string, 0)) + } + } } + + return appArgs, images, nil +} + +func runRun(args []string) (exit int) { if globalFlags.Dir == "" { log.Printf("dir unset - using temporary directory") var err error @@ -142,6 +176,17 @@ func runRun(args []string) (exit int) { } } + appArgs, images, err := parseAppArgs(args) + if err != nil { + stderr("run: error parsing app image arguments") + return 1 + } + + if len(images) < 1 { + stderr("run: Must provide at least one image") + return 1 + } + ds, err := cas.NewStore(globalFlags.Dir) if err != nil { stderr("run: cannot open store: %v") @@ -155,12 +200,17 @@ func runRun(args []string) (exit int) { return 1 } - imgs, err := findImages(args, ds, ks) + imgs, err := findImages(images, ds, ks) if err != nil { stderr("%v", err) return 1 } + if len(imgs) != len(appArgs) { + stderr("Unexpected mismatch of app args and app images") + return 1 + } + c, err := newContainer() if err != nil { stderr("Error creating new container: %v", err) @@ -176,6 +226,7 @@ func runRun(args []string) (exit int) { CommonConfig: cfg, Stage1Image: *s1img, Images: imgs, + ExecAppends: appArgs, Volumes: []types.Volume(flagVolumes), } err = stage0.Prepare(pcfg, c.path(), c.uuid) diff --git a/stage0/run.go b/stage0/run.go index c3352d7..4ca0063 100644 --- a/stage0/run.go +++ b/stage0/run.go @@ -52,15 +52,16 @@ const ( // configuration parameters required by Prepare type PrepareConfig struct { CommonConfig + // TODO(jonboulle): These images are partially-populated hashes, this should be clarified. Stage1Image types.Hash // stage1 image containing usable /init and /enter entrypoints Images []types.Hash // application images + ExecAppends [][]string // appendages to each image's app.exec lines (empty when none, length should match length of Images) Volumes []types.Volume // list of volumes that rocket can provide to applications } // configuration parameters needed by Run type RunConfig struct { CommonConfig - // TODO(jonboulle): These images are partially-populated hashes, this should be clarified. PrivateNet bool // container should have its own network stack SpawnMetadataSvc bool // launch metadata service LockFd int // lock file descriptor @@ -101,7 +102,7 @@ func Prepare(cfg PrepareConfig, dir string, uuid *types.UUID) error { } cm.ACVersion = *v - for _, img := range cfg.Images { + for i, img := range cfg.Images { am, err := setupAppImage(cfg, img, dir) if err != nil { return fmt.Errorf("error setting up image %s: %v", img, err) @@ -112,16 +113,19 @@ func Prepare(cfg PrepareConfig, dir string, uuid *types.UUID) error { if am.App == nil { return fmt.Errorf("error: image %s has no app section", img) } - rimg := schema.RuntimeImage{ - Name: am.Name, - ID: img, - } a := schema.RuntimeApp{ - Name: am.Name, - Image: rimg, - App: am.App, + // TODO(vc): leverage RuntimeApp.Name for disambiguating the apps + Name: am.Name, + Image: schema.RuntimeImage{ + Name: am.Name, + ID: img, + }, Annotations: am.Annotations, } + if len(cfg.ExecAppends[i]) > 0 { + a.App = am.App + a.App.Exec = append(a.App.Exec, cfg.ExecAppends[i]...) + } cm.Apps = append(cm.Apps, a) } diff --git a/stage1/init/container.go b/stage1/init/container.go index 488af3c..98a6308 100644 --- a/stage1/init/container.go +++ b/stage1/init/container.go @@ -110,10 +110,14 @@ func newUnitOption(section, name, value string) *unit.UnitOption { return &unit.UnitOption{Section: section, Name: name, Value: value} } -// appToSystemd transforms the provided app manifest into systemd units -func (c *Container) appToSystemd(am *schema.ImageManifest, id types.Hash) error { - name := am.Name.String() +// appToSystemd transforms the provided RuntimeApp+ImageManifest into systemd units +func (c *Container) appToSystemd(ra *schema.RuntimeApp, am *schema.ImageManifest) error { + name := ra.Name.String() + id := ra.Image.ID app := am.App + if ra.App != nil { + app = ra.App + } workDir := "/" if app.WorkingDirectory != "" { @@ -234,12 +238,12 @@ func (c *Container) writeEnvFile(env types.Environment, id types.Hash) error { // all the constituent apps of the Container func (c *Container) ContainerToSystemd() error { for _, am := range c.Apps { - a := c.Manifest.Apps.Get(am.Name) - if a == nil { + ra := c.Manifest.Apps.Get(am.Name) + if ra == nil { // should never happen panic("app not found in container manifest") } - if err := c.appToSystemd(am, a.Image.ID); err != nil { + if err := c.appToSystemd(ra, am); err != nil { return fmt.Errorf("failed to transform app %q into systemd service: %v", am.Name, err) } } @@ -249,9 +253,14 @@ func (c *Container) ContainerToSystemd() error { // appToNspawnArgs transforms the given app manifest, with the given associated // app image id, into a subset of applicable systemd-nspawn argument -func (c *Container) appToNspawnArgs(am *schema.ImageManifest, id types.Hash) ([]string, error) { +func (c *Container) appToNspawnArgs(ra *schema.RuntimeApp, am *schema.ImageManifest) ([]string, error) { args := []string{} - name := am.Name.String() + name := ra.Name.String() + id := ra.Image.ID + app := am.App + if ra.App != nil { + app = ra.App + } vols := make(map[types.ACName]types.Volume) @@ -264,7 +273,7 @@ func (c *Container) appToNspawnArgs(am *schema.ImageManifest, id types.Hash) ([] vols[v.Name] = v } - for _, mp := range am.App.MountPoints { + for _, mp := range app.MountPoints { key := mp.Name vol, ok := vols[key] if !ok { @@ -313,11 +322,11 @@ func (c *Container) ContainerToNspawnArgs() ([]string, error) { } for _, am := range c.Apps { - a := c.Manifest.Apps.Get(am.Name) - if a == nil { + ra := c.Manifest.Apps.Get(am.Name) + if ra == nil { panic("could not find app in container manifest!") } - aa, err := c.appToNspawnArgs(am, a.Image.ID) + aa, err := c.appToNspawnArgs(ra, am) if err != nil { return nil, fmt.Errorf("failed to construct args for app %q: %v", am.Name, err) } From 8e7f0e08eb330db2be7110203aa4e16f369694aa Mon Sep 17 00:00:00 2001 From: Vito Caputo Date: Fri, 6 Mar 2015 11:12:53 -0800 Subject: [PATCH 2/4] rkt: implement --inherit-environment in `rkt run` and `rkt prepare` When enabled the caller's environment is used to set variables not set by the app images. Fixes #565 --- rkt/prepare.go | 2 ++ rkt/run.go | 3 +++ stage0/run.go | 27 +++++++++++++++++++++++++++ 3 files changed, 32 insertions(+) diff --git a/rkt/prepare.go b/rkt/prepare.go index 651a475..4d1cf00 100644 --- a/rkt/prepare.go +++ b/rkt/prepare.go @@ -47,6 +47,7 @@ func init() { cmdPrepare.Flags.StringVar(&flagStage1Image, "stage1-image", defaultStage1Image, `image to use as stage1. Local paths and http/https URLs are supported. If empty, Rocket will look for a file called "stage1.aci" in the same directory as rkt itself`) cmdPrepare.Flags.Var(&flagVolumes, "volume", "volumes to mount into the shared container environment") cmdPrepare.Flags.BoolVar(&flagQuiet, "quiet", false, "suppress superfluous output on stdout, print only the UUID on success") + cmdPrepare.Flags.BoolVar(&flagInheritEnv, "inherit-environment", false, "inherit all environment variables not set by apps") } func runPrepare(args []string) (exit int) { @@ -117,6 +118,7 @@ func runPrepare(args []string) (exit int) { Images: imgs, ExecAppends: appArgs, Volumes: []types.Volume(flagVolumes), + InheritEnv: flagInheritEnv, } if err = stage0.Prepare(pcfg, c.path(), c.uuid); err != nil { diff --git a/rkt/run.go b/rkt/run.go index d736814..f7ef922 100644 --- a/rkt/run.go +++ b/rkt/run.go @@ -37,6 +37,7 @@ var ( flagVolumes volumeList flagPrivateNet bool flagSpawnMetadataSvc bool + flagInheritEnv bool cmdRun = &Command{ Name: "run", Summary: "Run image(s) in an application container in rocket", @@ -66,6 +67,7 @@ func init() { cmdRun.Flags.Var(&flagVolumes, "volume", "volumes to mount into the shared container environment") cmdRun.Flags.BoolVar(&flagPrivateNet, "private-net", false, "give container a private network") cmdRun.Flags.BoolVar(&flagSpawnMetadataSvc, "spawn-metadata-svc", false, "launch metadata svc if not running") + cmdRun.Flags.BoolVar(&flagInheritEnv, "inherit-environment", false, "inherit all environment variables not set by apps") flagVolumes = volumeList{} } @@ -228,6 +230,7 @@ func runRun(args []string) (exit int) { Images: imgs, ExecAppends: appArgs, Volumes: []types.Volume(flagVolumes), + InheritEnv: flagInheritEnv, } err = stage0.Prepare(pcfg, c.path(), c.uuid) if err != nil { diff --git a/stage0/run.go b/stage0/run.go index 4ca0063..6eb4040 100644 --- a/stage0/run.go +++ b/stage0/run.go @@ -35,6 +35,7 @@ import ( "os" "os/exec" "path/filepath" + "strings" "syscall" "github.com/coreos/rocket/Godeps/_workspace/src/github.com/appc/spec/schema" @@ -57,6 +58,7 @@ type PrepareConfig struct { Images []types.Hash // application images ExecAppends [][]string // appendages to each image's app.exec lines (empty when none, length should match length of Images) Volumes []types.Volume // list of volumes that rocket can provide to applications + InheritEnv bool // inherit parent environment into apps } // configuration parameters needed by Run @@ -78,6 +80,22 @@ func init() { log.SetOutput(ioutil.Discard) } +// MergeEnvs amends appEnv setting variables in setEnv before setting anything new from inheritEnv +// inheritEnv and setEnv are expected to be in the os.Environ() key=value format +func MergeEnvs(appEnv *types.Environment, inheritEnv, setEnv []string) { + for _, ev := range setEnv { + pair := strings.SplitN(ev, "=", 2) + appEnv.Set(pair[0], pair[1]) + } + + for _, ev := range inheritEnv { + pair := strings.SplitN(ev, "=", 2) + if _, exists := appEnv.Get(pair[0]); !exists { + appEnv.Set(pair[0], pair[1]) + } + } +} + // Prepare sets up a filesystem for a container based on the given config. func Prepare(cfg PrepareConfig, dir string, uuid *types.UUID) error { if cfg.Debug { @@ -122,10 +140,19 @@ func Prepare(cfg PrepareConfig, dir string, uuid *types.UUID) error { }, Annotations: am.Annotations, } + if len(cfg.ExecAppends[i]) > 0 { a.App = am.App a.App.Exec = append(a.App.Exec, cfg.ExecAppends[i]...) } + + if cfg.InheritEnv { + if a.App == nil { + a.App = am.App + } + // TODO(vc): use last parameter to propagate explicit override values + MergeEnvs(&a.App.Environment, os.Environ(), nil) + } cm.Apps = append(cm.Apps, a) } From c1e05f605c1a05ea0b627e4dd5b4442b722bc2f7 Mon Sep 17 00:00:00 2001 From: Brandon Philips Date: Sun, 8 Mar 2015 05:09:23 -0400 Subject: [PATCH 3/4] rkt: add some testing on parseAppArgs Add some testing and learn to ignore triple dashes since it is likely someone did something like: rkt run exmaple.com/foo ${ARGS} --- example.com/bar And wasn't intending to run the image "---" --- rkt/run.go | 12 +++++--- rkt/run_test.go | 75 +++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 83 insertions(+), 4 deletions(-) create mode 100644 rkt/run_test.go diff --git a/rkt/run.go b/rkt/run.go index f7ef922..89c5e9d 100644 --- a/rkt/run.go +++ b/rkt/run.go @@ -144,18 +144,22 @@ func parseAppArgs(args []string) ([][]string, []string, error) { inAppArgs := false for _, a := range args { if inAppArgs { - if a == "---" { + switch a { + case "---": // conclude this app's args inAppArgs = false - } else { + default: // keep appending to this app's args appArgs[len(appArgs)-1] = append(appArgs[len(appArgs)-1], a) } } else { - if a == "--" { + switch a { + case "--": // begin app's args, TODO(vc): this could be made more strict/police if deemed necessary inAppArgs = true - } else { + case "---": + // ignore triple dashes since they aren't images + default: // this is something else, append it to images // TODO(vc): for now these basically have to be images, but it should be possible to reenter cmdRun.flags.Parse() images = append(images, a) diff --git a/rkt/run_test.go b/rkt/run_test.go new file mode 100644 index 0000000..dffc949 --- /dev/null +++ b/rkt/run_test.go @@ -0,0 +1,75 @@ +// Copyright 2014 CoreOS, Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package main + +import ( + "reflect" + "strings" + "testing" +) + +func TestParseAppArgs(t *testing.T) { + tests := []struct { + in string + images []string + flags [][]string + werr bool + }{ + { + "example.com/foo example.com/bar -- --help --- example.com/baz -- --verbose", + []string{"example.com/foo", "example.com/bar", "example.com/baz"}, + [][]string{ + []string{}, + []string{"--help"}, + []string{"--verbose"}, + }, + false, + }, + { + "example.com/foo --- example.com/bar --- example.com/baz ---", + []string{"example.com/foo", "example.com/bar", "example.com/baz"}, + [][]string{ + []string{}, + []string{}, + []string{}, + }, + false, + }, + { + "example.com/foo example.com/bar example.com/baz", + []string{"example.com/foo", "example.com/bar", "example.com/baz"}, + [][]string{ + []string{}, + []string{}, + []string{}, + }, + false, + }, + } + + for i, tt := range tests { + gf, gi, err := parseAppArgs(strings.Split(tt.in, " ")) + if gerr := (err != nil); gerr != tt.werr { + t.Errorf("#%d: err==%v, want errstate %t", i, err, tt.werr) + } + if !reflect.DeepEqual(gf, tt.flags) { + t.Errorf("#%d: got flags %v, want flags %v", i, gf, tt.flags) + } + if !reflect.DeepEqual(gi, tt.images) { + t.Errorf("#%d: got images %v, want images %v", i, gi, tt.images) + } + } + +} From 3ad6788b3ed265fc6a7cb02d7a88e26ef5a4c1a9 Mon Sep 17 00:00:00 2001 From: Brandon Philips Date: Sun, 8 Mar 2015 05:31:12 -0400 Subject: [PATCH 4/4] Documentation: add rkt run env and flags information --- Documentation/commands.md | 31 +++++++++++++++++++++++++++++-- 1 file changed, 29 insertions(+), 2 deletions(-) diff --git a/Documentation/commands.md b/Documentation/commands.md index 2894674..f828120 100644 --- a/Documentation/commands.md +++ b/Documentation/commands.md @@ -138,6 +138,10 @@ Rocket can run ACIs based on name, hash, local file on disk or URL. If an ACI ha ### rkt run +#### Image Addressing + +Images can be ran by either their name, their hash or an explicit transport address. + ``` # Run by name $ sudo rkt run coreos.com/etcd:v2.0.0 @@ -153,8 +157,31 @@ $ sudo rkt run sha512-fa1cb92dc276b0f9bedf87981e61ecde $ sudo rkt run https://github.com/coreos/etcd/releases/download/v2.0.0/etcd-v2.0.0-linux-amd64.aci ``` +#### Passing Arguments + +To pass additional arguments to images use the pattern of `image1 -- [image1 flags] --- image2 -- [image2 flags]`. +For example: + +``` +$ sudo rkt run example.com/worker -- --loglevel verbose --- example.com/syncer -- --interval 30s +``` + +#### Inheriting Environment Variables + +To inherit environment variables from the parent use the `--inherit-environment` flag. + +The inheritance precedence is as follows with the last item replacing previous environment entries: + +- Parent environment +- App image environment + +``` +$ export EXAMPLE_ENV=hello +$ sudo rkt run --inherit-environment example.com/env-printer +EXAMPLE_ENV=hello +``` + _TODO: Exit codes_ -_TODO: Environment variables_ _TODO: Logging_ #### Disable Signature Verification @@ -268,4 +295,4 @@ $ rkt gc --grace-period=30m0s Garbage collecting container "21b1cb32-c156-4d26-82ae-eda1ab60f595" Garbage collecting container "5dd42e9c-7413-49a9-9113-c2a8327d08ab" Garbage collecting container "f07a4070-79a9-4db0-ae65-a090c9c393a3" -``` \ No newline at end of file +```