// NewBatchServiceStateManager creates a new, initialized ServiceStateManager
553698
func NewBatchServiceStateManager(facade Facade, ctx datastore.Context, runLevelTimeout time.Duration) *BatchServiceStateManager {
	return &BatchServiceStateManager{
		lock:             &sync.RWMutex{},
		currentStateLock: &sync.Mutex{},
		Facade:           facade,
		ctx:              ctx,
		ServiceRunLevelTimeout: runLevelTimeout,
		TenantQueues:           make(map[string]map[service.DesiredState]*ServiceStateQueue),
		TenantShutDowns:        make(map[string]chan<- int),
		currentStateWaits:      make(map[string]*CurrentStateWait),
	}
}
1331502
func KeybaseServiceStatus(context Context, label string, wait time.Duration, log Log) (status keybase1.ServiceStatus) {
	if label == "" {
		status = keybase1.ServiceStatus{Status: keybase1.StatusFromCode(keybase1.StatusCode_SCServiceStatusError, "No service label")}
		return
	}
	kbService := launchd.NewService(label)

	status, err := serviceStatusFromLaunchd(kbService, context.GetServiceInfoPath(), wait, log)
	status.BundleVersion = libkb.VersionString()
	if err != nil {
		return
	}
	if status.InstallStatus == keybase1.InstallStatus_NOT_INSTALLED {
		return
	}

	installStatus, installAction, kbStatus := ResolveInstallStatus(status.Version, status.BundleVersion, status.LastExitStatus, log)
	status.InstallStatus = installStatus
	status.InstallAction = installAction
	status.Status = kbStatus
	return
}
269124
func NewBatchChecker(backend ExecutorState, params Params, blockchain contexts.Blockchain, logger *logging.Logger,
	options ...ExecutionOption) BatchExecutor {

	return newExecutor("CheckCache", false, params, backend, blockchain, nil,
		logger.WithScope("NewBatchExecutor"), options...)
}
221917
func (b *Batcher) newBatch() {
	go func() {
		<-b.after(b.interval)

		id := b.nextID.Add(1)

		// Make sure to atomically reset the number of waiters to make
		// sure that all incoming requests either make it into the
		// current batch or the next one.
		waiters := b.waiters.Get()
		for !b.waiters.CompareAndSwap(waiters, 0) {
			waiters = b.waiters.Get()
		}

		for i := int32(0); i < waiters; i++ {
			b.queue <- int(id)
		}
	}()
}
944218
func (mh MultiHandle) ServiceGenerator() ServiceGenerator {
	msg := make(MultiServiceGenerator, 0, len(mh))
	for _, h := range mh {
		if sg := h.ServiceGenerator(); sg != nil {
			msg = append(msg, sg)
		}
	}
	return msg
}
748585
func (c *Cluster) CreateService(s types.ServiceSpec, encodedAuth string, queryRegistry bool) (*apitypes.ServiceCreateResponse, error) {
	var resp *apitypes.ServiceCreateResponse
	err := c.lockedManagerAction(func(ctx context.Context, state nodeState) error {
		err := c.populateNetworkID(ctx, state.controlClient, &s)
		if err != nil {
			return err
		}

		serviceSpec, err := convert.ServiceSpecToGRPC(s)
		if err != nil {
			return errdefs.InvalidParameter(err)
		}

		resp = &apitypes.ServiceCreateResponse{}

		switch serviceSpec.Task.Runtime.(type) {
		case *swarmapi.TaskSpec_Attachment:
			return fmt.Errorf("invalid task spec: spec type %q not supported", types.RuntimeNetworkAttachment)
		// handle other runtimes here
		case *swarmapi.TaskSpec_Generic:
			switch serviceSpec.Task.GetGeneric().Kind {
			case string(types.RuntimePlugin):
				if !c.config.Backend.HasExperimental() {
					return fmt.Errorf("runtime type %q only supported in experimental", types.RuntimePlugin)
				}
				if s.TaskTemplate.PluginSpec == nil {
					return errors.New("plugin spec must be set")
				}

			default:
				return fmt.Errorf("unsupported runtime type: %q", serviceSpec.Task.GetGeneric().Kind)
			}

			r, err := state.controlClient.CreateService(ctx, &swarmapi.CreateServiceRequest{Spec: &serviceSpec})
			if err != nil {
				return err
			}

			resp.ID = r.Service.ID
		case *swarmapi.TaskSpec_Container:
			ctnr := serviceSpec.Task.GetContainer()
			if ctnr == nil {
				return errors.New("service does not use container tasks")
			}
			if encodedAuth != "" {
				ctnr.PullOptions = &swarmapi.ContainerSpec_PullOptions{RegistryAuth: encodedAuth}
			}

			// retrieve auth config from encoded auth
			authConfig := &apitypes.AuthConfig{}
			if encodedAuth != "" {
				authReader := strings.NewReader(encodedAuth)
				dec := json.NewDecoder(base64.NewDecoder(base64.URLEncoding, authReader))
				if err := dec.Decode(authConfig); err != nil {
					logrus.Warnf("invalid authconfig: %v", err)
				}
			}

			// pin image by digest for API versions < 1.30
			// TODO(nishanttotla): The check on "DOCKER_SERVICE_PREFER_OFFLINE_IMAGE"
			// should be removed in the future. Since integration tests only use the
			// latest API version, so this is no longer required.
			if os.Getenv("DOCKER_SERVICE_PREFER_OFFLINE_IMAGE") != "1" && queryRegistry {
				digestImage, err := c.imageWithDigestString(ctx, ctnr.Image, authConfig)
				if err != nil {
					logrus.Warnf("unable to pin image %s to digest: %s", ctnr.Image, err.Error())
					// warning in the client response should be concise
					resp.Warnings = append(resp.Warnings, digestWarning(ctnr.Image))

				} else if ctnr.Image != digestImage {
					logrus.Debugf("pinning image %s by digest: %s", ctnr.Image, digestImage)
					ctnr.Image = digestImage

				} else {
					logrus.Debugf("creating service using supplied digest reference %s", ctnr.Image)

				}

				// Replace the context with a fresh one.
				// If we timed out while communicating with the
				// registry, then "ctx" will already be expired, which
				// would cause UpdateService below to fail. Reusing
				// "ctx" could make it impossible to create a service
				// if the registry is slow or unresponsive.
				var cancel func()
				ctx, cancel = c.getRequestContext()
				defer cancel()
			}

			r, err := state.controlClient.CreateService(ctx, &swarmapi.CreateServiceRequest{Spec: &serviceSpec})
			if err != nil {
				return err
			}

			resp.ID = r.Service.ID
		}
		return nil
	})

	return resp, err
}
506540
func NewDeleteBatchResultData(Metadata IsMetadata) *DeleteBatchResultData {
	s := new(DeleteBatchResultData)
	s.Metadata = Metadata
	return s
}
110354
func (_m *Facade) SetServicesCurrentState(ctx datastore.Context, currentState service.ServiceCurrentState, serviceIDs ...string) {
	_m.Called(ctx, currentState, serviceIDs)
}
84388
func NewServiceManager(channelSize uint) *ServiceManager {

	in := make(chan interface{}, channelSize)

	return &ServiceManager{in: in}
}
1101048
func (l *Ledis) newBatch(wb *store.WriteBatch, locker sync.Locker) *batch {
	b := new(batch)
	b.l = l
	b.WriteBatch = wb

	b.Locker = locker

	return b
}
1043842
func NewDeleteBatchResult(Entries []*DeleteBatchResultEntry) *DeleteBatchResult {
	s := new(DeleteBatchResult)
	s.Entries = Entries
	return s
}
686085
func NewMoveBatchArg(Entries []*RelocationPath) *MoveBatchArg {
	s := new(MoveBatchArg)
	s.Entries = Entries
	s.Autorename = false
	s.AllowOwnershipTransfer = false
	return s
}
282134
func NewEndpointServiceResolver(services listersv1.ServiceLister, endpoints listersv1.EndpointsLister) ServiceResolver {
	return &aggregatorEndpointRouting{
		services:  services,
		endpoints: endpoints,
	}
}
1076811
func (s *OutofbandManagementService) NewConfigureOutOfBandManagementParams(address string, driver string, hostid string, password string, port string, username string) *ConfigureOutOfBandManagementParams {
	p := &ConfigureOutOfBandManagementParams{}
	p.p = make(map[string]interface{})
	p.p["address"] = address
	p.p["driver"] = driver
	p.p["hostid"] = hostid
	p.p["password"] = password
	p.p["port"] = port
	p.p["username"] = username
	return p
}
774327
func RegisterSessionServiceHandler(ctx context.Context, mux *runtime.ServeMux, conn *grpc.ClientConn) error {
	return RegisterSessionServiceHandlerClient(ctx, mux, NewSessionServiceClient(conn))
}
829412
func (c *ServicedCli) cmdServiceStatus(ctx *cli.Context) {
	var states map[string]map[string]interface{}
	var err error

	//Determine whether to show healthcheck fields and rows based on user input:
	//   By default, we only show individual healthcheck rows if a specific service is requested
	//   However, we will show them if the user explicitly requests the "Healthcheck" or "Healthcheck Status" fields
	showIndividualHealthChecks := false       //whether or not to add rows to the table for individual health checks.
	fieldsToShow := ctx.String("show-fields") //we will modify this if not user-set

	if !ctx.IsSet("show-fields") {
		//only show the appropriate health fields based on arguments
		if len(ctx.Args()) > 0 { //don't show "HC Fail"
			fieldsToShow = strings.Replace(fieldsToShow, "HC Fail,", "", -1)
			fieldsToShow = strings.Replace(fieldsToShow, ",HC Fail", "", -1) //in case it was last in the list
		} else { //don't show "Healthcheck" or "Healthcheck Status"

			fieldsToShow = strings.Replace(fieldsToShow, "Healthcheck Status,", "", -1)
			fieldsToShow = strings.Replace(fieldsToShow, ",Healthcheck Status", "", -1) //in case it was last in the list

			fieldsToShow = strings.Replace(fieldsToShow, "Healthcheck,", "", -1)
			fieldsToShow = strings.Replace(fieldsToShow, ",Healthcheck", "", -1) //in case it was last in the list
		}
	}

	//set showIndividualHealthChecks based on the fields
	showIndividualHealthChecks = strings.Contains(fieldsToShow, "Healthcheck") || strings.Contains(fieldsToShow, "Healthcheck Status")

	if len(ctx.Args()) > 0 {
		svc, _, err := c.searchForService(ctx.Args().First(), ctx.Bool("no-prefix-match"))
		if err != nil {
			fmt.Fprintln(os.Stderr, err)
			c.exit(1)
			return
		}
		if states, err = c.driver.GetServiceStatus(svc.ID); err != nil {
			fmt.Fprintln(os.Stderr, err)
			c.exit(1)
			return
		}
	} else {
		if states, err = c.driver.GetServiceStatus(""); err != nil {
			fmt.Fprintln(os.Stderr, err)
			c.exit(1)
			return
		}
	}

	cmdSetTreeCharset(ctx, c.config)

	t := NewTable(fieldsToShow)
	childmap := make(map[string][]string)
	for id, state := range states {
		parent := fmt.Sprintf("%v", state["ParentID"])
		childmap[parent] = append(childmap[parent], id)
	}

	var addRows func(string)
	addRows = func(root string) {
		rows := childmap[root]
		if len(rows) > 0 {
			sort.Strings(rows)
			t.IndentRow()
			defer t.DedentRow()
			for _, rowid := range childmap[root] {
				row := states[rowid]
				if _, ok := row["Healthcheck"]; !ok || showIndividualHealthChecks { //if this is a healthcheck row, only include it if showIndividualHealthChecks is true
					t.AddRow(row)
				}

				nextRoot := rowid
				addRows(nextRoot)
			}
		}
	}
	addRows("")
	t.Padding = 3
	t.Print()
	return
}
434363
func (dc *DispatcherClient) NewBatch() *DispatcherBatch {
	return &DispatcherBatch{
		c: dc,
		b: dc.c.NewBatch(),
	}
}