func inspectImages(ctx *cobra.Command, args []string) { if len(args) < 1 { ErrorExit(ctx, "Needs an argument <NAME[:TAG]|ID> at least to inspect") } docker, err := client.NewDockerClient(configPath, hostName, ctx.Out()) if err != nil { log.Fatal(err) } var images []api.ImageInfo var gotError = false for _, name := range args { if imageInfo, err := docker.InspectImage(name); err != nil { log.Error(err) gotError = true } else { images = append(images, *imageInfo) } } if len(images) > 0 { if err := FormatPrint(ctx.Out(), images); err != nil { log.Fatal(err) } } if gotError { log.Fatal("Error: failed to inspect one or more images") } }
func inspectVolumes(ctx *cobra.Command, args []string) { if len(args) < 1 { ErrorExit(ctx, "Needs an argument <ID|CONTAINER-NAME:PATH> at least to inspect") } volumes, err := getVolumes(ctx) if err != nil { log.Fatal(err) } var _volumes Volumes var gotError = false for _, arg := range args { if volume := volumes.Find(arg); volume == nil { log.Errorf("No such volume: %s", arg) gotError = true } else { _volumes = append(_volumes, volume) } } if len(_volumes) > 0 { if err := FormatPrint(ctx.Out(), _volumes); err != nil { log.Fatal(err) } } if gotError { log.Fatal("Error: failed to inspect one or more volumes") } }
func tagImage(ctx *cobra.Command, args []string) { if len(args) < 2 { ErrorExit(ctx, "Needs two arguments <NAME[:TAG]|ID> <NEW-NAME[:TAG]>") } reg, name, tag, err := client.ParseRepositoryName(args[1]) if err != nil { log.Fatal(err) } if reg != "" { name = reg + "/" + name } docker, err := client.NewDockerClient(configPath, hostName, ctx.Out()) if err != nil { log.Fatal(err) } if err := docker.TagImage(args[0], name, tag, boolForce); err != nil { log.Fatal(err) } ctx.Printf("Tagged %s as %s:%s\n", args[0], name, tag) }
func inspectContainers(ctx *cobra.Command, args []string) { if len(args) < 1 { ErrorExit(ctx, "Needs an argument <NAME|ID> at least to inspect") } docker, err := client.NewDockerClient(configPath, hostName, ctx.Out()) if err != nil { log.Fatal(err) } var containers []api.ContainerInfo var gotError = false for _, name := range args { if containerInfo, err := docker.InspectContainer(name); err != nil { log.Error(err) gotError = true } else { containers = append(containers, *containerInfo) } } if len(containers) > 0 { if err := FormatPrint(ctx.Out(), containers); err != nil { log.Fatal(err) } } if gotError { log.Fatal("Error: failed to inspect one or more containers") } }
func checkChaincodeCmdParams(cmd *cobra.Command) error { if chaincodeName == undefinedParamValue { if chaincodePath == undefinedParamValue { err := fmt.Sprintf("Error: must supply value for %s path parameter.\n", chainFuncName) cmd.Out().Write([]byte(err)) cmd.Usage() return errors.New(err) } } if chaincodeCtorJSON != "{}" { // Check to ensure the JSON has "function" and "args" keys input := &pb.ChaincodeMessage{} jsonerr := json.Unmarshal([]byte(chaincodeCtorJSON), &input) if jsonerr != nil { err := fmt.Sprintf("Error: must supply 'function' and 'args' keys in %s constructor parameter.\n", chainFuncName) cmd.Out().Write([]byte(err)) cmd.Usage() return errors.New(err) } } return nil }
func (c *certCommander) certList(cmd *cobra.Command, args []string) error { if len(args) > 0 { cmd.Usage() return fmt.Errorf("") } config, err := c.configGetter() if err != nil { return err } trustDir := config.GetString("trust_dir") certPath := filepath.Join(trustDir, notary.TrustedCertsDir) // Load all individual (non-CA) certificates that aren't expired and don't use SHA1 certStore, err := trustmanager.NewX509FilteredFileStore( certPath, trustmanager.FilterCertsExpiredSha1, ) if err != nil { return fmt.Errorf("Failed to create a new truststore with directory: %s", trustDir) } trustedCerts := certStore.GetCertificates() cmd.Println("") prettyPrintCerts(trustedCerts, cmd.Out()) cmd.Println("") return nil }
func pullImage(ctx *cobra.Command, args []string) { if len(args) < 1 { ErrorExit(ctx, "Needs an argument <NAME[:TAG]> to pull") } reg, name, tag, err := client.ParseRepositoryName(args[0]) if err != nil { log.Fatal(err) } repository := name + ":" + tag if boolAll { repository = name } if reg != "" { repository = reg + "/" + repository } docker, err := client.NewDockerClient(configPath, hostName, ctx.Out()) if err != nil { log.Fatal(err) } if _, err := docker.PullImage(repository); err != nil { log.Fatal(err) } }
func setupAppConfig(f *clientcmd.Factory, out io.Writer, c *cobra.Command, args []string, config *newcmd.AppConfig) error { namespace, _, err := f.DefaultNamespace() if err != nil { return err } dockerClient, _, err := dockerutil.NewHelper().GetClient() if err == nil { if err = dockerClient.Ping(); err == nil { config.SetDockerClient(dockerClient) } } if err != nil { glog.V(2).Infof("No local Docker daemon detected: %v", err) } osclient, _, err := f.Clients() if err != nil { return err } config.SetOpenShiftClient(osclient, namespace) config.Out = out config.ErrOut = c.Out() unknown := config.AddArguments(args) if len(unknown) != 0 { return cmdutil.UsageError(c, "Did not recognize the following arguments: %v", unknown) } if config.AllowMissingImages && config.AsSearch { return cmdutil.UsageError(c, "--allow-missing-images and --search are mutually exclusive.") } return nil }
// Complete sets any default behavior for the command func (o *NewAppOptions) Complete(commandName string, f *clientcmd.Factory, c *cobra.Command, args []string, out io.Writer) error { o.Out = out o.ErrOut = c.Out() o.Output = kcmdutil.GetFlagString(c, "output") // Only output="" should print descriptions of intermediate steps. Everything // else should print only some specific output (json, yaml, go-template, ...) if len(o.Output) == 0 { o.Config.Out = o.Out } else { o.Config.Out = ioutil.Discard } o.Config.ErrOut = o.ErrOut o.Action.Out, o.Action.ErrOut = o.Out, o.ErrOut o.Action.Bulk.Mapper = clientcmd.ResourceMapper(f) o.Action.Bulk.Op = configcmd.Create // Retry is used to support previous versions of the API server that will // consider the presence of an unknown trigger type to be an error. o.Action.Bulk.Retry = retryBuildConfig o.Config.DryRun = o.Action.DryRun o.CommandPath = c.CommandPath() o.CommandName = commandName mapper, _ := f.Object(false) o.PrintObject = cmdutil.VersionedPrintObject(f.PrintObject, c, mapper, out) o.LogsForObject = f.LogsForObject if err := CompleteAppConfig(o.Config, f, c, args); err != nil { return err } if err := setAppConfigLabels(c, o.Config); err != nil { return err } return nil }
func (t *tufCommander) tufList(cmd *cobra.Command, args []string) error { if len(args) < 1 { cmd.Usage() return fmt.Errorf("Must specify a GUN") } config, err := t.configGetter() if err != nil { return err } gun := args[0] rt, err := getTransport(config, gun, true) if err != nil { return err } nRepo, err := notaryclient.NewNotaryRepository( config.GetString("trust_dir"), gun, getRemoteTrustServer(config), rt, t.retriever) if err != nil { return err } // Retrieve the remote list of signed targets, prioritizing the passed-in list over targets roles := append(t.roles, data.CanonicalTargetsRole) targetList, err := nRepo.ListTargets(roles...) if err != nil { return err } prettyPrintTargets(targetList, cmd.Out()) return nil }
func runScramble(cmd *cobra.Command, args []string) { globalFlags(cmd) t1 := time.Now() dir, err := ioutil.ReadDir(filepath.Join(graphdir, "graph")) if err != nil { logrus.Fatalf("Error reading graph dir: %s", err) } var ids = []string{} for _, v := range dir { id := v.Name() if len(id) != 64 { logrus.Debugf("Skipping: %s", v.Name()) continue } cacheDir, err := getCacheDir(id) if err != nil { if err == ErrNeedMigration { logrus.Debugf("%s not migrated", id) } logrus.Fatalf("Error getting image IDs: %s", err) } if _, err := os.Stat(cacheDir); err != nil { if os.IsNotExist(err) { logrus.Debugf("Skipping, missing cache dir: %s", id) continue } logrus.Fatalf("Error checking cache dir %s: %s", cacheDir, err) } ids = append(ids, id) } updates := map[string]string{} fileUpdates := []string{ filepath.Join(graphdir, fmt.Sprintf("repositories-%s", driver)), } for _, id := range ids { fmt.Fprintf(cmd.Out(), "Scrambling %s\n", id) newID := stringid.GenerateRandomID() updates[id] = newID oldPath := filepath.Join(graphdir, "graph", id) newPath := filepath.Join(graphdir, "graph", newID) if err := os.Rename(oldPath, newPath); err != nil { logrus.Errorf("Error renaming %s to %s: %s", oldPath, newPath, err) continue } updates[id] = newID fileUpdates = append(fileUpdates, filepath.Join(graphdir, "graph", newID, "json")) } updateReferences(updates, fileUpdates) logrus.Debugf("Ran scramble in %s", time.Since(t1).String()) }
func setupAppConfig(f *clientcmd.Factory, out io.Writer, c *cobra.Command, args []string, config *newcmd.AppConfig) error { namespace, _, err := f.DefaultNamespace() if err != nil { return err } dockerClient, _, err := dockerutil.NewHelper().GetClient() if err == nil { if err = dockerClient.Ping(); err == nil { config.SetDockerClient(dockerClient) } else { glog.V(4).Infof("Docker client did not respond to a ping: %v", err) } } if err != nil { glog.V(2).Infof("No local Docker daemon detected: %v", err) } osclient, kclient, err := f.Clients() if err != nil { return err } config.KubeClient = kclient config.SetOpenShiftClient(osclient, namespace) // Only output="" should print descriptions of intermediate steps. Everything // else should print only some specific output (json, yaml, go-template, ...) output := cmdutil.GetFlagString(c, "output") if len(output) == 0 { config.Out = out } else { config.Out = ioutil.Discard } config.ErrOut = c.Out() if config.AllowSecretUse { cfg, err := f.OpenShiftClientConfig.ClientConfig() if err != nil { return err } config.SecretAccessor = newConfigSecretRetriever(cfg) } unknown := config.AddArguments(args) if len(unknown) != 0 { return cmdutil.UsageError(c, "Did not recognize the following arguments: %v", unknown) } if config.AllowMissingImages && config.AsSearch { return cmdutil.UsageError(c, "--allow-missing-images and --search are mutually exclusive.") } if len(config.SourceImage) != 0 && len(config.SourceImagePath) == 0 { return cmdutil.UsageError(c, "--source-image-path must be specified when --source-image is specified.") } if len(config.SourceImage) == 0 && len(config.SourceImagePath) != 0 { return cmdutil.UsageError(c, "--source-image must be specified when --source-image-path is specified.") } return nil }
func getContainerChanges(ctx *cobra.Command, args []string) { if len(args) < 1 { ErrorExit(ctx, "Needs an argument <NAME|ID> to get changes") } docker, err := client.NewDockerClient(configPath, hostName, ctx.Out()) if err != nil { log.Fatal(err) } changes, err := docker.GetContainerChanges(args[0]) if err != nil { log.Fatal(err) } for _, change := range changes { var kind string switch change.Kind { case api.CHANGE_TYPE_MODIFY: kind = "C" case api.CHANGE_TYPE_ADD: kind = "A" case api.CHANGE_TYPE_DELETE: kind = "D" } ctx.Printf("%s %s\n", kind, change.Path) } }
// Complete sets any default behavior for the command func (o *NewAppOptions) Complete(commandName string, f *clientcmd.Factory, c *cobra.Command, args []string, out io.Writer) error { o.Out = out o.ErrOut = c.Out() o.Output = kcmdutil.GetFlagString(c, "output") // Only output="" should print descriptions of intermediate steps. Everything // else should print only some specific output (json, yaml, go-template, ...) if len(o.Output) == 0 { o.Config.Out = o.Out } else { o.Config.Out = ioutil.Discard } o.Config.ErrOut = o.ErrOut o.CommandPath = c.CommandPath() o.CommandName = commandName o.PrintObject = cmdutil.VersionedPrintObject(f.PrintObject, c, out) o.LogsForObject = f.LogsForObject if err := CompleteAppConfig(o.Config, f, c, args); err != nil { return err } if err := setAppConfigLabels(c, o.Config); err != nil { return err } return nil }
// keyRemove deletes a private key based on ID func (k *keyCommander) keyRemove(cmd *cobra.Command, args []string) error { if len(args) < 1 { cmd.Usage() return fmt.Errorf("must specify the key ID of the key to remove") } config, err := k.configGetter() if err != nil { return err } ks, err := k.getKeyStores(config, true, false) if err != nil { return err } keyID := args[0] // This is an invalid ID if len(keyID) != notary.SHA256HexSize { return fmt.Errorf("invalid key ID provided: %s", keyID) } cmd.Println("") err = removeKeyInteractively(ks, keyID, k.input, cmd.Out()) cmd.Println("") return err }
func commitContainer(ctx *cobra.Command, args []string) { if len(args) < 2 { ErrorExit(ctx, "Needs two arguments to commit <CONTAINER-NAME|ID> to <IMAGE-NAME[:TAG]>") } reg, name, tag, err := client.ParseRepositoryName(args[1]) if err != nil { log.Fatal(err) } if reg != "" { name = reg + "/" + name } docker, err := client.NewDockerClient(configPath, hostName, ctx.Out()) if err != nil { log.Fatal(err) } if _, err := docker.CommitContainer(args[0], name, tag, message, author, boolPause); err != nil { log.Fatal(err) } ctx.Printf("Committed %s as %s:%s\n", args[0], name, tag) }
// Complete completes any options that are required by validate or run steps. func (opts *RegistryOptions) Complete(f *clientcmd.Factory, cmd *cobra.Command, out io.Writer, args []string) error { if len(args) > 0 { return kcmdutil.UsageError(cmd, "No arguments are allowed to this command") } opts.image = opts.Config.ImageTemplate.ExpandOrDie(opts.Config.Type) opts.label = map[string]string{ "docker-registry": "default", } if opts.Config.Labels != defaultLabel { valid, remove, err := app.LabelsFromSpec(strings.Split(opts.Config.Labels, ",")) if err != nil { return err } if len(remove) > 0 { return kcmdutil.UsageError(cmd, "You may not pass negative labels in %q", opts.Config.Labels) } opts.label = valid } opts.nodeSelector = map[string]string{} if len(opts.Config.Selector) > 0 { valid, remove, err := app.LabelsFromSpec(strings.Split(opts.Config.Selector, ",")) if err != nil { return err } if len(remove) > 0 { return kcmdutil.UsageError(cmd, "You may not pass negative labels in selector %q", opts.Config.Selector) } opts.nodeSelector = valid } var portsErr error if opts.ports, portsErr = app.ContainerPortsFromString(opts.Config.Ports); portsErr != nil { return portsErr } var nsErr error if opts.namespace, _, nsErr = f.OpenShiftClientConfig.Namespace(); nsErr != nil { return fmt.Errorf("error getting namespace: %v", nsErr) } var kClientErr error if _, opts.serviceClient, kClientErr = f.Clients(); kClientErr != nil { return fmt.Errorf("error getting client: %v", kClientErr) } opts.Config.Action.Bulk.Mapper = clientcmd.ResourceMapper(f) opts.Config.Action.Out, opts.Config.Action.ErrOut = out, cmd.Out() opts.Config.Action.Bulk.Op = configcmd.Create opts.out = out opts.cmd = cmd opts.factory = f return nil }
// RunImportImage contains all the necessary functionality for the OpenShift cli import-image command. func RunImportImage(f *clientcmd.Factory, out io.Writer, cmd *cobra.Command, args []string) error { if len(args) == 0 || len(args[0]) == 0 { return cmdutil.UsageError(cmd, "you must specify the name of an image stream.") } streamName := args[0] namespace, _, err := f.DefaultNamespace() if err != nil { return err } osClient, _, err := f.Clients() if err != nil { return err } imageStreamClient := osClient.ImageStreams(namespace) stream, err := imageStreamClient.Get(streamName) if err != nil { return err } if len(stream.Spec.DockerImageRepository) == 0 { return errors.New("only image streams with spec.dockerImageRepository set may have images imported") } if stream.Annotations == nil { stream.Annotations = make(map[string]string) } stream.Annotations[imageapi.DockerImageRepositoryCheckAnnotation] = "" updatedStream, err := imageStreamClient.Update(stream) if err != nil { return err } resourceVersion := updatedStream.ResourceVersion fmt.Fprintln(cmd.Out(), "Waiting for the import to complete, CTRL+C to stop waiting.") updatedStream, err = waitForImport(imageStreamClient, stream.Name, resourceVersion) if err != nil { return fmt.Errorf("unable to determine if the import completed successfully - please run 'oc describe -n %s imagestream/%s' to see if the tags were updated as expected: %v", stream.Namespace, stream.Name, err) } fmt.Fprintln(cmd.Out(), "The import completed successfully.\n") d := describe.ImageStreamDescriber{osClient} info, err := d.Describe(updatedStream.Namespace, updatedStream.Name) if err != nil { return err } fmt.Fprintln(out, info) return nil }
// RunNewBuild contains all the necessary functionality for the OpenShift cli new-build command func RunNewBuild(fullName string, f *clientcmd.Factory, out io.Writer, in io.Reader, c *cobra.Command, args []string, config *newcmd.AppConfig) error { output := cmdutil.GetFlagString(c, "output") if config.Dockerfile == "-" { data, err := ioutil.ReadAll(in) if err != nil { return err } config.Dockerfile = string(data) } if err := setupAppConfig(f, out, c, args, config); err != nil { return err } if err := setAppConfigLabels(c, config); err != nil { return err } result, err := config.RunBuilds() if err != nil { if errs, ok := err.(errors.Aggregate); ok { if len(errs.Errors()) == 1 { err = errs.Errors()[0] } } if err == newcmd.ErrNoInputs { // TODO: suggest things to the user return cmdutil.UsageError(c, "You must specify one or more images, image streams and source code locations to create a build configuration.") } return err } if err := setLabels(config.Labels, result); err != nil { return err } if err := setAnnotations(map[string]string{newcmd.GeneratedByNamespace: newcmd.GeneratedByNewBuild}, result); err != nil { return err } if len(output) != 0 && output != "name" { return f.Factory.PrintObject(c, result.List, out) } if err := createObjects(f, out, output == "name", result); err != nil { return err } for _, item := range result.List.Items { switch t := item.(type) { case *buildapi.BuildConfig: fmt.Fprintf(c.Out(), "Build configuration %q created and build triggered.\n", t.Name) } } if len(result.List.Items) > 0 { fmt.Fprintf(c.Out(), "Run '%s %s' to check the progress.\n", fullName, StatusRecommendedName) } return nil }
func catConfig(ctx *cobra.Command, args []string) { config, err := client.LoadConfig(configPath) if err != nil { log.Fatal(err) } if err := FormatPrint(ctx.Out(), config); err != nil { log.Fatal(err) } }
// RunNewApplication contains all the necessary functionality for the OpenShift cli new-app command func RunNewApplication(fullName string, f *clientcmd.Factory, out io.Writer, c *cobra.Command, args []string, config *newcmd.AppConfig) error { if err := setupAppConfig(f, c, args, config); err != nil { return err } result, err := config.RunAll(out, c.Out()) if err != nil { if errs, ok := err.(errors.Aggregate); ok { if len(errs.Errors()) == 1 { err = errs.Errors()[0] } } if err == newcmd.ErrNoInputs { // TODO: suggest things to the user return cmdutil.UsageError(c, "You must specify one or more images, image streams, templates or source code locations to create an application.") } return err } if err := setLabels(c, result); err != nil { return err } if len(cmdutil.GetFlagString(c, "output")) != 0 { return f.Factory.PrintObject(c, result.List, out) } if err := createObjects(f, out, result); err != nil { return err } hasMissingRepo := false for _, item := range result.List.Items { switch t := item.(type) { case *kapi.Service: portMappings := "." if len(t.Spec.Ports) > 0 { portMappings = fmt.Sprintf(" with port mappings %s.", describeServicePorts(t.Spec)) } fmt.Fprintf(c.Out(), "Service %q created at %s%s\n", t.Name, t.Spec.ClusterIP, portMappings) case *buildapi.BuildConfig: fmt.Fprintf(c.Out(), "A build was created - you can run `%s start-build %s` to start it.\n", fullName, t.Name) case *imageapi.ImageStream: if len(t.Status.DockerImageRepository) == 0 { if hasMissingRepo { continue } hasMissingRepo = true fmt.Fprintf(c.Out(), "WARNING: We created an ImageStream %q, but it does not look like a Docker registry has been integrated with the OpenShift server. Automatic builds and deployments depend on that integration to detect new images and will not function properly.\n", t.Name) } } } fmt.Fprintf(c.Out(), "Run '%s status' to view your app.\n", fullName) return nil }
func (t *tufCommander) tufStatus(cmd *cobra.Command, args []string) error { if len(args) < 1 { cmd.Usage() return fmt.Errorf("Must specify a GUN") } config, err := t.configGetter() if err != nil { return err } gun := args[0] trustPin, err := getTrustPinning(config) if err != nil { return err } nRepo, err := notaryclient.NewFileCachedNotaryRepository( config.GetString("trust_dir"), gun, getRemoteTrustServer(config), nil, t.retriever, trustPin) if err != nil { return err } cl, err := nRepo.GetChangelist() if err != nil { return err } if len(cl.List()) == 0 { cmd.Printf("No unpublished changes for %s\n", gun) return nil } cmd.Printf("Unpublished changes for %s:\n\n", gun) tw := initTabWriter( []string{"#", "ACTION", "SCOPE", "TYPE", "PATH"}, cmd.Out(), ) for i, ch := range cl.List() { fmt.Fprintf( tw, fiveItemRow, fmt.Sprintf("%d", i), ch.Action(), ch.Scope(), ch.Type(), ch.Path(), ) } tw.Flush() return nil }
func keysList(cmd *cobra.Command, args []string) { if len(args) > 0 { cmd.Usage() os.Exit(1) } parseConfig() stores := getKeyStores(cmd, mainViper.GetString("trust_dir"), retriever, true) cmd.Println("") prettyPrintKeys(stores, cmd.Out()) cmd.Println("") }
func (k *keyCommander) keysRotate(cmd *cobra.Command, args []string) error { if len(args) < 2 { cmd.Usage() return fmt.Errorf("Must specify a GUN and a key role to rotate") } config, err := k.configGetter() if err != nil { return err } gun := args[0] rotateKeyRole := args[1] rt, err := getTransport(config, gun, admin) if err != nil { return err } trustPin, err := getTrustPinning(config) if err != nil { return err } nRepo, err := notaryclient.NewFileCachedNotaryRepository( config.GetString("trust_dir"), gun, getRemoteTrustServer(config), rt, k.getRetriever(), trustPin) if err != nil { return err } if rotateKeyRole == data.CanonicalRootRole { cmd.Print("Warning: you are about to rotate your root key.\n\n" + "You must use your old key to sign this root rotation. We recommend that\n" + "you sign all your future root changes with this key as well, so that\n" + "clients can have a smoother update process. Please do not delete\n" + "this key after rotating.\n\n" + "Are you sure you want to proceed? (yes/no) ") if !askConfirm(k.input) { fmt.Fprintln(cmd.Out(), "\nAborting action.") return nil } } if err := nRepo.RotateKey(rotateKeyRole, k.rotateKeyServerManaged); err != nil { return err } cmd.Printf("Successfully rotated %s key for repository %s\n", rotateKeyRole, gun) return nil }
func exportVolume(ctx *cobra.Command, args []string) { if len(args) < 1 { ErrorExit(ctx, "Needs an argument <ID|CONTAINER-NAME:PATH> to export") } volumes, err := getVolumes(ctx) if err != nil { log.Fatal(err) } volume := volumes.Find(args[0]) if volume == nil { log.Fatalf("No such volume: %s", args[0]) } var ( config api.Config hostConfig api.HostConfig ) config.Image = "busybox:latest" hostConfig.Binds = []string{volume.Path + ":/" + volume.ID} docker, err := client.NewDockerClient(configPath, hostName, ctx.Out()) if err != nil { log.Fatal(err) } var cid string cid, err = docker.CreateContainer("", config, hostConfig) if err != nil { if apiErr, ok := err.(api.Error); ok && (apiErr.StatusCode == 404) { if err := pullImageInSilence(ctx, config.Image); err != nil { log.Fatal(err) } cid, err = docker.CreateContainer("", config, hostConfig) if err != nil { log.Fatal(err) } } else { log.Fatal(err) } } defer docker.RemoveContainer(cid, true) if err := docker.CopyContainer(cid, "/"+volume.ID); err != nil { log.Fatal(err) } }
func (k *keyCommander) exportKeys(cmd *cobra.Command, args []string) error { var ( out io.Writer err error ) if len(args) > 0 { cmd.Usage() return fmt.Errorf("export does not take any positional arguments") } config, err := k.configGetter() if err != nil { return err } if k.outFile == "" { out = cmd.Out() } else { f, err := os.OpenFile(k.outFile, os.O_TRUNC|os.O_CREATE|os.O_WRONLY, notary.PrivExecPerms) if err != nil { return err } defer f.Close() out = f } directory := config.GetString("trust_dir") fileStore, err := store.NewPrivateKeyFileStorage(directory, notary.KeyExtension) if err != nil { return err } if len(k.exportGUNs) > 0 { if len(k.exportKeyIDs) > 0 { return fmt.Errorf("Only the --gun or --key flag may be provided, not a mix of the two flags") } for _, gun := range k.exportGUNs { return utils.ExportKeysByGUN(out, fileStore, gun) } } else if len(k.exportKeyIDs) > 0 { return utils.ExportKeysByID(out, fileStore, k.exportKeyIDs) } // export everything keys := fileStore.ListFiles() for _, k := range keys { err := utils.ExportKeys(out, fileStore, k) if err != nil { return err } } return nil }
func removeVolume(ctx *cobra.Command, volume *Volume) error { var ( config api.Config hostConfig api.HostConfig ) config.Cmd = []string{"/bin/sh", "-c", "rm -rf /.docker_volume_config/" + volume.ID} config.Image = "busybox:latest" hostConfig.Binds = []string{filepath.Dir(volume.configPath) + ":/.docker_volume_config"} if !volume.IsBindMount { config.Cmd[2] = config.Cmd[2] + (" && rm -rf /.docker_volume/" + volume.ID) hostConfig.Binds = append(hostConfig.Binds, filepath.Dir(volume.Path)+":/.docker_volume") } docker, err := client.NewDockerClient(configPath, hostName, ctx.Out()) if err != nil { return err } var cid string cid, err = docker.CreateContainer("", config, hostConfig) if err != nil { if apiErr, ok := err.(api.Error); ok && (apiErr.StatusCode == 404) { if err := pullImageInSilence(ctx, config.Image); err != nil { return err } cid, err = docker.CreateContainer("", config, hostConfig) if err != nil { return err } } else { return err } } defer docker.RemoveContainer(cid, true) if err := docker.StartContainer(cid); err != nil { return err } if _, err := docker.WaitContainer(cid); err != nil { return err } return nil }
func buildImage(ctx *cobra.Command, args []string) { path := "." if len(args) > 0 { path = args[0] } docker, err := client.NewDockerClient(configPath, hostName, ctx.Out()) if err != nil { log.Fatal(err) } if _, err := docker.BuildImage(path, imageTag, boolQuiet); err != nil { log.Fatal(err) } }
func (k *keyCommander) keysList(cmd *cobra.Command, args []string) error { if len(args) > 0 { return fmt.Errorf("") } config := k.configGetter() ks, err := k.getKeyStores(config, true) if err != nil { return err } cmd.Println("") prettyPrintKeys(ks, cmd.Out()) cmd.Println("") return nil }
// injectUserVars injects user specified variables into the Template func injectUserVars(values []string, cmd *cobra.Command, t *templateapi.Template) { for _, keypair := range values { p := strings.SplitN(keypair, "=", 2) if len(p) != 2 { fmt.Fprintf(cmd.Out(), "invalid parameter assignment in %q: %q\n", t.Name, keypair) continue } if v := template.GetParameterByName(t, p[0]); v != nil { v.Value = p[1] v.Generate = "" template.AddParameter(t, *v) } else { fmt.Fprintf(cmd.Out(), "unknown parameter name %q\n", p[0]) } } }