// RunConfigInspect inspects the given Swarm config.
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

}
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)
}
271540
func (d *driver) InstanceInspect(
	ctx types.Context,
	opts types.Store) (*types.Instance, error) {

	iid := context.MustInstanceID(ctx)
	if iid.ID != "" {
		return &types.Instance{InstanceID: iid}, nil
	}

	id, err := d.getInstanceID(ctx)
	if err != nil {
		return nil, err
	}
	instanceID := &types.InstanceID{ID: id, Driver: d.Name()}

	return &types.Instance{InstanceID: instanceID}, nil
}
749946
func (cli *Client) ServiceInspectWithRaw(ctx context.Context, serviceID string) (swarm.Service, []byte, error) {
	serverResp, err := cli.get(ctx, "/services/"+serviceID, nil, nil)
	if err != nil {
		if serverResp.statusCode == http.StatusNotFound {
			return swarm.Service{}, nil, serviceNotFoundError{serviceID}
		}
		return swarm.Service{}, nil, err
	}
	defer ensureReaderClosed(serverResp)

	body, err := ioutil.ReadAll(serverResp.body)
	if err != nil {
		return swarm.Service{}, nil, err
	}

	var response swarm.Service
	rdr := bytes.NewReader(body)
	err = json.NewDecoder(rdr).Decode(&response)
	return response, body, err
}
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")
	}
}
421248
func ConfigFromGRPC(s *swarmapi.Config) swarmtypes.Config {
	config := swarmtypes.Config{
		ID: s.ID,
		Spec: swarmtypes.ConfigSpec{
			Annotations: annotationsFromGRPC(s.Spec.Annotations),
			Data:        s.Spec.Data,
		},
	}

	config.Version.Index = s.Meta.Version.Index
	// Meta
	config.CreatedAt, _ = gogotypes.TimestampFromProto(s.Meta.CreatedAt)
	config.UpdatedAt, _ = gogotypes.TimestampFromProto(s.Meta.UpdatedAt)

	if s.Spec.Templating != nil {
		config.Spec.Templating = &types.Driver{
			Name:    s.Spec.Templating.Name,
			Options: s.Spec.Templating.Options,
		}
	}

	return config
}
968624
func (h *ProvisionHook) Run(ctx context.Context, name string, ui Ui, comm Communicator, data interface{}) error {
	// Shortcut
	if len(h.Provisioners) == 0 {
		return nil
	}

	if comm == nil {
		return fmt.Errorf(
			"No communicator found for provisioners! This is usually because the\n" +
				"`communicator` config was set to \"none\". If you have any provisioners\n" +
				"then a communicator is required. Please fix this to continue.")
	}

	for _, p := range h.Provisioners {
		ts := CheckpointReporter.AddSpan(p.TypeName, "provisioner", p.Config)

		err := p.Provisioner.Provision(ctx, ui, comm)

		ts.End(err)
		if err != nil {
			return err
		}
	}

	return nil
}
398733
func (d *driver) SnapshotInspect(
	ctx types.Context,
	snapshotID string,
	opts types.Store) (*types.Snapshot, error) {
	// TODO Snapshots are not implemented yet
	return nil, types.ErrNotImplemented
}
890676
func ServiceSpecToGRPC(s types.ServiceSpec) (swarmapi.ServiceSpec, error) {
	name := s.Name
	if name == "" {
		name = namesgenerator.GetRandomName(0)
	}

	serviceNetworks := make([]*swarmapi.NetworkAttachmentConfig, 0, len(s.Networks))
	for _, n := range s.Networks {
		netConfig := &swarmapi.NetworkAttachmentConfig{Target: n.Target, Aliases: n.Aliases, DriverAttachmentOpts: n.DriverOpts}
		serviceNetworks = append(serviceNetworks, netConfig)
	}

	taskNetworks := make([]*swarmapi.NetworkAttachmentConfig, 0, len(s.TaskTemplate.Networks))
	for _, n := range s.TaskTemplate.Networks {
		netConfig := &swarmapi.NetworkAttachmentConfig{Target: n.Target, Aliases: n.Aliases, DriverAttachmentOpts: n.DriverOpts}
		taskNetworks = append(taskNetworks, netConfig)

	}

	spec := swarmapi.ServiceSpec{
		Annotations: swarmapi.Annotations{
			Name:   name,
			Labels: s.Labels,
		},
		Task: swarmapi.TaskSpec{
			Resources:   resourcesToGRPC(s.TaskTemplate.Resources),
			LogDriver:   driverToGRPC(s.TaskTemplate.LogDriver),
			Networks:    taskNetworks,
			ForceUpdate: s.TaskTemplate.ForceUpdate,
		},
		Networks: serviceNetworks,
	}

	switch s.TaskTemplate.Runtime {
	case types.RuntimeContainer, "": // if empty runtime default to container
		if s.TaskTemplate.ContainerSpec != nil {
			containerSpec, err := containerToGRPC(s.TaskTemplate.ContainerSpec)
			if err != nil {
				return swarmapi.ServiceSpec{}, err
			}
			spec.Task.Runtime = &swarmapi.TaskSpec_Container{Container: containerSpec}
		} else {
			// If the ContainerSpec is nil, we can't set the task runtime
			return swarmapi.ServiceSpec{}, ErrMismatchedRuntime
		}
	case types.RuntimePlugin:
		if s.TaskTemplate.PluginSpec != nil {
			if s.Mode.Replicated != nil {
				return swarmapi.ServiceSpec{}, errors.New("plugins must not use replicated mode")
			}

			s.Mode.Global = &types.GlobalService{} // must always be global

			pluginSpec, err := proto.Marshal(s.TaskTemplate.PluginSpec)
			if err != nil {
				return swarmapi.ServiceSpec{}, err
			}
			spec.Task.Runtime = &swarmapi.TaskSpec_Generic{
				Generic: &swarmapi.GenericRuntimeSpec{
					Kind: string(types.RuntimePlugin),
					Payload: &gogotypes.Any{
						TypeUrl: string(types.RuntimeURLPlugin),
						Value:   pluginSpec,
					},
				},
			}
		} else {
			return swarmapi.ServiceSpec{}, ErrMismatchedRuntime
		}
	case types.RuntimeNetworkAttachment:
		// NOTE(dperny) I'm leaving this case here for completeness. The actual
		// code is left out deliberately, as we should refuse to parse a
		// Network Attachment runtime; it will cause weird behavior all over
		// the system if we do. Instead, fallthrough and return
		// ErrUnsupportedRuntime if we get one.
		fallthrough
	default:
		return swarmapi.ServiceSpec{}, ErrUnsupportedRuntime
	}

	restartPolicy, err := restartPolicyToGRPC(s.TaskTemplate.RestartPolicy)
	if err != nil {
		return swarmapi.ServiceSpec{}, err
	}
	spec.Task.Restart = restartPolicy

	if s.TaskTemplate.Placement != nil {
		var preferences []*swarmapi.PlacementPreference
		for _, pref := range s.TaskTemplate.Placement.Preferences {
			if pref.Spread != nil {
				preferences = append(preferences, &swarmapi.PlacementPreference{
					Preference: &swarmapi.PlacementPreference_Spread{
						Spread: &swarmapi.SpreadOver{
							SpreadDescriptor: pref.Spread.SpreadDescriptor,
						},
					},
				})
			}
		}
		var platforms []*swarmapi.Platform
		for _, plat := range s.TaskTemplate.Placement.Platforms {
			platforms = append(platforms, &swarmapi.Platform{
				Architecture: plat.Architecture,
				OS:           plat.OS,
			})
		}
		spec.Task.Placement = &swarmapi.Placement{
			Constraints: s.TaskTemplate.Placement.Constraints,
			Preferences: preferences,
			MaxReplicas: s.TaskTemplate.Placement.MaxReplicas,
			Platforms:   platforms,
		}
	}

	spec.Update, err = updateConfigToGRPC(s.UpdateConfig)
	if err != nil {
		return swarmapi.ServiceSpec{}, err
	}
	spec.Rollback, err = updateConfigToGRPC(s.RollbackConfig)
	if err != nil {
		return swarmapi.ServiceSpec{}, err
	}

	if s.EndpointSpec != nil {
		if s.EndpointSpec.Mode != "" &&
			s.EndpointSpec.Mode != types.ResolutionModeVIP &&
			s.EndpointSpec.Mode != types.ResolutionModeDNSRR {
			return swarmapi.ServiceSpec{}, fmt.Errorf("invalid resolution mode: %q", s.EndpointSpec.Mode)
		}

		spec.Endpoint = &swarmapi.EndpointSpec{}

		spec.Endpoint.Mode = swarmapi.EndpointSpec_ResolutionMode(swarmapi.EndpointSpec_ResolutionMode_value[strings.ToUpper(string(s.EndpointSpec.Mode))])

		for _, portConfig := range s.EndpointSpec.Ports {
			spec.Endpoint.Ports = append(spec.Endpoint.Ports, &swarmapi.PortConfig{
				Name:          portConfig.Name,
				Protocol:      swarmapi.PortConfig_Protocol(swarmapi.PortConfig_Protocol_value[strings.ToUpper(string(portConfig.Protocol))]),
				PublishMode:   swarmapi.PortConfig_PublishMode(swarmapi.PortConfig_PublishMode_value[strings.ToUpper(string(portConfig.PublishMode))]),
				TargetPort:    portConfig.TargetPort,
				PublishedPort: portConfig.PublishedPort,
			})
		}
	}

	// Mode
	if s.Mode.Global != nil && s.Mode.Replicated != nil {
		return swarmapi.ServiceSpec{}, fmt.Errorf("cannot specify both replicated mode and global mode")
	}

	if s.Mode.Global != nil {
		spec.Mode = &swarmapi.ServiceSpec_Global{
			Global: &swarmapi.GlobalService{},
		}
	} else if s.Mode.Replicated != nil && s.Mode.Replicated.Replicas != nil {
		spec.Mode = &swarmapi.ServiceSpec_Replicated{
			Replicated: &swarmapi.ReplicatedService{Replicas: *s.Mode.Replicated.Replicas},
		}
	} else {
		spec.Mode = &swarmapi.ServiceSpec_Replicated{
			Replicated: &swarmapi.ReplicatedService{Replicas: 1},
		}
	}

	return spec, nil
}
1138150
func RunOptionalJoinNodeChecks(execer utilsexec.Interface, cfg *kubeadmapi.ClusterConfiguration, ignorePreflightErrors sets.String) error {
	checks := []Checker{}

	// Check if IVPS kube-proxy mode is supported
	if cfg.ComponentConfigs.KubeProxy != nil && cfg.ComponentConfigs.KubeProxy.Mode == ipvsutil.IPVSProxyMode {
		checks = append(checks, IPVSProxierCheck{exec: execer})
	}

	return RunChecks(checks, os.Stderr, ignorePreflightErrors)
}
145471
func (l VirtualDeviceList) ConfigSpec(op types.VirtualDeviceConfigSpecOperation) ([]types.BaseVirtualDeviceConfigSpec, error) {
	var fop types.VirtualDeviceConfigSpecFileOperation
	switch op {
	case types.VirtualDeviceConfigSpecOperationAdd:
		fop = types.VirtualDeviceConfigSpecFileOperationCreate
	case types.VirtualDeviceConfigSpecOperationEdit:
		fop = types.VirtualDeviceConfigSpecFileOperationReplace
	case types.VirtualDeviceConfigSpecOperationRemove:
		fop = types.VirtualDeviceConfigSpecFileOperationDestroy
	default:
		panic("unknown op")
	}

	var res []types.BaseVirtualDeviceConfigSpec
	for _, device := range l {
		config := &types.VirtualDeviceConfigSpec{
			Device:    device,
			Operation: op,
		}

		if disk, ok := device.(*types.VirtualDisk); ok {
			config.FileOperation = fop

			// Special case to attach an existing disk
			if op == types.VirtualDeviceConfigSpecOperationAdd && disk.CapacityInKB == 0 {
				childDisk := false
				if b, ok := disk.Backing.(*types.VirtualDiskFlatVer2BackingInfo); ok {
					childDisk = b.Parent != nil
				}

				if !childDisk {
					// Existing disk, clear file operation
					config.FileOperation = ""
				}
			}
		}

		res = append(res, config)
	}

	return res, nil
}
757721
func (r *Runc) Run(context context.Context, id, bundle string, opts *CreateOpts) (int, error) {
	args := []string{"run", "--bundle", bundle}
	if opts != nil {
		oargs, err := opts.args()
		if err != nil {
			return -1, err
		}
		args = append(args, oargs...)
	}
	cmd := r.command(context, append(args, id)...)
	if opts != nil && opts.IO != nil {
		opts.Set(cmd)
	}
	ec, err := Monitor.Start(cmd)
	if err != nil {
		return -1, err
	}
	return Monitor.Wait(cmd, ec)
}
1246998
func (cli *Client) ConfigInspectWithRaw(ctx context.Context, id string) (swarm.Config, []byte, error) {
	if id == "" {
		return swarm.Config{}, nil, objectNotFoundError{object: "config", id: id}
	}
	if err := cli.NewVersionError("1.30", "config inspect"); err != nil {
		return swarm.Config{}, nil, err
	}
	resp, err := cli.get(ctx, "/configs/"+id, nil, nil)
	defer ensureReaderClosed(resp)
	if err != nil {
		return swarm.Config{}, nil, wrapResponseError(err, resp, "config", id)
	}

	body, err := ioutil.ReadAll(resp.body)
	if err != nil {
		return swarm.Config{}, nil, err
	}

	var config swarm.Config
	rdr := bytes.NewReader(body)
	err = json.NewDecoder(rdr).Decode(&config)

	return config, body, err
}
872631
func (c *EndpointsConfig) Run(stopCh <-chan struct{}) {
	defer utilruntime.HandleCrash()

	klog.Info("Starting endpoints config controller")
	defer klog.Info("Shutting down endpoints config controller")

	if !controller.WaitForCacheSync("endpoints config", stopCh, c.listerSynced) {
		return
	}

	for i := range c.eventHandlers {
		klog.V(3).Infof("Calling handler.OnEndpointsSynced()")
		c.eventHandlers[i].OnEndpointsSynced()
	}

	<-stopCh
}
749610
func (d *driver) InstanceInspect(
	ctx types.Context,
	opts types.Store) (*types.Instance, error) {

	return &types.Instance{
		InstanceID: context.MustInstanceID(ctx),
	}, nil
}
424002
func (cfg Config) Run(ctx context.Context, fn func(context.Context) error) error {
	retryDelay := func() time.Duration { return 2 * time.Second }
	if cfg.RetryDelay != nil {
		retryDelay = cfg.RetryDelay
	}
	shouldRetry := func(error) bool { return true }
	if cfg.ShouldRetry != nil {
		shouldRetry = cfg.ShouldRetry
	}
	var startTimeout <-chan time.Time // nil chans never unlock !
	if cfg.StartTimeout != 0 {
		startTimeout = time.After(cfg.StartTimeout)
	}

	var err error
	for try := 0; ; try++ {
		if cfg.Tries != 0 && try == cfg.Tries {
			return &RetryExhaustedError{err}
		}
		if err = fn(ctx); err == nil {
			return nil
		}
		if !shouldRetry(err) {
			return err
		}

		log.Print(fmt.Errorf("Retryable error: %s", err))

		select {
		case <-ctx.Done():
			return err
		case <-startTimeout:
			return err
		default:
			time.Sleep(retryDelay())
		}
	}
}
791640
func NewRunListener(cfg RunListenerConfig) (*RunListener, error) {
	if err := cfg.Validate(); err != nil {
		return nil, errors.Trace(err)
	}
	listener, err := sockets.Listen(cfg.SocketPath)
	if err != nil {
		return nil, errors.Trace(err)
	}
	runListener := &RunListener{
		RunListenerConfig: cfg,
		listener:          listener,
		server:            rpc.NewServer(),
		closed:            make(chan struct{}),
		closing:           make(chan struct{}),
	}
	if err := runListener.server.Register(&JujuRunServer{runListener}); err != nil {
		return nil, errors.Trace(err)
	}
	go runListener.Run()
	return runListener, nil
}