// BuildHostnameFile writes the container's hostname file.
775040
func (container *Container) BuildHostnameFile() error {
	hostnamePath, err := container.GetRootResourcePath("hostname")
	if err != nil {
		return err
	}
	container.HostnamePath = hostnamePath
	return ioutil.WriteFile(container.HostnamePath, []byte(container.Config.Hostname+"\n"), 0644)
}
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
}
1196518
func Hostname(c context.Context) string {
	p := getPayload(c)
	if p == nil {
		return ""
	}
	return p.Instance
}
566147
func (s *CloneStackInput) SetHostnameTheme(v string) *CloneStackInput {
	s.HostnameTheme = &v
	return s
}
942462
func (sa *StubAPIClient) ContainerCreate(ctx context.Context, config *container.Config, hostConfig *container.HostConfig, networking *network.NetworkingConfig, containerName string) (container.ContainerCreateCreatedBody, error) {
	sa.called()
	return sa.ContainerCreateFn(ctx, config, hostConfig, networking, containerName)
}
929057
func (b *KubeletBuilder) buildSystemdEnvironmentFile(kubeletConfig *kops.KubeletConfigSpec) (*nodetasks.File, error) {
	// @step: ensure the masters do not get a bootstrap configuration
	if b.UseBootstrapTokens() && b.IsMaster {
		kubeletConfig.BootstrapKubeconfig = ""
	}

	if kubeletConfig.ExperimentalAllowedUnsafeSysctls != nil {
		// The ExperimentalAllowedUnsafeSysctls flag was renamed in k/k #63717
		if b.IsKubernetesGTE("1.11") {
			glog.V(1).Info("ExperimentalAllowedUnsafeSysctls was renamed in k8s 1.11+, please use AllowedUnsafeSysctls instead.")
			kubeletConfig.AllowedUnsafeSysctls = append(kubeletConfig.ExperimentalAllowedUnsafeSysctls, kubeletConfig.AllowedUnsafeSysctls...)
			kubeletConfig.ExperimentalAllowedUnsafeSysctls = nil
		}
	}

	// TODO: Dump the separate file for flags - just complexity!
	flags, err := flagbuilder.BuildFlags(kubeletConfig)
	if err != nil {
		return nil, fmt.Errorf("error building kubelet flags: %v", err)
	}

	// Add cloud config file if needed
	// We build this flag differently because it depends on CloudConfig, and to expose it directly
	// would be a degree of freedom we don't have (we'd have to write the config to different files)
	// We can always add this later if it is needed.
	if b.Cluster.Spec.CloudConfig != nil {
		flags += " --cloud-config=" + CloudConfigFilePath
	}

	if b.UsesCNI() {
		flags += " --cni-bin-dir=" + b.CNIBinDir()
		flags += " --cni-conf-dir=" + b.CNIConfDir()
	}

	if b.UsesSecondaryIP() {
		sess := session.Must(session.NewSession())
		metadata := ec2metadata.New(sess)
		localIpv4, err := metadata.GetMetadata("local-ipv4")
		if err != nil {
			return nil, fmt.Errorf("error fetching the local-ipv4 address from the ec2 meta-data: %v", err)
		}
		flags += " --node-ip=" + localIpv4
	}

	if b.Cluster.Spec.Networking != nil && b.Cluster.Spec.Networking.Kubenet != nil {
		// Kubenet is neither CNI nor not-CNI, so we need to pass it `--cni-bin-dir` also
		if b.IsKubernetesGTE("1.9") {
			// Flag renamed in #53564
			flags += " --cni-bin-dir=" + b.CNIBinDir()
		} else {
			flags += " --network-plugin-dir=" + b.CNIBinDir()
		}
	}

	if b.usesContainerizedMounter() {
		// We don't want to expose this in the model while it is experimental, but it is needed on COS
		flags += " --experimental-mounter-path=" + path.Join(containerizedMounterHome, "mounter")
	}

	sysconfig := "DAEMON_ARGS=\"" + flags + "\"\n"
	// Makes kubelet read /root/.docker/config.json properly
	sysconfig = sysconfig + "HOME=\"/root" + "\"\n"

	t := &nodetasks.File{
		Path:     "/etc/sysconfig/kubelet",
		Contents: fi.NewStringResource(sysconfig),
		Type:     nodetasks.FileType_File,
	}

	return t, nil
}
543940
func buildBody(level, title string) map[string]interface{} {
	timestamp := time.Now().Unix()
	hostname, _ := os.Hostname()

	data := map[string]interface{}{
		"environment": Environment,
		"title":       title,
		"level":       level,
		"timestamp":   timestamp,
		"platform":    Platform,
		"language":    "go",
		"server": map[string]interface{}{
			"host": hostname,
		},
		"notifier": map[string]interface{}{
			"name":    NAME,
			"version": VERSION,
		},
	}
	if CodeVersion != "" {
		data["code_version"] = CodeVersion
	}

	return map[string]interface{}{
		"access_token": Token,
		"data":         data,
	}
}
235766
func (d *HypervPS4Driver) GetHostName(ip string) (string, error) {
	return powershell.GetHostName(ip)
}
262073
func (s *HostService) GetHostByName(name string, opts ...OptionFunc) (*Host, int, error) {
	id, count, err := s.GetHostID(name, opts...)
	if err != nil {
		return nil, count, err
	}

	r, count, err := s.GetHostByID(id, opts...)
	if err != nil {
		return nil, count, err
	}
	return r, count, nil
}
958924
func (a *AgentServer) BuildHost(request BuildHostRequest, hostResponse *host.Host) error {
	*hostResponse = host.Host{}

	h, err := host.Build(request.IP, fmt.Sprintf("%d", request.Port), request.PoolID, request.Memory, a.staticIPs...)
	if err != nil {
		return err
	}

	plog.WithFields(logrus.Fields{
		"poolid": request.PoolID,
		"staticips": a.staticIPs,
		"ipcount": len(a.staticIPs),
	}).Info("Built Host record")
	if h != nil {
		*hostResponse = *h
	}
	return nil
}
1273719
func (o *GetMapNameURL) Build() (*url.URL, error) {
	var _result url.URL

	var _path = "/map/{name}"

	name := o.Name
	if name != "" {
		_path = strings.Replace(_path, "{name}", name, -1)
	} else {
		return nil, errors.New("name is required on GetMapNameURL")
	}

	_basePath := o._basePath
	if _basePath == "" {
		_basePath = "/v1"
	}
	_result.Path = golangswaggerpaths.Join(_basePath, _path)

	return &_result, nil
}
1367620
func buildPrecreateDNSHostnames(cluster *kops.Cluster) []string {
	dnsInternalSuffix := ".internal." + cluster.ObjectMeta.Name

	var dnsHostnames []string

	if cluster.Spec.MasterPublicName != "" {
		dnsHostnames = append(dnsHostnames, cluster.Spec.MasterPublicName)
	} else {
		glog.Warningf("cannot pre-create MasterPublicName - not set")
	}

	if cluster.Spec.MasterInternalName != "" {
		dnsHostnames = append(dnsHostnames, cluster.Spec.MasterInternalName)
	} else {
		glog.Warningf("cannot pre-create MasterInternalName - not set")
	}

	for _, etcdCluster := range cluster.Spec.EtcdClusters {
		etcClusterName := "etcd-" + etcdCluster.Name
		if etcdCluster.Name == "main" {
			// Special case
			etcClusterName = "etcd"
		}
		for _, etcdClusterMember := range etcdCluster.Members {
			name := etcClusterName + "-" + etcdClusterMember.Name + dnsInternalSuffix
			dnsHostnames = append(dnsHostnames, name)
		}
	}

	return dnsHostnames
}
555194
func setHostnameRhel(hostname, file string) error {
	return ioutils.FindAndReplace(file, file, `HOSTNAME\s*=\s*\S+`,
		fmt.Sprintf("HOSTNAME=%s", hostname), 0644)
}
980801
func ContainerCreateFile(
	ctx context.Context,
	client api.Client,
	containerPath, fileName string,
	fileSize int,
	fileMode FileMode,
	fileHndl io.ReadCloser,
	overwrite bool) error {

	var params api.OrderedValues
	if !overwrite {
		params = overwriteFalseQueryString
	}

	return client.Put(
		ctx,
		realNamespacePath(client),
		path.Join(containerPath, fileName),
		params,
		map[string]string{
			"x-isi-ifs-target-type":    "object",
			"x-isi-ifs-access-control": fileMode.String(),
			"Content-Length":           fmt.Sprintf("%d", fileSize),
		},
		fileHndl,
		nil)
}
506395
func buildNameList(args []string, file string) ([]string, error) {
	var list []string
	if len(args) > 0 {
		list = append(list, args...)
	}

	// unpack file from source
	if len(file) != 0 {
		listData, err := readLines(file)
		if err != nil {
			return nil, err
		}
		list = append(list, listData...)
	}

	return list, nil
}
278070
func (p *propHost) GetHostName() string {
	if p.Host == nil {
		return ""
	}
	return p.Host.GetName()
}
790223
func (c *Conn) VerifyHostname(host string) error {
	cert, err := c.PeerCertificate()
	if err != nil {
		return err
	}
	return cert.VerifyHostname(host)
}