// CreateLease creates the handler that responds to the POST /lease endpoint
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)
		}
	})
}
1314719
func (l *leaseManager) GetLease(ctx context.Context, ttl int64) (clientv3.LeaseID, error) {
	now := time.Now()
	l.leaseMu.Lock()
	defer l.leaseMu.Unlock()
	// check if previous lease can be reused
	reuseDurationSeconds := l.getReuseDurationSecondsLocked(ttl)
	valid := now.Add(time.Duration(ttl) * time.Second).Before(l.prevLeaseExpirationTime)
	sufficient := now.Add(time.Duration(ttl+reuseDurationSeconds) * time.Second).After(l.prevLeaseExpirationTime)
	if valid && sufficient {
		return l.prevLeaseID, nil
	}
	// request a lease with a little extra ttl from etcd
	ttl += reuseDurationSeconds
	lcr, err := l.client.Lease.Grant(ctx, ttl)
	if err != nil {
		return clientv3.LeaseID(0), err
	}
	// cache the new lease id
	l.prevLeaseID = lcr.ID
	l.prevLeaseExpirationTime = now.Add(time.Duration(ttl) * time.Second)
	return lcr.ID, nil
}
447162
func (p *PostService) Create(teamName string, post Post) (*PostResponse, error) {
	postURL := PostURL + "/" + teamName + "/posts"
	var postRes PostResponse
	var postReq PostReq
	postReq.Post = post
	var data []byte
	var err error
	if data, err = json.Marshal(postReq); err != nil {
		return nil, err
	}

	res, err := p.client.post(postURL, "application/json", bytes.NewReader(data), &postRes)
	if err != nil {
		return nil, err
	}

	defer res.Body.Close()

	return &postRes, nil
}
258538
func (c *Client) LeasesService() leases.Manager {
	if c.leasesService != nil {
		return c.leasesService
	}
	c.connMu.Lock()
	defer c.connMu.Unlock()
	return leasesproxy.NewLeaseManager(leasesapi.NewLeasesClient(c.conn))
}
808937
func (p *Project) CreateService(name string) (Service, error) {
	existing, ok := p.GetServiceConfig(name)
	if !ok {
		return nil, fmt.Errorf("Failed to find service: %s", name)
	}

	// Copy because we are about to modify the environment
	config := *existing

	if p.context.EnvironmentLookup != nil {
		parsedEnv := make([]string, 0, len(config.Environment))

		for _, env := range config.Environment {
			parts := strings.SplitN(env, "=", 2)
			if len(parts) > 1 {
				parsedEnv = append(parsedEnv, env)
				continue
			} else {
				env = parts[0]
			}

			for _, value := range p.context.EnvironmentLookup.Lookup(env, &config) {
				parsedEnv = append(parsedEnv, value)
			}
		}

		config.Environment = parsedEnv

		// check the environment for extra build Args that are set but not given a value in the compose file
		for arg, value := range config.Build.Args {
			if *value == "\x00" {
				envValue := p.context.EnvironmentLookup.Lookup(arg, &config)
				// depending on what we get back we do different things
				switch l := len(envValue); l {
				case 0:
					delete(config.Build.Args, arg)
				case 1:
					parts := strings.SplitN(envValue[0], "=", 2)
					config.Build.Args[parts[0]] = &parts[1]
				default:
					return nil, fmt.Errorf("tried to set Build Arg %#v to multi-value %#v", arg, envValue)
				}
			}
		}
	}

	return p.context.ServiceFactory.Create(p, name, &config)
}
958646
func (m *Memory) Create(ctx context.Context, i backend.Item) (*backend.Lease, error) {
	if len(i.Key) == 0 {
		return nil, trace.BadParameter("missing parameter key")
	}
	m.Lock()
	defer m.Unlock()
	m.removeExpired()
	if m.tree.Get(&btreeItem{Item: i}) != nil {
		return nil, trace.AlreadyExists("key %q already exists", string(i.Key))
	}
	m.processEvent(backend.Event{
		Type: backend.OpPut,
		Item: i,
	})
	return m.newLease(i), nil
}
1297060
func (c *controller) ensureLease() (*coordv1beta1.Lease, bool, error) {
	lease, err := c.leaseClient.Get(c.holderIdentity, metav1.GetOptions{})
	if apierrors.IsNotFound(err) {
		// lease does not exist, create it
		lease, err := c.leaseClient.Create(c.newLease(nil))
		if err != nil {
			return nil, false, err
		}
		return lease, true, nil
	} else if err != nil {
		// unexpected error getting lease
		return nil, false, err
	}
	// lease already existed
	return lease, false, nil
}
688309
func CreateIfExists(condKey, key string, value []byte, lease bool) error {
	err := Client().CreateIfExists(condKey, key, value, lease)
	Trace("CreateIfExists", err, logrus.Fields{fieldKey: key, fieldValue: string(value), fieldCondition: condKey, fieldAttachLease: lease})
	return err
}
1043430
func createService(client corev1.ServicesGetter, namespace string) error {
	obj := generateService(namespace)
	_, err := client.Services(obj.Namespace).Create(obj)
	return err
}
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
}
745418
func (s *leaseStore) PinLease(key lease.Key, entity string, _ <-chan struct{}) error {
	return errors.NotImplementedf("lease pinning")
}
1131277
func (s *Store) ClaimLease(key lease.Key, req lease.Request, stop <-chan struct{}) error {
	return errors.Trace(s.runOnLeader(&Command{
		Version:   CommandVersion,
		Operation: OperationClaim,
		Namespace: key.Namespace,
		ModelUUID: key.ModelUUID,
		Lease:     key.Lease,
		Holder:    req.Holder,
		Duration:  req.Duration,
	}, stop))
}
1276456
func (c *consulClient) CreateOnly(ctx context.Context, key string, value []byte, lease bool) (bool, error) {
	k := &consulAPI.KVPair{
		Key:         key,
		Value:       value,
		CreateIndex: 0,
	}

	if lease {
		k.Session = c.lease
	}
	opts := &consulAPI.WriteOptions{}

	duration := spanstat.Start()
	success, _, err := c.KV().CAS(k, opts.WithContext(ctx))
	increaseMetric(key, metricSet, "CreateOnly", duration.EndError(err).Total(), err)
	if err != nil {
		return false, fmt.Errorf("unable to compare-and-swap: %s", err)
	}
	return success, nil
}
912498
func (client *MyInventoryClient) GetLease(leaseID string) (lease InventoryLease, err error) {
  if !client.Enabled {
    return
  }
  effectiveURL := fmt.Sprint(client.ServiceBaseURL, "/leases/", leaseID)
  log.Printf("Fetching lease at %s", effectiveURL)
  response, err := getRawResponseFromURL(effectiveURL)

  if err != nil {
    log.Println(err)
    return
  }

  var remoteLease inventoryLease
  err = json.Unmarshal(response.Data, &remoteLease)
  lease = InventoryLease{Username: remoteLease.User, DaysUntilExpires: getDaysRemainingFromEndDate(remoteLease.EndDate)}

  return
}
315239
func (p *PullRequestsService) Create(params interface{}) (pull *PullRequest, result *Result) {
	result = p.client.post(p.URL, params, &pull)
	return
}
580258
func (store *store) ExtendLease(key lease.Key, request lease.Request, _ <-chan struct{}) error {
	return store.request(key.Lease, request, store.extendLeaseOps, "extending")
}
867634
func (s *SourceService) CreateSource(ctx context.Context, b *platform.Source) error {
	u, err := newURL(s.Addr, sourcePath)
	if err != nil {
		return err
	}

	octets, err := json.Marshal(b)
	if err != nil {
		return err
	}

	req, err := http.NewRequest("POST", u.String(), bytes.NewReader(octets))
	if err != nil {
		return err
	}

	req.Header.Set("Content-Type", "application/json")
	SetToken(s.Token, req)

	hc := newClient(u.Scheme, s.InsecureSkipVerify)

	resp, err := hc.Do(req)
	if err != nil {
		return err
	}
	defer resp.Body.Close()

	// TODO(jsternberg): Should this check for a 201 explicitly?
	if err := CheckError(resp); err != nil {
		return err
	}

	if err := json.NewDecoder(resp.Body).Decode(b); err != nil {
		return err
	}

	return nil
}