// NewPreflightPhase creates a kubeadm workflow phase that implements preflight checks for a new node join
426241
func NewPreflightPhase() workflow.Phase {
	return workflow.Phase{
		Name:    "preflight [api-server-endpoint]",
		Short:   "Run join pre-flight checks",
		Long:    "Run pre-flight checks for kubeadm join.",
		Example: preflightExample,
		Run:     runPreflight,
		InheritFlags: []string{
			options.CfgPath,
			options.IgnorePreflightErrors,
			options.TLSBootstrapToken,
			options.TokenStr,
			options.ControlPlane,
			options.APIServerAdvertiseAddress,
			options.APIServerBindPort,
			options.NodeCRISocket,
			options.NodeName,
			options.FileDiscovery,
			options.TokenDiscovery,
			options.TokenDiscoveryCAHash,
			options.TokenDiscoverySkipCAHash,
			options.CertificateKey,
		},
	}
}
322257
func NewDefaultComponentConfig(insecurePort int32) (kubectrlmgrconfig.KubeControllerManagerConfiguration, error) {
	versioned := kubectrlmgrconfigv1alpha1.KubeControllerManagerConfiguration{}
	kubectrlmgrconfigscheme.Scheme.Default(&versioned)

	internal := kubectrlmgrconfig.KubeControllerManagerConfiguration{}
	if err := kubectrlmgrconfigscheme.Scheme.Convert(&versioned, &internal, nil); err != nil {
		return internal, err
	}
	internal.Generic.Port = insecurePort
	return internal, nil
}
513920
func (woc *wfOperationCtx) markNodePhase(nodeName string, phase wfv1.NodePhase, message ...string) *wfv1.NodeStatus {
	node := woc.getNodeByName(nodeName)
	if node == nil {
		panic(fmt.Sprintf("node %s uninitialized", nodeName))
	}
	if node.Phase != phase {
		woc.log.Infof("node %s phase %s -> %s", node, node.Phase, phase)
		node.Phase = phase
		woc.updated = true
	}
	if len(message) > 0 {
		if message[0] != node.Message {
			woc.log.Infof("node %s message: %s", node, message[0])
			node.Message = message[0]
			woc.updated = true
		}
	}
	if node.Completed() && node.FinishedAt.IsZero() {
		node.FinishedAt = metav1.Time{Time: time.Now().UTC()}
		woc.log.Infof("node %s finished: %s", node, node.FinishedAt)
		woc.updated = true
	}
	woc.wf.Status.Nodes[node.ID] = *node
	return node
}
1171239
func Convert_kubeadm_JoinControlPlane_To_v1beta2_JoinControlPlane(in *kubeadm.JoinControlPlane, out *JoinControlPlane, s conversion.Scope) error {
	return autoConvert_kubeadm_JoinControlPlane_To_v1beta2_JoinControlPlane(in, out, s)
}
1012013
func (wr *Wrangler) PreflightSchema(ctx context.Context, tabletAlias *topodatapb.TabletAlias, changes []string) ([]*tabletmanagerdatapb.SchemaChangeResult, error) {
	ti, err := wr.ts.GetTablet(ctx, tabletAlias)
	if err != nil {
		return nil, fmt.Errorf("GetTablet(%v) failed: %v", tabletAlias, err)
	}
	return wr.tmc.PreflightSchema(ctx, ti.Tablet, changes)
}
1133505
func addJoinOtherFlags(flagSet *flag.FlagSet, joinOptions *joinOptions) {
	flagSet.StringVar(
		&joinOptions.cfgPath, options.CfgPath, joinOptions.cfgPath,
		"Path to kubeadm config file.",
	)
	flagSet.StringSliceVar(
		&joinOptions.ignorePreflightErrors, options.IgnorePreflightErrors, joinOptions.ignorePreflightErrors,
		"A list of checks whose errors will be shown as warnings. Example: 'IsPrivilegedUser,Swap'. Value 'all' ignores errors from all checks.",
	)
	flagSet.StringVar(
		&joinOptions.token, options.TokenStr, "",
		"Use this token for both discovery-token and tls-bootstrap-token when those values are not provided.",
	)
	flagSet.BoolVar(
		&joinOptions.controlPlane, options.ControlPlane, joinOptions.controlPlane,
		"Create a new control plane instance on this node",
	)
	flagSet.StringVar(
		&joinOptions.certificateKey, options.CertificateKey, "",
		"Use this key to decrypt the certificate secrets uploaded by init.",
	)
}
23387
func (sc *syncContext) startedSyncPhase() bool {
	for _, res := range sc.syncRes.Resources {
		if !res.IsHook() {
			return true
		}
		if res.HookType == appv1.HookTypeSync || res.HookType == appv1.HookTypePostSync {
			return true
		}
	}
	return false
}
355664
func (r Resource) Phase(rpt ResourceInstancePhaseType) ResourcePhase {
	return ResourcePhase{
		Resource: r,
		Phase:    rpt,
	}
}
972212
func newJoinOptions() *joinOptions {
	// initialize the public kubeadm config API by applying defaults
	externalcfg := &kubeadmapiv1beta2.JoinConfiguration{}

	// Add optional config objects to host flags.
	// un-set objects will be cleaned up afterwards (into newJoinData func)
	externalcfg.Discovery.File = &kubeadmapiv1beta2.FileDiscovery{}
	externalcfg.Discovery.BootstrapToken = &kubeadmapiv1beta2.BootstrapTokenDiscovery{}
	externalcfg.ControlPlane = &kubeadmapiv1beta2.JoinControlPlane{}

	// Apply defaults
	kubeadmscheme.Scheme.Default(externalcfg)

	return &joinOptions{
		externalcfg: externalcfg,
	}
}
618098
func NewDefaultConfig() *Config {
	return &Config{
		DNSZone:            env.GetOrFile("DNS_ZONE"),
		PropagationTimeout: env.GetOrDefaultSecond("LIGHTSAIL_PROPAGATION_TIMEOUT", dns01.DefaultPropagationTimeout),
		PollingInterval:    env.GetOrDefaultSecond("LIGHTSAIL_POLLING_INTERVAL", dns01.DefaultPollingInterval),
		Region:             env.GetOrDefaultString("LIGHTSAIL_REGION", "us-east-1"),
	}
}
23621
func NewFS(config libkbfs.Config, conn *fuse.Conn, debug bool,
	platformParams PlatformParams) *FS {
	log := config.MakeLogger("kbfsfuse")
	// We need extra depth for errors, so that we can report the line
	// number for the caller of processError, not processError itself.
	errLog := log.CloneWithAddedDepth(1)
	if debug {
		// Turn on debugging.  TODO: allow a proper log file and
		// style to be specified.
		log.Configure("", true, "")
		errLog.Configure("", true, "")
	}

	serveMux := http.NewServeMux()

	// Replicate the default endpoints from pprof's init function.
	serveMux.HandleFunc("/debug/pprof/", pprof.Index)
	serveMux.HandleFunc("/debug/pprof/cmdline", pprof.Cmdline)
	serveMux.HandleFunc("/debug/pprof/profile", pprof.Profile)
	serveMux.HandleFunc("/debug/pprof/symbol", pprof.Symbol)
	serveMux.HandleFunc("/debug/pprof/trace", pprof.Trace)

	// Replicate the default endpoints from net/trace's init function.
	serveMux.HandleFunc("/debug/requests", makeTraceHandler(func(w http.ResponseWriter, req *http.Request, sensitive bool) {
		trace.Render(w, req, sensitive)
	}))
	serveMux.HandleFunc("/debug/events", makeTraceHandler(trace.RenderEvents))

	// Leave Addr blank to be set in enableDebugServer() and
	// disableDebugServer().
	debugServer := &http.Server{
		Handler:      serveMux,
		ReadTimeout:  10 * time.Second,
		WriteTimeout: 10 * time.Second,
	}

	quLog := config.MakeLogger(libkbfs.QuotaUsageLogModule("FS"))
	fs := &FS{
		config:         config,
		conn:           conn,
		log:            log,
		errLog:         errLog,
		vlog:           config.MakeVLogger(log),
		errVlog:        config.MakeVLogger(errLog),
		debugServer:    debugServer,
		notifications:  libfs.NewFSNotifications(log),
		platformParams: platformParams,
		quotaUsage: libkbfs.NewEventuallyConsistentQuotaUsage(
			config, quLog, config.MakeVLogger(quLog)),
		nextInode: 2, // root is 1
	}
	fs.root.private = &FolderList{
		fs:      fs,
		tlfType: tlf.Private,
		folders: make(map[string]*TLF),
		inode:   fs.assignInode(),
	}
	fs.root.public = &FolderList{
		fs:      fs,
		tlfType: tlf.Public,
		folders: make(map[string]*TLF),
		inode:   fs.assignInode(),
	}
	fs.root.team = &FolderList{
		fs:      fs,
		tlfType: tlf.SingleTeam,
		folders: make(map[string]*TLF),
		inode:   fs.assignInode(),
	}
	fs.execAfterDelay = func(d time.Duration, f func()) {
		time.AfterFunc(d, f)
	}
	return fs
}
260513
func (c *Cors) handlePreflight(w http.ResponseWriter, r *http.Request) {
	headers := w.Header()
	origin := r.Header.Get("Origin")

	if r.Method != "OPTIONS" {
		c.logf("Preflight aborted: %s!=OPTIONS", r.Method)
		return
	}
	// Always set Vary headers
	// see https://github.com/rs/cors/issues/10,
	//     https://github.com/rs/cors/commit/dbdca4d95feaa7511a46e6f1efb3b3aa505bc43f#commitcomment-12352001
	headers.Add("Vary", "Origin")
	headers.Add("Vary", "Access-Control-Request-Method")
	headers.Add("Vary", "Access-Control-Request-Headers")

	if origin == "" {
		c.logf("Preflight aborted: empty origin")
		return
	}
	if !c.isOriginAllowed(r, origin) {
		c.logf("Preflight aborted: origin '%s' not allowed", origin)
		return
	}

	reqMethod := r.Header.Get("Access-Control-Request-Method")
	if !c.isMethodAllowed(reqMethod) {
		c.logf("Preflight aborted: method '%s' not allowed", reqMethod)
		return
	}
	reqHeaders := parseHeaderList(r.Header.Get("Access-Control-Request-Headers"))
	if !c.areHeadersAllowed(reqHeaders) {
		c.logf("Preflight aborted: headers '%v' not allowed", reqHeaders)
		return
	}
	headers.Set("Access-Control-Allow-Origin", origin)
	// Spec says: Since the list of methods can be unbounded, simply returning the method indicated
	// by Access-Control-Request-Method (if supported) can be enough
	headers.Set("Access-Control-Allow-Methods", strings.ToUpper(reqMethod))
	if len(reqHeaders) > 0 {

		// Spec says: Since the list of headers can be unbounded, simply returning supported headers
		// from Access-Control-Request-Headers can be enough
		headers.Set("Access-Control-Allow-Headers", strings.Join(reqHeaders, ", "))
	}
	if c.allowCredentials {
		headers.Set("Access-Control-Allow-Credentials", "true")
	}
	if c.maxAge > 0 {
		headers.Set("Access-Control-Max-Age", strconv.Itoa(c.maxAge))
	}
	c.logf("Preflight response headers: %v", headers)
}
1303927
func (r *ProxyREST) NewConnectOptions() (runtime.Object, bool, string) {
	return &api.PodProxyOptions{}, true, "path"
}
1302161
func NewUploadCertsPhase() workflow.Phase {
	return workflow.Phase{
		Name:  "upload-certs",
		Short: fmt.Sprintf("Upload certificates to %s", kubeadmconstants.KubeadmCertsSecret),
		Long:  cmdutil.MacroCommandLongDescription,
		Run:   runUploadCerts,
		InheritFlags: []string{
			options.CfgPath,
			options.UploadCerts,
			options.CertificateKey,
			options.SkipCertificateKeyPrint,
		},
	}
}
77979
func RunJoinNodeChecks(execer utilsexec.Interface, cfg *kubeadmapi.JoinConfiguration, ignorePreflightErrors sets.String) error {
	// First, check if we're root separately from the other preflight checks and fail fast
	if err := RunRootCheckOnly(ignorePreflightErrors); err != nil {
		return err
	}

	checks := []Checker{
		DirAvailableCheck{Path: filepath.Join(kubeadmconstants.KubernetesDir, kubeadmconstants.ManifestsSubDirName)},
		FileAvailableCheck{Path: filepath.Join(kubeadmconstants.KubernetesDir, kubeadmconstants.KubeletKubeConfigFileName)},
		FileAvailableCheck{Path: filepath.Join(kubeadmconstants.KubernetesDir, kubeadmconstants.KubeletBootstrapKubeConfigFileName)},
	}
	checks = addCommonChecks(execer, "", &cfg.NodeRegistration, checks)
	if cfg.ControlPlane == nil {
		checks = append(checks, FileAvailableCheck{Path: cfg.CACertPath})
	}

	addIPv6Checks := false
	if cfg.Discovery.BootstrapToken != nil {
		ipstr, _, err := net.SplitHostPort(cfg.Discovery.BootstrapToken.APIServerEndpoint)
		if err == nil {
			checks = append(checks,
				HTTPProxyCheck{Proto: "https", Host: ipstr},
			)
			if !addIPv6Checks {
				if ip := net.ParseIP(ipstr); ip != nil {
					if ip.To4() == nil && ip.To16() != nil {
						addIPv6Checks = true
					}
				}
			}
		}
	}
	if addIPv6Checks {
		checks = append(checks,
			FileContentCheck{Path: bridgenf6, Content: []byte{'1'}},
			FileContentCheck{Path: ipv6DefaultForwarding, Content: []byte{'1'}},
		)
	}

	return RunChecks(checks, os.Stderr, ignorePreflightErrors)
}
1217900
func NewBootstrapTokenPhase() workflow.Phase {
	return workflow.Phase{
		Name:    "bootstrap-token",
		Aliases: []string{"bootstraptoken"},
		Short:   "Generates bootstrap tokens used to join a node to a cluster",
		Example: bootstrapTokenExamples,
		Long:    bootstrapTokenLongDesc,
		InheritFlags: []string{
			options.CfgPath,
			options.KubeconfigPath,
			options.SkipTokenPrint,
		},
		Run: runBootstrapToken,
	}
}
299149
func (env *sessionEnviron) newRawInstance(
	ctx context.ProviderCallContext,
	args environs.StartInstanceParams,
	img *OvaFileMetadata,
) (_ *mo.VirtualMachine, _ *instance.HardwareCharacteristics, err error) {

	vmName, err := env.namespace.Hostname(args.InstanceConfig.MachineId)
	if err != nil {
		return nil, nil, common.ZoneIndependentError(err)
	}

	series := args.Tools.OneSeries()
	cloudcfg, err := cloudinit.New(series)
	if err != nil {
		return nil, nil, common.ZoneIndependentError(err)
	}
	cloudcfg.AddPackage("open-vm-tools")
	cloudcfg.AddPackage("iptables-persistent")

	// Make sure the hostname is resolvable by adding it to /etc/hosts.
	cloudcfg.ManageEtcHosts(true)

	internalMac, err := vsphereclient.GenerateMAC()
	if err != nil {
		return nil, nil, errors.Trace(err)
	}

	interfaces := []network.InterfaceInfo{{
		InterfaceName: "eth0",
		MACAddress:    internalMac,
		InterfaceType: network.EthernetInterface,
		ConfigType:    network.ConfigDHCP,
	}}
	networkDevices := []vsphereclient.NetworkDevice{{MAC: internalMac, Network: env.ecfg.primaryNetwork()}}

	// TODO(wpk) We need to add a firewall -AND- make sure that if it's a controller we
	// have API port open.
	externalNetwork := env.ecfg.externalNetwork()
	if externalNetwork != "" {
		externalMac, err := vsphereclient.GenerateMAC()
		if err != nil {
			return nil, nil, errors.Trace(err)
		}
		interfaces = append(interfaces, network.InterfaceInfo{
			InterfaceName: "eth1",
			MACAddress:    externalMac,
			InterfaceType: network.EthernetInterface,
			ConfigType:    network.ConfigDHCP,
		})
		networkDevices = append(networkDevices, vsphereclient.NetworkDevice{MAC: externalMac, Network: externalNetwork})
	}
	// TODO(wpk) There's no (known) way to tell cloud-init to disable network (using cloudinit.CloudInitNetworkConfigDisabled)
	// so the network might be double-configured. That should be ok as long as we're using DHCP.
	err = cloudcfg.AddNetworkConfig(interfaces)
	if err != nil {
		return nil, nil, errors.Trace(err)
	}
	userData, err := providerinit.ComposeUserData(args.InstanceConfig, cloudcfg, VsphereRenderer{})
	if err != nil {
		return nil, nil, common.ZoneIndependentError(
			errors.Annotate(err, "cannot make user data"),
		)
	}
	logger.Debugf("Vmware user data; %d bytes", len(userData))

	// Obtain the final constraints by merging with defaults.
	cons := args.Constraints
	minRootDisk := common.MinRootDiskSizeGiB(args.InstanceConfig.Series) * 1024
	if cons.RootDisk == nil || *cons.RootDisk < minRootDisk {
		cons.RootDisk = &minRootDisk
	}
	defaultDatastore := env.ecfg.datastore()
	if cons.RootDiskSource == nil || *cons.RootDiskSource == "" {
		cons.RootDiskSource = &defaultDatastore
	}

	// Download and extract the OVA file. If we're bootstrapping we use
	// a temporary directory, otherwise we cache the image for future use.
	updateProgressInterval := startInstanceUpdateProgressInterval
	if args.InstanceConfig.Bootstrap != nil {
		updateProgressInterval = bootstrapUpdateProgressInterval
	}
	updateProgress := func(message string) {
		args.StatusCallback(status.Provisioning, message, nil)
	}

	readOVA := func() (string, io.ReadCloser, error) {
		resp, err := http.Get(img.URL)
		if err != nil {
			return "", nil, errors.Trace(err)
		}
		return img.URL, resp.Body, nil
	}

	createVMArgs := vsphereclient.CreateVirtualMachineParams{
		Name: vmName,
		Folder: path.Join(
			controllerFolderName(args.ControllerUUID),
			env.modelFolderName(),
		),
		Series:                 series,
		ReadOVA:                readOVA,
		OVASHA256:              img.Sha256,
		VMDKDirectory:          vmdkDirectoryName(args.ControllerUUID),
		UserData:               string(userData),
		Metadata:               args.InstanceConfig.Tags,
		Constraints:            cons,
		NetworkDevices:         networkDevices,
		UpdateProgress:         updateProgress,
		UpdateProgressInterval: updateProgressInterval,
		Clock:                  clock.WallClock,
		EnableDiskUUID:         env.ecfg.enableDiskUUID(),
	}

	// Attempt to create a VM in each of the AZs in turn.
	logger.Debugf("attempting to create VM in availability zone %s", args.AvailabilityZone)
	availZone, err := env.availZone(ctx, args.AvailabilityZone)
	if err != nil {
		return nil, nil, errors.Trace(err)
	}

	createVMArgs.ComputeResource = &availZone.r
	createVMArgs.ResourcePool = availZone.pool.Reference()

	vm, err := env.client.CreateVirtualMachine(env.ctx, createVMArgs)
	if vsphereclient.IsExtendDiskError(err) {
		// Ensure we don't try to make the same extension across
		// different resource groups.
		err = common.ZoneIndependentError(err)
	}
	if err != nil {
		HandleCredentialError(err, ctx)
		return nil, nil, errors.Trace(err)
	}

	hw := &instance.HardwareCharacteristics{
		Arch:           &img.Arch,
		Mem:            cons.Mem,
		CpuCores:       cons.CpuCores,
		CpuPower:       cons.CpuPower,
		RootDisk:       cons.RootDisk,
		RootDiskSource: cons.RootDiskSource,
	}
	return vm, hw, err
}