// Runs the step required to collate all build artifacts under the
// specified output directory
337062
func (s *StepCollateArtifacts) Run(ctx context.Context, state multistep.StateBag) multistep.StepAction {
	driver := state.Get("driver").(Driver)
	ui := state.Get("ui").(packer.Ui)

	ui.Say("Collating build artifacts...")

	if s.SkipExport {
		// Get the path to the main build directory from the statebag
		var buildDir string
		if v, ok := state.GetOk("build_dir"); ok {
			buildDir = v.(string)
		}
		// If the user has chosen to skip a full export of the VM the only
		// artifacts that they are interested in will be the VHDs. The
		// called function searches for all disks under the given source
		// directory and moves them to a 'Virtual Hard Disks' folder under
		// the destination directory
		err := driver.MoveCreatedVHDsToOutputDir(buildDir, s.OutputDir)
		if err != nil {
			err = fmt.Errorf("Error moving VHDs from build dir to output dir: %s", err)
			state.Put("error", err)
			ui.Error(err.Error())
			return multistep.ActionHalt
		}
	} else {
		// Get the full path to the export directory from the statebag
		var exportPath string
		if v, ok := state.GetOk("export_path"); ok {
			exportPath = v.(string)
		}
		// The export process exports the VM into a folder named 'vm name'
		// under the output directory. However, to maintain backwards
		// compatibility, we now need to shuffle around the exported folders
		// so the 'Snapshots', 'Virtual Hard Disks' and 'Virtual Machines'
		// directories appear *directly* under <output directory>.
		// The empty '<output directory>/<vm name>' directory is removed
		// when complete.
		// The 'Snapshots' folder will not be moved into the output
		// directory if it is empty.
		err := driver.PreserveLegacyExportBehaviour(exportPath, s.OutputDir)
		if err != nil {
			// No need to halt here; Just warn the user instead
			err = fmt.Errorf("WARNING: Error restoring legacy export dir structure: %s", err)
			ui.Error(err.Error())
		}
	}

	return multistep.ActionContinue
}
969489
func Run(cfg RunConfig, dir string, dataDir string) {
	privateUsers, err := preparedWithPrivateUsers(dir)
	if err != nil {
		log.FatalE("error preparing private users", err)
	}

	debug("Setting up stage1")
	if err := setupStage1Image(cfg, dir, cfg.UseOverlay); err != nil {
		log.FatalE("error setting up stage1", err)
	}
	debug("Wrote filesystem to %s\n", dir)

	for _, app := range cfg.Apps {
		if err := setupAppImage(cfg, app.Name, app.Image.ID, dir, cfg.UseOverlay); err != nil {
			log.FatalE("error setting up app image", err)
		}
	}

	destRootfs := common.Stage1RootfsPath(dir)

	writeDnsConfig(&cfg, destRootfs)

	if err := os.Setenv(common.EnvLockFd, fmt.Sprintf("%v", cfg.LockFd)); err != nil {
		log.FatalE("setting lock fd environment", err)
	}

	if err := os.Setenv(common.EnvSELinuxContext, fmt.Sprintf("%v", cfg.ProcessLabel)); err != nil {
		log.FatalE("setting SELinux context environment", err)
	}

	if err := os.Setenv(common.EnvSELinuxMountContext, fmt.Sprintf("%v", cfg.MountLabel)); err != nil {
		log.FatalE("setting SELinux mount context environment", err)
	}

	debug("Pivoting to filesystem %s", dir)
	if err := os.Chdir(dir); err != nil {
		log.FatalE("failed changing to dir", err)
	}

	ep, err := getStage1Entrypoint(dir, runEntrypoint)
	if err != nil {
		log.FatalE("error determining 'run' entrypoint", err)
	}
	args := []string{filepath.Join(destRootfs, ep)}

	if cfg.Debug {
		args = append(args, "--debug")
	}

	args = append(args, "--net="+cfg.Net.String())

	if cfg.Interactive {
		args = append(args, "--interactive")
	}
	if len(privateUsers) > 0 {
		args = append(args, "--private-users="+privateUsers)
	}
	if cfg.MDSRegister {
		mdsToken, err := registerPod(".", cfg.UUID, cfg.Apps)
		if err != nil {
			log.FatalE("failed to register the pod", err)
		}

		args = append(args, "--mds-token="+mdsToken)
	}

	if cfg.LocalConfig != "" {
		args = append(args, "--local-config="+cfg.LocalConfig)
	}

	s1v, err := getStage1InterfaceVersion(dir)
	if err != nil {
		log.FatalE("error determining stage1 interface version", err)
	}

	if cfg.Hostname != "" {
		if interfaceVersionSupportsHostname(s1v) {
			args = append(args, "--hostname="+cfg.Hostname)
		} else {
			log.Printf("warning: --hostname option is not supported by stage1")
		}
	}

	if cfg.DNSConfMode.Hosts != "default" || cfg.DNSConfMode.Resolv != "default" {
		if interfaceVersionSupportsDNSConfMode(s1v) {
			args = append(args, fmt.Sprintf("--dns-conf-mode=resolv=%s,hosts=%s", cfg.DNSConfMode.Resolv, cfg.DNSConfMode.Hosts))
		} else {
			log.Printf("warning: --dns-conf-mode option not supported by stage1")
		}
	}

	if interfaceVersionSupportsInsecureOptions(s1v) {
		if cfg.InsecureCapabilities {
			args = append(args, "--disable-capabilities-restriction")
		}
		if cfg.InsecurePaths {
			args = append(args, "--disable-paths")
		}
		if cfg.InsecureSeccomp {
			args = append(args, "--disable-seccomp")
		}
	}

	if cfg.Mutable {
		mutable, err := supportsMutableEnvironment(dir)

		switch {
		case err != nil:
			log.FatalE("error determining stage1 mutable support", err)
		case !mutable:
			log.Fatalln("stage1 does not support mutable pods")
		}

		args = append(args, "--mutable")
	}

	if cfg.IPCMode != "" {
		if interfaceVersionSupportsIPCMode(s1v) {
			args = append(args, "--ipc="+cfg.IPCMode)
		} else {
			log.Printf("warning: --ipc option is not supported by stage1")
		}
	}

	args = append(args, cfg.UUID.String())

	// make sure the lock fd stays open across exec
	if err := sys.CloseOnExec(cfg.LockFd, false); err != nil {
		log.Fatalf("error clearing FD_CLOEXEC on lock fd")
	}

	tpmEvent := fmt.Sprintf("rkt: Rootfs: %s Manifest: %s Stage1 args: %s", cfg.CommonConfig.RootHash, cfg.CommonConfig.ManifestData, strings.Join(args, " "))
	// If there's no TPM available or there's a failure for some other
	// reason, ignore it and continue anyway. Long term we'll want policy
	// that enforces TPM behaviour, but we don't have any infrastructure
	// around that yet.
	_ = tpm.Extend(tpmEvent)

	debug("Execing %s", args)
	if err := syscall.Exec(args[0], args, os.Environ()); err != nil {
		log.FatalE("error execing init", err)
	}
}
894602
func (s *StepPrepareParallelsTools) Run(ctx context.Context, state multistep.StateBag) multistep.StepAction {
	driver := state.Get("driver").(Driver)

	if s.ParallelsToolsMode == ParallelsToolsModeDisable {
		return multistep.ActionContinue
	}

	path, err := driver.ToolsISOPath(s.ParallelsToolsFlavor)

	if err != nil {
		state.Put("error", err)
		return multistep.ActionHalt
	}

	if _, err := os.Stat(path); err != nil {
		state.Put("error", fmt.Errorf(
			"Couldn't find Parallels Tools for the '%s' flavor! Please, check the\n"+
				"value of 'parallels_tools_flavor'. Valid flavors are: 'win', 'lin',\n"+
				"'mac', 'os2' and 'other'", s.ParallelsToolsFlavor))
		return multistep.ActionHalt
	}

	state.Put("parallels_tools_path", path)
	return multistep.ActionContinue
}
564257
func run() error {
	// Reduce noise in logging output.
	log.SetFlags(0)

	// Check the command-line arguments.
	flag.Parse()

	cmdLineArgs := flag.Args()
	if len(cmdLineArgs) < 2 {
		return errors.New("Usage: createmock [package] [interface ...]")
	}

	// Create a temporary directory inside of $GOPATH to hold generated code.
	buildPkg, err := build.Import("github.com/jacobsa/oglemock", "", build.FindOnly)
	if err != nil {
		return errors.New(fmt.Sprintf("Couldn't find oglemock in $GOPATH: %v", err))
	}

	tmpDir, err := ioutil.TempDir(buildPkg.SrcRoot, "tmp-createmock-")
	if err != nil {
		return errors.New(fmt.Sprintf("Creating temp dir: %v", err))
	}

	defer os.RemoveAll(tmpDir)

	// Create a file to hold generated code.
	codeFile, err := os.Create(path.Join(tmpDir, "tool.go"))
	if err != nil {
		return errors.New(fmt.Sprintf("Couldn't create a file to hold code: %v", err))
	}

	// Create an appropriate path for the built binary.
	binaryPath := path.Join(tmpDir, "tool")

	// Create an appropriate template argument.
	arg := tmplArg{
		InterfacePkgPath: cmdLineArgs[0],
		TypeNames:        cmdLineArgs[1:],
	}

	if *fSamePackage {
		arg.OutputPkgPath = arg.InterfacePkgPath
	} else {
		arg.OutputPkgPath = "mock_" + path.Base(arg.InterfacePkgPath)
	}

	arg.Imports = make(importMap)
	arg.Imports[path.Base(arg.InterfacePkgPath)] = arg.InterfacePkgPath
	arg.Imports["generate"] = "github.com/jacobsa/oglemock/generate"
	arg.Imports["log"] = "log"
	arg.Imports["os"] = "os"
	arg.Imports["reflect"] = "reflect"

	// Execute the template to generate code that will itself generate the mock
	// code. Write the code to the temp file.
	tmpl := template.Must(
		template.New("code").Funcs(
			template.FuncMap{
				"pathBase": path.Base,
			}).Parse(tmplStr))
	if err := tmpl.Execute(codeFile, arg); err != nil {
		return errors.New(fmt.Sprintf("Error executing template: %v", err))
	}

	codeFile.Close()

	// Attempt to build the code.
	cmd := exec.Command("go", "build", "-o", binaryPath)
	cmd.Dir = tmpDir
	buildOutput, err := cmd.CombinedOutput()

	if err != nil {
		// Did the compilation fail due to the user-specified package not being found?
		pkg := findUnknownPackage(buildOutput)
		if pkg != nil && *pkg == arg.InterfacePkgPath {
			return errors.New(fmt.Sprintf("Unknown package: %s", *pkg))
		}

		// Did the compilation fail due to an unknown interface?
		if in := findUndefinedInterface(buildOutput); in != nil {
			return errors.New(fmt.Sprintf("Unknown interface: %s", *in))
		}

		// Otherwise return a generic error.
		return errors.New(fmt.Sprintf(
			"%s\n\nError building generated code:\n\n"+
				"    %v\n\nPlease report this oglemock bug.",
			buildOutput,
			err))
	}

	// Run the binary.
	cmd = exec.Command(binaryPath)
	binaryOutput, err := cmd.CombinedOutput()

	if err != nil {
		return errors.New(fmt.Sprintf(
			"%s\n\nError running generated code:\n\n"+
				"    %v\n\n Please report this oglemock bug.",
			binaryOutput,
			err))
	}

	// Copy its output.
	_, err = os.Stdout.Write(binaryOutput)
	if err != nil {
		return errors.New(fmt.Sprintf("Error copying binary output: %v", err))
	}

	return nil
}
766391
func compile(c context.Context, gopath, importPaths, protoFiles []string, dir, descSetOut string) (outDir string, err error) {
	// make it absolute to find in $GOPATH and because protoc wants paths
	// to be under proto paths.
	if dir, err = filepath.Abs(dir); err != nil {
		return "", err
	}

	// By default place go files in CWD,
	// unless proto files are under a $GOPATH/src.
	goOut := "."

	// Combine user-defined proto paths with $GOPATH/src.
	allProtoPaths := make([]string, 0, len(importPaths)+len(gopath)+1)
	for _, p := range importPaths {
		if p, err = filepath.Abs(p); err != nil {
			return "", err
		}
		allProtoPaths = append(allProtoPaths, p)
	}
	for _, p := range gopath {
		path := filepath.Join(p, "src")
		if info, err := os.Stat(path); os.IsNotExist(err) || !info.IsDir() {
			continue
		} else if err != nil {
			return "", err
		}
		allProtoPaths = append(allProtoPaths, path)

		// If the dir is under $GOPATH/src, generate .go files near .proto files.
		if strings.HasPrefix(dir, path) {
			goOut = path
		}

		// Include well-known protobuf types.
		wellKnownProtoDir := filepath.Join(path, "go.chromium.org", "luci", "grpc", "proto")
		if info, err := os.Stat(wellKnownProtoDir); err == nil && info.IsDir() {
			allProtoPaths = append(allProtoPaths, wellKnownProtoDir)
		}
	}

	// Find where Go files will be generated.
	for _, p := range allProtoPaths {
		if strings.HasPrefix(dir, p) {
			outDir = filepath.Join(goOut, dir[len(p):])
			break
		}
	}
	if outDir == "" {
		return "", fmt.Errorf("proto files are neither under $GOPATH/src nor -proto-path")
	}

	args := []string{
		"--descriptor_set_out=" + descSetOut,
		"--include_imports",
		"--include_source_info",
	}
	for _, p := range allProtoPaths {
		args = append(args, "--proto_path="+p)
	}

	var params []string
	for k, v := range pathMap {
		params = append(params, fmt.Sprintf("M%s=%s", k, v))
	}
	params = append(params, "plugins=grpc")
	args = append(args, fmt.Sprintf("--go_out=%s:%s", strings.Join(params, ","), goOut))

	for _, f := range protoFiles {
		// We must prepend an go-style absolute path to the filename otherwise
		// protoc will complain that the files we specify here are not found
		// in any of proto-paths.
		//
		// We cannot specify --proto-path=. because of the following scenario:
		// we have file structure
		// - A
		//   - x.proto, imports "y.proto"
		//   - y.proto
		// - B
		//   - z.proto, imports "github.com/user/repo/A/x.proto"
		// If cproto is executed in B, proto path does not include A, so y.proto
		// is not found.
		// The solution is to always use absolute paths.
		args = append(args, path.Join(dir, f))
	}
	logging.Infof(c, "protoc %s", strings.Join(args, " "))
	protoc := exec.Command("protoc", args...)
	protoc.Stdout = os.Stdout
	protoc.Stderr = os.Stderr
	return outDir, protoc.Run()
}
614098
func (step extraConfigUpgradeStep) Run(ctx context.ProviderCallContext) error {
	const (
		legacyControllerTag   = "juju_controller_uuid_key"
		legacyIsControllerTag = "juju_is_controller_key"
	)
	return step.env.withSession(ctx, func(env *sessionEnviron) error {
		vms, err := env.client.VirtualMachines(env.ctx, env.namespace.Prefix()+"*")
		if err != nil || len(vms) == 0 {
			HandleCredentialError(err, ctx)
			return err
		}
		for _, vm := range vms {
			update := false
			isController := false
			for _, opt := range vm.Config.ExtraConfig {
				value := opt.GetOptionValue()
				switch value.Key {
				case legacyControllerTag:
					update = true
				case legacyIsControllerTag:
					isController = true
				}
			}
			if !update {
				continue
			}
			metadata := map[string]string{
				tags.JujuController: step.controllerUUID,
				tags.JujuModel:      env.Config().UUID(),
			}
			if isController {
				metadata[tags.JujuIsController] = "true"
			}
			if err := env.client.UpdateVirtualMachineExtraConfig(
				env.ctx, vm, metadata,
			); err != nil {
				HandleCredentialError(err, ctx)
				return errors.Annotatef(err, "updating VM %s", vm.Name)
			}
		}
		return nil
	})
}
1254415
func (ctx *workflowContext) registerFileCleanupFinalizer(localPath string) {
	cleanup := func(logger *logrus.Logger) {
		errRemove := os.Remove(localPath)
		if nil != errRemove {
			logger.WithFields(logrus.Fields{
				"Path":  localPath,
				"Error": errRemove,
			}).Warn("Failed to cleanup intermediate artifact")
		} else {
			logger.WithFields(logrus.Fields{
				"Path": relativePath(localPath),
			}).Debug("Build artifact deleted")
		}
	}
	ctx.registerFinalizer(cleanup)
}
987130
func (Pipe) Run(ctx *context.Context) error {
	var tmpl = tmpl.New(ctx)
	/* #nosec */
	for _, step := range ctx.Config.Before.Hooks {
		s, err := tmpl.Apply(step)
		if err != nil {
			return err
		}
		args := strings.Fields(s)
		log.Infof("running %s", color.CyanString(step))
		cmd := exec.Command(args[0], args[1:]...)
		cmd.Env = ctx.Env.Strings()
		out, err := cmd.CombinedOutput()
		log.Debug(string(out))
		if err != nil {
			return fmt.Errorf("hook failed: %s\n%v", step, string(out))
		}
	}
	return nil
}
1105187
func (s *StepCreateInstance) Run(ctx context.Context, state multistep.StateBag) multistep.StepAction {
	c := state.Get("config").(*Config)
	d := state.Get("driver").(Driver)

	ui := state.Get("ui").(packer.Ui)

	sourceImage, err := getImage(c, d)
	if err != nil {
		err := fmt.Errorf("Error getting source image for instance creation: %s", err)
		state.Put("error", err)
		ui.Error(err.Error())
		return multistep.ActionHalt
	}

	ui.Say(fmt.Sprintf("Using image: %s", sourceImage.Name))

	if sourceImage.IsWindows() && c.Comm.Type == "winrm" && c.Comm.WinRMPassword == "" {
		state.Put("create_windows_password", true)
	}

	ui.Say("Creating instance...")
	name := c.InstanceName

	var errCh <-chan error
	var metadata map[string]string
	metadata, err = c.createInstanceMetadata(sourceImage, string(c.Comm.SSHPublicKey))
	errCh, err = d.RunInstance(&InstanceConfig{
		AcceleratorType:              c.AcceleratorType,
		AcceleratorCount:             c.AcceleratorCount,
		Address:                      c.Address,
		Description:                  "New instance created by Packer",
		DisableDefaultServiceAccount: c.DisableDefaultServiceAccount,
		DiskSizeGb:                   c.DiskSizeGb,
		DiskType:                     c.DiskType,
		Image:                        sourceImage,
		Labels:                       c.Labels,
		MachineType:                  c.MachineType,
		Metadata:                     metadata,
		MinCpuPlatform:               c.MinCpuPlatform,
		Name:                         name,
		Network:                      c.Network,
		NetworkProjectId:             c.NetworkProjectId,
		OmitExternalIP:               c.OmitExternalIP,
		OnHostMaintenance:            c.OnHostMaintenance,
		Preemptible:                  c.Preemptible,
		Region:                       c.Region,
		ServiceAccountEmail:          c.ServiceAccountEmail,
		Scopes:                       c.Scopes,
		Subnetwork:                   c.Subnetwork,
		Tags:                         c.Tags,
		Zone:                         c.Zone,
	})

	if err == nil {
		ui.Message("Waiting for creation operation to complete...")
		select {
		case err = <-errCh:
		case <-time.After(c.stateTimeout):
			err = errors.New("time out while waiting for instance to create")
		}
	}

	if err != nil {
		err := fmt.Errorf("Error creating instance: %s", err)
		state.Put("error", err)
		ui.Error(err.Error())
		return multistep.ActionHalt
	}

	ui.Message("Instance has been created!")

	if s.Debug {
		if name != "" {
			ui.Message(fmt.Sprintf("Instance: %s started in %s", name, c.Zone))
		}
	}

	// Things succeeded, store the name so we can remove it later
	state.Put("instance_name", name)

	return multistep.ActionContinue
}
821877
func (b *Builder) Run(ctx context.Context, ui packer.Ui, hook packer.Hook) (packer.Artifact, error) {
	// Create the driver that we'll use to communicate with Parallels
	driver, err := parallelscommon.NewDriver()
	if err != nil {
		return nil, fmt.Errorf("Failed creating Parallels driver: %s", err)
	}

	// Set up the state.
	state := new(multistep.BasicStateBag)
	state.Put("config", b.config)
	state.Put("debug", b.config.PackerDebug)
	state.Put("driver", driver)
	state.Put("hook", hook)
	state.Put("ui", ui)
	state.Put("http_port", 0)

	// Build the steps.
	steps := []multistep.Step{
		&parallelscommon.StepPrepareParallelsTools{
			ParallelsToolsMode:   b.config.ParallelsToolsMode,
			ParallelsToolsFlavor: b.config.ParallelsToolsFlavor,
		},
		&parallelscommon.StepOutputDir{
			Force: b.config.PackerForce,
			Path:  b.config.OutputDir,
		},
		&common.StepCreateFloppy{
			Files:       b.config.FloppyConfig.FloppyFiles,
			Directories: b.config.FloppyConfig.FloppyDirectories,
		},
		&StepImport{
			Name:       b.config.VMName,
			SourcePath: b.config.SourcePath,
		},
		&parallelscommon.StepAttachParallelsTools{
			ParallelsToolsMode: b.config.ParallelsToolsMode,
		},
		new(parallelscommon.StepAttachFloppy),
		&parallelscommon.StepPrlctl{
			Commands: b.config.Prlctl,
			Ctx:      b.config.ctx,
		},
		&parallelscommon.StepRun{},
		&parallelscommon.StepTypeBootCommand{
			BootCommand:    b.config.FlatBootCommand(),
			BootWait:       b.config.BootWait,
			HostInterfaces: []string{},
			VMName:         b.config.VMName,
			Ctx:            b.config.ctx,
			GroupInterval:  b.config.BootConfig.BootGroupInterval,
		},
		&communicator.StepConnect{
			Config:    &b.config.SSHConfig.Comm,
			Host:      parallelscommon.CommHost,
			SSHConfig: b.config.SSHConfig.Comm.SSHConfigFunc(),
		},
		&parallelscommon.StepUploadVersion{
			Path: b.config.PrlctlVersionFile,
		},
		&parallelscommon.StepUploadParallelsTools{
			ParallelsToolsFlavor:    b.config.ParallelsToolsFlavor,
			ParallelsToolsGuestPath: b.config.ParallelsToolsGuestPath,
			ParallelsToolsMode:      b.config.ParallelsToolsMode,
			Ctx:                     b.config.ctx,
		},
		new(common.StepProvision),
		&parallelscommon.StepShutdown{
			Command: b.config.ShutdownCommand,
			Timeout: b.config.ShutdownTimeout,
		},
		&common.StepCleanupTempKeys{
			Comm: &b.config.SSHConfig.Comm,
		},
		&parallelscommon.StepPrlctl{
			Commands: b.config.PrlctlPost,
			Ctx:      b.config.ctx,
		},
		&parallelscommon.StepCompactDisk{
			Skip: b.config.SkipCompaction,
		},
	}

	// Run the steps.
	b.runner = common.NewRunnerWithPauseFn(steps, b.config.PackerConfig, ui, state)
	b.runner.Run(ctx, state)

	// Report any errors.
	if rawErr, ok := state.GetOk("error"); ok {
		return nil, rawErr.(error)
	}

	// If we were interrupted or cancelled, then just exit.
	if _, ok := state.GetOk(multistep.StateCancelled); ok {
		return nil, errors.New("Build was cancelled.")
	}

	if _, ok := state.GetOk(multistep.StateHalted); ok {
		return nil, errors.New("Build was halted.")
	}

	return parallelscommon.NewArtifact(b.config.OutputDir)
}
1317826
func (b *RefreshGraphBuilder) Build(path addrs.ModuleInstance) (*Graph, tfdiags.Diagnostics) {
	return (&BasicGraphBuilder{
		Steps:    b.Steps(),
		Validate: b.Validate,
		Name:     "RefreshGraphBuilder",
	}).Build(path)
}
718976
func (b *Builder) Run() error {
	wg := &errgroup.Group{}
	root, err := filepath.EvalSymlinks(b.RootPath)
	if err != nil {
		return err
	}
	err = filepath.Walk(root, func(path string, info os.FileInfo, err error) error {
		if info == nil {
			return filepath.SkipDir
		}

		base := strings.ToLower(filepath.Base(path))
		if strings.HasPrefix(base, "_") {
			return filepath.SkipDir
		}
		for _, f := range b.IgnoredFolders {
			if strings.ToLower(f) == base {
				if info.IsDir() {
					return filepath.SkipDir
				} else {
					return nil
				}
			}
		}
		if !info.IsDir() {
			wg.Go(func() error {
				return b.process(path)
			})
		}
		return nil
	})
	if err != nil {
		return err
	}
	if err := wg.Wait(); err != nil {
		return err
	}
	return b.dump()
}
837188
func (sdw *SplitDiffWorker) Run(ctx context.Context) error {
	resetVars()
	err := sdw.run(ctx)

	sdw.SetState(WorkerStateCleanUp)
	cerr := sdw.cleaner.CleanUp(sdw.wr)
	if cerr != nil {
		if err != nil {
			sdw.wr.Logger().Errorf2(cerr, "CleanUp failed in addition to job error")
		} else {
			err = cerr
		}
	}
	if err != nil {
		sdw.wr.Logger().Errorf2(err, "Run() error")
		sdw.SetState(WorkerStateError)
		return err
	}
	sdw.SetState(WorkerStateDone)
	return nil
}
1127079
func (d *dependencyUpdateCmd) run() error {
	man := &downloader.Manager{
		Out:        d.out,
		ChartPath:  d.chartpath,
		HelmHome:   d.helmhome,
		Keyring:    d.keyring,
		SkipUpdate: d.skipRefresh,
		Getters:    getter.All(settings),
	}
	if d.verify {
		man.Verify = downloader.VerifyAlways
	}
	if settings.Debug {
		man.Debug = true
	}
	return man.Update()
}
521716
func (b *PlanGraphBuilder) Steps() []GraphTransformer {
	b.once.Do(b.init)

	concreteResourceInstanceDeposed := func(a *NodeAbstractResourceInstance, key states.DeposedKey) dag.Vertex {
		return &NodePlanDeposedResourceInstanceObject{
			NodeAbstractResourceInstance: a,
			DeposedKey:                   key,
		}
	}

	steps := []GraphTransformer{
		// Creates all the resources represented in the config
		&ConfigTransformer{
			Concrete: b.ConcreteResource,
			Config:   b.Config,
		},

		// Add the local values
		&LocalTransformer{Config: b.Config},

		// Add the outputs
		&OutputTransformer{Config: b.Config},

		// Add orphan resources
		&OrphanResourceInstanceTransformer{
			Concrete: b.ConcreteResourceOrphan,
			State:    b.State,
			Config:   b.Config,
		},

		// We also need nodes for any deposed instance objects present in the
		// state, so we can plan to destroy them. (This intentionally
		// skips creating nodes for _current_ objects, since ConfigTransformer
		// created nodes that will do that during DynamicExpand.)
		&StateTransformer{
			ConcreteDeposed: concreteResourceInstanceDeposed,
			State:           b.State,
		},

		// Create orphan output nodes
		&OrphanOutputTransformer{
			Config: b.Config,
			State:  b.State,
		},

		// Attach the configuration to any resources
		&AttachResourceConfigTransformer{Config: b.Config},

		// Attach the state
		&AttachStateTransformer{State: b.State},

		// Add root variables
		&RootVariableTransformer{Config: b.Config},

		&MissingProvisionerTransformer{Provisioners: b.Components.ResourceProvisioners()},
		&ProvisionerTransformer{},

		// Add module variables
		&ModuleVariableTransformer{
			Config: b.Config,
		},

		TransformProviders(b.Components.ResourceProviders(), b.ConcreteProvider, b.Config),

		// Remove modules no longer present in the config
		&RemovedModuleTransformer{Config: b.Config, State: b.State},

		// Must attach schemas before ReferenceTransformer so that we can
		// analyze the configuration to find references.
		&AttachSchemaTransformer{Schemas: b.Schemas},

		// Connect so that the references are ready for targeting. We'll
		// have to connect again later for providers and so on.
		&ReferenceTransformer{},

		// Add the node to fix the state count boundaries
		&CountBoundaryTransformer{
			Config: b.Config,
		},

		// Target
		&TargetsTransformer{
			Targets: b.Targets,

			// Resource nodes from config have not yet been expanded for
			// "count", so we must apply targeting without indices. Exact
			// targeting will be dealt with later when these resources
			// DynamicExpand.
			IgnoreIndices: true,
		},

		// Detect when create_before_destroy must be forced on for a particular
		// node due to dependency edges, to avoid graph cycles during apply.
		&ForcedCBDTransformer{},

		// Close opened plugin connections
		&CloseProviderTransformer{},
		&CloseProvisionerTransformer{},

		// Single root
		&RootTransformer{},
	}

	if !b.DisableReduce {
		// Perform the transitive reduction to make our graph a bit
		// more sane if possible (it usually is possible).
		steps = append(steps, &TransitiveReductionTransformer{})
	}

	return steps
}
145172
func (mb *configManifestBuilder) Build(ctx context.Context) (m distribution.Manifest, err error) {
	type imageRootFS struct {
		Type      string   `json:"type"`
		DiffIDs   []diffID `json:"diff_ids,omitempty"`
		BaseLayer string   `json:"base_layer,omitempty"`
	}

	type imageHistory struct {
		Created    time.Time `json:"created"`
		Author     string    `json:"author,omitempty"`
		CreatedBy  string    `json:"created_by,omitempty"`
		Comment    string    `json:"comment,omitempty"`
		EmptyLayer bool      `json:"empty_layer,omitempty"`
	}

	type imageConfig struct {
		RootFS       *imageRootFS   `json:"rootfs,omitempty"`
		History      []imageHistory `json:"history,omitempty"`
		Architecture string         `json:"architecture,omitempty"`
	}

	var img imageConfig

	if err := json.Unmarshal(mb.configJSON, &img); err != nil {
		return nil, err
	}

	if len(img.History) == 0 {
		return nil, errors.New("empty history when trying to create schema1 manifest")
	}

	if len(img.RootFS.DiffIDs) != len(mb.descriptors) {
		return nil, fmt.Errorf("number of descriptors and number of layers in rootfs must match: len(%v) != len(%v)", img.RootFS.DiffIDs, mb.descriptors)
	}

	// Generate IDs for each layer
	// For non-top-level layers, create fake V1Compatibility strings that
	// fit the format and don't collide with anything else, but don't
	// result in runnable images on their own.
	type v1Compatibility struct {
		ID              string    `json:"id"`
		Parent          string    `json:"parent,omitempty"`
		Comment         string    `json:"comment,omitempty"`
		Created         time.Time `json:"created"`
		ContainerConfig struct {
			Cmd []string
		} `json:"container_config,omitempty"`
		Author    string `json:"author,omitempty"`
		ThrowAway bool   `json:"throwaway,omitempty"`
	}

	fsLayerList := make([]FSLayer, len(img.History))
	history := make([]History, len(img.History))

	parent := ""
	layerCounter := 0
	for i, h := range img.History[:len(img.History)-1] {
		var blobsum digest.Digest
		if h.EmptyLayer {
			if blobsum, err = mb.emptyTar(ctx); err != nil {
				return nil, err
			}
		} else {
			if len(img.RootFS.DiffIDs) <= layerCounter {
				return nil, errors.New("too many non-empty layers in History section")
			}
			blobsum = mb.descriptors[layerCounter].Digest
			layerCounter++
		}

		v1ID := digest.FromBytes([]byte(blobsum.Hex() + " " + parent)).Hex()

		if i == 0 && img.RootFS.BaseLayer != "" {
			// windows-only baselayer setup
			baseID := sha512.Sum384([]byte(img.RootFS.BaseLayer))
			parent = fmt.Sprintf("%x", baseID[:32])
		}

		v1Compatibility := v1Compatibility{
			ID:      v1ID,
			Parent:  parent,
			Comment: h.Comment,
			Created: h.Created,
			Author:  h.Author,
		}
		v1Compatibility.ContainerConfig.Cmd = []string{img.History[i].CreatedBy}
		if h.EmptyLayer {
			v1Compatibility.ThrowAway = true
		}
		jsonBytes, err := json.Marshal(&v1Compatibility)
		if err != nil {
			return nil, err
		}

		reversedIndex := len(img.History) - i - 1
		history[reversedIndex].V1Compatibility = string(jsonBytes)
		fsLayerList[reversedIndex] = FSLayer{BlobSum: blobsum}

		parent = v1ID
	}

	latestHistory := img.History[len(img.History)-1]

	var blobsum digest.Digest
	if latestHistory.EmptyLayer {
		if blobsum, err = mb.emptyTar(ctx); err != nil {
			return nil, err
		}
	} else {
		if len(img.RootFS.DiffIDs) <= layerCounter {
			return nil, errors.New("too many non-empty layers in History section")
		}
		blobsum = mb.descriptors[layerCounter].Digest
	}

	fsLayerList[0] = FSLayer{BlobSum: blobsum}
	dgst := digest.FromBytes([]byte(blobsum.Hex() + " " + parent + " " + string(mb.configJSON)))

	// Top-level v1compatibility string should be a modified version of the
	// image config.
	transformedConfig, err := MakeV1ConfigFromConfig(mb.configJSON, dgst.Hex(), parent, latestHistory.EmptyLayer)
	if err != nil {
		return nil, err
	}

	history[0].V1Compatibility = string(transformedConfig)

	tag := ""
	if tagged, isTagged := mb.ref.(reference.Tagged); isTagged {
		tag = tagged.Tag()
	}

	mfst := Manifest{
		Versioned: manifest.Versioned{
			SchemaVersion: 1,
		},
		Name:         mb.ref.Name(),
		Tag:          tag,
		Architecture: img.Architecture,
		FSLayers:     fsLayerList,
		History:      history,
	}

	return Sign(&mfst, mb.pk)
}
972166
func (c *diffCommand) Run(ctx *cmd.Context) error {
	client, err := c.getAPI()
	if err != nil {
		return err
	}
	defer func() { _ = client.Close() }()

	// Partially apply our time format
	formatTime := func(t time.Time) string {
		return common.FormatTime(&t, c.isoTime)
	}

	deltas, err := client.BranchInfo(c.branchName, c.detailed, formatTime)
	if err != nil {
		return errors.Trace(err)
	}
	return errors.Trace(c.out.Write(ctx, deltas))
}