// Units lists all Units stored in the Registry, ordered by name. This includes both global and non-global units.
4709
func (r *EtcdRegistry) Units() ([]job.Unit, error) {
	key := r.prefixed(jobPrefix)
	opts := &etcd.GetOptions{
		// We need Job Units to be sorted
		Sort:      true,
		Recursive: true,
	}
	res, err := r.kAPI.Get(context.Background(), key, opts)
	if err != nil {
		if isEtcdError(err, etcd.ErrorCodeKeyNotFound) {
			err = nil
		}
		return nil, err
	}

	// Fetch all units by hash recursively to avoid sending N requests to Etcd.
	hashToUnit, err := r.getAllUnitsHashMap()
	if err != nil {
		log.Errorf("failed fetching all Units from etcd: %v", err)
		return nil, err
	}
	unitHashLookupFunc := func(hash unit.Hash) *unit.UnitFile {
		stringHash := hash.String()
		unit, ok := hashToUnit[stringHash]
		if !ok {
			log.Errorf("did not find Unit %v in list of all units", stringHash)
			return nil
		}
		return unit
	}

	units := make([]job.Unit, 0)
	for _, dir := range res.Node.Nodes {
		u, err := r.dirToUnit(dir, unitHashLookupFunc)
		if err != nil {
			log.Errorf("Failed to parse Unit from etcd: %v", err)
			continue
		}
		if u == nil {
			continue
		}

		units = append(units, *u)
	}

	return units, nil
}
850190
func (r *EtcdRegistry) getAllUnitsHashMap() (map[string]*unit.UnitFile, error) {
	key := r.prefixed(unitPrefix)
	opts := &etcd.GetOptions{
		Recursive: true,
		Quorum:    true,
	}
	hashToUnit := map[string]*unit.UnitFile{}
	start := time.Now()
	resp, err := r.kAPI.Get(context.Background(), key, opts)
	if err != nil {
		metrics.ReportRegistryOpFailure(metrics.GetAll)
		return nil, err
	}
	metrics.ReportRegistryOpSuccess(metrics.GetAll, start)

	for _, node := range resp.Node.Nodes {
		parts := strings.Split(node.Key, "/")
		if len(parts) == 0 {
			log.Errorf("key '%v' doesn't have enough parts", node.Key)
			continue
		}
		stringHash := parts[len(parts)-1]
		hash, err := unit.HashFromHexString(stringHash)
		if err != nil {
			log.Errorf("failed to get Hash for key '%v' with stringHash '%v': %v", node.Key, stringHash, err)
			continue
		}
		unit := r.unitFromEtcdNode(hash, node)
		if unit == nil {
			continue
		}
		hashToUnit[stringHash] = unit
	}

	return hashToUnit, nil
}
576892
func (c *FleetClient) ListUnits() (err error) {
	var states []*schema.UnitState

	unitStates, err := c.Fleet.UnitStates()
	if err != nil {
		return err
	}

	for _, us := range unitStates {
		for _, prefix := range units.Names {
			if strings.HasPrefix(us.Name, prefix) {
				states = append(states, us)
				break
			}
		}
	}
	c.printUnits(states)
	return
}
1164762
func (u Vec) Unit() Vec {
	if u.X == 0 && u.Y == 0 {
		return Vec{1, 0}
	}
	return u.Scaled(1 / u.Len())
}
917036
func (m *Manager) ListRegistryEntries(username string, globalid string) (registryEntries []RegistryEntry, err error) {
	var selector bson.M
	if username != "" {
		selector = bson.M{"username": username}
	} else {
		selector = bson.M{"globalid": globalid}
	}
	result := struct {
		Entries []RegistryEntry
	}{}
	err = m.getRegistryCollection().Find(selector).Select(bson.M{"entries": 1}).One(&result)
	if err == mgo.ErrNotFound {
		err = nil
		registryEntries = []RegistryEntry{}
		return
	}
	registryEntries = result.Entries
	return
}
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
}
1344178
func (c *Conn) GetUnitProperties(unit string) (map[string]interface{}, error) {
	path := unitPath(unit)
	return c.getProperties(path, "org.freedesktop.systemd1.Unit")
}
63073
func (gp *GoPdf) UnitsToPoints(u float64) float64 {
	return UnitsToPoints(gp.config.Unit, u)
}
450786
func (g *Generation) AssignAllUnits(appName string) error {
	buildTxn := func(attempt int) ([]txn.Op, error) {
		if attempt > 0 {
			if err := g.Refresh(); err != nil {
				return nil, errors.Trace(err)
			}
		}
		if err := g.CheckNotComplete(); err != nil {
			return nil, errors.Trace(err)
		}
		unitNames, err := appUnitNames(g.st, appName)
		if err != nil {
			return nil, errors.Trace(err)
		}
		app, err := g.st.Application(appName)
		if err != nil {
			return nil, errors.Trace(err)
		}
		ops := []txn.Op{
			{
				C:  applicationsC,
				Id: app.doc.DocID,
				Assert: bson.D{
					{"life", Alive},
					{"unitcount", app.doc.UnitCount},
				},
			},
		}
		assignedUnits := set.NewStrings(g.doc.AssignedUnits[appName]...)
		for _, name := range unitNames {
			if !assignedUnits.Contains(name) {
				unit, err := g.st.Unit(name)
				if err != nil {
					return nil, errors.Trace(err)
				}
				ops = append(ops, assignGenerationUnitTxnOps(g.doc.DocId, appName, unit)...)
			}
		}
		// If there are no units to add to the generation, quit here.
		if len(ops) < 2 {
			return nil, jujutxn.ErrNoOperations
		}
		return ops, nil
	}
	return errors.Trace(g.st.db().Run(buildTxn))
}
892851
func (mr *MockLXDProfileBackendMockRecorder) Unit(arg0 interface{}) *gomock.Call {
	return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Unit", reflect.TypeOf((*MockLXDProfileBackend)(nil).Unit), arg0)
}
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
}
1215494
func (q *SearchSortGeoDistance) Unit(unit string) *SearchSortGeoDistance {
	q.options["unit"] = unit
	return q
}
248148
func (a *API) UnitsPrepared(args params.Entities) (params.EntitiesResults, error) {
	result, err := a.unitsInState(args, model.UpgradeSeriesPrepareCompleted)
	return result, errors.Trace(err)
}
875386
func Names() []string {
	out := []string{}
	for name := range Registry {
		out = append(out, name)
	}
	sort.Strings(out)
	return out
}
460593
func identifyNumLabelUnits(p *profile.Profile, ui plugin.UI) map[string]string {
	numLabelUnits, ignoredUnits := p.NumLabelUnits()

	// Print errors for tags with multiple units associated with
	// a single key.
	for k, units := range ignoredUnits {
		ui.PrintErr(fmt.Sprintf("For tag %s used unit %s, also encountered unit(s) %s", k, numLabelUnits[k], strings.Join(units, ", ")))
	}
	return numLabelUnits
}
160687
func (st *State) Unit(name string) (*Unit, error) {
	if !names.IsValidUnit(name) {
		return nil, errors.Errorf("%q is not a valid unit name", name)
	}
	units, closer := st.db().GetCollection(unitsC)
	defer closer()

	doc := unitDoc{}
	err := units.FindId(name).One(&doc)
	if err == mgo.ErrNotFound {
		return nil, errors.NotFoundf("unit %q", name)
	}
	if err != nil {
		return nil, errors.Annotatef(err, "cannot get unit %q", name)
	}
	model, err := st.Model()
	if err != nil {
		return nil, errors.Trace(err)
	}
	return newUnit(st, model.Type(), &doc), nil
}
807003
func (m *MockUpgradeSeriesMachine) Units() ([]common.UpgradeSeriesUnit, error) {
	ret := m.ctrl.Call(m, "Units")
	ret0, _ := ret[0].([]common.UpgradeSeriesUnit)
	ret1, _ := ret[1].(error)
	return ret0, ret1
}