// Life returns the lifecycle state for the specified CAAS application
// or unit in the current model.
509249
func (c *Client) Life(entityName string) (life.Value, error) {
	var tag names.Tag
	switch {
	case names.IsValidApplication(entityName):
		tag = names.NewApplicationTag(entityName)
	case names.IsValidUnit(entityName):
		tag = names.NewUnitTag(entityName)
	default:
		return "", errors.NotValidf("application or unit name %q", entityName)
	}
	args := entities(tag)

	var results params.LifeResults
	if err := c.facade.FacadeCall("Life", args, &results); err != nil {
		return "", err
	}
	if n := len(results.Results); n != 1 {
		return "", errors.Errorf("expected 1 result, got %d", n)
	}
	if err := results.Results[0].Error; err != nil {
		return "", maybeNotFound(err)
	}
	return life.Value(results.Results[0].Life), nil
}
486728
func (c *Client) Unit(tag names.UnitTag) (*Unit, error) {
	life, err := c.life(tag)
	if err != nil {
		return nil, err
	}
	return &Unit{
		tag:  tag,
		life: life,
		st:   c,
	}, nil
}
627910
func (c *asyncClient) Lastsave() (result FutureInt64, err Error) {
	var resp *PendingResponse
	resp, err = c.conn.QueueRequest(&LASTSAVE, [][]byte{})
	if err == nil {
		result = resp.future.(FutureInt64)
	}
	return result, err

}
102935
func storageEntityLife(ctx *context, tags []names.Tag) (alive, dying, dead []names.Tag, _ error) {
	lifeResults, err := ctx.config.Life.Life(tags)
	if err != nil {
		return nil, nil, nil, errors.Annotate(err, "getting storage entity life")
	}
	for i, result := range lifeResults {
		life := result.Life
		if result.Error != nil {
			if !params.IsCodeNotFound(result.Error) {
				return nil, nil, nil, errors.Annotatef(
					result.Error, "getting life of %s",
					names.ReadableString(tags[i]),
				)
			}
			life = params.Dead
		}
		switch life {
		case params.Alive:
			alive = append(alive, tags[i])
		case params.Dying:
			dying = append(dying, tags[i])
		case params.Dead:
			dead = append(dead, tags[i])
		}
	}
	return alive, dying, dead, nil
}
621779
func (a *Application) ApplicationAndUnitsStatus() (status.StatusInfo, map[string]status.StatusInfo, error) {
	applicationStatus, err := a.Status()
	if err != nil {
		return status.StatusInfo{}, nil, errors.Trace(err)
	}
	units, err := a.AllUnits()
	if err != nil {
		return status.StatusInfo{}, nil, err
	}
	results := make(map[string]status.StatusInfo, len(units))
	for _, unit := range units {
		unitStatus, err := unit.Status()
		if err != nil {
			return status.StatusInfo{}, nil, err
		}
		results[unit.Name()] = unitStatus
	}
	return applicationStatus, results, nil

}
558988
func (s *Bucket) GetLifecycle() (*GetBucketLifecycleOutput, error) {
	r, x, err := s.GetLifecycleRequest()

	if err != nil {
		return x, err
	}

	err = r.Send()
	if err != nil {
		return nil, err
	}

	requestID := r.HTTPResponse.Header.Get(http.CanonicalHeaderKey("X-QS-Request-ID"))
	x.RequestID = &requestID

	return x, err
}
76205
func (s *Instance) SetLifecycleState(v string) *Instance {
	s.LifecycleState = &v
	return s
}
908715
func (c *statusContext) processMachine(machine *state.Machine) (out params.DetailedStatus) {
	wrapped := &contextMachine{machine, c}
	statusInfo, err := c.presence.MachineStatus(wrapped)
	populateStatusFromStatusInfoAndErr(&out, statusInfo, err)

	out.Life = processLife(machine)

	if t, err := machine.AgentTools(); err == nil {
		out.Version = t.Version.Number.String()
	}
	return
}
902596
func (a *Application) Status() (status.StatusInfo, error) {
	statuses, closer := a.st.db().GetCollection(statusesC)
	defer closer()
	query := statuses.Find(bson.D{{"_id", a.globalKey()}, {"neverset", true}})
	if count, err := query.Count(); err != nil {
		return status.StatusInfo{}, errors.Trace(err)
	} else if count != 0 {
		// This indicates that SetStatus has never been called on this application.
		// This in turn implies the application status document is likely to be
		// inaccurate, so we return aggregated unit statuses instead.
		//
		// TODO(fwereade): this is completely wrong and will produce bad results
		// in not-very-challenging scenarios. The leader unit remains responsible
		// for setting the application status in a timely way, *whether or not the
		// charm's hooks exists or sets an application status*. This logic should be
		// removed as soon as possible, and the responsibilities implemented in
		// the right places rather than being applied at seeming random.
		units, err := a.AllUnits()
		if err != nil {
			return status.StatusInfo{}, err
		}
		logger.Tracef("application %q has %d units", a.Name(), len(units))
		var unitStatuses []status.StatusInfo
		for _, unit := range units {
			unitStatus, err := unit.Status()
			if err != nil {
				return status.StatusInfo{}, errors.Annotatef(err, "deriving application status from %q", unit.Name())
			}
			unitStatuses = append(unitStatuses, unitStatus)
		}
		if len(unitStatuses) > 0 {
			return deriveApplicationStatus(unitStatuses), nil
		}
	}
	return getStatus(a.st.db(), a.globalKey(), "application")
}
891284
func (tr *Transport) Lifespan() time.Duration {
	cert := tr.Provider.Certificate()
	if cert == nil {
		return 0
	}

	now := time.Now()
	if now.After(cert.NotAfter) {
		return 0
	}

	now = now.Add(tr.Before)
	ls := cert.NotAfter.Sub(now)
	log.Debugf("   LIFESPAN:\t%s", ls)
	if ls < 0 {
		return 0
	}
	return ls
}
1144988
func (m *ModelStatus) Application(appName string, unitNames []string) (status.StatusInfo, error) {
	// This is kinda terrible, see notes in application.go for *Application.Status().
	doc, err := m.getDoc(applicationGlobalKey(appName), "application")
	if err != nil {
		return status.StatusInfo{}, err
	}
	appStatus := doc.asStatusInfo()
	expectWorkload, err := expectWorkload(m.model.st, appName)
	if err != nil {
		return status.StatusInfo{}, errors.Trace(err)
	}
	if doc.NeverSet {
		// Get the status for the agents, and derive a status from that.
		var unitStatuses []status.StatusInfo
		for _, name := range unitNames {
			unitStatus, err := m.UnitWorkload(name, expectWorkload)
			if err != nil {
				return status.StatusInfo{}, errors.Annotatef(err, "deriving application status from %q", name)
			}
			unitStatuses = append(unitStatuses, unitStatus)
		}
		if len(unitStatuses) > 0 {
			appStatus = deriveApplicationStatus(unitStatuses)
		}

	}
	if m.model.Type() == ModelTypeIAAS {
		return appStatus, nil
	}

	operatorStatusDoc, err := m.getDoc(applicationGlobalOperatorKey(appName), "operator")
	if err != nil {
		return status.StatusInfo{}, errors.Trace(err)
	}
	return caasApplicationDisplayStatus(appStatus, operatorStatusDoc.asStatusInfo(), expectWorkload), nil
}
1042286
func (st *State) Life(tags []names.Tag) ([]params.LifeResult, error) {
	var results params.LifeResults
	args := params.Entities{
		Entities: make([]params.Entity, len(tags)),
	}
	for i, tag := range tags {
		args.Entities[i].Tag = tag.String()
	}
	if err := st.facade.FacadeCall("Life", args, &results); err != nil {
		return nil, err
	}
	if len(results.Results) != len(tags) {
		return nil, errors.Errorf("expected %d result(s), got %d", len(tags), len(results.Results))
	}
	return results.Results, nil
}
555366
func (w *DefaultWorker) SetLifecycle(lf Lifecycle) {
	w.ensureUnstarted()
	w.lifecycle = lf
}
815483
func (s *InstanceDetails) SetLifecycleState(v string) *InstanceDetails {
	s.LifecycleState = &v
	return s
}
711106
func (d *Execution_Data) State() Execution_State {
	if d != nil {
		switch d.ExecutionType.(type) {
		case *Execution_Data_Scheduling_:
			return Execution_SCHEDULING
		case *Execution_Data_Running_:
			return Execution_RUNNING
		case *Execution_Data_Stopping_:
			return Execution_STOPPING
		case *Execution_Data_Finished_:
			return Execution_FINISHED
		case *Execution_Data_AbnormalFinish:
			return Execution_ABNORMAL_FINISHED
		}
	}
	return Execution_SCHEDULING
}
504317
func (k *kubernetesClient) Units(appName string) ([]caas.Unit, error) {
	pods := k.client().CoreV1().Pods(k.namespace)
	podsList, err := pods.List(v1.ListOptions{
		LabelSelector: applicationSelector(appName),
	})
	if err != nil {
		return nil, errors.Trace(err)
	}

	var units []caas.Unit
	now := time.Now()
	for _, p := range podsList.Items {
		var ports []string
		for _, c := range p.Spec.Containers {
			for _, p := range c.Ports {
				ports = append(ports, fmt.Sprintf("%v/%v", p.ContainerPort, p.Protocol))
			}
		}
		terminated := p.DeletionTimestamp != nil
		statusMessage, unitStatus, since, err := k.getPODStatus(p, now)
		if err != nil {
			return nil, errors.Trace(err)
		}
		providerId := string(p.UID)
		stateful := false

		// Pods managed by a stateful set use the pod name
		// as the provider id as this is stable across pod restarts.
		for _, ref := range p.OwnerReferences {
			if stateful = ref.Kind == "StatefulSet"; stateful {
				providerId = p.Name
				break
			}
		}
		unitInfo := caas.Unit{
			Id:       providerId,
			Address:  p.Status.PodIP,
			Ports:    ports,
			Dying:    terminated,
			Stateful: stateful,
			Status: status.StatusInfo{
				Status:  unitStatus,
				Message: statusMessage,
				Since:   &since,
			},
		}

		volumesByName := make(map[string]core.Volume)
		for _, pv := range p.Spec.Volumes {
			volumesByName[pv.Name] = pv
		}

		// Gather info about how filesystems are attached/mounted to the pod.
		// The mount name represents the filesystem tag name used by Juju.
		for _, volMount := range p.Spec.Containers[0].VolumeMounts {
			vol, ok := volumesByName[volMount.Name]
			if !ok {
				logger.Warningf("volume for volume mount %q not found", volMount.Name)
				continue
			}
			var fsInfo *caas.FilesystemInfo
			if vol.PersistentVolumeClaim != nil && vol.PersistentVolumeClaim.ClaimName != "" {
				fsInfo, err = k.volumeInfoForPVC(vol, volMount, vol.PersistentVolumeClaim.ClaimName, now)
			} else if vol.EmptyDir != nil {
				fsInfo, err = k.volumeInfoForEmptyDir(vol, volMount, now)
			} else {
				// Ignore volumes which are not Juju managed filesystems.
				logger.Debugf("Ignoring blank EmptyDir, PersistentVolumeClaim or ClaimName")
				continue
			}
			if err != nil {
				return nil, errors.Annotatef(err, "finding filesystem info for %v", volMount.Name)
			}
			if fsInfo == nil {
				continue
			}
			if fsInfo.StorageName == "" {
				if valid := legacyJujuPVNameRegexp.MatchString(volMount.Name); valid {
					fsInfo.StorageName = legacyJujuPVNameRegexp.ReplaceAllString(volMount.Name, "$storageName")
				} else if valid := jujuPVNameRegexp.MatchString(volMount.Name); valid {
					fsInfo.StorageName = jujuPVNameRegexp.ReplaceAllString(volMount.Name, "$storageName")
				}
			}
			logger.Debugf("filesystem info for %v: %+v", volMount.Name, *fsInfo)
			unitInfo.FilesystemInfo = append(unitInfo.FilesystemInfo, *fsInfo)
		}
		units = append(units, unitInfo)
	}
	return units, nil
}
288333
func (d *Attempt_Data) State() Attempt_State {
	if d != nil {
		switch d.AttemptType.(type) {
		case *Attempt_Data_Scheduling_:
			return Attempt_SCHEDULING
		case *Attempt_Data_Executing_:
			return Attempt_EXECUTING
		case *Attempt_Data_Waiting_:
			return Attempt_WAITING
		case *Attempt_Data_Finished_:
			return Attempt_FINISHED
		case *Attempt_Data_AbnormalFinish:
			return Attempt_ABNORMAL_FINISHED
		}
	}
	return Attempt_SCHEDULING
}