// createCompose creates "dir/docker-compose.yml".
// If dir is empty, TempDir() is used.
496812
func createCompose(dir string, cli *client.Client, opts composeOptions) (string, error) {
	if dir == "" {
		var err error
		dir, err = ioutil.TempDir("", "integration-cli-on-swarm-")
		if err != nil {
			return "", err
		}
	}
	resolved := composeTemplateOptions{}
	resolved.composeOptions = opts
	workerImageInspect, _, err := cli.ImageInspectWithRaw(context.Background(), defaultWorkerImageName)
	if err != nil {
		return "", err
	}
	if len(workerImageInspect.RepoDigests) > 0 {
		resolved.WorkerImageDigest = workerImageInspect.RepoDigests[0]
	} else {
		// fall back for non-pushed image
		resolved.WorkerImageDigest = workerImageInspect.ID
	}
	info, err := cli.Info(context.Background())
	if err != nil {
		return "", err
	}
	resolved.SelfNodeID = info.Swarm.NodeID
	resolved.EnvDockerGraphDriver = os.Getenv("DOCKER_GRAPHDRIVER")
	resolved.EnvDockerExperimental = os.Getenv("DOCKER_EXPERIMENTAL")
	composeFilePath := filepath.Join(dir, "docker-compose.yml")
	tmpl, err := template.New("").Parse(composeTemplate)
	if err != nil {
		return "", err
	}
	f, err := os.Create(composeFilePath)
	if err != nil {
		return "", err
	}
	defer f.Close()
	if err = tmpl.Execute(f, resolved); err != nil {
		return "", err
	}
	return composeFilePath, nil
}
592446
func (d *DockerHelper) CreateContainers(num int) []string {
	ids := []string{}
	for i := 0; i < num; i++ {
		name := newContainerName()
		cfg := &container.Config{
			AttachStderr: false,
			AttachStdin:  false,
			AttachStdout: false,
			Tty:          true,
			Cmd:          strslice.StrSlice([]string{TestCommand}),
			Image:        TestImage,
		}
		container, err := d.client.ContainerCreate(getContext(), cfg, &container.HostConfig{}, &network.NetworkingConfig{}, name)
		ids = append(ids, container.ID)
		d.errStats.add("create containers", err)
	}
	return ids
}
1325552
func (s *service) Create(ctx context.Context, r *taskAPI.CreateTaskRequest) (*taskAPI.CreateTaskResponse, error) {
	log.G(ctx).Debugf("Create: %s", r.ID)

	// Hold the lock for the entire duration to avoid duplicate process creation.
	s.mu.Lock()
	defer s.mu.Unlock()

	_, err := namespaces.NamespaceRequired(ctx)
	if err != nil {
		return nil, errors.Wrap(err, "create namespace")
	}

	if r.Options != nil {
		v, err := typeurl.UnmarshalAny(r.Options)
		if err != nil {
			return nil, err
		}
		s.shimOpts = *v.(*options.Options)
	}

	if p := s.processes[r.ID]; p != nil {
		return nil, errdefs.ToGRPCf(errdefs.ErrAlreadyExists, "process %s already exists", r.ID)
	}
	if r.ID != s.id {
		return nil, errdefs.ToGRPCf(errdefs.ErrFailedPrecondition, "init process id '%s' != shim id '%s'", r.ID, s.id)
	}

	// Add the mounts to the layer paths
	if err := writeMountsToConfig(r.Bundle, r.Rootfs); err != nil {
		return nil, errdefs.ToGRPC(err)
	}

	// Create the IO for the process
	io, err := runc.NewPipeIO()
	if err != nil {
		return nil, errors.Wrap(err, "failed to create io pipes")
	}
	defer func() {
		if err != nil {
			io.Close()
		}
	}()
	// Create the upstream IO
	ps, err := newPipeSet(ctx, r.Stdin, r.Stdout, r.Stderr, r.Terminal)
	if err != nil {
		return nil, errors.Wrap(err, "failed to connect to upstream IO")
	}
	defer func() {
		if err != nil {
			ps.Close()
		}
	}()
	// Create the relay for them both.
	pr := newPipeRelay(ctx, ps, io)
	defer func() {
		if err != nil {
			pr.close()
		}
	}()

	if s.shimOpts.Debug {
		if s.debugLog == "" {
			if s.shimOpts.DebugType == options.Options_FILE {
				s.debugLog = filepath.Join(r.Bundle, fmt.Sprintf("runhcs-%s.log", r.ID))
			} else {
				logPath := safePipePrefix + fmt.Sprintf("runhcs-log-%s", r.ID)
				l, err := winio.ListenPipe(logPath, nil)
				if err != nil {
					return nil, err
				}
				s.debugLog = logPath
				s.debugListener = l

				// Accept connections and forward all logs for each runhcs.exe
				// invocation
				go func() {
					for {
						c, err := s.debugListener.Accept()
						if err != nil {
							if err == winio.ErrPipeListenerClosed {
								break
							}
							log.G(ctx).WithError(err).Debug("log accept failure")
							// Logrus error locally?
							continue
						}
						fields := map[string]interface{}{
							"log-source": "runhcs",
							"task-id":    r.ID,
						}
						go forwardRunhcsLogs(ctx, c, fields)
					}
				}()
			}
		}
	}

	pidfilePath := path.Join(r.Bundle, "runhcs-pidfile.pid")
	copts := &runhcs.CreateOpts{
		IO:      io,
		PidFile: pidfilePath,
	}
	rhcs := s.newRunhcs()
	if rhcs.Debug {
		if s.shimOpts.DebugType == options.Options_FILE {
			copts.ShimLog = filepath.Join(r.Bundle, fmt.Sprintf("runhcs-shim-%s.log", r.ID))
			copts.VMLog = filepath.Join(r.Bundle, fmt.Sprintf("runhcs-vmshim-%s.log", r.ID))
		} else {
			doForwardLogs := func(source, logPipeFmt string, opt *string) error {
				pipeName := fmt.Sprintf(logPipeFmt, r.ID)
				*opt = safePipePrefix + pipeName
				l, err := winio.ListenPipe(*opt, nil)
				if err != nil {
					return err
				}
				go func() {
					defer l.Close()
					c, err := l.Accept()
					if err != nil {
						log.G(ctx).
							WithField("task-id", r.ID).
							WithError(err).
							Errorf("failed to accept %s", pipeName)
					} else {
						fields := map[string]interface{}{
							"log-source": source,
							"task-id":    r.ID,
						}
						go forwardRunhcsLogs(ctx, c, fields)
					}
				}()
				return nil
			}

			err = doForwardLogs("runhcs-shim", "runhcs-shim-log-%s", &copts.ShimLog)
			if err != nil {
				return nil, err
			}

			err = doForwardLogs("runhcs--vm-shim", "runhcs-vm-shim-log-%s", &copts.VMLog)
			if err != nil {
				return nil, err
			}
		}
	}
	err = rhcs.Create(ctx, r.ID, r.Bundle, copts)
	if err != nil {
		return nil, err
	}

	// We successfully created the process. Convert from initpid to the container process.
	pid, err := runc.ReadPidFile(pidfilePath)
	if err != nil {
		return nil, errors.Wrap(err, "failed to read container pid from pidfile")
	}

	process, err := newProcess(
		ctx,
		s,
		r.ID,
		uint32(pid),
		pr,
		r.Bundle,
		r.Stdin,
		r.Stdout,
		r.Stderr,
		r.Terminal)

	if err != nil {
		return nil, err
	}
	s.processes[r.ID] = process

	s.publisher.Publish(ctx,
		runtime.TaskCreateEventTopic,
		&eventstypes.TaskCreate{
			ContainerID: process.id,
			Bundle:      process.bundle,
			Rootfs:      r.Rootfs,
			IO: &eventstypes.TaskIO{
				Stdin:    r.Stdin,
				Stdout:   r.Stdout,
				Stderr:   r.Stderr,
				Terminal: r.Terminal,
			},
			Checkpoint: "",
			Pid:        uint32(pid),
		})

	return &taskAPI.CreateTaskResponse{
		Pid: uint32(pid),
	}, nil
}
774287
func createDirWithOverlayOpaque(tmp string) (string, error) {
	lower := filepath.Join(tmp, "l")
	upper := filepath.Join(tmp, "u")
	work := filepath.Join(tmp, "w")
	merged := filepath.Join(tmp, "m")
	for _, s := range []string{lower, upper, work, merged} {
		if err := os.MkdirAll(s, 0700); err != nil {
			return "", errors.Wrapf(err, "failed to mkdir %s", s)
		}
	}
	dummyBase := "d"
	lowerDummy := filepath.Join(lower, dummyBase)
	if err := os.MkdirAll(lowerDummy, 0700); err != nil {
		return "", errors.Wrapf(err, "failed to create a dummy lower directory %s", lowerDummy)
	}
	mOpts := fmt.Sprintf("lowerdir=%s,upperdir=%s,workdir=%s", lower, upper, work)
	// docker/pkg/mount.Mount() requires procfs to be mounted. So we use syscall.Mount() directly instead.
	if err := syscall.Mount("overlay", merged, "overlay", uintptr(0), mOpts); err != nil {
		return "", errors.Wrapf(err, "failed to mount overlay (%s) on %s", mOpts, merged)
	}
	mergedDummy := filepath.Join(merged, dummyBase)
	if err := os.Remove(mergedDummy); err != nil {
		syscall.Unmount(merged, 0)
		return "", errors.Wrapf(err, "failed to rmdir %s", mergedDummy)
	}
	// upperDummy becomes a 0,0-char device file here
	if err := os.Mkdir(mergedDummy, 0700); err != nil {
		syscall.Unmount(merged, 0)
		return "", errors.Wrapf(err, "failed to mkdir %s", mergedDummy)
	}
	// upperDummy becomes a directory with trusted.overlay.opaque xattr
	// (but can't be verified in userns)
	if err := syscall.Unmount(merged, 0); err != nil {
		return "", errors.Wrapf(err, "failed to unmount %s", merged)
	}
	upperDummy := filepath.Join(upper, dummyBase)
	return upperDummy, nil
}
755499
func (fl *FolderList) Create(ctx context.Context, req *fuse.CreateRequest, resp *fuse.CreateResponse) (_ fs.Node, _ fs.Handle, err error) {
	fl.fs.vlog.CLogf(ctx, libkb.VLog1, "FL Create")
	tlfName := tlf.CanonicalName(req.Name)
	defer func() { err = fl.processError(ctx, libkbfs.WriteMode, tlfName, err) }()
	if strings.HasPrefix(req.Name, "._") {
		// Quietly ignore writes to special macOS files, without
		// triggering a notification.
		return nil, nil, syscall.ENOENT
	}
	return nil, nil, libkbfs.NewWriteUnsupportedError(tlfhandle.BuildCanonicalPath(fl.PathType(), string(tlfName)))
}
38230
func (s *Service) Create(ctx context.Context, options options.Create) error {
	containers, err := s.collectContainers(ctx)
	if err != nil {
		return err
	}

	if err := s.ensureImageExists(ctx, options.NoBuild, options.ForceBuild); err != nil {
		return err
	}

	if len(containers) != 0 {
		return s.eachContainer(ctx, containers, func(c *container.Container) error {
			_, err := s.recreateIfNeeded(ctx, c, options.NoRecreate, options.ForceRecreate)
			return err
		})
	}

	namer, err := s.namer(ctx, 1)
	if err != nil {
		return err
	}

	_, err = s.createContainer(ctx, namer, "", nil, false)
	return err
}
914365
func LoadComposefile(dockerCli command.Cli, opts options.Deploy) (*composetypes.Config, error) {
	configDetails, err := getConfigDetails(opts.Composefiles, dockerCli.In())
	if err != nil {
		return nil, err
	}

	dicts := getDictsFrom(configDetails.ConfigFiles)
	config, err := loader.Load(configDetails)
	if err != nil {
		if fpe, ok := err.(*loader.ForbiddenPropertiesError); ok {
			return nil, errors.Errorf("Compose file contains unsupported options:\n\n%s\n",
				propertyWarnings(fpe.Properties))
		}

		return nil, err
	}

	unsupportedProperties := loader.GetUnsupportedProperties(dicts...)
	if len(unsupportedProperties) > 0 {
		fmt.Fprintf(dockerCli.Err(), "Ignoring unsupported options: %s\n\n",
			strings.Join(unsupportedProperties, ", "))
	}

	deprecatedProperties := loader.GetDeprecatedProperties(dicts...)
	if len(deprecatedProperties) > 0 {
		fmt.Fprintf(dockerCli.Err(), "Ignoring deprecated options:\n\n%s\n\n",
			propertyWarnings(deprecatedProperties))
	}
	return config, nil
}
640141
func (d *kubeDockerClient) CreateExec(id string, opts dockertypes.ExecConfig) (*dockertypes.IDResponse, error) {
	ctx, cancel := d.getTimeoutContext()
	defer cancel()
	resp, err := d.client.ContainerExecCreate(ctx, id, opts)
	if ctxErr := contextError(ctx); ctxErr != nil {
		return nil, ctxErr
	}
	if err != nil {
		return nil, err
	}
	return &resp, nil
}
517564
func (f *DockerFactory) Create(projectName string, volumeConfigs map[string]*config.VolumeConfig, serviceConfigs *config.ServiceConfigs, volumeEnabled bool) (project.Volumes, error) {
	cli := f.ClientFactory.Create(nil)
	return VolumesFromServices(cli, projectName, volumeConfigs, serviceConfigs, volumeEnabled)
}
829007
func (virtualDisk *VirtualDisk) Create(ctx context.Context, datastore *vclib.Datastore) (string, error) {
	if virtualDisk.VolumeOptions.DiskFormat == "" {
		virtualDisk.VolumeOptions.DiskFormat = vclib.ThinDiskType
	}
	if !virtualDisk.VolumeOptions.VerifyVolumeOptions() {
		klog.Error("VolumeOptions verification failed. volumeOptions: ", virtualDisk.VolumeOptions)
		return "", vclib.ErrInvalidVolumeOptions
	}
	if virtualDisk.VolumeOptions.StoragePolicyID != "" && virtualDisk.VolumeOptions.StoragePolicyName != "" {
		return "", fmt.Errorf("Storage Policy ID and Storage Policy Name both set, Please set only one parameter")
	}
	return getDiskManager(virtualDisk, VirtualDiskCreateOperation).Create(ctx, datastore)
}
424043
func CreateCommand(factory app.ProjectFactory) cli.Command {
	return cli.Command{
		Name:   "create",
		Usage:  "Create all services but do not start",
		Action: app.WithProject(factory, app.ProjectCreate),
		Flags: []cli.Flag{
			cli.BoolFlag{
				Name:  "no-recreate",
				Usage: "If containers already exist, don't recreate them. Incompatible with --force-recreate.",
			},
			cli.BoolFlag{
				Name:  "force-recreate",
				Usage: "Recreate containers even if their configuration and image haven't changed. Incompatible with --no-recreate.",
			},
			cli.BoolFlag{
				Name:  "no-build",
				Usage: "Don't build an image, even if it's missing.",
			},
		},
	}
}
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
}
212850
func (s *VolumeSource) CreateVolumes(ctx context.ProviderCallContext, params []storage.VolumeParams) ([]storage.CreateVolumesResult, error) {
	s.MethodCall(s, "CreateVolumes", ctx, params)
	if s.CreateVolumesFunc != nil {
		return s.CreateVolumesFunc(ctx, params)
	}
	return nil, errors.NotImplementedf("CreateVolumes")
}
1372644
func cmdCreate(params Parameters) *subcommands.Command {
	return &subcommands.Command{
		UsageLine: "create [options]",
		ShortDesc: "builds and uploads a package instance file",
		LongDesc:  "Builds and uploads a package instance file.",
		CommandRun: func() subcommands.CommandRun {
			c := &createRun{}
			c.registerBaseFlags()
			c.Opts.inputOptions.registerFlags(&c.Flags)
			c.Opts.refsOptions.registerFlags(&c.Flags)
			c.Opts.tagsOptions.registerFlags(&c.Flags)
			c.Opts.clientOptions.registerFlags(&c.Flags, params, withoutRootDir)
			c.Opts.uploadOptions.registerFlags(&c.Flags)
			c.Opts.hashOptions.registerFlags(&c.Flags)
			return c
		},
	}
}
710580
func (s *VolumeService) CreateVolume(p *CreateVolumeParams) (*CreateVolumeResponse, error) {
	resp, err := s.cs.newRequest("createVolume", p.toURLValues())
	if err != nil {
		return nil, err
	}

	var r CreateVolumeResponse
	if err := json.Unmarshal(resp, &r); err != nil {
		return nil, err
	}

	// If we have a async client, we need to wait for the async result
	if s.cs.async {
		b, err := s.cs.GetAsyncJobResult(r.JobID, s.cs.timeout)
		if err != nil {
			if err == AsyncTimeoutErr {
				return &r, err
			}
			return nil, err
		}

		b, err = getRawValue(b)
		if err != nil {
			return nil, err
		}

		if err := json.Unmarshal(b, &r); err != nil {
			return nil, err
		}
	}

	return &r, nil
}
867887
func (m *TaskManager) Create(ctx context.Context, id string, opts runtime.CreateOpts) (_ runtime.Task, err error) {
	bundle, err := NewBundle(ctx, m.root, m.state, id, opts.Spec.Value)
	if err != nil {
		return nil, err
	}
	defer func() {
		if err != nil {
			bundle.Delete()
		}
	}()
	b := shimBinary(ctx, bundle, opts.Runtime, m.containerdAddress, m.events, m.tasks)
	shim, err := b.Start(ctx)
	if err != nil {
		return nil, err
	}
	defer func() {
		if err != nil {
			shim.Shutdown(ctx)
			shim.Close()
		}
	}()
	t, err := shim.Create(ctx, opts)
	if err != nil {
		return nil, err
	}
	m.tasks.Add(ctx, t)
	return t, nil
}
344038
func Create(rootFS vfs.Filesystem) *MountFS {
	return &MountFS{
		rootFS:  rootFS,
		mounts:  make(map[string]vfs.Filesystem),
		parents: make(map[string][]string),
	}
}