// Leases gets information about all of the leases in the system,
// optionally filtered by the input lease keys.
509232
func (f *FSM) Leases(getLocalTime func() time.Time, keys ...lease.Key) map[lease.Key]lease.Info {
	if len(keys) > 0 {
		return f.filteredLeases(getLocalTime, keys)
	}
	return f.allLeases(getLocalTime)
}
146279
func NewLeases(storage storage.Interface, baseKey string, leaseTime time.Duration) Leases {
	return &storageLeases{
		storage:   storage,
		baseKey:   baseKey,
		leaseTime: leaseTime,
	}
}
775948
func (lm *LeaseManager) Delete(ctx context.Context, lease leases.Lease, _ ...leases.DeleteOpt) error {
	namespace, err := namespaces.NamespaceRequired(ctx)
	if err != nil {
		return err
	}

	topbkt := getBucket(lm.tx, bucketKeyVersion, []byte(namespace), bucketKeyObjectLeases)
	if topbkt == nil {
		return errors.Wrapf(errdefs.ErrNotFound, "lease %q", lease.ID)
	}
	if err := topbkt.DeleteBucket([]byte(lease.ID)); err != nil {
		if err == bolt.ErrBucketNotFound {
			err = errors.Wrapf(errdefs.ErrNotFound, "lease %q", lease.ID)
		}
		return err
	}
	return nil
}
275463
func Convert_coordination_Lease_To_v1beta1_Lease(in *coordination.Lease, out *v1beta1.Lease, s conversion.Scope) error {
	return autoConvert_coordination_Lease_To_v1beta1_Lease(in, out, s)
}
1228227
func (store *store) expireLeaseOps(name string) ([]txn.Op, error) {

	// We can't expire a lease that doesn't exist.
	lastEntry, found := store.entries[name]
	if !found {
		return nil, lease.ErrInvalid
	}

	// We also can't expire a lease whose expiry time may be in the future.
	latestExpiry := lastEntry.start.Add(lastEntry.duration)
	if !store.globalTime.After(latestExpiry) {
		globalTime, err := store.refreshGlobalTime()
		if err != nil {
			return nil, errors.Annotate(err, "refreshing global time")
		}
		if !globalTime.After(latestExpiry) {
			return nil, errors.Annotatef(lease.ErrInvalid, "lease %q expires in the future", name)
		}
	}

	// The database change is simple, and depends on the lease doc being
	// untouched since we looked:
	expireLeaseOp := txn.Op{
		C:  store.config.Collection,
		Id: store.leaseDocId(name),
		Assert: bson.M{
			fieldHolder:   lastEntry.holder,
			fieldStart:    toInt64(lastEntry.start),
			fieldDuration: lastEntry.duration,
			fieldWriter:   lastEntry.writer,
		},
		Remove: true,
	}

	ops := []txn.Op{expireLeaseOp}
	return ops, nil
}
1108355
func (l Lease) ExpirationTime() (time.Time, error) {
	t, err := time.Parse(TimeFormat, l.LeaseExpirationTime)
	if err != nil {
		return zeroTime, err
	}
	return t, nil
}
319126
func (c *signerInfoContext) Keys() string {
	sort.Strings(c.s.Keys)
	truncatedKeys := []string{}
	if c.trunc {
		for _, keyID := range c.s.Keys {
			truncatedKeys = append(truncatedKeys, stringid.TruncateID(keyID))
		}
		return strings.Join(truncatedKeys, ", ")
	}
	return strings.Join(c.s.Keys, ", ")
}
989012
func (m Map) LeaseByClusterName(clusterName string) (*Lease, bool) {
	u, ok := m.nameMap[clusterName]
	if !ok {
		return nil, false
	}
	l, ok := m.uuidMap[u.String()]
	if !ok {
		return nil, false
	}
	return l, true
}
40338
func (v *version) Leases() LeaseInformer {
	return &leaseInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions}
}
612163
func findExpiredLeases(leaseMap *leases.Map) ([]*leases.UUIDAndLease, error) {
	var leasesUUIDs []*leases.UUIDAndLease
	now := time.Now()
	uuids, err := leaseMap.UUIDs()
	if err != nil {
		return nil, err
	}
	for _, u := range uuids {
		lease, _ := leaseMap.LeaseForUUID(u)
		exprTime, err := lease.ExpirationTime()
		if err != nil {
			return nil, err
		}
		if now.After(exprTime) {
			leasesUUIDs = append(leasesUUIDs, leases.NewUUIDAndLease(u, lease))
		}
	}
	if len(leasesUUIDs) > 0 {
		return leasesUUIDs, nil
	}
	return nil, errNoExpiredLeases
}
738634
func (store *store) Leases(keys ...lease.Key) map[lease.Key]lease.Info {
	cfg := store.config
	limit := set.NewStrings()

	// Do a single pass over the keys for model and namespace.
	// This lets us use a set for filtering on lease name when we iterate
	// over the collection of leases.
	filtering := len(keys) > 0
	if filtering {
		for _, key := range keys {
			if key.Namespace == cfg.Namespace && key.ModelUUID == cfg.ModelUUID {
				limit.Add(key.Lease)
			}
		}
	}

	store.mu.Lock()
	localTime := store.config.LocalClock.Now()
	leases := make(map[lease.Key]lease.Info)
	for name, entry := range store.entries {
		if filtering && !limit.Contains(name) {
			continue
		}

		globalExpiry := entry.start.Add(entry.duration)
		remaining := globalExpiry.Sub(store.globalTime)
		localExpiry := localTime.Add(remaining)
		key := lease.Key{
			Namespace: store.config.Namespace,
			ModelUUID: store.config.ModelUUID,
			Lease:     name,
		}
		leases[key] = lease.Info{
			Holder:   entry.holder,
			Expiry:   localExpiry,
			Trapdoor: store.assertOpTrapdoor(name, entry.holder),
		}
	}
	defer store.mu.Unlock()

	return leases
}
26073
func Lease(w http.ResponseWriter,
	req *api.CreateLeaseReq,
	clusterLister ClusterLister,
	services k8s.ServiceGetterUpdater,
	azureConfig *config.Azure,
	k8sServiceName string) {

	clusterMap, svc, err := getSvcsAndClusters(clusterLister, services, k8sServiceName)
	if err != nil {
		log.Printf("Error listing Azure clusters or talking to the k8s API -- %s", err)
		htp.Error(w, http.StatusInternalServerError, "Error listing Azure clusters or talking to the k8s API -- %s", err)
		return
	}

	leaseMap, err := leases.ParseMapFromAnnotations(svc.Annotations)
	if err != nil {
		log.Printf("Error parsing leases from Kubernetes annotations -- %s", err)
		htp.Error(w, http.StatusInternalServerError, "error parsing leases from Kubernetes annotations -- %s", err)
		return
	}

	availableCluster, err := searchForFreeCluster(clusterMap, leaseMap, req.ClusterRegex, req.ClusterVersion)
	if err != nil {
		switch e := err.(type) {
		case errNoAvailableOrExpiredClustersFound:
			log.Printf("No available clusters found")
			htp.Error(w, http.StatusConflict, "No available clusters found")
			return
		case errExpiredLeaseAzureMissing:
			log.Printf("Cluster %s has an expired lease but doesn't exist in Azure", e.clusterName)
			htp.Error(w, http.StatusInternalServerError, "Cluster %s has an expired lease but doesn't exist in Azure", e.clusterName)
			return
		default:
			log.Printf("Unknown error %s", e.Error())
			htp.Error(w, http.StatusInternalServerError, "Unknown error %s", e.Error())
			return
		}
	}

	// There is currently no way to fetch the kubeconfig from the Azure API
	// So we must scp the file off the master node
	kubeConfig, err := FetchKubeConfig(*availableCluster.MasterProfile.Fqdn)
	if err != nil {
		log.Printf("Error creating kubeconfig file for cluster %s -- %s", *availableCluster.Name, err)
		htp.Error(w, http.StatusInternalServerError, "Error creating kubeconfig file for cluster %s -- %s", *availableCluster.Name, err)
		return
	}
	newToken := uuid.NewUUID()
	kubeConfigStr, err := k8s.MarshalAndEncodeKubeConfig(kubeConfig)
	if err != nil {
		log.Printf("Error marshaling & encoding kubeconfig -- %s", err)
		htp.Error(w, http.StatusInternalServerError, "Error marshaling & encoding kubeconfig -- %s", err)
		return
	}

	resp := api.CreateLeaseResp{
		KubeConfigStr: kubeConfigStr,
		IP:            *availableCluster.MasterProfile.Fqdn,
		Token:         newToken.String(),
		ClusterName:   *availableCluster.Name,
	}

	leaseMap.CreateLease(newToken, leases.NewLease(*availableCluster.Name, req.ExpirationTime(time.Now())))
	if err := k8s.SaveAnnotations(services, svc, leaseMap); err != nil {
		log.Printf("Error saving new lease to Kubernetes annotations -- %s", err)
		htp.Error(w, http.StatusInternalServerError, "Error saving new lease to Kubernetes annotations -- %s", err)
		return
	}

	if err := json.NewEncoder(w).Encode(resp); err != nil {
		log.Printf("Error encoding json -- %s", err)
		htp.Error(w, http.StatusInternalServerError, "Error encoding json -- %s", err)
		return
	}
}
493337
func FilterKeys(authorizer acl.Authorizer, keys []string) []string {
	kf := keyFilter{authorizer: authorizer, keys: keys}
	return keys[:FilterEntries(&kf)]
}
791443
func groupKeyFor(key lease.Key) groupKey {
	return groupKey{
		namespace: key.Namespace,
		modelUUID: key.ModelUUID,
	}
}
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
}
935795
func Convert_v1_Lease_To_coordination_Lease(in *v1.Lease, out *coordination.Lease, s conversion.Scope) error {
	return autoConvert_v1_Lease_To_coordination_Lease(in, out, s)
}
740116
func (t *MemoryPool) AddLease(newLease leasepool.Lease) error {
	t.poolLock.Lock()
	defer t.poolLock.Unlock()

	if t.pool == nil {
		t.pool = make([]leasepool.Lease, 0)
	}

	for i := range t.pool {
		if t.pool[i].IP.Equal(newLease.IP) {
			//Lease Already Exists In Pool
			return errors.New("Error: Lease IP \"" + newLease.IP.String() + "\" alreay exists in Pool")
		}
	}

	t.pool = append([]leasepool.Lease{newLease}, t.pool...)
	return nil
}