// RunKustomizeBuild runs kustomize build given a filesystem and a path
771389
func RunKustomizeBuild(out io.Writer, fSys fs.FileSystem, path string) error {
	f := k8sdeps.NewFactory()
	o := build.NewOptions(path, "")
	return o.RunBuild(out, fSys, f.ResmapF, f.TransformerF)
}
1362854
func (o *BuildChainOptions) RunBuildChain() error {
	ist := imagegraph.MakeImageStreamTagObjectMeta2(o.defaultNamespace, o.name)

	desc, err := describe.NewChainDescriber(o.buildClient, o.namespaces, o.output).Describe(ist, !o.triggerOnly, o.reverse)
	if err != nil {
		if _, isNotFoundErr := err.(describe.NotFoundErr); isNotFoundErr {
			// Try to get the imageStreamTag via a direct GET
			if _, getErr := o.imageClient.ImageStreamTags(o.defaultNamespace).Get(o.name, metav1.GetOptions{}); getErr != nil {
				return getErr
			}
			fmt.Printf("Image stream tag %q in %q doesn't have any dependencies.\n", o.name, o.defaultNamespace)
			return nil
		}
		return err
	}

	fmt.Println(desc)

	return nil
}
1193159
func (b *KubeletBuilder) Build(c *fi.ModelBuilderContext) error {
	kubeletConfig, err := b.buildKubeletConfig()
	if err != nil {
		return fmt.Errorf("error building kubelet config: %v", err)
	}

	{
		t, err := b.buildSystemdEnvironmentFile(kubeletConfig)
		if err != nil {
			return err
		}
		c.AddTask(t)
	}

	{
		// @TODO Extract to common function?
		assetName := "kubelet"
		assetPath := ""
		// @TODO make Find call to an interface, we cannot mock out this function because it finds a file on disk
		asset, err := b.Assets.Find(assetName, assetPath)
		if err != nil {
			return fmt.Errorf("error trying to locate asset %q: %v", assetName, err)
		}
		if asset == nil {
			return fmt.Errorf("unable to locate asset %q", assetName)
		}

		c.AddTask(&nodetasks.File{
			Path:     b.kubeletPath(),
			Contents: asset,
			Type:     nodetasks.FileType_File,
			Mode:     s("0755"),
		})
	}
	{
		if kubeletConfig.PodManifestPath != "" {
			t, err := b.buildManifestDirectory(kubeletConfig)
			if err != nil {
				return err
			}
			c.EnsureTask(t)
		}
	}
	{
		// We always create the directory, avoids circular dependency on a bind-mount
		c.AddTask(&nodetasks.File{
			Path: filepath.Dir(b.KubeletKubeConfig()),
			Type: nodetasks.FileType_Directory,
			Mode: s("0755"),
		})

		// @check if bootstrap tokens are enabled and create the appropreiate certificates
		if b.UseBootstrapTokens() {
			// @check if a master and if so, we bypass the token strapping and instead generate our own kubeconfig
			if b.IsMaster {
				glog.V(3).Info("kubelet bootstrap tokens are enabled and running on a master")

				task, err := b.buildMasterKubeletKubeconfig()
				if err != nil {
					return err
				}
				c.AddTask(task)
			}
		} else {
			kubeconfig, err := b.BuildPKIKubeconfig("kubelet")
			if err != nil {
				return err
			}

			c.AddTask(&nodetasks.File{
				Path:     b.KubeletKubeConfig(),
				Contents: fi.NewStringResource(kubeconfig),
				Type:     nodetasks.FileType_File,
				Mode:     s("0400"),
			})
		}
	}

	if b.UsesCNI() {
		c.AddTask(&nodetasks.File{
			Path: b.CNIConfDir(),
			Type: nodetasks.FileType_Directory,
		})
	}

	if err := b.addStaticUtils(c); err != nil {
		return err
	}

	if err := b.addContainerizedMounter(c); err != nil {
		return err
	}

	c.AddTask(b.buildSystemdService())

	return nil
}
1000456
func (d *resetCmd) run() error {
	if d.kubeClient == nil {
		_, c, err := getKubeClient(settings.KubeContext, settings.KubeConfig)
		if err != nil {
			return fmt.Errorf("could not get kubernetes client: %s", err)
		}
		d.kubeClient = c
	}

	res, err := d.client.ListReleases(
		helm.ReleaseListStatuses([]release.Status_Code{release.Status_DEPLOYED}),
	)
	if !d.force && err != nil {
		return prettyError(err)
	}

	if !d.force && res != nil && len(res.Releases) > 0 {
		return fmt.Errorf("there are still %d deployed releases (Tip: use --force to remove Tiller. Releases will not be deleted.)", len(res.Releases))
	}

	if err := installer.Uninstall(d.kubeClient, &installer.Options{Namespace: d.namespace}); err != nil {
		return fmt.Errorf("error unstalling Tiller: %s", err)
	}

	if d.removeHelmHome {
		if err := deleteDirectories(d.home, d.out); err != nil {
			return err
		}
	}

	fmt.Fprintln(d.out, "Tiller (the Helm server-side component) has been uninstalled from your Kubernetes Cluster.")
	return nil
}
991403
func (c *AddCAASCommand) Run(ctx *cmd.Context) error {
	if err := c.verifyName(c.caasName); err != nil {
		return errors.Trace(err)
	}
	rdr, clusterName, err := c.getConfigReader(ctx)
	if err != nil {
		return errors.Trace(err)
	}
	if closer, ok := rdr.(io.Closer); ok {
		defer closer.Close()
	}

	config := provider.KubeCloudParams{
		ClusterName:        clusterName,
		CaasName:           c.caasName,
		ContextName:        c.contextName,
		HostCloudRegion:    c.hostCloudRegion,
		CaasType:           c.caasType,
		ClientConfigGetter: c.newClientConfigReader,
	}

	newCloud, credential, credentialName, err := provider.CloudFromKubeConfig(rdr, config)
	if err != nil {
		return errors.Trace(err)
	}

	broker, err := c.brokerGetter(newCloud, credential)
	if err != nil {
		return errors.Trace(err)
	}
	storageParams := provider.KubeCloudStorageParams{
		WorkloadStorage:        c.workloadStorage,
		HostCloudRegion:        c.hostCloudRegion,
		MetadataChecker:        broker,
		GetClusterMetadataFunc: c.getClusterMetadataFunc(ctx),
	}

	storageMsg, err := provider.UpdateKubeCloudWithStorage(&newCloud, storageParams)
	if err != nil {
		if provider.IsClusterQueryError(err) {
			if err.Error() == "" {
				return errors.New(clusterQueryErrMsg)
			}
			return errors.Annotate(err, clusterQueryErrMsg)
		}
		if provider.IsNoRecommendedStorageError(err) {
			return errors.Errorf(noRecommendedStorageErrMsg, err.(provider.NoRecommendedStorageError).StorageProvider())
		}
		if provider.IsUnknownClusterError(err) {
			return errors.Errorf(unknownClusterErrMsg, err.(provider.UnknownClusterError).CloudName)
		}
		return errors.Trace(err)
	}

	if err := addCloudToLocal(c.cloudMetadataStore, newCloud); err != nil {
		return errors.Trace(err)
	}

	if err := c.addCredentialToLocal(c.caasName, credential, credentialName); err != nil {
		return errors.Trace(err)
	}

	if clusterName == "" {
		clusterName = c.hostCloudRegion
		if clusterName == "" {
			clusterName = newCloud.HostCloudRegion
		}
	}
	if c.controllerName == "" {
		successMsg := fmt.Sprintf("k8s substrate %q added as cloud %q%s", clusterName, c.caasName, storageMsg)
		successMsg += fmt.Sprintf("\nYou can now bootstrap to this cloud by running 'juju bootstrap %s'.", c.caasName)
		fmt.Fprintln(ctx.Stdout, successMsg)
		return nil
	}

	cloudClient, err := c.addCloudAPIFunc()
	if err != nil {
		return errors.Trace(err)
	}
	defer cloudClient.Close()

	if err := c.addCloudToControllerWithRegion(cloudClient, newCloud); err != nil {
		return errors.Trace(err)
	}
	if err := c.addCredentialToController(cloudClient, credential, credentialName); err != nil {
		return errors.Trace(err)
	}
	successMsg := fmt.Sprintf("k8s substrate %q added as cloud %q%s", clusterName, c.caasName, storageMsg)
	fmt.Fprintln(ctx.Stdout, successMsg)

	return nil
}
569290
func (o *OpenShiftKubeAPIServerServer) RunAPIServer(stopCh <-chan struct{}) error {
	// try to decode into our new types first.  right now there is no validation, no file path resolution.  this unsticks the operator to start.
	// TODO add those things
	configContent, err := ioutil.ReadFile(o.ConfigFile)
	if err != nil {
		return err
	}
	scheme := runtime.NewScheme()
	utilruntime.Must(kubecontrolplanev1.Install(scheme))
	codecs := serializer.NewCodecFactory(scheme)
	obj, err := runtime.Decode(codecs.UniversalDecoder(kubecontrolplanev1.GroupVersion, configv1.GroupVersion, osinv1.GroupVersion), configContent)
	switch {
	case runtime.IsMissingVersion(err): // fall through to legacy master config
	case runtime.IsMissingKind(err): // fall through to legacy master config
	case runtime.IsNotRegisteredError(err): // fall through to legacy master config
	case err != nil:
		return err
	case err == nil:
		// Resolve relative to CWD
		absoluteConfigFile, err := api.MakeAbs(o.ConfigFile, "")
		if err != nil {
			return err
		}
		configFileLocation := path.Dir(absoluteConfigFile)

		config := obj.(*kubecontrolplanev1.KubeAPIServerConfig)
		if err := helpers.ResolvePaths(configconversion.GetKubeAPIServerConfigFileReferences(config), configFileLocation); err != nil {
			return err
		}
		configdefault.SetRecommendedKubeAPIServerConfigDefaults(config)
		configdefault.ResolveDirectoriesForSATokenVerification(config)

		return RunOpenShiftKubeAPIServerServer(config, stopCh)
	}

	// TODO this code disappears once the kube-core operator switches to external types
	// TODO we will simply run some defaulting code and convert
	// reading internal gives us defaulting that we need for now
	masterConfig, err := configapilatest.ReadAndResolveMasterConfig(o.ConfigFile)
	if err != nil {
		return err
	}
	validationResults := validation.ValidateMasterConfig(masterConfig, nil)
	if len(validationResults.Warnings) != 0 {
		for _, warning := range validationResults.Warnings {
			klog.Warningf("%v", warning)
		}
	}
	if len(validationResults.Errors) != 0 {
		return kerrors.NewInvalid(configapi.Kind("MasterConfig"), "master-config.yaml", validationResults.Errors)
	}
	// round trip to external
	externalMasterConfig, err := configapi.Scheme.ConvertToVersion(masterConfig, legacyconfigv1.LegacySchemeGroupVersion)
	if err != nil {
		return err
	}
	kubeAPIServerConfig, err := configconversion.ConvertMasterConfigToKubeAPIServerConfig(externalMasterConfig.(*legacyconfigv1.MasterConfig))
	if err != nil {
		return err
	}

	return RunOpenShiftKubeAPIServerServer(kubeAPIServerConfig, stopCh)
}
788193
func RunBuildController(ctx *ControllerContext) (bool, error) {
	imageTemplate := variable.NewDefaultImageTemplate()
	imageTemplate.Format = ctx.OpenshiftControllerConfig.Build.ImageTemplateFormat.Format
	imageTemplate.Latest = ctx.OpenshiftControllerConfig.Build.ImageTemplateFormat.Latest

	buildClient := ctx.ClientBuilder.OpenshiftBuildClientOrDie(bootstrappolicy.InfraBuildControllerServiceAccountName)
	externalKubeClient := ctx.ClientBuilder.ClientOrDie(bootstrappolicy.InfraBuildControllerServiceAccountName)
	securityClient := ctx.ClientBuilder.OpenshiftSecurityClientOrDie(bootstrappolicy.InfraBuildControllerServiceAccountName)

	buildInformer := ctx.BuildInformers.Build().V1().Builds()
	buildConfigInformer := ctx.BuildInformers.Build().V1().BuildConfigs()
	imageStreamInformer := ctx.ImageInformers.Image().V1().ImageStreams()
	podInformer := ctx.KubernetesInformers.Core().V1().Pods()
	secretInformer := ctx.KubernetesInformers.Core().V1().Secrets()
	controllerConfigInformer := ctx.ConfigInformers.Config().V1().Builds()
	imageConfigInformer := ctx.ConfigInformers.Config().V1().Images()
	configMapInformer := ctx.OpenshiftConfigKubernetesInformers.Core().V1().ConfigMaps()

	buildControllerParams := &buildcontroller.BuildControllerParams{
		BuildInformer:                    buildInformer,
		BuildConfigInformer:              buildConfigInformer,
		BuildControllerConfigInformer:    controllerConfigInformer,
		ImageConfigInformer:              imageConfigInformer,
		ImageStreamInformer:              imageStreamInformer,
		PodInformer:                      podInformer,
		SecretInformer:                   secretInformer,
		OpenshiftConfigConfigMapInformer: configMapInformer,
		KubeClient:                       externalKubeClient,
		BuildClient:                      buildClient,
		DockerBuildStrategy: &buildstrategy.DockerBuildStrategy{
			Image: imageTemplate.ExpandOrDie("docker-builder"),
		},
		SourceBuildStrategy: &buildstrategy.SourceBuildStrategy{
			Image:          imageTemplate.ExpandOrDie("docker-builder"),
			SecurityClient: securityClient.SecurityV1(),
		},
		CustomBuildStrategy:      &buildstrategy.CustomBuildStrategy{},
		BuildDefaults:            builddefaults.BuildDefaults{Config: ctx.OpenshiftControllerConfig.Build.BuildDefaults},
		BuildOverrides:           buildoverrides.BuildOverrides{Config: ctx.OpenshiftControllerConfig.Build.BuildOverrides},
		InternalRegistryHostname: ctx.OpenshiftControllerConfig.DockerPullSecret.InternalRegistryHostname,
	}

	go buildcontroller.NewBuildController(buildControllerParams).Run(5, ctx.Stop)
	return true, nil
}
578
func (b *KubeletBuilder) buildKubeletConfig() (*kops.KubeletConfigSpec, error) {
	if b.InstanceGroup == nil {
		glog.Fatalf("InstanceGroup was not set")
	}

	kubeletConfigSpec, err := b.buildKubeletConfigSpec()
	if err != nil {
		return nil, fmt.Errorf("error building kubelet config: %v", err)
	}

	// TODO: Memoize if we reuse this
	return kubeletConfigSpec, nil
}
1078082
func BuildCommand(factory app.ProjectFactory) cli.Command {
	return cli.Command{
		Name:   "build",
		Usage:  "Build or rebuild services.",
		Action: app.WithProject(factory, app.ProjectBuild),
		Flags: []cli.Flag{
			cli.BoolFlag{
				Name:  "no-cache",
				Usage: "Do not use cache when building the image",
			},
			cli.BoolFlag{
				Name:  "force-rm",
				Usage: "Always remove intermediate containers",
			},
			cli.BoolFlag{
				Name:  "pull",
				Usage: "Always attempt to pull a newer version of the image",
			},
		},
	}
}
1057018
func (s *StepCompactDisk) Run(ctx context.Context, state multistep.StateBag) multistep.StepAction {
	driver := state.Get("driver").(Driver)
	ui := state.Get("ui").(packer.Ui)

	if s.SkipCompaction {
		ui.Say("Skipping disk compaction...")
		return multistep.ActionContinue
	}

	// Get the dir used to store the VMs files during the build process
	var buildDir string
	if v, ok := state.GetOk("build_dir"); ok {
		buildDir = v.(string)
	}

	ui.Say("Compacting disks...")
	// CompactDisks searches for all VHD/VHDX files under the supplied
	// path and runs the compacting process on each of them. If no disks
	// are found under the supplied path this is treated as a 'soft' error
	// and a warning message is printed. All other errors halt the build.
	result, err := driver.CompactDisks(buildDir)
	if err != nil {
		err := fmt.Errorf("Error compacting disks: %s", err)
		state.Put("error", err)
		ui.Error(err.Error())
		return multistep.ActionHalt
	}
	// Report disk compaction results/warn if no disks were found
	ui.Message(result)

	return multistep.ActionContinue
}
837545
func RunRemove(dockerCli *KubeCli, opts options.Remove) error {
	composeClient, err := dockerCli.composeClient()
	if err != nil {
		return err
	}
	stacks, err := composeClient.Stacks(false)
	if err != nil {
		return err
	}
	for _, stack := range opts.Namespaces {
		fmt.Fprintf(dockerCli.Out(), "Removing stack: %s\n", stack)
		if err := stacks.Delete(stack); err != nil {
			return errors.Wrapf(err, "Failed to remove stack %s", stack)
		}
	}
	return nil
}
786547
func runMigrate() {
	if opts.name == "" {
		hostname, err := os.Hostname()
		if err != nil {
			klog.Errorf("Error while getting hostname to supply default --name: %v", err)
			os.Exit(1)
		}
		opts.name = fmt.Sprintf("etcd-%s", hostname)
	}

	if opts.ttlKeysDirectory == "" {
		opts.ttlKeysDirectory = fmt.Sprintf("%s/events", opts.etcdDataPrefix)
	}
	if opts.initialCluster == "" {
		opts.initialCluster = fmt.Sprintf("%s=http://localhost:2380", opts.name)
	}
	if opts.targetStorage == "" {
		klog.Errorf("--target-storage is required")
		os.Exit(1)
	}
	if opts.targetVersion == "" {
		klog.Errorf("--target-version is required")
		os.Exit(1)
	}
	if opts.dataDir == "" {
		klog.Errorf("--data-dir is required")
		os.Exit(1)
	}
	if opts.bundledVersionString == "" {
		klog.Errorf("--bundled-versions is required")
		os.Exit(1)
	}

	bundledVersions, err := ParseSupportedVersions(opts.bundledVersionString)
	if err != nil {
		klog.Errorf("Failed to parse --supported-versions: %v", err)
	}
	err = validateBundledVersions(bundledVersions, opts.binDir)
	if err != nil {
		klog.Errorf("Failed to validate that 'etcd-<version>' and 'etcdctl-<version>' binaries exist in --bin-dir '%s' for all --bundled-versions '%s': %v",
			opts.binDir, opts.bundledVersionString, err)
		os.Exit(1)
	}

	target := &EtcdVersionPair{
		version:        MustParseEtcdVersion(opts.targetVersion),
		storageVersion: MustParseEtcdStorageVersion(opts.targetStorage),
	}

	migrate(opts.name, opts.port, opts.peerListenUrls, opts.peerAdvertiseUrls, opts.binDir, opts.dataDir, opts.etcdDataPrefix, opts.ttlKeysDirectory, opts.initialCluster, target, bundledVersions, opts.etcdServerArgs)
}
661266
func PerformPostUpgradeTasks(client clientset.Interface, cfg *kubeadmapi.InitConfiguration, newK8sVer *version.Version, dryRun bool) error {
	errs := []error{}

	// Upload currently used configuration to the cluster
	// Note: This is done right in the beginning of cluster initialization; as we might want to make other phases
	// depend on centralized information from this source in the future
	if err := uploadconfig.UploadConfiguration(cfg, client); err != nil {
		errs = append(errs, err)
	}

	// Create the new, version-branched kubelet ComponentConfig ConfigMap
	if err := kubeletphase.CreateConfigMap(cfg.ClusterConfiguration.ComponentConfigs.Kubelet, cfg.KubernetesVersion, client); err != nil {
		errs = append(errs, errors.Wrap(err, "error creating kubelet configuration ConfigMap"))
	}

	// Write the new kubelet config down to disk and the env file if needed
	if err := writeKubeletConfigFiles(client, cfg, newK8sVer, dryRun); err != nil {
		errs = append(errs, err)
	}

	// Annotate the node with the crisocket information, sourced either from the InitConfiguration struct or
	// --cri-socket.
	// TODO: In the future we want to use something more official like NodeStatus or similar for detecting this properly
	if err := patchnodephase.AnnotateCRISocket(client, cfg.NodeRegistration.Name, cfg.NodeRegistration.CRISocket); err != nil {
		errs = append(errs, errors.Wrap(err, "error uploading crisocket"))
	}

	// Create/update RBAC rules that makes the bootstrap tokens able to post CSRs
	if err := nodebootstraptoken.AllowBootstrapTokensToPostCSRs(client); err != nil {
		errs = append(errs, err)
	}

	// Create/update RBAC rules that makes the bootstrap tokens able to get their CSRs approved automatically
	if err := nodebootstraptoken.AutoApproveNodeBootstrapTokens(client); err != nil {
		errs = append(errs, err)
	}

	// Create/update RBAC rules that makes the nodes to rotate certificates and get their CSRs approved automatically
	if err := nodebootstraptoken.AutoApproveNodeCertificateRotation(client); err != nil {
		errs = append(errs, err)
	}

	// TODO: Is this needed to do here? I think that updating cluster info should probably be separate from a normal upgrade
	// Create the cluster-info ConfigMap with the associated RBAC rules
	// if err := clusterinfo.CreateBootstrapConfigMapIfNotExists(client, kubeadmconstants.GetAdminKubeConfigPath()); err != nil {
	// 	return err
	//}
	// Create/update RBAC rules that makes the cluster-info ConfigMap reachable
	if err := clusterinfo.CreateClusterInfoRBACRules(client); err != nil {
		errs = append(errs, err)
	}

	// Upgrade kube-dns/CoreDNS and kube-proxy
	if err := dns.EnsureDNSAddon(&cfg.ClusterConfiguration, client); err != nil {
		errs = append(errs, err)
	}
	// Remove the old DNS deployment if a new DNS service is now used (kube-dns to CoreDNS or vice versa)
	if err := removeOldDNSDeploymentIfAnotherDNSIsUsed(&cfg.ClusterConfiguration, client, dryRun); err != nil {
		errs = append(errs, err)
	}

	if err := proxy.EnsureProxyAddon(&cfg.ClusterConfiguration, &cfg.LocalAPIEndpoint, client); err != nil {
		errs = append(errs, err)
	}
	return errorsutil.NewAggregate(errs)
}
517235
func (b *KubeletBuilder) buildMasterKubeletKubeconfig() (*nodetasks.File, error) {
	nodeName, err := b.NodeName()
	if err != nil {
		return nil, fmt.Errorf("error getting NodeName: %v", err)
	}

	caCert, err := b.KeyStore.FindCert(fi.CertificateId_CA)
	if err != nil {
		return nil, fmt.Errorf("error fetching CA certificate from keystore: %v", err)
	}
	if caCert == nil {
		return nil, fmt.Errorf("unable to find CA certificate %q in keystore", fi.CertificateId_CA)
	}

	caKey, err := b.KeyStore.FindPrivateKey(fi.CertificateId_CA)
	if err != nil {
		return nil, fmt.Errorf("error fetching CA certificate from keystore: %v", err)
	}
	if caKey == nil {
		return nil, fmt.Errorf("unable to find CA key %q in keystore", fi.CertificateId_CA)
	}

	privateKey, err := pki.GeneratePrivateKey()
	if err != nil {
		return nil, err
	}

	template := &x509.Certificate{
		BasicConstraintsValid: true,
		IsCA:                  false,
	}

	template.Subject = pkix.Name{
		CommonName:   fmt.Sprintf("system:node:%s", nodeName),
		Organization: []string{user.NodesGroup},
	}

	// https://tools.ietf.org/html/rfc5280#section-4.2.1.3
	//
	// Digital signature allows the certificate to be used to verify
	// digital signatures used during TLS negotiation.
	template.KeyUsage = template.KeyUsage | x509.KeyUsageDigitalSignature
	// KeyEncipherment allows the cert/key pair to be used to encrypt
	// keys, including the symmetric keys negotiated during TLS setup
	// and used for data transfer.
	template.KeyUsage = template.KeyUsage | x509.KeyUsageKeyEncipherment
	// ClientAuth allows the cert to be used by a TLS client to
	// authenticate itself to the TLS server.
	template.ExtKeyUsage = append(template.ExtKeyUsage, x509.ExtKeyUsageClientAuth)

	t := time.Now().UnixNano()
	template.SerialNumber = pki.BuildPKISerial(t)

	certificate, err := pki.SignNewCertificate(privateKey, template, caCert.Certificate, caKey)
	if err != nil {
		return nil, fmt.Errorf("error signing certificate for master kubelet: %v", err)
	}

	caBytes, err := caCert.AsBytes()
	if err != nil {
		return nil, fmt.Errorf("failed to get certificate authority data: %s", err)
	}
	certBytes, err := certificate.AsBytes()
	if err != nil {
		return nil, fmt.Errorf("failed to get certificate data: %s", err)
	}
	keyBytes, err := privateKey.AsBytes()
	if err != nil {
		return nil, fmt.Errorf("failed to get private key data: %s", err)
	}

	content, err := b.BuildKubeConfig("kubelet", caBytes, certBytes, keyBytes)
	if err != nil {
		return nil, err
	}

	return &nodetasks.File{
		Path:     b.KubeletKubeConfig(),
		Contents: fi.NewStringResource(content),
		Type:     nodetasks.FileType_File,
		Mode:     s("600"),
	}, nil
}
53791
func (bc *BuildController) cancelBuild(build *buildv1.Build) (*buildUpdate, error) {
	klog.V(4).Infof("Cancelling build %s", buildDesc(build))

	podName := buildapihelpers.GetBuildPodName(build)
	err := bc.podClient.Pods(build.Namespace).Delete(podName, &metav1.DeleteOptions{})
	if err != nil && !errors.IsNotFound(err) {
		return nil, fmt.Errorf("could not delete build pod %s/%s to cancel build %s: %v", build.Namespace, podName, buildDesc(build), err)
	}

	return transitionToPhase(buildv1.BuildPhaseCancelled, buildv1.StatusReasonCancelledBuild, buildutil.StatusMessageCancelledBuild), nil
}
102900
func buildKubeletArgMap(opts kubeletFlagsOpts) map[string]string {
	kubeletFlags := map[string]string{}

	if opts.nodeRegOpts.CRISocket == constants.DefaultDockerCRISocket {
		// These flags should only be set when running docker
		kubeletFlags["network-plugin"] = "cni"
		driver, err := kubeadmutil.GetCgroupDriverDocker(opts.execer)
		if err != nil {
			klog.Warningf("cannot automatically assign a '--cgroup-driver' value when starting the Kubelet: %v\n", err)
		} else {
			kubeletFlags["cgroup-driver"] = driver
		}
		if opts.pauseImage != "" {
			kubeletFlags["pod-infra-container-image"] = opts.pauseImage
		}
	} else {
		kubeletFlags["container-runtime"] = "remote"
		kubeletFlags["container-runtime-endpoint"] = opts.nodeRegOpts.CRISocket
	}

	if opts.registerTaintsUsingFlags && opts.nodeRegOpts.Taints != nil && len(opts.nodeRegOpts.Taints) > 0 {
		taintStrs := []string{}
		for _, taint := range opts.nodeRegOpts.Taints {
			taintStrs = append(taintStrs, taint.ToString())
		}

		kubeletFlags["register-with-taints"] = strings.Join(taintStrs, ",")
	}

	if pids, _ := opts.pidOfFunc("systemd-resolved"); len(pids) > 0 {
		// procfs.PidOf only returns an error if the regex is empty or doesn't compile, so we can ignore it
		kubeletFlags["resolv-conf"] = "/run/systemd/resolve/resolv.conf"
	}

	// Make sure the node name we're passed will work with Kubelet
	if opts.nodeRegOpts.Name != "" && opts.nodeRegOpts.Name != opts.defaultHostname {
		klog.V(1).Infof("setting kubelet hostname-override to %q", opts.nodeRegOpts.Name)
		kubeletFlags["hostname-override"] = opts.nodeRegOpts.Name
	}

	// TODO: Conditionally set `--cgroup-driver` to either `systemd` or `cgroupfs` for CRI other than Docker

	return kubeletFlags
}
586521
func runIsImportPath(pathToCheck string) bool {
	if _, err := build.Import(pathToCheck, "", build.FindOnly);err==nil {
		return true
	}
	return filepath.IsAbs(pathToCheck)
}