Merge pull request #584 from philips/config-env-flags

Config env flags
This commit is contained in:
Brandon Philips
2015-03-09 18:16:20 -07:00
6 changed files with 253 additions and 34 deletions
+29 -2
View File
@@ -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"
```
```
+23 -4
View File
@@ -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
@@ -43,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) {
@@ -54,7 +59,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 +92,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,7 +116,9 @@ func runPrepare(args []string) (exit int) {
},
Stage1Image: *s1img,
Images: imgs,
ExecAppends: appArgs,
Volumes: []types.Volume(flagVolumes),
InheritEnv: flagInheritEnv,
}
if err = stage0.Prepare(pcfg, c.path(), c.uuid); err != nil {
+65 -7
View File
@@ -37,12 +37,17 @@ var (
flagVolumes volumeList
flagPrivateNet bool
flagSpawnMetadataSvc bool
flagInheritEnv bool
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,
}
)
@@ -62,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{}
}
@@ -127,11 +133,45 @@ 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 {
switch a {
case "---":
// conclude this app's args
inAppArgs = false
default:
// keep appending to this app's args
appArgs[len(appArgs)-1] = append(appArgs[len(appArgs)-1], a)
}
} else {
switch a {
case "--":
// begin app's args, TODO(vc): this could be made more strict/police if deemed necessary
inAppArgs = true
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)
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 +182,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 +206,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,7 +232,9 @@ func runRun(args []string) (exit int) {
CommonConfig: cfg,
Stage1Image: *s1img,
Images: imgs,
ExecAppends: appArgs,
Volumes: []types.Volume(flagVolumes),
InheritEnv: flagInheritEnv,
}
err = stage0.Prepare(pcfg, c.path(), c.uuid)
if err != nil {
+75
View File
@@ -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)
}
}
}
+40 -9
View File
@@ -35,6 +35,7 @@ import (
"os"
"os/exec"
"path/filepath"
"strings"
"syscall"
"github.com/coreos/rocket/Godeps/_workspace/src/github.com/appc/spec/schema"
@@ -52,15 +53,17 @@ 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
InheritEnv bool // inherit parent environment into apps
}
// 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
@@ -77,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 {
@@ -101,7 +120,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 +131,28 @@ 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]...)
}
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)
}
+21 -12
View File
@@ -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)
}