// Units returns all the units that have been assigned to the machine.
511367
func (m *Machine) Units() (units []*Unit, err error) {
	defer errors.DeferredAnnotatef(&err, "cannot get units assigned to machine %v", m)
	unitsCollection, closer := m.st.db().GetCollection(unitsC)
	defer closer()

	pudocs := []unitDoc{}
	err = unitsCollection.Find(bson.D{{"machineid", m.doc.Id}}).All(&pudocs)
	if err != nil {
		return nil, err
	}
	model, err := m.st.Model()
	if err != nil {
		return nil, errors.Trace(err)
	}
	for _, pudoc := range pudocs {
		units = append(units, newUnit(m.st, model.Type(), &pudoc))
		docs := []unitDoc{}
		err = unitsCollection.Find(bson.D{{"principal", pudoc.Name}}).All(&docs)
		if err != nil {
			return nil, err
		}
		for _, doc := range docs {
			units = append(units, newUnit(m.st, model.Type(), &doc))
		}
	}
	return units, nil
}
1358587
func (m *Model) Unit(unitName string) (*Unit, error) {
	defer m.doLocked()()

	unit, found := m.units[unitName]
	if !found {
		return nil, errors.NotFoundf("unit %q", unitName)
	}
	return unit, nil
}
881940
func (m *Machine) Units() ([]*Unit, error) {
	m.mu.Lock()
	defer m.mu.Unlock()

	result := make([]*Unit, 0)
	for unitName, unit := range m.model.units {
		if unit.details.MachineId == m.details.Id {
			result = append(result, unit)
		}
		if unit.details.Subordinate {
			principalUnit, found := m.model.units[unit.details.Principal]
			if !found {
				return result, errors.NotFoundf("principal unit %q for subordinate %s", unit.details.Principal, unitName)
			}
			if principalUnit.details.MachineId == m.details.Id {
				result = append(result, unit)
			}
		}
	}
	return result, nil
}
1065142
func (mr *MockMeterStatusStateMockRecorder) Unit(arg0 interface{}) *gomock.Call {
	return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Unit", reflect.TypeOf((*MockMeterStatusState)(nil).Unit), arg0)
}
1284377
func (a *Application) UnitNames() ([]string, error) {
	u, err := appUnitNames(a.st, a.Name())
	return u, errors.Trace(err)
}
562058
func (w *MachineLXDProfileWatcher) init(machine *Machine) error {
	units, err := machine.Units()
	if err != nil {
		return errors.Annotatef(err, "failed to get units to start MachineLXDProfileWatcher")
	}

	for _, unit := range units {
		appName := unit.Application()
		unitName := unit.Name()

		if info, found := w.applications[appName]; found {
			info.units.Add(unitName)
			continue
		}

		app, err := w.modeler.Application(appName)
		if errors.IsNotFound(err) {
			// This is unlikely, but could happen because Units()
			// added the parent'd machine id to subordinates.
			// If the unit has no machineId, it will be added
			// to what is watched when the machineId is assigned.
			// Otherwise return an error.
			if unit.MachineId() != "" {
				return errors.Errorf("programming error, unit %s has machineId but not application", unitName)
			}
			logger.Errorf("unit %s has no application, nor machine id, start watching when machine id assigned.", unitName)
			w.metrics.LXDProfileChangeError.Inc()
			continue
		}

		chURL := app.CharmURL()
		info := appInfo{
			charmURL: chURL,
			units:    set.NewStrings(unitName),
		}

		ch, err := w.modeler.Charm(chURL)
		if err != nil {
			return err
		}
		lxdProfile := ch.LXDProfile()
		if !lxdProfile.Empty() {
			info.charmProfile = lxdProfile
		}

		w.applications[appName] = info
	}
	return nil
}
733309
func (st *State) MetricBatchesForUnit(unit string) ([]MetricBatch, error) {
	_, err := st.Unit(unit)
	if err != nil {
		return nil, errors.Trace(err)
	}
	return st.queryMetricBatches(bson.M{"unit": unit})
}
788528
func (r *Relation) Unit(u *Unit) (*RelationUnit, error) {
	if u == nil {
		return nil, fmt.Errorf("unit is nil")
	}
	result, err := r.st.relation(r.tag, u.tag)
	if err != nil {
		return nil, err
	}
	return &RelationUnit{
		relation: r,
		unit:     u,
		endpoint: Endpoint{r.toCharmRelation(result.Endpoint.Relation)},
		st:       r.st,
	}, nil
}
715308
func (rect *Rect) UnitsToPoints(t int) (r *Rect) {
	if rect == nil {
		return
	}

	if rect.unitOverride != Unit_Unset {
		t = rect.unitOverride
	}

	r = &Rect{W: rect.W, H: rect.H}
	UnitsToPointsVar(t, &r.W, &r.H)
	return
}
306367
func (a *API) UnitsCompleted(args params.Entities) (params.EntitiesResults, error) {
	result, err := a.unitsInState(args, model.UpgradeSeriesCompleted)
	return result, errors.Trace(err)
}
1118010
func (api *APIBase) AddUnits(args params.AddApplicationUnits) (params.AddApplicationUnitsResults, error) {
	if api.modelType == state.ModelTypeCAAS {
		return params.AddApplicationUnitsResults{}, errors.NotSupportedf("adding units on a non-container model")
	}
	if err := api.checkCanWrite(); err != nil {
		return params.AddApplicationUnitsResults{}, errors.Trace(err)
	}
	if err := api.check.ChangeAllowed(); err != nil {
		return params.AddApplicationUnitsResults{}, errors.Trace(err)
	}
	units, err := addApplicationUnits(api.backend, api.modelType, args)
	if err != nil {
		return params.AddApplicationUnitsResults{}, errors.Trace(err)
	}
	unitNames := make([]string, len(units))
	for i, unit := range units {
		unitNames[i] = unit.UnitTag().Id()
	}
	return params.AddApplicationUnitsResults{Units: unitNames}, nil
}
63073
func (gp *GoPdf) UnitsToPoints(u float64) float64 {
	return UnitsToPoints(gp.config.Unit, u)
}
586726
func (m *Machine) VerifyUnitsSeries(unitNames []string, series string, force bool) ([]*Unit, error) {
	var results []*Unit
	for _, u := range unitNames {
		unit, err := m.st.Unit(u)
		if err != nil {
			return nil, err
		}
		app, err := unit.Application()
		if err != nil {
			return nil, err
		}
		err = app.VerifySupportedSeries(series, force)
		if err != nil {
			return nil, err
		}

		subordinates := unit.SubordinateNames()
		subUnits, err := m.VerifyUnitsSeries(subordinates, series, force)
		if err != nil {
			return nil, err
		}
		results = append(results, unit)
		results = append(results, subUnits...)
	}
	return results, nil
}
684405
func (st *State) AssignUnit(u *Unit, policy AssignmentPolicy) (err error) {
	if !u.IsPrincipal() {
		return errors.Errorf("subordinate unit %q cannot be assigned directly to a machine", u)
	}
	defer errors.DeferredAnnotatef(&err, "cannot assign unit %q to machine", u)
	var m *Machine
	switch policy {
	case AssignLocal:
		m, err = st.Machine("0")
		if err != nil {
			return errors.Trace(err)
		}
		return u.AssignToMachine(m)
	case AssignClean:
		if _, err = u.AssignToCleanMachine(); errors.Cause(err) != noCleanMachines {
			return errors.Trace(err)
		}
		return u.AssignToNewMachineOrContainer()
	case AssignCleanEmpty:
		if _, err = u.AssignToCleanEmptyMachine(); errors.Cause(err) != noCleanMachines {
			return errors.Trace(err)
		}
		return u.AssignToNewMachineOrContainer()
	case AssignNew:
		return errors.Trace(u.AssignToNewMachine())
	}
	return errors.Errorf("unknown unit assignment policy: %q", policy)
}
1040189
func (c *FleetClient) Units(target string) (units []string, err error) {
	allUnits, err := c.Fleet.Units()
	if err != nil {
		return
	}
	// Look for units starting with the given target name first. If the given
	// name starts with "deis-", this will easily locate platform components,
	// but we search without canonicalizing the target name FIRST so we have the
	// opportunity to locate application containers (whose containers do not
	// adhere to the same naming convention as the platform's own components).
	for _, u := range allUnits {
		if strings.HasPrefix(u.Name, target) {
			units = append(units, u.Name)
		}
	}
	// If none are found, canonicalize the target string and search again. This
	// will locate platform components that were referenced by a target string
	// NOT already beginning with "deis-".
	if len(units) == 0 {
		canonTarget := strings.ToLower(target)
		if !strings.HasPrefix(canonTarget, "deis-") {
			canonTarget = "deis-" + canonTarget
		}
		for _, u := range allUnits {
			if strings.HasPrefix(u.Name, canonTarget) {
				units = append(units, u.Name)
			}
		}
	}
	// If still nothing is found, then we have an error on our hands.
	if len(units) == 0 {
		err = fmt.Errorf("could not find unit: %s", target)
	}
	return
}
75858
func (c *Client) DestroyUnits(in DestroyUnitsParams) ([]params.DestroyUnitResult, error) {
	argsV5 := params.DestroyUnitsParams{
		Units: make([]params.DestroyUnitParams, 0, len(in.Units)),
	}
	allResults := make([]params.DestroyUnitResult, len(in.Units))
	index := make([]int, 0, len(in.Units))
	for i, name := range in.Units {
		if !names.IsValidUnit(name) {
			allResults[i].Error = &params.Error{
				Message: errors.NotValidf("unit ID %q", name).Error(),
			}
			continue
		}
		index = append(index, i)
		argsV5.Units = append(argsV5.Units, params.DestroyUnitParams{
			UnitTag:        names.NewUnitTag(name).String(),
			DestroyStorage: in.DestroyStorage,
			Force:          in.Force,
			MaxWait:        in.MaxWait,
		})
	}
	if len(argsV5.Units) == 0 {
		return allResults, nil
	}

	args := interface{}(argsV5)
	if c.BestAPIVersion() < 5 {
		if in.DestroyStorage {
			return nil, errors.New("this controller does not support --destroy-storage")
		}
		argsV4 := params.Entities{
			Entities: make([]params.Entity, len(argsV5.Units)),
		}
		for i, arg := range argsV5.Units {
			argsV4.Entities[i].Tag = arg.UnitTag
		}
		args = argsV4
	}

	var result params.DestroyUnitResults
	if err := c.facade.FacadeCall("DestroyUnit", args, &result); err != nil {
		return nil, errors.Trace(err)
	}
	if n := len(result.Results); n != len(argsV5.Units) {
		return nil, errors.Errorf("expected %d result(s), got %d", len(argsV5.Units), n)
	}
	for i, result := range result.Results {
		allResults[index[i]] = result
	}
	return allResults, nil
}
570399
func (m *MockApplication) UnitNames() ([]string, error) {
	ret := m.ctrl.Call(m, "UnitNames")
	ret0, _ := ret[0].([]string)
	ret1, _ := ret[1].(error)
	return ret0, ret1
}