// This file contains helper functions to convert docker API types to runtime
// API types, or vice versa.
973958
func imageToRuntimeAPIImage(image *dockertypes.ImageSummary) (*runtimeapi.Image, error) {
	if image == nil {
		return nil, fmt.Errorf("unable to convert a nil pointer to a runtime API image")
	}

	size := uint64(image.VirtualSize)
	return &runtimeapi.Image{
		Id:          image.ID,
		RepoTags:    image.RepoTags,
		RepoDigests: image.RepoDigests,
		Size_:       size,
	}, nil
}
1273759
func main() {
	if len(os.Args) <= 1 {
		log.Fatal("Supply a version")
	}
	version := os.Args[1]
	if !strings.HasPrefix(version, "v") {
		version = "v" + version
	}
	oAPIDefs := wfv1.GetOpenAPIDefinitions(func(name string) spec.Ref {
		return spec.MustCreateRef("#/definitions/" + common.EscapeJsonPointer(swaggify(name)))
	})
	defs := spec.Definitions{}
	for defName, val := range oAPIDefs {
		defs[swaggify(defName)] = val.Schema
	}
	swagger := spec.Swagger{
		SwaggerProps: spec.SwaggerProps{
			Swagger:     "2.0",
			Definitions: defs,
			Paths:       &spec.Paths{Paths: map[string]spec.PathItem{}},
			Info: &spec.Info{
				InfoProps: spec.InfoProps{
					Title:   "Argo",
					Version: version,
				},
			},
		},
	}
	jsonBytes, err := json.MarshalIndent(swagger, "", "  ")
	if err != nil {
		log.Fatal(err.Error())
	}
	fmt.Println(string(jsonBytes))
}
168532
func (b *lowBuilder) kvFileType() string {
	switch {
	case b.high.SQLite != "":
		return "sqlite"
	case b.high.KVFile != "":
		return "kv"
	case b.high.LevelDB != "":
		return "leveldb"
	default:
		return sorted.DefaultKVFileType
	}
}
8531
func WithDockerfile(dockerfile string) func(*icmd.Cmd) func() {
	return func(cmd *icmd.Cmd) func() {
		cmd.Command = append(cmd.Command, "-")
		cmd.Stdin = strings.NewReader(dockerfile)
		return nil
	}
}
1242445
func BuildDockerImageWithFlags(serviceName string,
	dockerFilepath string,
	dockerTags map[string]string,
	buildTags string,
	linkFlags string,
	logger *logrus.Logger) error {

	// BEGIN DOCKER PRECONDITIONS
	// Ensure that serviceName and tags are lowercase to make Docker happy
	var dockerErrors []string
	for eachKey, eachValue := range dockerTags {
		if eachKey != strings.ToLower(eachKey) ||
			eachValue != strings.ToLower(eachValue) {
			dockerErrors = append(dockerErrors, fmt.Sprintf("--tag %s:%s MUST be lower case", eachKey, eachValue))
		}
	}

	if len(dockerErrors) > 0 {
		return errors.Errorf("Docker build errors: %s", strings.Join(dockerErrors[:], ", "))
	}
	// BEGIN Informational - output the docker version...
	dockerVersionCmd := exec.Command("docker", "-v")
	dockerVersionCmdErr := system.RunOSCommand(dockerVersionCmd, logger)
	if dockerVersionCmdErr != nil {
		return errors.Wrapf(dockerVersionCmdErr, "Attempting to get docker version")
	}
	// END Informational - output the docker version...

	// END DOCKER PRECONDITIONS

	// Compile this binary for minimal Docker size
	// https://blog.codeship.com/building-minimal-docker-containers-for-go-applications/
	currentTime := time.Now().UnixNano()
	executableOutput := fmt.Sprintf("%s-%d-docker.lambda.amd64", serviceName, currentTime)
	buildErr := system.BuildGoBinary(serviceName,
		executableOutput,
		false,
		fmt.Sprintf("%d", currentTime),
		buildTags,
		linkFlags,
		false,
		logger)
	if buildErr != nil {
		return errors.Wrapf(buildErr, "Attempting to build Docker binary")
	}
	defer func() {
		removeErr := os.Remove(executableOutput)
		if removeErr != nil {
			logger.WithFields(logrus.Fields{
				"Path":  executableOutput,
				"Error": removeErr,
			}).Warn("Failed to delete temporary Docker binary")
		}
	}()

	// ARG SPARTA_DOCKER_BINARY reference s.t. we can supply the binary
	// name to the build..
	// We need to build the static binary s.t. we can add it to the Docker container...
	// Build the image...
	dockerArgs := []string{
		"build",
		"--build-arg",
		fmt.Sprintf("%s=%s", BinaryNameArgument, executableOutput),
	}

	if dockerFilepath != "" {
		dockerArgs = append(dockerArgs, "--file", dockerFilepath)
	}
	// Add the latest tag
	// dockerArgs = append(dockerArgs, "--tag", fmt.Sprintf("sparta/%s:latest", serviceName))
	logger.WithFields(logrus.Fields{
		"Tags": dockerTags,
	}).Info("Creating Docker image")

	for eachKey, eachValue := range dockerTags {
		dockerArgs = append(dockerArgs, "--tag", fmt.Sprintf("%s:%s",
			strings.ToLower(eachKey),
			strings.ToLower(eachValue)))
	}

	dockerArgs = append(dockerArgs, ".")
	dockerCmd := exec.Command("docker", dockerArgs...)
	return system.RunOSCommand(dockerCmd, logger)
}
492722
func NewContainerRuntime(execer utilsexec.Interface, criSocket string) (ContainerRuntime, error) {
	var toolName string
	var runtime ContainerRuntime

	if criSocket != constants.DefaultDockerCRISocket {
		toolName = "crictl"
		// !!! temporary work around crictl warning:
		// Using "/var/run/crio/crio.sock" as endpoint is deprecated,
		// please consider using full url format "unix:///var/run/crio/crio.sock"
		if filepath.IsAbs(criSocket) && goruntime.GOOS != "windows" {
			criSocket = "unix://" + criSocket
		}
		runtime = &CRIRuntime{execer, criSocket}
	} else {
		toolName = "docker"
		runtime = &DockerRuntime{execer}
	}

	if _, err := execer.LookPath(toolName); err != nil {
		return nil, errors.Wrapf(err, "%s is required for container runtime", toolName)
	}

	return runtime, nil
}
16815
func Runtime(t api.TaskSpec) (string, error) {
	switch r := t.GetRuntime().(type) {
	case *api.TaskSpec_Attachment:
		return "attachment", nil
	case *api.TaskSpec_Container:
		return "container", nil
	case *api.TaskSpec_Generic:
		return strings.ToLower(r.Generic.Kind), nil
	default:
		return "", errUnknownRuntime
	}
}
924274
func (apiDef *APIDefinition) allResourceTypes(rts map[string]ResourceType, libraries map[string]*Library) map[string]ResourceType {
	if len(rts) == 0 {
		rts = map[string]ResourceType{}
	}
	for libName, l := range libraries {
		for rtName, rt := range l.ResourceTypes {
			rts[libName+"."+rtName] = rt
		}
		// Recursively processing siblings
		if l.Libraries != nil {
			apiDef.allResourceTypes(rts, l.Libraries)
		}
	}
	return rts
}
752619
func MakeFileFunc(baseDir string, encBase64 bool) function.Function {
	return function.New(&function.Spec{
		Params: []function.Parameter{
			{
				Name: "path",
				Type: cty.String,
			},
		},
		Type: function.StaticReturnType(cty.String),
		Impl: func(args []cty.Value, retType cty.Type) (cty.Value, error) {
			path := args[0].AsString()
			src, err := readFileBytes(baseDir, path)
			if err != nil {
				return cty.UnknownVal(cty.String), err
			}

			switch {
			case encBase64:
				enc := base64.StdEncoding.EncodeToString(src)
				return cty.StringVal(enc), nil
			default:
				if !utf8.Valid(src) {
					return cty.UnknownVal(cty.String), fmt.Errorf("contents of %s are not valid UTF-8; use the filebase64 function to obtain the Base64 encoded contents or the other file functions (e.g. filemd5, filesha256) to obtain file hashing results instead", path)
				}
				return cty.StringVal(string(src)), nil
			}
		},
	})
}
537525
func Convert_api_to_public_DockerImage(in *docker10.DockerImage, out *public.DockerImage) error {
	*out = public.DockerImage{
		ID:            in.ID,
		Parent:        in.Parent,
		Comment:       in.Comment,
		Created:       in.Created.Time,
		Container:     in.Container,
		DockerVersion: in.DockerVersion,
		Author:        in.Author,
		Architecture:  in.Architecture,
		Size:          in.Size,
	}
	if err := Convert_api_to_public_DockerConfig(&in.ContainerConfig, &out.ContainerConfig); err != nil {
		return err
	}
	if in.Config != nil {
		out.Config = &public.DockerConfig{}
		if err := Convert_api_to_public_DockerConfig(in.Config, out.Config); err != nil {
			return err
		}
	}
	return nil
}
766120
func (ds *dockerService) ListContainers(_ context.Context, r *runtimeapi.ListContainersRequest) (*runtimeapi.ListContainersResponse, error) {
	filter := r.GetFilter()
	opts := dockertypes.ContainerListOptions{All: true}

	opts.Filters = dockerfilters.NewArgs()
	f := newDockerFilter(&opts.Filters)
	// Add filter to get *only* (non-sandbox) containers.
	f.AddLabel(containerTypeLabelKey, containerTypeLabelContainer)

	if filter != nil {
		if filter.Id != "" {
			f.Add("id", filter.Id)
		}
		if filter.State != nil {
			f.Add("status", toDockerContainerStatus(filter.GetState().State))
		}
		if filter.PodSandboxId != "" {
			f.AddLabel(sandboxIDLabelKey, filter.PodSandboxId)
		}

		if filter.LabelSelector != nil {
			for k, v := range filter.LabelSelector {
				f.AddLabel(k, v)
			}
		}
	}
	containers, err := ds.client.ListContainers(opts)
	if err != nil {
		return nil, err
	}
	// Convert docker to runtime api containers.
	result := []*runtimeapi.Container{}
	for i := range containers {
		c := containers[i]

		converted, err := toRuntimeAPIContainer(&c)
		if err != nil {
			klog.V(4).Infof("Unable to convert docker to runtime API container: %v", err)
			continue
		}

		result = append(result, converted)
	}

	return &runtimeapi.ListContainersResponse{Containers: result}, nil
}
1326893
func (p *Pod) SaveRuntime() error {
	path := filepath.Join(p.Root, RuntimeConfigPath)
	buf, err := json.Marshal(p.RuntimePod)
	if err != nil {
		return err
	}

	return ioutil.WriteFile(path, buf, 0644)
}
1095698
func (_m *APIClient) ContainerList(ctx context.Context, options types.ContainerListOptions) ([]types.Container, error) {
	ret := _m.Called(ctx, options)

	var r0 []types.Container
	if rf, ok := ret.Get(0).(func(context.Context, types.ContainerListOptions) []types.Container); ok {
		r0 = rf(ctx, options)
	} else {
		if ret.Get(0) != nil {
			r0 = ret.Get(0).([]types.Container)
		}
	}

	var r1 error
	if rf, ok := ret.Get(1).(func(context.Context, types.ContainerListOptions) error); ok {
		r1 = rf(ctx, options)
	} else {
		r1 = ret.Error(1)
	}

	return r0, r1
}
1206735
func writeFunctions(api *design.APIDefinition, outDir string) ([]string, error) {
	ctxFile := filepath.Join(outDir, "jsonapi_errors_stringer.go")
	ctxWr, err := codegen.SourceFileFor(ctxFile)
	if err != nil {
		panic(err) // bug
	}
	title := fmt.Sprintf("%s: String functions for JSONAPI Errors - See goasupport/jsonapi_errors_stringer/generator.go", api.Context())
	imports := []*codegen.ImportSpec{
		codegen.SimpleImport("fmt"),
		codegen.SimpleImport("github.com/davecgh/go-spew/spew"),
	}
	ctxWr.WriteHeader(title, "app", imports)
	if err := ctxWr.ExecuteTemplate("jsonAPIErrorsStringer", jsonAPIErrorsStringer, nil, nil); err != nil {
		return nil, err
	}
	return []string{ctxFile}, nil
}
570162
func (engine *Engine) DumpAllToFile(fp string, tp ...core.DbType) error {
	f, err := os.Create(fp)
	if err != nil {
		return err
	}
	defer f.Close()
	return engine.DumpAll(f, tp...)
}
610447
func (builder *Layered) CreateDockerfile(config *api.Config) error {
	buffer := bytes.Buffer{}

	user, err := builder.docker.GetImageUser(builder.config.BuilderImage)
	if err != nil {
		return err
	}

	scriptsDir := filepath.Join(getDestination(config), "scripts")
	sourcesDir := filepath.Join(getDestination(config), "src")

	uploadScriptsDir := path.Join(config.WorkingDir, constants.UploadScripts)

	buffer.WriteString(fmt.Sprintf("FROM %s\n", builder.config.BuilderImage))
	// only COPY scripts dir if required scripts are present, i.e. the dir is not empty;
	// even if the "scripts" dir exists, the COPY would fail if it was empty
	scriptsIncluded := checkValidDirWithContents(uploadScriptsDir)
	if scriptsIncluded {
		glog.V(2).Infof("The scripts are included in %q directory", uploadScriptsDir)
		buffer.WriteString(fmt.Sprintf("COPY scripts %s\n", filepath.ToSlash(scriptsDir)))
	} else {
		// if an err on reading or opening dir, can't copy it
		glog.V(2).Infof("Could not gather scripts from the directory %q", uploadScriptsDir)
	}
	buffer.WriteString(fmt.Sprintf("COPY src %s\n", filepath.ToSlash(sourcesDir)))

	//TODO: We need to account for images that may not have chown. There is a proposal
	//      to specify the owner for COPY here: https://github.com/docker/docker/pull/28499
	if len(user) > 0 {
		buffer.WriteString("USER root\n")
		if scriptsIncluded {
			buffer.WriteString(fmt.Sprintf("RUN chown -R %s -- %s %s\n", user, filepath.ToSlash(scriptsDir), filepath.ToSlash(sourcesDir)))
		} else {
			buffer.WriteString(fmt.Sprintf("RUN chown -R %s -- %s\n", user, filepath.ToSlash(sourcesDir)))
		}
		buffer.WriteString(fmt.Sprintf("USER %s\n", user))
	}

	uploadDir := filepath.Join(builder.config.WorkingDir, "upload")
	if err := builder.fs.WriteFile(filepath.Join(uploadDir, "Dockerfile"), buffer.Bytes()); err != nil {
		return err
	}
	glog.V(2).Infof("Writing custom Dockerfile to %s", uploadDir)
	return nil
}
97200
func DumpClosureEnvFunction(env *Zlisp, name string, args []Sexp) (Sexp, error) {
	if len(args) != 1 {
		return SexpNull, WrongNargs
	}

	switch f := args[0].(type) {
	case *SexpFunction:
		s := ClosureToString(f, env)
		return &SexpStr{S: s}, nil
	default:
		return SexpNull, fmt.Errorf("_closdump needs an *SexpFunction to inspect")
	}
}