// CreateServiceKey creates a new service key using the provided name and
// parameters for the requested service instance.
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
}
959366
func (t *tenantServiceImpl) createClientWithServiceAccountSigner(ctx context.Context) (*tenant.Client, error) {
	c, err := t.createClient(ctx)
	if err != nil {
		return nil, err
	}
	signer, err := manager.AuthServiceAccountSigner(ctx)
	if err != nil {
		return nil, err
	}
	c.SetJWTSigner(signer)
	return c, nil
}
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
}
270133
func NewFromKiteKey(file string) (*Config, error) {
	key, err := kitekey.ParseFile(file)
	if err != nil {
		return nil, err
	}

	var c Config
	if err := c.ReadToken(key); err != nil {
		return nil, err
	}

	return &c, nil
}
274714
func (cli *Client) ServiceCreate(ctx context.Context, service swarm.ServiceSpec, options types.ServiceCreateOptions) (types.ServiceCreateResponse, error) {
	var headers map[string][]string

	if options.EncodedRegistryAuth != "" {
		headers = map[string][]string{
			"X-Registry-Auth": []string{options.EncodedRegistryAuth},
		}
	}

	var response types.ServiceCreateResponse
	resp, err := cli.post(ctx, "/services/create", nil, service, headers)
	if err != nil {
		return response, err
	}

	err = json.NewDecoder(resp.body).Decode(&response)
	ensureReaderClosed(resp)
	return response, err
}
719614
func (o *Enterprise) CreateIKEEncryptionprofile(child *IKEEncryptionprofile) *bambou.Error {

	return bambou.CurrentSession().CreateChild(o, child)
}
190272
func (ctx *Context) createService(vsID string, opts *ServiceOptions) error {
	if err := opts.Validate(ctx.endpoint); err != nil {
		return err
	}

	if _, exists := ctx.services[vsID]; exists {
		return ErrObjectExists
	}

	if ctx.vipInterface != nil {
		ifName := ctx.vipInterface.Attrs().Name
		vip := &netlink.Addr{IPNet: &net.IPNet{
			net.ParseIP(opts.host.String()), net.IPv4Mask(255, 255, 255, 255)}}
		if err := netlink.AddrAdd(ctx.vipInterface, vip); err != nil {
			log.Infof(
				"failed to add VIP %s to interface '%s' for service [%s]: %s",
				opts.host, ifName, vsID, err)
		} else {
			opts.delIfAddr = true
		}
		log.Infof("VIP %s has been added to interface '%s'", opts.host, ifName)
	}

	log.Infof("creating virtual service [%s] on %s:%d", vsID, opts.host,
		opts.Port)

	// create service to external store
	if ctx.store != nil {
		if err := ctx.store.CreateService(vsID, opts); err != nil {
			log.Errorf("error while create service : %s", err)
			return err
		}
	}

	var flags int
	for _, flag := range strings.Split(opts.Flags, "|") {
		flags = flags | schedulerFlags[flag]
	}

	if flags != 0 {
		if err := ctx.ipvs.AddServiceWithFlags(
			opts.host.String(),
			opts.Port,
			opts.protocol,
			opts.Method,
			gnl2go.U32ToBinFlags(uint32(flags)),
		); err != nil {
			log.Errorf("error while creating virtual service: %s", err)
			return ErrIpvsSyscallFailed
		}
	} else {
		if err := ctx.ipvs.AddService(
			opts.host.String(),
			opts.Port,
			opts.protocol,
			opts.Method,
		); err != nil {
			log.Errorf("error while creating virtual service: %s", err)
			return ErrIpvsSyscallFailed
		}
	}

	ctx.services[vsID] = &service{options: opts}

	if err := ctx.disco.Expose(vsID, opts.host.String(), opts.Port); err != nil {
		log.Errorf("error while exposing service to Disco: %s", err)
	}

	return nil
}
1070857
func (c *Client) AddAPIKey(key Key, opts ...interface{}) (res CreateKeyRes, err error) {
	path := c.path("/keys")
	err = c.transport.Request(&res, http.MethodPost, path, key, call.Write, opts...)
	res.wait = c.waitKeyIsAvailable(res.Key)
	return
}
570325
func (s *UsergroupsService) Create(name string) *UsergroupsCreateCall {
	var call UsergroupsCreateCall
	call.service = s
	call.name = name
	return &call
}
788038
func ServiceCreate(info *model.ServiceInfo) error { // nolint: gocyclo
	return mgr.Do(func(ctx context.Context, cli *client.Client) (err error) {
		service := swarm.ServiceSpec{
			Annotations: swarm.Annotations{
				Name:   info.Name,
				Labels: info.ServiceLabels.ToMap(),
			},
			TaskTemplate: swarm.TaskSpec{
				ContainerSpec: &swarm.ContainerSpec{
					Image:  info.Image,
					Dir:    info.Dir,
					User:   info.User,
					Labels: info.ContainerLabels.ToMap(),
				},
			},
			EndpointSpec: &swarm.EndpointSpec{Mode: swarm.ResolutionModeVIP},
		}

		if info.Command != "" {
			service.TaskTemplate.ContainerSpec.Command = strings.Split(info.Command, " ")
		}
		if info.Args != "" {
			service.TaskTemplate.ContainerSpec.Args = strings.Split(info.Args, " ")
		}

		if info.Mode == "replicated" {
			service.Mode.Replicated = &swarm.ReplicatedService{Replicas: &info.Replicas}
		} else if info.Mode == "global" {
			service.Mode.Global = &swarm.GlobalService{}
		}

		if envs := info.Environments.ToMap(); len(envs) > 0 {
			for n, v := range envs {
				service.TaskTemplate.ContainerSpec.Env = append(service.TaskTemplate.ContainerSpec.Env, n+"="+v)
			}
		}

		for _, n := range info.Networks {
			service.TaskTemplate.Networks = append(service.TaskTemplate.Networks, swarm.NetworkAttachmentConfig{Target: n})
		}

		if info.Endpoint.Mode != "" && len(info.Endpoint.Ports) > 0 {
			service.EndpointSpec = &swarm.EndpointSpec{Mode: swarm.ResolutionMode(info.Endpoint.Mode)}
			for _, p := range info.Endpoint.Ports {
				port := swarm.PortConfig{
					Protocol:      p.Protocol,
					TargetPort:    p.TargetPort,
					PublishedPort: p.PublishedPort,
					PublishMode:   p.PublishMode,
				}
				service.EndpointSpec.Ports = append(service.EndpointSpec.Ports, port)
			}
		}

		for _, s := range info.Secrets {
			service.TaskTemplate.ContainerSpec.Secrets = append(service.TaskTemplate.ContainerSpec.Secrets, s.ToSecret())
		}

		for _, c := range info.Configs {
			service.TaskTemplate.ContainerSpec.Configs = append(service.TaskTemplate.ContainerSpec.Configs, c.ToConfig())
		}

		for _, m := range info.Mounts {
			if m.Target != "" {
				mnt := mount.Mount{
					Type:     mount.Type(m.Type),
					Source:   m.Source,
					Target:   m.Target,
					ReadOnly: m.ReadOnly,
				}
				if m.Propagation != "" {
					mnt.BindOptions = &mount.BindOptions{Propagation: m.Propagation}
				}
				service.TaskTemplate.ContainerSpec.Mounts = append(service.TaskTemplate.ContainerSpec.Mounts, mnt)
			}
		}

		service.TaskTemplate.Placement = &swarm.Placement{}
		for _, c := range info.Placement.Constraints {
			if cons := c.ToConstraint(); cons != "" {
				service.TaskTemplate.Placement.Constraints = append(service.TaskTemplate.Placement.Constraints, cons)
			}
		}
		for _, p := range info.Placement.Preferences {
			if p.Spread != "" {
				pref := swarm.PlacementPreference{
					Spread: &swarm.SpreadOver{SpreadDescriptor: p.Spread},
				}
				service.TaskTemplate.Placement.Preferences = append(service.TaskTemplate.Placement.Preferences, pref)
			}
		}

		// update policy
		service.UpdateConfig = &swarm.UpdateConfig{
			Parallelism:   info.UpdatePolicy.Parallelism,
			FailureAction: info.UpdatePolicy.FailureAction,
			Order:         info.UpdatePolicy.Order,
		}
		if info.UpdatePolicy.Delay != "" {
			service.UpdateConfig.Delay, err = time.ParseDuration(info.UpdatePolicy.Delay)
			if err != nil {
				return err
			}
		}

		// rollback policy
		service.RollbackConfig = &swarm.UpdateConfig{
			Parallelism:   info.RollbackPolicy.Parallelism,
			FailureAction: info.RollbackPolicy.FailureAction,
			Order:         info.RollbackPolicy.Order,
		}
		if info.RollbackPolicy.Delay != "" {
			service.RollbackConfig.Delay, err = time.ParseDuration(info.RollbackPolicy.Delay)
			if err != nil {
				return err
			}
		}

		// restart policy
		var d time.Duration
		service.TaskTemplate.RestartPolicy = &swarm.RestartPolicy{
			Condition:   info.RestartPolicy.Condition,
			MaxAttempts: &info.RestartPolicy.MaxAttempts,
		}
		if info.RestartPolicy.Delay != "" {
			d, err = time.ParseDuration(info.RestartPolicy.Delay)
			if err != nil {
				return err
			}
			service.TaskTemplate.RestartPolicy.Delay = &d
		}
		if info.RestartPolicy.Window != "" {
			d, err = time.ParseDuration(info.RestartPolicy.Window)
			if err != nil {
				return err
			}
			service.TaskTemplate.RestartPolicy.Window = &d
		}

		// resources
		if info.Resource.Limit.IsSet() || info.Resource.Reserve.IsSet() {
			service.TaskTemplate.Resources = &swarm.ResourceRequirements{}
			if info.Resource.Limit.IsSet() {
				service.TaskTemplate.Resources.Limits, err = info.Resource.Limit.ToResources()
				if err != nil {
					return err
				}
			}
			if info.Resource.Limit.IsSet() {
				service.TaskTemplate.Resources.Reservations, err = info.Resource.Reserve.ToResources()
				if err != nil {
					return err
				}
			}
		}

		// log driver
		if info.LogDriver.Name != "" {
			service.TaskTemplate.LogDriver = &swarm.Driver{
				Name:    info.LogDriver.Name,
				Options: info.LogDriver.Options.ToMap(),
			}
		}

		// Host & DNS
		service.TaskTemplate.ContainerSpec.Hostname = info.Hostname
		if info.Hosts != "" {
			service.TaskTemplate.ContainerSpec.Hosts = strings.Split(info.Hosts, "\n")
		}
		service.TaskTemplate.ContainerSpec.DNSConfig = info.GetDNSConfig()

		opts := types.ServiceCreateOptions{EncodedRegistryAuth: info.RegistryAuth}
		var resp types.ServiceCreateResponse
		resp, err = cli.ServiceCreate(ctx, service, opts)
		if err == nil && len(resp.Warnings) > 0 {
			mgr.Logger().Warnf("service %s was created but got warnings: %v", info.Name, resp.Warnings)
		}
		return
	})
}
1289067
func (client *Client) CreateServiceInstance(spaceGUID, servicePlanGUID, serviceInstance string, parameters map[string]interface{}, tags []string) (ServiceInstance, Warnings, error) {
	requestBody := createServiceInstanceRequestBody{
		Name:            serviceInstance,
		ServicePlanGUID: servicePlanGUID,
		SpaceGUID:       spaceGUID,
		Parameters:      parameters,
		Tags:            tags,
	}

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

	request, err := client.newHTTPRequest(requestOptions{
		RequestName: internal.PostServiceInstancesRequest,
		Body:        bytes.NewReader(bodyBytes),
		Query:       url.Values{"accepts_incomplete": {"true"}},
	})
	if err != nil {
		return ServiceInstance{}, nil, err
	}

	var instance ServiceInstance
	response := cloudcontroller.Response{
		DecodeJSONResponseInto: &instance,
	}

	err = client.connection.Make(request, &response)
	return instance, response.Warnings, err
}
939846
func (m *Mgr) CreateService(name, exepath string, c Config) (*Service, error) {
	if c.StartType == 0 {
		c.StartType = StartManual
	}
	if c.ErrorControl == 0 {
		c.ErrorControl = ErrorNormal
	}
	c.BinaryPathName = exepath // execpath is important, do not rely on BinaryPathName field to be set
	h, err := winapi.CreateService(m.Handle, toPtr(name), toPtr(c.DisplayName),
		winapi.SERVICE_ALL_ACCESS, winapi.SERVICE_WIN32_OWN_PROCESS,
		c.StartType, c.ErrorControl, toPtr(exepath), toPtr(c.LoadOrderGroup),
		nil, toPtr(c.Dependencies), toPtr(c.ServiceStartName), toPtr(c.Password))
	if err != nil {
		return nil, err
	}
	if c.Description != "" {
		err = updateDescription(h, c.Description)
		if err != nil {
			return nil, err
		}
	}
	return &Service{Name: name, Handle: h}, nil
}
438807
func (c *ConfigLocal) KeybaseService() KeybaseService {
	c.lock.RLock()
	defer c.lock.RUnlock()
	return c.service
}
864596
func CreatePublicKey(c *context.APIContext, form api.CreateKeyOption) {
	CreateUserPublicKey(c, form, c.User.ID)
}
542965
func CreateLease(
	services k8s.ServiceGetterUpdater,
	k8sServiceName string,
	gkeClusterLister gke.ClusterLister,
	azureClusterLister azure.ClusterLister,
	azureConfig *config.Azure,
	googleConfig *config.Google,
) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		req := new(api.CreateLeaseReq)
		if err := json.NewDecoder(r.Body).Decode(req); err != nil {
			log.Printf("Error decoding JSON -- %s", err)
			htp.Error(w, http.StatusBadRequest, "Error decoding JSON -- %s", err)
			return
		}

		switch req.CloudProvider {
		case "google":
			if googleConfig.ValidConfig() {
				gke.Lease(w, req, gkeClusterLister, services, k8sServiceName, googleConfig.ProjectID, googleConfig.Zone)
			} else {
				log.Println("Unable to satisfy this request because the Google provider is not properly configured.")
				htp.Error(w, http.StatusInternalServerError, "Unable to satisfy this request because the Google provider is not properly configured.")
			}
		case "azure":
			if azureConfig.ValidConfig() {
				azure.Lease(w, req, azureClusterLister, services, azureConfig, k8sServiceName)
			} else {
				log.Println("Unable to satisfy this request because the Azure provider is not properly configured.")
				htp.Error(w, http.StatusInternalServerError, "Unable to satisfy this request because the Azure provider is not properly configured.")
			}
		default:
			log.Printf("Unable to find suitable provider for this request -- Provider:%s", req.CloudProvider)
			htp.Error(w, http.StatusBadRequest, "Unable to find suitable provider for this request -- Provider:%s", req.CloudProvider)
		}
	})
}
850902
func CreateServiceAccount(
	clientset kubernetes.Interface,
	serviceAccountName string,
	namespace string,
) error {
	serviceAccount := apiv1.ServiceAccount{
		TypeMeta: metav1.TypeMeta{
			APIVersion: "v1",
			Kind:       "ServiceAccount",
		},
		ObjectMeta: metav1.ObjectMeta{
			Name:      serviceAccountName,
			Namespace: namespace,
		},
	}
	_, err := clientset.CoreV1().ServiceAccounts(namespace).Create(&serviceAccount)
	if err != nil {
		if !apierr.IsAlreadyExists(err) {
			return fmt.Errorf("Failed to create service account %q: %v", serviceAccountName, err)
		}
		log.Infof("ServiceAccount %q already exists", serviceAccountName)
		return nil
	}
	log.Infof("ServiceAccount %q created", serviceAccountName)
	return nil
}
20271
func (k *KeyPairsClient) Create(ctx context.Context, pubKey *envelope.PublicKey,
	privKey *envelope.PrivateKey, claim *envelope.Claim) (*envelope.PublicKey,
	*envelope.PrivateKey, []envelope.Claim, error) {

	req := ClaimedKeyPair{
		PublicKeySegment: apitypes.PublicKeySegment{
			PublicKey: pubKey,
			Claims:    []envelope.Claim{*claim},
		},
		PrivateKey: privKey,
	}
	resp := ClaimedKeyPair{}
	err := k.client.RoundTrip(ctx, "POST", "/keypairs", nil, &req, &resp)
	if err != nil {
		return nil, nil, nil, err
	}

	return resp.PublicKey, resp.PrivateKey, resp.Claims, nil
}