// addUnit adds a single unit to an application already present in the environment.
8664
func (h *bundleHandler) addUnit(change *bundlechanges.AddUnitChange) error {
	if h.dryRun {
		return nil
	}

	p := change.Params
	applicationName := resolve(p.Application, h.results)
	var err error
	var placementArg []*instance.Placement
	targetMachine := p.To
	if targetMachine != "" {
		logger.Debugf("addUnit: placement %q", targetMachine)
		// The placement maybe "container:machine"
		container := ""
		if parts := strings.Split(targetMachine, ":"); len(parts) > 1 {
			container = parts[0]
			targetMachine = parts[1]
		}
		targetMachine, err = h.resolveMachine(targetMachine)
		if err != nil {
			// Should never happen.
			return errors.Annotatef(err, "cannot retrieve placement for %q unit", applicationName)
		}
		directive := targetMachine
		if container != "" {
			directive = container + ":" + directive
		}
		placement, err := parsePlacement(directive)
		if err != nil {
			return errors.Errorf("invalid --to parameter %q", directive)
		}
		logger.Debugf("  resolved: placement %q", directive)
		placementArg = append(placementArg, placement)
	}
	r, err := h.api.AddUnits(application.AddUnitsParams{
		ApplicationName: applicationName,
		NumUnits:        1,
		Placement:       placementArg,
	})
	if err != nil {
		return errors.Annotatef(err, "cannot add unit for application %q", applicationName)
	}
	unit := r[0]
	if targetMachine == "" {
		logger.Debugf("added %s unit to new machine", unit)
		// In this case, the unit name is stored in results instead of the
		// machine id, which is lazily evaluated later only if required.
		// This way we avoid waiting for watcher updates.
		h.results[change.Id()] = unit
	} else {
		logger.Debugf("added %s unit to new machine", unit)
		h.results[change.Id()] = targetMachine
	}

	// Note that the targetMachine can be empty for now, resulting in a partially
	// incomplete unit status. That's ok as the missing info is provided later
	// when it is required.
	h.unitStatus[unit] = targetMachine
	return nil
}
591476
func (r *EtcdRegistry) CreateUnit(u *job.Unit) error {
	if err := r.storeOrGetUnitFile(u.Unit); err != nil {
		return err
	}

	jm := jobModel{
		Name:     u.Name,
		UnitHash: u.Unit.Hash(),
	}
	val, err := marshal(jm)
	if err != nil {
		return err
	}

	opts := &etcd.SetOptions{
		// Since we support replacing units, just ignore previous
		// job keys if they exist, this allows us to update the
		// job object key with a new unit.
		PrevExist: etcd.PrevIgnore,
	}
	key := r.prefixed(jobPrefix, u.Name, "object")
	_, err = r.kAPI.Set(context.Background(), key, val, opts)
	if err != nil {
		return err
	}

	return r.SetUnitTargetState(u.Name, u.TargetState)
}
406490
func (pb *ProgressBar) SetUnits(units Units) *ProgressBar {
	pb.Units = units
	return pb
}
303276
func (m *MockUpgradeSeriesBackend) Unit(arg0 string) (common.UpgradeSeriesUnit, error) {
	ret := m.ctrl.Call(m, "Unit", arg0)
	ret0, _ := ret[0].(common.UpgradeSeriesUnit)
	ret1, _ := ret[1].(error)
	return ret0, ret1
}
1160038
func (g *Generation) AssignUnit(unitName string) error {
	appName, err := names.UnitApplication(unitName)
	if err != nil {
		return errors.Trace(err)
	}

	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)
		}
		if set.NewStrings(g.doc.AssignedUnits[appName]...).Contains(unitName) {
			return nil, jujutxn.ErrNoOperations
		}
		unit, err := g.st.Unit(unitName)
		if err != nil {
			return nil, errors.Trace(err)
		}
		return assignGenerationUnitTxnOps(g.doc.DocId, appName, unit), nil
	}

	return errors.Trace(g.st.db().Run(buildTxn))
}
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

}
1043903
func (s *DateRange) SetUnit(v string) *DateRange {
	s.Unit = &v
	return s
}
1243080
func NewUnit(component string, templatePaths []string, decorate bool) (uf *unit.UnitFile, err error) {
	template, err := readTemplate(component, templatePaths)
	if err != nil {
		return
	}
	if decorate {
		decorator, err := readDecorator(component)
		if err != nil {
			return nil, err
		}
		uf, err = unit.NewUnitFile(string(template) + "\n" + string(decorator))
	} else {
		uf, err = unit.NewUnitFile(string(template))
	}
	return
}
18119
func (ctx *hookContext) addJujuUnitsMetric() error {
	if ctx.recorder.IsDeclaredMetric("juju-units") {
		// TODO(fwereade): 2016-03-17 lp:1558657
		err := ctx.recorder.AddMetric("juju-units", "1", time.Now().UTC(), nil)
		if err != nil {
			return errors.Trace(err)
		}
	}
	return nil
}
1361030
func (c *Controller) removeUnit(ch RemoveUnit) error {
	return errors.Trace(c.removeResident(ch.ModelUUID, func(m *Model) error { return m.removeUnit(ch) }))
}
8078
func (uw *UnitWriter) WriteUnit(path string, errmsg string, opts ...*unit.UnitOption) {
	if uw.err != nil {
		return
	}

	file, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644)
	if err != nil {
		uw.err = errwrap.Wrap(errors.New(errmsg), err)
		return
	}
	defer file.Close()

	if _, err = io.Copy(file, unit.Serialize(opts)); err != nil {
		uw.err = errwrap.Wrap(errors.New(errmsg), err)
		return
	}
	if err := user.ShiftFiles([]string{path}, &uw.p.UidRange); err != nil {
		uw.err = errwrap.Wrap(errors.New(errmsg), err)
		return
	}
}
485283
func addApplicationUnits(backend Backend, modelType state.ModelType, args params.AddApplicationUnits) ([]Unit, error) {
	if args.NumUnits < 1 {
		return nil, errors.New("must add at least one unit")
	}

	assignUnits := true
	if modelType != state.ModelTypeIAAS {
		// In a CAAS model, there are no machines for
		// units to be assigned to.
		assignUnits = false
		if len(args.AttachStorage) > 0 {
			return nil, errors.Errorf(
				"AttachStorage may not be specified for %s models",
				modelType,
			)
		}
		if len(args.Placement) > 1 {
			return nil, errors.Errorf(
				"only 1 placement directive is supported for %s models, got %d",
				modelType,
				len(args.Placement),
			)
		}
	}

	// Parse storage tags in AttachStorage.
	if len(args.AttachStorage) > 0 && args.NumUnits != 1 {
		return nil, errors.Errorf("AttachStorage is non-empty, but NumUnits is %d", args.NumUnits)
	}
	attachStorage := make([]names.StorageTag, len(args.AttachStorage))
	for i, tagString := range args.AttachStorage {
		tag, err := names.ParseStorageTag(tagString)
		if err != nil {
			return nil, errors.Trace(err)
		}
		attachStorage[i] = tag
	}
	application, err := backend.Application(args.ApplicationName)
	if err != nil {
		return nil, errors.Trace(err)
	}
	return addUnits(
		application,
		args.ApplicationName,
		args.NumUnits,
		args.Placement,
		attachStorage,
		assignUnits,
	)
}
1367244
func addUnitOps(st *State, args addUnitOpsArgs) ([]txn.Op, error) {
	name := args.unitDoc.Name
	agentGlobalKey := unitAgentGlobalKey(name)

	// TODO: consider the constraints op
	// TODO: consider storageOps
	var prereqOps []txn.Op
	if args.containerDoc != nil {
		prereqOps = append(prereqOps, txn.Op{
			C:      cloudContainersC,
			Id:     args.containerDoc.Id,
			Insert: args.containerDoc,
			Assert: txn.DocMissing,
		})
	}
	prereqOps = append(prereqOps,
		createStatusOp(st, agentGlobalKey, args.agentStatusDoc),
		createStatusOp(st, unitGlobalKey(name), *args.workloadStatusDoc),
		createMeterStatusOp(st, agentGlobalKey, args.meterStatusDoc),
		createStatusOp(st, globalWorkloadVersionKey(name), *args.workloadVersionDoc),
	)

	// Freshly-created units will not have a charm URL set; migrated
	// ones will, and they need to maintain their refcounts. If we
	// relax the restrictions on migrating apps mid-upgrade, this
	// will need to be more sophisticated, because it might need to
	// create the settings doc.
	if curl := args.unitDoc.CharmURL; curl != nil {
		appName := args.unitDoc.Application
		charmRefOps, err := appCharmIncRefOps(st, appName, curl, false)
		if err != nil {
			return nil, errors.Trace(err)
		}
		prereqOps = append(prereqOps, charmRefOps...)
	}

	return append(prereqOps, txn.Op{
		C:      unitsC,
		Id:     name,
		Assert: txn.DocMissing,
		Insert: args.unitDoc,
	}), nil
}
749211
func (s *StorageAPI) AddUnitStorage(
	args params.StoragesAddParams,
) (params.ErrorResults, error) {
	canAccess, err := s.accessUnit()
	if err != nil {
		return params.ErrorResults{}, err
	}
	if len(args.Storages) == 0 {
		return params.ErrorResults{}, nil
	}

	serverErr := func(err error) params.ErrorResult {
		return params.ErrorResult{common.ServerError(err)}
	}

	storageErr := func(err error, s, u string) params.ErrorResult {
		return serverErr(errors.Annotatef(err, "adding storage %v for %v", s, u))
	}

	result := make([]params.ErrorResult, len(args.Storages))
	for i, one := range args.Storages {
		u, err := accessUnitTag(one.UnitTag, canAccess)
		if err != nil {
			result[i] = serverErr(err)
			continue
		}

		cons, err := unitStorageConstraints(s.backend, u)
		if err != nil {
			result[i] = serverErr(err)
			continue
		}

		oneCons, err := validConstraints(one, cons)
		if err != nil {
			result[i] = storageErr(err, one.StorageName, one.UnitTag)
			continue
		}

		_, err = s.storage.AddStorageForUnit(u, one.StorageName, oneCons)
		if err != nil {
			result[i] = storageErr(err, one.StorageName, one.UnitTag)
		}
	}
	return params.ErrorResults{Results: result}, nil
}
1279883
func NewUnit(m map[string]int64) (*Unit, error) {
	var found bool
	for _, mult := range m {
		if mult == 1 {
			found = true
			break
		}
	}
	if !found {
		return nil, fmt.Errorf("could not find unit that maps to multiplier 1 for %v", m)
	}
	return &Unit{m}, nil
}
1020569
func (s *GeoDistanceSort) Unit(unit string) *GeoDistanceSort {
	s.unit = unit
	return s
}
39490
func (s *CustomizedMetricSpecification) SetUnit(v string) *CustomizedMetricSpecification {
	s.Unit = &v
	return s
}