// generateServices writes generated code for the Services interface into w
964734
func generateServices(ctx *context, w *bufio.Writer, services []Service) {
	// generate services comment
	generateComment(ctx, w, "Services", "services", "service")

	// generate interface
	fmt.Fprintf(w, "type %s interface {\n", "Services")
	for _, svc := range services {
		generateService(ctx, w, &svc)
	}
	fmt.Fprintln(w, "}")

	fmt.Fprintln(w)
}
350073
func AddServices(objects Objects, firstPortOnly bool) Objects {
	svcs := []runtime.Object{}
	for _, o := range objects {
		switch t := o.(type) {
		case *appsv1.DeploymentConfig:
			svc := addService(t.Spec.Template.Spec.Containers, t.ObjectMeta, t.Spec.Selector, firstPortOnly)
			if svc != nil {
				svcs = append(svcs, svc)
			}
		case *kappsv1.DaemonSet:
			svc := addService(t.Spec.Template.Spec.Containers, t.ObjectMeta, t.Spec.Template.Labels, firstPortOnly)
			if svc != nil {
				svcs = append(svcs, svc)
			}
		case *extensionsv1beta1.DaemonSet:
			svc := addService(t.Spec.Template.Spec.Containers, t.ObjectMeta, t.Spec.Template.Labels, firstPortOnly)
			if svc != nil {
				svcs = append(svcs, svc)
			}
		case *kappsv1beta2.DaemonSet:
			svc := addService(t.Spec.Template.Spec.Containers, t.ObjectMeta, t.Spec.Template.Labels, firstPortOnly)
			if svc != nil {
				svcs = append(svcs, svc)
			}
		}
	}
	return append(objects, svcs...)
}
1189339
func (s *DescribeServicesInput) SetServices(v []*string) *DescribeServicesInput {
	s.Services = v
	return s
}
1209650
func (_m *Store) GetServices() ([]types.Service, error) {
	ret := _m.Called()

	var r0 []types.Service
	if rf, ok := ret.Get(0).(func() []types.Service); ok {
		r0 = rf()
	} else {
		if ret.Get(0) != nil {
			r0 = ret.Get(0).([]types.Service)
		}
	}

	var r1 error
	if rf, ok := ret.Get(1).(func() error); ok {
		r1 = rf()
	} else {
		r1 = ret.Error(1)
	}

	return r0, r1
}
308518
func (m *marathonAdapter) CreateServices(services []*api.Service) ([]*api.Service, *api.Error) {
	var apiErr *api.Error

	myGroup := m.deployer.BuildDeploymentGroup(services, m.client)
	status := m.deployer.DeployGroup(myGroup, DEPLOY_TIMEOUT)

	switch status.code {
	case FAIL:
		apiErr = api.NewError(http.StatusConflict, "Group deployment failed.")
	case TIMEOUT:
		apiErr = api.NewError(http.StatusInternalServerError, "Group deployment timed out.")
	}

	return services, apiErr
}
432601
func generateMappings(appendCurrent bool) {
	hdr := "package main\n"

	initfn := `
	func init() {


	`
	t, err := bindgen.Parse(model, hdrfile)
	handleErr(err)

	var buf io.WriteCloser
	if appendCurrent {
		buf, err = os.OpenFile("mappings.go", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0644)
	} else {
		buf, err = os.OpenFile("mappings.go", os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0644)
	}
	handleErr(err)
	defer buf.Close()

	if !appendCurrent {
		fmt.Fprintln(buf, hdr)
		bindgen.GenIgnored(buf, t, functions)
		fmt.Fprintln(buf, initfn)
		bindgen.GenNameMap(buf, t, "fnNameMap", processNameBasic, functions, true)
		bindgen.GenNameMap(buf, t, "enumMappings", processNameBasic, enums, true)

		generateCRUD(buf, t, "create")
		generateCRUD(buf, t, "set")
		generateCRUD(buf, t, "destroy")
		generateCRUD(buf, t, "methods")
		fmt.Fprintln(buf, "}\n")
	}
	generateAlphaBeta(buf, t)
	fmt.Fprintln(buf, initfn)
	fmt.Fprintln(buf, "}\n")
}
495699
func (g *Generator) Generate() (_ []string, err error) {
	if g.API == nil {
		return nil, fmt.Errorf("missing API definition, make sure design is properly initialized")
	}

	go utils.Catch(nil, func() { g.Cleanup() })

	defer func() {
		if err != nil {
			g.Cleanup()
		}
	}()

	codegen.Reserved[g.Target] = true

	os.RemoveAll(g.OutDir)

	if err := os.MkdirAll(g.OutDir, 0755); err != nil {
		return nil, err
	}
	g.genfiles = []string{g.OutDir}
	if err := g.generateContexts(); err != nil {
		return nil, err
	}
	if err := g.generateControllers(); err != nil {
		return nil, err
	}
	if err := g.generateSecurity(); err != nil {
		return nil, err
	}
	if err := g.generateHrefs(); err != nil {
		return nil, err
	}
	if err := g.generateMediaTypes(); err != nil {
		return nil, err
	}
	if err := g.generateUserTypes(); err != nil {
		return nil, err
	}
	if !g.NoTest {
		if err := g.generateResourceTest(); err != nil {
			return nil, err
		}
	}

	return g.genfiles, nil
}
1321669
func (c *Client) Generate() error {
	rs := getAllResources(c.APIDef, false)

	if err := generateAllObjects(c.APIDef, c.Dir); err != nil {
		return err
	}
	// services files
	if err := c.generateServices(rs); err != nil {
		return err
	}

	if err := c.generateSecurity(); err != nil {
		return err
	}
	// main client file
	if err := c.generateMain(); err != nil {
		return err
	}
	return nil
}
1336936
func SetServices(svcs []*Service) error {
	if defaultDevice == nil {
		return ErrDefaultDevice
	}
	return defaultDevice.SetServices(svcs)
}
911546
func (a *Agent) loadServices(conf *config.RuntimeConfig) error {
	// Register the services from config
	for _, service := range conf.Services {
		ns := service.NodeService()
		chkTypes, err := service.CheckTypes()
		if err != nil {
			return fmt.Errorf("Failed to validate checks for service %q: %v", service.Name, err)
		}

		// Grab and validate sidecar if there is one too
		sidecar, sidecarChecks, sidecarToken, err := a.sidecarServiceFromNodeService(ns, service.Token)
		if err != nil {
			return fmt.Errorf("Failed to validate sidecar for service %q: %v", service.Name, err)
		}

		// Remove sidecar from NodeService now it's done it's job it's just a config
		// syntax sugar and shouldn't be persisted in local or server state.
		ns.Connect.SidecarService = nil

		if err := a.addServiceLocked(ns, chkTypes, false, service.Token, ConfigSourceLocal); err != nil {
			return fmt.Errorf("Failed to register service %q: %v", service.Name, err)
		}

		// If there is a sidecar service, register that too.
		if sidecar != nil {
			if err := a.addServiceLocked(sidecar, sidecarChecks, false, sidecarToken, ConfigSourceLocal); err != nil {
				return fmt.Errorf("Failed to register sidecar for service %q: %v", service.Name, err)
			}
		}
	}

	// Load any persisted services
	svcDir := filepath.Join(a.config.DataDir, servicesDir)
	files, err := ioutil.ReadDir(svcDir)
	if err != nil {
		if os.IsNotExist(err) {
			return nil
		}
		return fmt.Errorf("Failed reading services dir %q: %s", svcDir, err)
	}
	for _, fi := range files {
		// Skip all dirs
		if fi.IsDir() {
			continue
		}

		// Skip all partially written temporary files
		if strings.HasSuffix(fi.Name(), "tmp") {
			a.logger.Printf("[WARN] agent: Ignoring temporary service file %v", fi.Name())
			continue
		}

		// Open the file for reading
		file := filepath.Join(svcDir, fi.Name())
		fh, err := os.Open(file)
		if err != nil {
			return fmt.Errorf("failed opening service file %q: %s", file, err)
		}

		// Read the contents into a buffer
		buf, err := ioutil.ReadAll(fh)
		fh.Close()
		if err != nil {
			return fmt.Errorf("failed reading service file %q: %s", file, err)
		}

		// Try decoding the service definition
		var p persistedService
		if err := json.Unmarshal(buf, &p); err != nil {
			// Backwards-compatibility for pre-0.5.1 persisted services
			if err := json.Unmarshal(buf, &p.Service); err != nil {
				a.logger.Printf("[ERR] agent: Failed decoding service file %q: %s", file, err)
				continue
			}
		}
		serviceID := p.Service.ID

		if a.State.Service(serviceID) != nil {
			// Purge previously persisted service. This allows config to be
			// preferred over services persisted from the API.
			a.logger.Printf("[DEBUG] agent: service %q exists, not restoring from %q",
				serviceID, file)
			if err := a.purgeService(serviceID); err != nil {
				return fmt.Errorf("failed purging service %q: %s", serviceID, err)
			}
		} else {
			a.logger.Printf("[DEBUG] agent: restored service definition %q from %q",
				serviceID, file)
			if err := a.addServiceLocked(p.Service, nil, false, p.Token, ConfigSourceLocal); err != nil {
				return fmt.Errorf("failed adding service %q: %s", serviceID, err)
			}
		}
	}

	return nil
}
95146
func (g *Generator) generateSetters(mc *msgCtx, topLevelFields []topLevelField) {
	for _, pf := range topLevelFields {
		pf.setter(g, mc)
	}
}
1353465
func (g *Plugin) Generate(file *generator.FileDescriptor) {
	if len(file.FileDescriptorProto.Service) == 0 {
		return
	}

	g.P("// Reference imports to suppress errors if they are not otherwise used.")
	g.P("var _ ", contextPkg, ".Context")
	g.P("var _ ", yarpcPkg, ".ClientConn")
	g.P()

	// Assert version compatibility.
	g.P("// This is a compile-time assertion to ensure that this generated file")
	g.P("// is compatible with the yarpc package it is being compiled against.")
	g.P("const _ = ", yarpcPkg, ".SupportPackageIsVersion", generatedCodeVersion)
	g.P()

	for i, service := range file.FileDescriptorProto.Service {
		g.generateService(file, service, i)
	}
}
757582
func (f *Facade) getServices(ctx datastore.Context) ([]service.Service, error) {
	defer ctx.Metrics().Stop(ctx.Metrics().Start("Facade.getServices"))
	plog.Debug("Started Facade.getServices")
	defer plog.Debug("Finished Facade.getServices")

	store := f.serviceStore
	results, err := store.GetServices(ctx)
	if err != nil {
		plog.WithError(err).Error("Unable to get a list of all services")
		return results, err
	}
	return results, nil
}
449391
func (sc *syncContext) generateSyncTasks() ([]syncTask, bool) {
	syncTasks := make([]syncTask, 0)
	successful := true
	for _, resourceState := range sc.compareResult.managedResources {
		if resourceState.Hook {
			continue
		}
		if sc.syncResources == nil ||
			(resourceState.Live != nil && argo.ContainsSyncResource(resourceState.Live.GetName(), resourceState.Live.GroupVersionKind(), sc.syncResources)) ||
			(resourceState.Target != nil && argo.ContainsSyncResource(resourceState.Target.GetName(), resourceState.Target.GroupVersionKind(), sc.syncResources)) {

			skipDryRun := false
			var targetObj *unstructured.Unstructured
			if resourceState.Target != nil {
				targetObj = resourceState.Target.DeepCopy()
				if targetObj.GetNamespace() == "" {
					// If target object's namespace is empty, we set namespace in the object. We do
					// this even though it might be a cluster-scoped resource. This prevents any
					// possibility of the resource from unintentionally becoming created in the
					// namespace during the `kubectl apply`
					targetObj.SetNamespace(sc.namespace)
				}
				gvk := targetObj.GroupVersionKind()
				serverRes, err := kube.ServerResourceForGroupVersionKind(sc.disco, gvk)

				if err != nil {
					// Special case for custom resources: if CRD is not yet known by the K8s API server,
					// skip verification during `kubectl apply --dry-run` since we expect the CRD
					// to be created during app synchronization.
					if apierr.IsNotFound(err) && hasCRDOfGroupKind(sc.compareResult.managedResources, gvk.Group, gvk.Kind) {
						skipDryRun = true
					} else {
						sc.setResourceDetails(&appv1.ResourceResult{
							Name:      targetObj.GetName(),
							Group:     gvk.Group,
							Version:   gvk.Version,
							Kind:      targetObj.GetKind(),
							Namespace: targetObj.GetNamespace(),
							Message:   err.Error(),
							Status:    appv1.ResultCodeSyncFailed,
						})
						successful = false
					}
				} else {
					if !sc.proj.IsResourcePermitted(metav1.GroupKind{Group: gvk.Group, Kind: gvk.Kind}, serverRes.Namespaced) {
						sc.setResourceDetails(&appv1.ResourceResult{
							Name:      targetObj.GetName(),
							Group:     gvk.Group,
							Version:   gvk.Version,
							Kind:      targetObj.GetKind(),
							Namespace: targetObj.GetNamespace(),
							Message:   fmt.Sprintf("Resource %s:%s is not permitted in project %s.", gvk.Group, gvk.Kind, sc.proj.Name),
							Status:    appv1.ResultCodeSyncFailed,
						})
						successful = false
					}

					if serverRes.Namespaced && !sc.proj.IsDestinationPermitted(appv1.ApplicationDestination{Namespace: targetObj.GetNamespace(), Server: sc.server}) {
						sc.setResourceDetails(&appv1.ResourceResult{
							Name:      targetObj.GetName(),
							Group:     gvk.Group,
							Version:   gvk.Version,
							Kind:      targetObj.GetKind(),
							Namespace: targetObj.GetNamespace(),
							Message:   fmt.Sprintf("namespace %v is not permitted in project '%s'", targetObj.GetNamespace(), sc.proj.Name),
							Status:    appv1.ResultCodeSyncFailed,
						})
						successful = false
					}
				}
			}
			syncTask := syncTask{
				liveObj:    resourceState.Live,
				targetObj:  targetObj,
				skipDryRun: skipDryRun,
			}
			syncTasks = append(syncTasks, syncTask)
		}
	}

	sort.Sort(newKindSorter(syncTasks, resourceOrder))
	return syncTasks, successful
}
502055
func (g *Generator) generateContexts() (err error) {
	var (
		ctxFile string
		ctxWr   *ContextsWriter
	)
	{
		ctxFile = filepath.Join(g.OutDir, "contexts.go")
		ctxWr, err = NewContextsWriter(ctxFile)
		if err != nil {
			return
		}
	}
	defer func() {
		ctxWr.Close()
		if err == nil {
			err = ctxWr.FormatCode()
		}
	}()
	title := fmt.Sprintf("%s: Application Contexts", g.API.Context())
	imports := []*codegen.ImportSpec{
		codegen.SimpleImport("fmt"),
		codegen.SimpleImport("net/http"),
		codegen.SimpleImport("strconv"),
		codegen.SimpleImport("strings"),
		codegen.SimpleImport("time"),
		codegen.SimpleImport("unicode/utf8"),
		codegen.SimpleImport("github.com/goadesign/goa"),
		codegen.NewImport("uuid", "github.com/gofrs/uuid"),
		codegen.SimpleImport("context"),
	}
	g.API.IterateResources(func(r *design.ResourceDefinition) error {
		return r.IterateActions(func(a *design.ActionDefinition) error {
			if a.Payload != nil {
				imports = codegen.AttributeImports(a.Payload.AttributeDefinition, imports, nil)
			}
			return nil
		})
	})

	g.genfiles = append(g.genfiles, ctxFile)
	if err = ctxWr.WriteHeader(title, g.Target, imports); err != nil {
		return
	}
	err = g.API.IterateResources(func(r *design.ResourceDefinition) error {
		return r.IterateActions(func(a *design.ActionDefinition) error {
			ctxName := codegen.Goify(a.Name, true) + codegen.Goify(a.Parent.Name, true) + "Context"
			headers := &design.AttributeDefinition{
				Type: design.Object{},
			}
			if r.Headers != nil {
				headers.Merge(r.Headers)
				headers.Validation = r.Headers.Validation
			}
			if a.Headers != nil {
				headers.Merge(a.Headers)
				headers.Validation = a.Headers.Validation
			}
			if headers != nil && len(headers.Type.ToObject()) == 0 {
				headers = nil // So that {{if .Headers}} returns false in templates
			}
			params := a.AllParams()
			if params != nil && len(params.Type.ToObject()) == 0 {
				params = nil // So that {{if .Params}} returns false in templates
			}

			non101 := make(map[string]*design.ResponseDefinition)
			for k, v := range a.Responses {
				if v.Status != 101 {
					non101[k] = v
				}
			}
			ctxData := ContextTemplateData{
				Name:         ctxName,
				ResourceName: r.Name,
				ActionName:   a.Name,
				Payload:      a.Payload,
				Params:       params,
				Headers:      headers,
				Routes:       a.Routes,
				Responses:    non101,
				API:          g.API,
				DefaultPkg:   g.Target,
				Security:     a.Security,
			}
			return ctxWr.Execute(&ctxData)
		})
	})
	return
}
62882
func (sn *SimNode) Services() []node.Service {
	sn.lock.RLock()
	defer sn.lock.RUnlock()
	services := make([]node.Service, 0, len(sn.running))
	for _, service := range sn.running {
		services = append(services, service)
	}
	return services
}
1063631
func (e *Etcd) Services(state request.Request, exact bool, opt plugin.Options) (services []msg.Service, err error) {
	services, err = e.Records(state, exact)
	if err != nil {
		return
	}

	services = msg.Group(services)
	return
}