// CreateDockerfile takes the various inputs and creates the Dockerfile used by
// the docker cmd to create the image produced by s2i.
421505
func (builder *Dockerfile) CreateDockerfile(config *api.Config) error {
	glog.V(4).Infof("Constructing image build context directory at %s", config.WorkingDir)
	buffer := bytes.Buffer{}

	if len(config.ImageWorkDir) == 0 {
		config.ImageWorkDir = "/opt/app-root/src"
	}

	imageUser := config.AssembleUser

	// where files will land inside the new image.
	scriptsDestDir := filepath.Join(getDestination(config), "scripts")
	sourceDestDir := filepath.Join(getDestination(config), "src")
	artifactsDestDir := filepath.Join(getDestination(config), "artifacts")
	artifactsTar := sanitize(filepath.ToSlash(filepath.Join(defaultDestination, "artifacts.tar")))
	// hasAllScripts indicates that we blindly trust all scripts are provided in the image scripts dir
	imageScriptsDir, hasAllScripts := getImageScriptsDir(config)
	var providedScripts map[string]bool
	if !hasAllScripts {
		providedScripts = scanScripts(filepath.Join(config.WorkingDir, builder.uploadScriptsDir))
	}

	if config.Incremental {
		imageTag := util.FirstNonEmpty(config.IncrementalFromTag, config.Tag)
		if len(imageTag) == 0 {
			return errors.New("Image tag is missing for incremental build")
		}
		// Incremental builds run via a multistage Dockerfile
		buffer.WriteString(fmt.Sprintf("FROM %s as cached\n", imageTag))
		var artifactsScript string
		if _, provided := providedScripts[constants.SaveArtifacts]; provided {
			// switch to root to COPY and chown content
			glog.V(2).Infof("Override save-artifacts script is included in directory %q", builder.uploadScriptsDir)
			buffer.WriteString("# Copying in override save-artifacts script\n")
			buffer.WriteString("USER root\n")
			artifactsScript = sanitize(filepath.ToSlash(filepath.Join(scriptsDestDir, "save-artifacts")))
			uploadScript := sanitize(filepath.ToSlash(filepath.Join(builder.uploadScriptsDir, "save-artifacts")))
			buffer.WriteString(fmt.Sprintf("COPY %s %s\n", uploadScript, artifactsScript))
			buffer.WriteString(fmt.Sprintf("RUN chown %s:0 %s\n", sanitize(imageUser), artifactsScript))
		} else {
			buffer.WriteString(fmt.Sprintf("# Save-artifacts script sourced from builder image based on user input or image metadata.\n"))
			artifactsScript = sanitize(filepath.ToSlash(filepath.Join(imageScriptsDir, "save-artifacts")))
		}
		// switch to the image user if it is not root
		if len(imageUser) > 0 && imageUser != "root" {
			buffer.WriteString(fmt.Sprintf("USER %s\n", imageUser))
		}
		buffer.WriteString(fmt.Sprintf("RUN if [ -s %[1]s ]; then %[1]s > %[2]s; else touch %[2]s; fi\n", artifactsScript, artifactsTar))
	}

	// main stage of the Dockerfile
	buffer.WriteString(fmt.Sprintf("FROM %s\n", config.BuilderImage))

	imageLabels := util.GenerateOutputImageLabels(builder.sourceInfo, config)
	for k, v := range config.Labels {
		imageLabels[k] = v
	}
	if len(imageLabels) > 0 {
		first := true
		buffer.WriteString("LABEL ")
		for k, v := range imageLabels {
			if !first {
				buffer.WriteString(fmt.Sprintf(" \\\n      "))
			}
			buffer.WriteString(fmt.Sprintf("%q=%q", k, v))
			first = false
		}
		buffer.WriteString("\n")
	}

	env := createBuildEnvironment(config.WorkingDir, config.Environment)
	buffer.WriteString(fmt.Sprintf("%s", env))

	// run as root to COPY and chown source content
	buffer.WriteString("USER root\n")
	chownList := make([]string, 0)

	if config.Incremental {
		// COPY artifacts.tar from the `cached` stage
		buffer.WriteString(fmt.Sprintf("COPY --from=cached %[1]s %[1]s\n", artifactsTar))
		chownList = append(chownList, artifactsTar)
	}

	if len(providedScripts) > 0 {
		// Only COPY scripts dir if required scripts are present and needed.
		// Even if the "scripts" dir exists, the COPY would fail if it was empty.
		glog.V(2).Infof("Override scripts are included in directory %q", builder.uploadScriptsDir)
		scriptsDest := sanitize(filepath.ToSlash(scriptsDestDir))
		buffer.WriteString("# Copying in override assemble/run scripts\n")
		buffer.WriteString(fmt.Sprintf("COPY %s %s\n", sanitize(filepath.ToSlash(builder.uploadScriptsDir)), scriptsDest))
		chownList = append(chownList, scriptsDest)
	}

	// copy in the user's source code.
	buffer.WriteString("# Copying in source code\n")
	sourceDest := sanitize(filepath.ToSlash(sourceDestDir))
	buffer.WriteString(fmt.Sprintf("COPY %s %s\n", sanitize(filepath.ToSlash(builder.uploadSrcDir)), sourceDest))
	chownList = append(chownList, sourceDest)

	// add injections
	glog.V(4).Infof("Processing injected inputs: %#v", config.Injections)
	config.Injections = util.FixInjectionsWithRelativePath(config.ImageWorkDir, config.Injections)
	glog.V(4).Infof("Processed injected inputs: %#v", config.Injections)

	if len(config.Injections) > 0 {
		buffer.WriteString("# Copying in injected content\n")
	}
	for _, injection := range config.Injections {
		src := sanitize(filepath.ToSlash(filepath.Join(constants.Injections, injection.Source)))
		dest := sanitize(filepath.ToSlash(injection.Destination))
		buffer.WriteString(fmt.Sprintf("COPY %s %s\n", src, dest))
		chownList = append(chownList, dest)
	}

	// chown directories COPYed to image
	if len(chownList) > 0 {
		buffer.WriteString("# Change file ownership to the assemble user. Builder image must support chown command.\n")
		buffer.WriteString(fmt.Sprintf("RUN chown -R %s:0", sanitize(imageUser)))
		for _, dir := range chownList {
			buffer.WriteString(fmt.Sprintf(" %s", dir))
		}
		buffer.WriteString("\n")
	}

	// run remaining commands as the image user
	if len(imageUser) > 0 && imageUser != "root" {
		buffer.WriteString(fmt.Sprintf("USER %s\n", imageUser))
	}

	if config.Incremental {
		buffer.WriteString("# Extract artifact content\n")
		buffer.WriteString(fmt.Sprintf("RUN if [ -s %[1]s ]; then mkdir -p %[2]s; tar -xf %[1]s -C %[2]s; fi && \\\n", artifactsTar, sanitize(filepath.ToSlash(artifactsDestDir))))
		buffer.WriteString(fmt.Sprintf("    rm %s\n", artifactsTar))
	}

	if _, provided := providedScripts[constants.Assemble]; provided {
		buffer.WriteString(fmt.Sprintf("RUN %s\n", sanitize(filepath.ToSlash(filepath.Join(scriptsDestDir, "assemble")))))
	} else {
		buffer.WriteString(fmt.Sprintf("# Assemble script sourced from builder image based on user input or image metadata.\n"))
		buffer.WriteString(fmt.Sprintf("# If this file does not exist in the image, the build will fail.\n"))
		buffer.WriteString(fmt.Sprintf("RUN %s\n", sanitize(filepath.ToSlash(filepath.Join(imageScriptsDir, "assemble")))))
	}

	filesToDelete, err := util.ListFilesToTruncate(builder.fs, config.Injections)
	if err != nil {
		return err
	}
	if len(filesToDelete) > 0 {
		wroteRun := false
		buffer.WriteString("# Cleaning up injected secret content\n")
		for _, file := range filesToDelete {
			if !wroteRun {
				buffer.WriteString(fmt.Sprintf("RUN rm %s", file))
				wroteRun = true
				continue
			}
			buffer.WriteString(fmt.Sprintf(" && \\\n"))
			buffer.WriteString(fmt.Sprintf("    rm %s", file))
		}
		buffer.WriteString("\n")
	}

	if _, provided := providedScripts[constants.Run]; provided {
		buffer.WriteString(fmt.Sprintf("CMD %s\n", sanitize(filepath.ToSlash(filepath.Join(scriptsDestDir, "run")))))
	} else {
		buffer.WriteString(fmt.Sprintf("# Run script sourced from builder image based on user input or image metadata.\n"))
		buffer.WriteString(fmt.Sprintf("# If this file does not exist in the image, the build will fail.\n"))
		buffer.WriteString(fmt.Sprintf("CMD %s\n", sanitize(filepath.ToSlash(filepath.Join(imageScriptsDir, "run")))))
	}

	if err := builder.fs.WriteFile(filepath.Join(config.AsDockerfile), buffer.Bytes()); err != nil {
		return err
	}
	glog.V(2).Infof("Wrote custom Dockerfile to %s", config.AsDockerfile)
	return nil
}
153727
func (api *ImagesAPI) CreateFromFile(imagePath string, options *ImageCreateOptions) (task *Task, err error) {
	params := imageCreateOptionsToMap(options)
	res, err := api.client.restClient.MultipartUploadFile(api.client.Endpoint+imageUrl, imagePath, params, api.client.options.TokenOptions)
	if err != nil {
		return
	}
	defer res.Body.Close()
	result, err := getTask(getError(res))
	return result, err
}
131445
func (f *FS) CreateFile(ctx context.Context, fi *dokan.FileInfo, cd *dokan.CreateData) (dokan.File, dokan.CreateStatus, error) {
	// Only allow the current user access
	if !fi.IsRequestorUserSidEqualTo(currentUserSID) {
		f.log.CErrorf(ctx, "FS CreateFile - Refusing real access: SID match error")
		return openFakeRoot(ctx, f, fi)
	}
	return f.openRaw(ctx, fi, cd)
}
120976
func (s *Server) createContainerPlatform(container *oci.Container, infraContainer *oci.Container, cgroupParent string) error {
	if s.defaultIDMappings != nil && !s.defaultIDMappings.Empty() {
		rootPair := s.defaultIDMappings.RootPair()

		for _, path := range []string{container.BundlePath(), container.MountPoint()} {
			if err := os.Chown(path, rootPair.UID, rootPair.GID); err != nil {
				return errors.Wrapf(err, "cannot chown %s to %d:%d", path, rootPair.UID, rootPair.GID)
			}
			if err := makeAccessible(path, rootPair.UID, rootPair.GID); err != nil {
				return errors.Wrapf(err, "cannot make %s accessible to %d:%d", path, rootPair.UID, rootPair.GID)
			}
		}
	}
	return s.Runtime().CreateContainer(container, cgroupParent)
}
998124
func (l *localFileSystem) CreateFile(filePath string, length uint64) (io.WriteCloser, error) {
	f, err := os.Create(filePath)
	if err != nil {
		return nil, trace.Wrap(err)
	}

	return f, nil
}
441484
func (c *Communicator) uploadFile(dst string, src io.Reader, fi *os.FileInfo) error {
	// command format: docker cp /path/to/infile containerid:/path/to/outfile
	log.Printf("Copying to %s on container %s.", dst, c.ContainerID)

	localCmd := exec.Command("docker", "cp", "-",
		fmt.Sprintf("%s:%s", c.ContainerID, filepath.Dir(dst)))

	stderrP, err := localCmd.StderrPipe()
	if err != nil {
		return fmt.Errorf("Failed to open pipe: %s", err)
	}

	stdin, err := localCmd.StdinPipe()
	if err != nil {
		return fmt.Errorf("Failed to open pipe: %s", err)
	}

	if err := localCmd.Start(); err != nil {
		return err
	}

	archive := tar.NewWriter(stdin)
	header, err := tar.FileInfoHeader(*fi, "")
	if err != nil {
		return err
	}
	header.Name = filepath.Base(dst)
	archive.WriteHeader(header)
	numBytes, err := io.Copy(archive, src)
	if err != nil {
		return fmt.Errorf("Failed to pipe upload: %s", err)
	}
	log.Printf("Copied %d bytes for %s", numBytes, dst)

	if err := archive.Close(); err != nil {
		return fmt.Errorf("Failed to close archive: %s", err)
	}
	if err := stdin.Close(); err != nil {
		return fmt.Errorf("Failed to close stdin: %s", err)
	}

	stderrOut, err := ioutil.ReadAll(stderrP)
	if err != nil {
		return err
	}

	if err := localCmd.Wait(); err != nil {
		return fmt.Errorf("Failed to upload to '%s' in container: %s. %s.", dst, stderrOut, err)
	}

	if err := c.fixDestinationOwner(dst); err != nil {
		return err
	}

	return nil
}
533571
func fsCreateFile(ctx context.Context, filePath string, reader io.Reader, buf []byte, fallocSize int64) (int64, error) {
	if filePath == "" || reader == nil {
		logger.LogIf(ctx, errInvalidArgument)
		return 0, errInvalidArgument
	}

	if err := checkPathLength(filePath); err != nil {
		logger.LogIf(ctx, err)
		return 0, err
	}

	if err := mkdirAll(pathutil.Dir(filePath), 0777); err != nil {
		logger.LogIf(ctx, err)
		return 0, err
	}

	if err := checkDiskFree(pathutil.Dir(filePath), fallocSize); err != nil {
		logger.LogIf(ctx, err)
		return 0, err
	}

	writer, err := lock.Open(filePath, os.O_CREATE|os.O_WRONLY, 0666)
	if err != nil {
		return 0, osErrToFSFileErr(err)
	}
	defer writer.Close()

	// Fallocate only if the size is final object is known.
	if fallocSize > 0 {
		if err = fsFAllocate(int(writer.Fd()), 0, fallocSize); err != nil {
			logger.LogIf(ctx, err)
			return 0, err
		}
	}

	var bytesWritten int64
	if buf != nil {
		bytesWritten, err = io.CopyBuffer(writer, reader, buf)
		if err != nil {
			if err != io.ErrUnexpectedEOF {
				logger.LogIf(ctx, err)
			}
			return 0, err
		}
	} else {
		bytesWritten, err = io.Copy(writer, reader)
		if err != nil {
			logger.LogIf(ctx, err)
			return 0, err
		}
	}

	return bytesWritten, nil
}
454957
func (f *FakeDockerClient) CreateContainer(c dockertypes.ContainerCreateConfig) (*dockercontainer.ContainerCreateCreatedBody, error) {
	f.Lock()
	defer f.Unlock()
	f.appendCalled(CalledDetail{name: "create"})
	if err := f.popError("create"); err != nil {
		return nil, err
	}
	// This is not a very good fake. We'll just add this container's name to the list.
	name := dockerNamePrefix + c.Name
	id := GetFakeContainerID(name)
	f.appendContainerTrace("Created", id)
	timestamp := f.Clock.Now()
	// The newest container should be in front, because we assume so in GetPodStatus()
	f.RunningContainerList = append([]dockertypes.Container{
		{ID: id, Names: []string{name}, Image: c.Config.Image, Created: timestamp.Unix(), State: StatusCreatedPrefix, Labels: c.Config.Labels},
	}, f.RunningContainerList...)
	f.ContainerMap[id] = convertFakeContainer(&FakeContainer{
		ID: id, Name: name, Config: c.Config, HostConfig: c.HostConfig, CreatedAt: timestamp})

	f.normalSleep(100, 25, 25)

	return &dockercontainer.ContainerCreateCreatedBody{ID: id}, nil
}
327451
func (c *FakeImageStreamMappings) Create(imageStreamMapping *image.ImageStreamMapping) (result *v1.Status, err error) {
	obj, err := c.Fake.
		Invokes(testing.NewCreateAction(imagestreammappingsResource, c.ns, imageStreamMapping), &v1.Status{})

	if obj == nil {
		return nil, err
	}
	return obj.(*v1.Status), err
}
456354
func (dh *Client) CreateContainer(options *docker.ContainerConfig, name string) (containerId string, e error) {
	imageId := options.Image

	// Verify image available on host.
	_, e = dh.ImageHistory(imageId)
	if e != nil && e.Error() == "resource not found" {
		if e = dh.PullImage(imageId); e != nil {
			return "", e
		}
	}

	imgDetails, err := dh.ImageDetails(imageId)
	if err != nil {
		return "", err
	}
	options.Env = append(options.Env, "DOCKER_IMAGE="+imgDetails.Id)

	container := &docker.Container{}
	u := dh.Address + "/containers/create"

	if name != "" {
		u += "?name=" + name
	}

	if _, e = dh.postJSON(u, options, container); e != nil {
		return "", fmt.Errorf("failed creating container: %s", e.Error())
	}
	return container.Id, e
}
1308243
func (c *FakeImageStreams) Create(imageStream *image.ImageStream) (result *image.ImageStream, err error) {
	obj, err := c.Fake.
		Invokes(testing.NewCreateAction(imagestreamsResource, c.ns, imageStream), &image.ImageStream{})

	if obj == nil {
		return nil, err
	}
	return obj.(*image.ImageStream), err
}
877962
func (c *container) Create(cmds []string) {
	adHoc := (len(cmds) > 0)
	if !adHoc {
		c.Rm(true, false)
	}
	msg := "Creating container %s"
	if adHoc {
		msg += " (ad-hoc)"
	}
	fmt.Fprintf(c.CommandsOut(), msg+" ...\n", c.ActualName(adHoc))

	args := append([]string{"create"}, c.createArgs(cmds)...)
	executeCommand("docker", args, c.CommandsOut(), c.CommandsErr())

	c.connectWithNetworks(adHoc)
}
117679
func (r *SourceRepository) AddDockerfile(contents string) error {
	dockerfile, err := NewDockerfile(contents)
	if err != nil {
		return err
	}
	if r.info == nil {
		r.info = &SourceRepositoryInfo{}
	}
	r.info.Dockerfile = dockerfile
	r.SetStrategy(newapp.StrategyDocker)
	r.forceAddDockerfile = true
	return nil
}
649713
func (c *Client) CreateDiskOffering(p *CreateDiskOfferingParameter) (*DiskOffering, error) {
	obj, err := c.Request("createDiskOffering", convertParamToMap(p))
	if err != nil {
		return nil, err
	}
	return obj.(*DiskOffering), err
}
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
}
1314228
func createConfigFile() error {
	filePath := filepath.Join(ConfigDir(), ConfigFileName)

	var err error

	if _, err = os.Stat(filePath); os.IsNotExist(err) {
		if err = ioutil.WriteFile(filePath, []byte(defaultConfigFile), 0644); err != nil {
			return err
		}
	} else if err != nil {
		return err
	}

	return nil
}
1253486
func (fs *memFS) createFile(
	parentID fuseops.InodeID,
	name string,
	mode os.FileMode) (entry fuseops.ChildInodeEntry, err error) {
	// Grab the parent, which we will update shortly.
	parent := fs.getInodeOrDie(parentID)

	// Ensure that the name doesn't already exist, so we don't wind up with a
	// duplicate.
	_, _, exists := parent.LookUpChild(name)
	if exists {
		err = fuse.EEXIST
		return
	}

	// Set up attributes for the child.
	now := time.Now()
	childAttrs := fuseops.InodeAttributes{
		Nlink:  1,
		Mode:   mode,
		Atime:  now,
		Mtime:  now,
		Ctime:  now,
		Crtime: now,
		Uid:    fs.uid,
		Gid:    fs.gid,
	}

	// Allocate a child.
	childID, child := fs.allocateInode(childAttrs)

	// Add an entry in the parent.
	parent.AddChild(childID, name, fuseutil.DT_File)

	// Fill in the response entry.
	entry.Child = childID
	entry.Attributes = child.attrs

	// We don't spontaneously mutate, so the kernel can cache as long as it wants
	// (since it also handles invalidation).
	entry.AttributesExpiration = time.Now().Add(365 * 24 * time.Hour)
	entry.EntryExpiration = entry.AttributesExpiration

	return
}