// RunConfigView gets the configuration persisted in the cluster
482784
func RunConfigView(out io.Writer, client clientset.Interface) error {

	klog.V(1).Infoln("[config] getting the cluster configuration")
	cfgConfigMap, err := client.CoreV1().ConfigMaps(metav1.NamespaceSystem).Get(constants.KubeadmConfigConfigMap, metav1.GetOptions{})
	if err != nil {
		return err
	}
	// No need to append \n as that already exists in the ConfigMap
	fmt.Fprintf(out, "%s", cfgConfigMap.Data[constants.ClusterConfigurationConfigMapKey])
	return nil
}
1359059
func run() error {
	var o Options
	o.InitDefaults()

	flags.BoolVar(&o.Containerized, "containerized", o.Containerized, "Set if we are running containerized.")
	flags.StringVar(&o.ClusterID, "cluster-id", o.ClusterID, "Cluster ID")

	// Trick to avoid 'logging before flag.Parse' warning
	flag.CommandLine.Parse([]string{})

	flag.Set("logtostderr", "true")
	flags.AddGoFlagSet(flag.CommandLine)
	flags.Parse(os.Args)

	if o.ClusterID == "" {
		glog.Infof("updating records for all discovered clusters")
	} else {
		glog.Infof("updating records for cluster %q", o.ClusterID)
	}

	c := &DiscoveryController{
		Options: o,
	}
	return c.Run()
}
1086168
func runKubeConfigFile(kubeConfigFileName string) func(workflow.RunData) error {
	return func(c workflow.RunData) error {
		data, ok := c.(InitData)
		if !ok {
			return errors.New("kubeconfig phase invoked with an invalid data struct")
		}

		// if external CA mode, skip certificate authority generation
		if data.ExternalCA() {
			fmt.Printf("[kubeconfig] External CA mode: Using user provided %s\n", kubeConfigFileName)
			return nil
		}

		// if dryrunning, reads certificates from a temporary folder (and defer restore to the path originally specified by the user)
		cfg := data.Cfg()
		cfg.CertificatesDir = data.CertificateWriteDir()
		defer func() { cfg.CertificatesDir = data.CertificateDir() }()

		// creates the KubeConfig file (or use existing)
		return kubeconfigphase.CreateKubeConfigFile(kubeConfigFileName, data.KubeConfigDir(), data.Cfg())
	}
}
1332127
func Run() {
	if Config.Debug {
		gin.SetMode(gin.DebugMode)
		log.SetLevel(log.DebugLevel)
	} else {
		gin.SetMode(gin.ReleaseMode)
		log.SetLevel(log.InfoLevel)
	}

	if Config.MongoLogging {
		mongoURIParsed, _ := url.Parse(Config.MongoURL)

		hooker, err := mgorus.NewHooker(mongoURIParsed.Host, mongoURIParsed.Path[1:], "logs")

		if err == nil {
			log.AddHook(hooker)
		}
	}

	// This will test TG tokens and creates API
	time.Sleep(time.Second * 1)
	initBots()

	for _, s := range services {
		if Config.IsStandAloneServiceInstance() {
			// save the service info as a job to Redis. The MAIN instance will process it
			serviceURL := Config.StandAloneServiceURL
			if serviceURL == "" {
				serviceURL = fmt.Sprintf("http://%s:%s", s.Name, Config.Port)
			}
			_, err := ensureStandAloneServiceJob.Schedule(1, time.Now(), s.Name, serviceURL, s.Bot().tgToken())

			if err != nil {
				log.WithError(err).Panic("ensureStandAloneServiceJob error")
			}
		}
	}

	// Configure
	router := gin.New()

	// register some HTML templates
	templ := template.Must(template.New("webpreview").Parse(htmlTemplateWebpreview))
	template.Must(templ.New("determineTZ").Parse(htmlTemplateDetermineTZ))

	router.SetHTMLTemplate(templ)

	// Middlewares
	router.Use(cloneMiddleware)
	router.Use(ginRecovery)
	router.Use(ginLogger)

	if Config.Debug {
		router.Use(gin.Logger())
	}

	if Config.IsMainInstance() || Config.IsSingleProcessInstance() {
		router.StaticFile("/", "index.html")
	}

	router.NoRoute(func(c *gin.Context) {
		// todo: good 404
		if len(c.Request.RequestURI) > 10 && (c.Request.RequestURI[1:2] == "c" || c.Request.RequestURI[1:2] == "u" || c.Request.RequestURI[1:2] == "h") {
			c.String(404, "Hi here!! This link isn't working in a browser. Please follow the instructions in the chat")
		}
	})

	/*
		Possible URLs

		Service webhooks:

		token resolving handled by framework:
		/service_name/token
		/token - DEPRECATED, to be removed, auto-detect the service

		token resolving handled by service
		/service_name/service
		/service_name

		OAuth:
		/oauth1/service_name/auth_temp_id – OAuth1 initial redirect

		/auth/service_name - OAuth2 redirect URL
		/auth/service_name/provider_id - adds provider_id for the custom OAuth provider (e.g. self-hosted instance)


		WebPreview resolving:
		/a/token
	*/

	router.HEAD("/:param1/:param2/:param3", serviceHookHandler)
	router.GET("/:param1/:param2/:param3", serviceHookHandler)
	router.POST("/:param1/:param2/:param3", serviceHookHandler)

	router.HEAD("/:param1/:param2", serviceHookHandler)
	router.GET("/:param1/:param2", serviceHookHandler)
	router.POST("/:param1/:param2", serviceHookHandler)

	router.HEAD("/:param1", serviceHookHandler)
	router.GET("/:param1", serviceHookHandler)
	router.POST("/:param1", serviceHookHandler)

	// Start listening

	var err error

	go gracefulShutdownJobPools()

	if Config.Port == "443" || Config.Port == "1443" {
		if _, err := os.Stat(Config.ConfigDir + string(os.PathSeparator) + "ssl.crt"); !os.IsNotExist(err) {
			log.Infof("SSL: Using ssl.key/ssl.crt")
			err = router.RunTLS(":"+Config.Port, Config.ConfigDir+string(os.PathSeparator)+"ssl.crt", Config.ConfigDir+string(os.PathSeparator)+"ssl.key")
		} else {
			log.Fatalf("INTEGRAM_PORT set to 443, but ssl.crt and ssl.key files not found at '%s'", Config.ConfigDir)
		}

	} else {
		if Config.IsMainInstance() || Config.IsSingleProcessInstance() {
			log.Warnf("WARNING! It is recommended to use Integram with a SSL.\n"+
				"Set the INTEGRAM_PORT to 443 and put integram.crt & integram.key files at '%s'", Config.ConfigDir)
		}
		err = router.Run(":" + Config.Port)
	}

	if err != nil {
		log.WithError(err).Fatal("Can't start the router")
	}
}
10402
func RunConfigInspect(dockerCli command.Cli, opts InspectOptions) error {
	client := dockerCli.Client()
	ctx := context.Background()

	if opts.Pretty {
		opts.Format = "pretty"
	}

	getRef := func(id string) (interface{}, []byte, error) {
		return client.ConfigInspectWithRaw(ctx, id)
	}
	f := opts.Format

	// check if the user is trying to apply a template to the pretty format, which
	// is not supported
	if strings.HasPrefix(f, "pretty") && f != "pretty" {
		return fmt.Errorf("Cannot supply extra formatting options to the pretty template")
	}

	configCtx := formatter.Context{
		Output: dockerCli.Out(),
		Format: NewFormat(f, false),
	}

	if err := InspectFormatWrite(configCtx, opts.Names, getRef); err != nil {
		return cli.StatusError{StatusCode: 1, Status: err.Error()}
	}
	return nil

}
1343676
func RunConfigRemove(dockerCli command.Cli, opts RemoveOptions) error {
	client := dockerCli.Client()
	ctx := context.Background()

	var errs []string

	for _, name := range opts.Names {
		if err := client.ConfigRemove(ctx, name); err != nil {
			errs = append(errs, err.Error())
			continue
		}

		fmt.Fprintln(dockerCli.Out(), name)
	}

	if len(errs) > 0 {
		return errors.Errorf("%s", strings.Join(errs, "\n"))
	}

	return nil
}
166717
func (s preparedGenericAPIServer) Run(stopCh <-chan struct{}) error {
	err := s.NonBlockingRun(stopCh)
	if err != nil {
		return err
	}

	<-stopCh

	err = s.RunPreShutdownHooks()
	if err != nil {
		return err
	}

	// Wait for all requests to finish, which are bounded by the RequestTimeout variable.
	s.HandlerChainWaitGroup.Wait()

	return nil
}
566193
func Run(ctx context.Context, conf Config) error {
	tcpAddr, err := net.ResolveTCPAddr("tcp", conf.Addr)
	if err != nil {
		return err
	}
	var lsnr net.Listener
	lsnr, err = net.ListenTCP("tcp", tcpAddr)
	if err != nil {
		return err
	}

	if conf.TLSConfig != nil {
		logrus.Info("Enabling TLS")
		lsnr = tls.NewListener(lsnr, conf.TLSConfig)
	}

	var ac auth.AccessController
	if conf.AuthMethod == "token" {
		authOptions, ok := conf.AuthOpts.(map[string]interface{})
		if !ok {
			return fmt.Errorf("auth.options must be a map[string]interface{}")
		}
		ac, err = auth.GetAccessController(conf.AuthMethod, authOptions)
		if err != nil {
			return err
		}
	}

	svr := http.Server{
		Addr: conf.Addr,
		Handler: RootHandler(
			ctx, ac, conf.Trust,
			conf.ConsistentCacheControlConfig, conf.CurrentCacheControlConfig,
			conf.RepoPrefixes),
	}

	logrus.Info("Starting on ", conf.Addr)

	err = svr.Serve(lsnr)

	return err
}
73500
func (o *CreateSubcommandOptions) Run() error {
	obj, err := o.StructuredGenerator.StructuredGenerate()
	if err != nil {
		return err
	}
	if !o.DryRun {
		// create subcommands have compiled knowledge of things they create, so type them directly
		gvks, _, err := scheme.Scheme.ObjectKinds(obj)
		if err != nil {
			return err
		}
		gvk := gvks[0]
		mapping, err := o.Mapper.RESTMapping(schema.GroupKind{Group: gvk.Group, Kind: gvk.Kind}, gvk.Version)
		if err != nil {
			return err
		}

		if err := kubectl.CreateOrUpdateAnnotation(o.CreateAnnotation, obj, scheme.DefaultJSONEncoder()); err != nil {
			return err
		}

		asUnstructured := &unstructured.Unstructured{}

		if err := scheme.Scheme.Convert(obj, asUnstructured, nil); err != nil {
			return err
		}
		if mapping.Scope.Name() == meta.RESTScopeNameRoot {
			o.Namespace = ""
		}
		actualObject, err := o.DynamicClient.Resource(mapping.Resource).Namespace(o.Namespace).Create(asUnstructured, metav1.CreateOptions{})
		if err != nil {
			return err
		}

		// ensure we pass a versioned object to the printer
		obj = actualObject
	} else {
		if meta, err := meta.Accessor(obj); err == nil && o.EnforceNamespace {
			meta.SetNamespace(o.Namespace)
		}
	}

	return o.PrintObj(obj, o.Out)
}
887635
func (kubemarkController *KubemarkController) Run(stopCh chan struct{}) {
	nodeTemplate, err := kubemarkController.getNodeTemplate()
	if err != nil {
		klog.Fatalf("failed to get node template: %s", err)
	}
	kubemarkController.nodeTemplate = nodeTemplate

	go kubemarkController.runNodeCreation(stopCh)
	<-stopCh
}
850068
func RunConfigList(dockerCli command.Cli, options ListOptions) error {
	client := dockerCli.Client()
	ctx := context.Background()

	configs, err := client.ConfigList(ctx, types.ConfigListOptions{Filters: options.Filter.Value()})
	if err != nil {
		return err
	}

	format := options.Format
	if len(format) == 0 {
		if len(dockerCli.ConfigFile().ConfigFormat) > 0 && !options.Quiet {
			format = dockerCli.ConfigFile().ConfigFormat
		} else {
			format = formatter.TableFormatKey
		}
	}

	sort.Slice(configs, func(i, j int) bool {
		return sortorder.NaturalLess(configs[i].Spec.Name, configs[j].Spec.Name)
	})

	configCtx := formatter.Context{
		Output: dockerCli.Out(),
		Format: NewFormat(format, options.Quiet),
	}
	return FormatWrite(configCtx, configs)
}
371131
func (config *Config) Run(cmd string) (string, error) {
	if config.DisplayOutput == true {
		fmt.Printf("run: %s\n", cmd)
	}
	return config.doRun(cmd, false)
}
507693
func (t *LaunchTemplate) Run(c *fi.Context) error {
	t.Normalize()

	return fi.DefaultDeltaRunMethod(t, c)
}
736674
func View() error {
	cfg, err := config.ReadConfig()
	if err != nil {
		return err
	}
	for k, v := range cfg {
		tmpl, err := template.New("view").Parse(viewFormat)
		if err != nil {
			exit.WithError("Error creating view template", err)
		}
		viewTmplt := ViewTemplate{k, v}
		err = tmpl.Execute(os.Stdout, viewTmplt)
		if err != nil {
			exit.WithError("Error executing view template", err)
		}
	}
	return nil
}
68435
func (o PruneDeploymentsOptions) Run() error {
	deploymentConfigList, err := o.AppsClient.DeploymentConfigs(o.Namespace).List(metav1.ListOptions{})
	if err != nil {
		return err
	}
	deploymentConfigs := []*appsv1.DeploymentConfig{}
	for i := range deploymentConfigList.Items {
		deploymentConfigs = append(deploymentConfigs, &deploymentConfigList.Items[i])
	}

	deploymentList, err := o.KubeClient.ReplicationControllers(o.Namespace).List(metav1.ListOptions{})
	if err != nil {
		return err
	}
	deployments := []*corev1.ReplicationController{}
	for i := range deploymentList.Items {
		deployments = append(deployments, &deploymentList.Items[i])
	}

	options := PrunerOptions{
		KeepYoungerThan:   o.KeepYoungerThan,
		Orphans:           o.Orphans,
		KeepComplete:      o.KeepComplete,
		KeepFailed:        o.KeepFailed,
		DeploymentConfigs: deploymentConfigs,
		Deployments:       deployments,
	}
	pruner := NewPruner(options)

	w := tabwriter.NewWriter(o.Out, 10, 4, 3, ' ', 0)
	defer w.Flush()

	deploymentDeleter := &describingDeploymentDeleter{w: w}

	if o.Confirm {
		deploymentDeleter.delegate = NewDeploymentDeleter(o.KubeClient)
	} else {
		fmt.Fprintln(os.Stderr, "Dry run enabled - no modifications will be made. Add --confirm to remove deployments")
	}

	return pruner.Prune(deploymentDeleter)
}
1290061
func NewCmdConfigView(out io.Writer, kubeConfigFile *string) *cobra.Command {
	return &cobra.Command{
		Use:   "view",
		Short: "View the kubeadm configuration stored inside the cluster",
		Long: fmt.Sprintf(dedent.Dedent(`
			Using this command, you can view the ConfigMap in the cluster where the configuration for kubeadm is located.

			The configuration is located in the %q namespace in the %q ConfigMap.
		`), metav1.NamespaceSystem, constants.KubeadmConfigConfigMap),
		Run: func(cmd *cobra.Command, args []string) {
			klog.V(1).Infoln("[config] retrieving ClientSet from file")
			client, err := kubeconfigutil.ClientSetFromFile(*kubeConfigFile)
			kubeadmutil.CheckErr(err)

			err = RunConfigView(out, client)
			kubeadmutil.CheckErr(err)
		},
	}
}
109241
func (r *Orchestrator) Run(ctx context.Context) error {
	defer close(r.doneChan)

	// Watch changes to services and tasks
	queue := r.store.WatchQueue()
	watcher, cancel := queue.Watch()
	defer cancel()

	// Balance existing services and drain initial tasks attached to invalid
	// nodes
	var err error
	r.store.View(func(readTx store.ReadTx) {
		if err = r.initTasks(ctx, readTx); err != nil {
			return
		}

		if err = r.initServices(readTx); err != nil {
			return
		}

		if err = r.initCluster(readTx); err != nil {
			return
		}
	})
	if err != nil {
		return err
	}

	r.tick(ctx)

	for {
		select {
		case event := <-watcher:
			// TODO(stevvooe): Use ctx to limit running time of operation.
			r.handleTaskEvent(ctx, event)
			r.handleServiceEvent(ctx, event)
			switch v := event.(type) {
			case state.EventCommit:
				r.tick(ctx)
			case api.EventUpdateCluster:
				r.cluster = v.Cluster
			}
		case <-r.stopChan:
			return nil
		}
	}
}