//createServiceLB is a netctl interface routine to delete
//service object
775227
func createServiceLB(ctx *cli.Context) {
	if len(ctx.Args()) != 1 {
		errExit(ctx, exitHelp, "Service name required", true)
	}

	serviceName := ctx.Args()[0]
	serviceSubnet := ctx.String("network")
	tenantName := ctx.String("tenant")
	if len(tenantName) == 0 {
		tenantName = "default"
	}
	selectors := ctx.StringSlice("selector")
	ports := ctx.StringSlice("port")
	ipAddress := ctx.String("preferred-ip")
	service := &contivClient.ServiceLB{
		ServiceName: serviceName,
		TenantName:  tenantName,
		NetworkName: serviceSubnet,
		IpAddress:   ipAddress,
	}
	service.Selectors = append(service.Selectors, selectors...)
	service.Ports = append(service.Ports, ports...)
	errCheck(ctx, getClient(ctx).ServiceLBPost(service))

	fmt.Printf("Creating ServiceLB %s:%s\n", tenantName, serviceName)
}
843194
func (c *testCluster) CreateService(name string, instances int) (string, error) {
	spec := &api.ServiceSpec{
		Annotations: api.Annotations{Name: name},
		Mode: &api.ServiceSpec_Replicated{
			Replicated: &api.ReplicatedService{
				Replicas: uint64(instances),
			},
		},
		Task: api.TaskSpec{
			Runtime: &api.TaskSpec_Container{
				Container: &api.ContainerSpec{Image: "alpine", Command: []string{"sh"}},
			},
		},
	}

	resp, err := c.api.CreateService(context.Background(), &api.CreateServiceRequest{Spec: spec})
	if err != nil {
		return "", err
	}
	return resp.Service.ID, nil
}
660646
func CreateServiceProfile(db sqlx.Execer, sp *ServiceProfile) error {
	now := time.Now()

	if sp.ID == uuid.Nil {
		var err error
		sp.ID, err = uuid.NewV4()
		if err != nil {
			return errors.Wrap(err, "new uuid v4 error")
		}
	}

	sp.CreatedAt = now
	sp.UpdatedAt = now

	_, err := db.Exec(`
		insert into service_profile (
			created_at,
			updated_at,

			service_profile_id,
			ul_rate,
			ul_bucket_size,
			ul_rate_policy,
			dl_rate,
			dl_bucket_size,
			dl_rate_policy,
			add_gw_metadata,
			dev_status_req_freq,
			report_dev_status_battery,
			report_dev_status_margin,
			dr_min,
			dr_max,
			channel_mask,
			pr_allowed,
			hr_allowed,
			ra_allowed,
			nwk_geo_loc,
			target_per,
			min_gw_diversity
		) values ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18, $19, $20, $21, $22)`,
		sp.CreatedAt,
		sp.UpdatedAt,
		sp.ID,
		sp.ULRate,
		sp.ULBucketSize,
		sp.ULRatePolicy,
		sp.DLRate,
		sp.DLBucketSize,
		sp.DLRatePolicy,
		sp.AddGWMetadata,
		sp.DevStatusReqFreq,
		sp.ReportDevStatusBattery,
		sp.ReportDevStatusMargin,
		sp.DRMin,
		sp.DRMax,
		sp.ChannelMask,
		sp.PRAllowed,
		sp.HRAllowed,
		sp.RAAllowed,
		sp.NwkGeoLoc,
		sp.TargetPER,
		sp.MinGWDiversity,
	)
	if err != nil {
		return handlePSQLError(err, "insert error")
	}

	log.WithFields(log.Fields{
		"id": sp.ID,
	}).Info("service-profile created")

	return nil
}
1020322
func CreateOrUpdateServiceAccount(client clientset.Interface, sa *v1.ServiceAccount) error {
	if _, err := client.CoreV1().ServiceAccounts(sa.ObjectMeta.Namespace).Create(sa); err != nil {
		// Note: We don't run .Update here afterwards as that's probably not required
		// Only thing that could be updated is annotations/labels in .metadata, but we don't use that currently
		if !apierrors.IsAlreadyExists(err) {
			return errors.Wrap(err, "unable to create serviceaccount")
		}
	}
	return nil
}
171887
func (client *Client) CreateServiceKey(serviceInstanceGUID string, keyName string, parameters map[string]interface{}) (ServiceKey, Warnings, error) {
	requestBody := serviceKeyRequestBody{
		ServiceInstanceGUID: serviceInstanceGUID,
		Name:                keyName,
		Parameters:          parameters,
	}

	bodyBytes, err := json.Marshal(requestBody)
	if err != nil {
		return ServiceKey{}, nil, err
	}

	request, err := client.newHTTPRequest(requestOptions{
		RequestName: internal.PostServiceKeyRequest,
		Body:        bytes.NewReader(bodyBytes),
	})
	if err != nil {
		return ServiceKey{}, nil, err
	}

	var serviceKey ServiceKey
	response := cloudcontroller.Response{
		DecodeJSONResponseInto: &serviceKey,
	}
	err = client.connection.Make(request, &response)

	return serviceKey, response.Warnings, err
}
1224573
func createPortAndServiceSpec(servicePort int, targetServicePort int, nodePort int, servicePortName string, extraServicePorts []corev1.ServicePort) ([]corev1.ServicePort, corev1.ServiceType) {
	//Use the Cluster IP type for the service port if NodePort isn't provided.
	//Otherwise, we will be binding the master service to a NodePort.
	servicePorts := []corev1.ServicePort{{Protocol: corev1.ProtocolTCP,
		Port:       int32(servicePort),
		Name:       servicePortName,
		TargetPort: intstr.FromInt(targetServicePort)}}
	serviceType := corev1.ServiceTypeClusterIP
	if nodePort > 0 {
		servicePorts[0].NodePort = int32(nodePort)
		serviceType = corev1.ServiceTypeNodePort
	}
	if extraServicePorts != nil {
		servicePorts = append(servicePorts, extraServicePorts...)
	}
	return servicePorts, serviceType
}
1022141
func serviceToServiceMap(service *v1.Service, hns HostNetworkService) proxyServiceMap {
	if service == nil {
		return nil
	}
	svcName := types.NamespacedName{Namespace: service.Namespace, Name: service.Name}
	if shouldSkipService(svcName, service) {
		return nil
	}

	serviceMap := make(proxyServiceMap)
	for i := range service.Spec.Ports {
		servicePort := &service.Spec.Ports[i]
		svcPortName := proxy.ServicePortName{NamespacedName: svcName, Port: servicePort.Name}
		serviceMap[svcPortName] = newServiceInfo(svcPortName, servicePort, service, hns)
	}
	return serviceMap
}
1020764
func (c *Client) CreateServiceOffering(p *CreateServiceOfferingParameter) (*ServiceOffering, error) {
	obj, err := c.Request("createServiceOffering", convertParamToMap(p))
	if err != nil {
		return nil, err
	}
	return obj.(*ServiceOffering), err
}
338083
func (_m *APIClient) ServiceCreate(ctx context.Context, service swarm.ServiceSpec, options types.ServiceCreateOptions) (types.ServiceCreateResponse, error) {
	ret := _m.Called(ctx, service, options)

	var r0 types.ServiceCreateResponse
	if rf, ok := ret.Get(0).(func(context.Context, swarm.ServiceSpec, types.ServiceCreateOptions) types.ServiceCreateResponse); ok {
		r0 = rf(ctx, service, options)
	} else {
		r0 = ret.Get(0).(types.ServiceCreateResponse)
	}

	var r1 error
	if rf, ok := ret.Get(1).(func(context.Context, swarm.ServiceSpec, types.ServiceCreateOptions) error); ok {
		r1 = rf(ctx, service, options)
	} else {
		r1 = ret.Error(1)
	}

	return r0, r1
}
208295
func deleteService(client corev1.ServicesGetter, namespace string) error {
	err := client.Services(namespace).Delete(serviceName, &metav1.DeleteOptions{})
	return ingoreNotFound(err)
}
73084
func (vm *VM) createHostedService() error {
	sc, err := vm.getServiceClient()
	if err != nil {
		return fmt.Errorf(errGetClient, err)
	}

	// create hosted service
	if err := sc.CreateHostedService(hostedservice.CreateHostedServiceParameters{
		ServiceName: vm.ServiceName,
		Location:    vm.Location,
		Label:       base64.StdEncoding.EncodeToString([]byte(vm.Label))}); err != nil {
		return err
	}

	if vm.Cert.Data != nil {
		err = vm.addAddCertificate()
		if err != nil {
			return err
		}

	}

	return nil
}
359123
func (_m *FacadeInterface) DeleteServiceConfig(ctx datastore.Context, fileID string) error {
	ret := _m.Called(ctx, fileID)

	var r0 error
	if rf, ok := ret.Get(0).(func(datastore.Context, string) error); ok {
		r0 = rf(ctx, fileID)
	} else {
		r0 = ret.Error(0)
	}

	return r0
}
577657
func (s *ChannelsService) Create(name string) *ChannelsCreateCall {
	var call ChannelsCreateCall
	call.service = s
	call.name = name
	return &call
}
413561
func (p *NetPlugin) AddServiceLB(servicename string, spec *core.ServiceSpec) error {
	p.Lock()
	defer p.Unlock()
	return p.NetworkDriver.AddSvcSpec(servicename, spec)
}
586798
func CreateServiceLB(stateDriver core.StateDriver, serviceLbCfg *intent.ConfigServiceLB) error {

	var providersPresent bool
	serviceIP := serviceLbCfg.IPAddress

	log.Infof("Recevied Create Service Load Balancer config {%v}", serviceLbCfg)

	//Check if service already exists.
	svcID := GetServiceID(serviceLbCfg.ServiceName, serviceLbCfg.Tenant)

	mastercfg.SvcMutex.RLock()
	oldServiceInfo := mastercfg.ServiceLBDb[svcID]
	mastercfg.SvcMutex.RUnlock()

	if oldServiceInfo != nil {
		//ServiceInfo Exists
		if reflect.DeepEqual(oldServiceInfo.Ports, serviceLbCfg.Ports) &&
			reflect.DeepEqual(oldServiceInfo.Selectors, serviceLbCfg.Selectors) &&
			serviceLbCfg.Tenant == oldServiceInfo.Tenant {
			return nil
		}
		serviceIP = oldServiceInfo.IPAddress
		DeleteServiceLB(stateDriver, oldServiceInfo.ServiceName, oldServiceInfo.Tenant)
	}

	//New Service
	serviceLbState := &mastercfg.CfgServiceLBState{}
	serviceLbState.ServiceName = serviceLbCfg.ServiceName
	serviceLbState.Tenant = serviceLbCfg.Tenant
	serviceLbState.Network = serviceLbCfg.Network
	serviceLbState.StateDriver = stateDriver
	serviceLbState.ID = GetServiceID(serviceLbCfg.ServiceName, serviceLbCfg.Tenant)
	serviceLbState.Ports = append(serviceLbState.Ports, serviceLbCfg.Ports...)
	serviceLbState.Selectors = make(map[string]string)
	serviceLbState.Providers = make(map[string]*mastercfg.Provider)
	for k, v := range serviceLbCfg.Selectors {
		serviceLbState.Selectors[k] = v
	}

	// find the network from network id
	networkID := serviceLbState.Network + "." + serviceLbState.Tenant
	nwCfg := &mastercfg.CfgNetworkState{}
	nwCfg.StateDriver = stateDriver
	err := nwCfg.Read(networkID)
	if err != nil {
		log.Errorf("network %s on tenant %s is not created %s", serviceLbState.Network, serviceLbCfg.Tenant, networkID)
		return err
	}

	// Alloc addresses
	addr, err := networkAllocAddress(nwCfg, nil, serviceIP, false)
	if err != nil {
		log.Errorf("Failed to allocate address. Err: %v", err)
		return err
	}
	serviceLbState.IPAddress = addr
	mastercfg.SvcMutex.Lock()
	err = serviceLbState.Write()

	if err != nil {
		mastercfg.SvcMutex.Unlock()
		return err
	}

	serviceID := GetServiceID(serviceLbState.ServiceName, serviceLbState.Tenant)

	mastercfg.ServiceLBDb[serviceID] = &mastercfg.ServiceLBInfo{
		IPAddress:   serviceLbState.IPAddress,
		Tenant:      serviceLbState.Tenant,
		ServiceName: serviceLbState.ServiceName,
		Network:     serviceLbState.Network,
	}
	mastercfg.ServiceLBDb[serviceID].Ports = append(mastercfg.ServiceLBDb[serviceID].Ports, serviceLbState.Ports...)
	mastercfg.ServiceLBDb[serviceID].Selectors = make(map[string]string)
	mastercfg.ServiceLBDb[serviceID].Providers = make(map[string]*mastercfg.Provider)

	for k, v := range serviceLbCfg.Selectors {
		mastercfg.ServiceLBDb[serviceID].Selectors[k] = v
	}

	//Check for containers in the tenant matching service selectors
	for _, providerInfo := range mastercfg.ProviderDb {
		if providerInfo.Tenant == serviceLbState.Tenant {
			if eq := reflect.DeepEqual(providerInfo.Labels, mastercfg.ServiceLBDb[serviceID].Selectors); eq {
				//provider matches service selectors
				providerID := getProviderID(providerInfo)
				providerDbID := getProviderDbID(providerInfo)
				providerInfo.Services = append(providerInfo.Services, serviceID)
				mastercfg.ServiceLBDb[serviceID].Providers[providerID] = providerInfo
				mastercfg.ProviderDb[providerDbID] = providerInfo
				serviceLbState.Providers[providerID] = providerInfo
				providersPresent = true
			}
		}
	}

	//Write into cluster store
	err = serviceLbState.Write()

	if err != nil {
		mastercfg.SvcMutex.Unlock()
		return err
	}

	if providersPresent {
		err = SvcProviderUpdate(serviceID, false)
		if err != nil {
			log.Errorf("Error updating Provider for service %s : %s", serviceID, err)
			return err
		}
	}
	mastercfg.SvcMutex.Unlock()

	return nil
}
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
}
422672
func (c *Client) CreateService(i *CreateServiceInput) (*Service, error) {
	resp, err := c.PostForm("/service", i, nil)
	if err != nil {
		return nil, err
	}

	var s *Service
	if err := decodeJSON(&s, resp.Body); err != nil {
		return nil, err
	}
	return s, nil
}