// AgentTools returns the tools that the agent is currently running.
// It an error that satisfies errors.IsNotFound if the tools have not
// yet been set.
481479
func (u *Unit) AgentTools() (*tools.Tools, error) {
	if u.doc.Tools == nil {
		return nil, errors.NotFoundf("agent binaries for unit %q", u)
	}
	result := *u.doc.Tools
	return &result, nil
}
1001083
func (u *Unit) Agent() *UnitAgent {
	return newUnitAgent(u.st, u.Tag(), u.Name())
}
909991
func Manifold(config ManifoldConfig) dependency.Manifold {
	inputs := []string{
		config.AgentName,
		config.APICallerName,
	}

	// The machine agent uses these but the application agent doesn't.
	if config.UpgradeStepsGateName != "" {
		inputs = append(inputs, config.UpgradeStepsGateName)
	}
	if config.UpgradeCheckGateName != "" {
		inputs = append(inputs, config.UpgradeCheckGateName)
	}

	return dependency.Manifold{
		Inputs: inputs,
		Start: func(context dependency.Context) (worker.Worker, error) {
			if config.PreviousAgentVersion == version.Zero {
				return nil, errors.New("previous agent version not specified")
			}

			var agent agent.Agent
			if err := context.Get(config.AgentName, &agent); err != nil {
				return nil, err
			}
			currentConfig := agent.CurrentConfig()

			var apiCaller base.APICaller
			if err := context.Get(config.APICallerName, &apiCaller); err != nil {
				return nil, err
			}

			upgraderFacade := upgrader.NewState(apiCaller)
			operatorUpgraderFacade := caasoperatorupgrader.NewClient(apiCaller)

			var upgradeStepsWaiter gate.Waiter
			if config.UpgradeStepsGateName == "" {
				upgradeStepsWaiter = gate.NewLock()
			} else {
				if config.PreviousAgentVersion == version.Zero {
					return nil, errors.New("previous agent version not specified")
				}
				if err := context.Get(config.UpgradeStepsGateName, &upgradeStepsWaiter); err != nil {
					return nil, err
				}
			}

			var initialCheckUnlocker gate.Unlocker
			if config.UpgradeCheckGateName == "" {
				initialCheckUnlocker = gate.NewLock()
			} else {
				if err := context.Get(config.UpgradeCheckGateName, &initialCheckUnlocker); err != nil {
					return nil, err
				}
			}

			return NewUpgrader(Config{
				UpgraderClient:              upgraderFacade,
				CAASOperatorUpgrader:        operatorUpgraderFacade,
				AgentTag:                    currentConfig.Tag(),
				OrigAgentVersion:            config.PreviousAgentVersion,
				UpgradeStepsWaiter:          upgradeStepsWaiter,
				InitialUpgradeCheckComplete: initialCheckUnlocker,
			})
		},
	}
}
1111044
func (a *Agent) MembersOpts(opts MembersOpts) ([]*AgentMember, error) {
	r := a.c.newRequest("GET", "/v1/agent/members")
	r.params.Set("segment", opts.Segment)
	if opts.WAN {
		r.params.Set("wan", "1")
	}

	_, resp, err := requireOK(a.c.doRequest(r))
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()

	var out []*AgentMember
	if err := decodeBody(resp, &out); err != nil {
		return nil, err
	}
	return out, nil
}
169512
func (st *State) Tools(tag string) (tools.List, error) {
	var results params.ToolsResults
	args := params.Entities{
		Entities: []params.Entity{{Tag: tag}},
	}
	err := st.facade.FacadeCall("Tools", args, &results)
	if err != nil {
		// TODO: Not directly tested
		return nil, err
	}
	if len(results.Results) != 1 {
		// TODO: Not directly tested
		return nil, fmt.Errorf("expected 1 result, got %d", len(results.Results))
	}
	result := results.Results[0]
	if err := result.Error; err != nil {
		return nil, err
	}
	return result.ToolsList, nil
}
1362661
func checkToolsSeries(toolsList coretools.List, series string) error {
	toolsSeries := toolsList.AllSeries()
	if len(toolsSeries) != 1 {
		return fmt.Errorf("expected single series, got %v", toolsSeries)
	}
	if toolsSeries[0] != series {
		return fmt.Errorf("agent binary mismatch: expected series %v, got %v", series, toolsSeries[0])
	}
	return nil
}
46510
func NewAgentToolsAPI(
	modelGetter ModelGetter,
	newEnviron func() (environs.Environ, error),
	findTools toolsFinder,
	envVersionUpdate func(*state.Model, version.Number) error,
	authorizer facade.Authorizer,
) (*AgentToolsAPI, error) {
	return &AgentToolsAPI{
		modelGetter:      modelGetter,
		newEnviron:       newEnviron,
		authorizer:       authorizer,
		findTools:        findTools,
		envVersionUpdate: envVersionUpdate,
	}, nil
}
848570
func (s *CustomerAgentInfo) SetTotalAgents(v int64) *CustomerAgentInfo {
	s.TotalAgents = &v
	return s
}
508445
func (s *systemdServiceManager) StartAllAgents(
	machineAgent string, unitAgents []string, dataDir string,
) (string, []string, error) {
	if !s.isRunning() {
		return "", nil, errors.Errorf("cannot interact with systemd; reboot to start agents")
	}

	var startedUnits []string
	for _, unit := range unitAgents {
		if err := s.startAgent(unit, AgentKindUnit, dataDir); err != nil {
			return "", startedUnits, errors.Annotatef(err, "failed to start %s service", serviceName(unit))
		}
		startedUnits = append(startedUnits, serviceName(unit))
		logger.Infof("started %s service", serviceName(unit))
	}

	machineService := serviceName(machineAgent)
	err := s.startAgent(machineAgent, AgentKindMachine, dataDir)
	if err == nil {
		logger.Infof("started %s service", machineService)
		return machineService, startedUnits, nil
	}

	return "", startedUnits, errors.Annotatef(err, "failed to start %s service", machineService)
}
749534
func (c *Client) AgentVersion() (version.Number, error) {
	var result params.AgentVersionResult
	if err := c.facade.FacadeCall("AgentVersion", nil, &result); err != nil {
		return version.Number{}, err
	}
	return result.Version, nil
}
711602
func (c *Client) FindTools(args params.FindToolsParams) (params.FindToolsResult, error) {
	if err := c.checkCanWrite(); err != nil {
		return params.FindToolsResult{}, err
	}

	return c.api.toolsFinder.FindTools(args)
}
951370
func AgentConf(info AgentInfo, renderer shell.Renderer) common.Conf {
	conf := common.Conf{
		Desc:          fmt.Sprintf("juju agent for %s", info.name),
		ExecStart:     info.cmd(renderer),
		Logfile:       info.logFile(renderer),
		Env:           osenv.FeatureFlags(),
		Timeout:       agentServiceTimeout,
		ServiceBinary: info.jujud(renderer),
		ServiceArgs:   info.execArgs(renderer),
	}

	switch info.Kind {
	case AgentKindMachine:
		conf.Limit = map[string]string{
			"nofile": "64000",
		}
	case AgentKindUnit:
		conf.Desc = "juju unit agent for " + info.ID
	}

	return conf
}
213528
func (u *UnitUpgraderAPI) Tools(args params.Entities) (params.ToolsResults, error) {
	result := params.ToolsResults{
		Results: make([]params.ToolsResult, len(args.Entities)),
	}
	for i, entity := range args.Entities {
		result.Results[i].Error = common.ServerError(common.ErrPerm)
		tag, err := names.ParseTag(entity.Tag)
		if err != nil {
			continue
		}
		if u.authorizer.AuthOwner(tag) {
			result.Results[i] = u.getMachineTools(tag)
		}
	}
	return result, nil
}
858348
func matchHostArchTools(allTools coretools.List) (coretools.List, error) {
	arch := arch.HostArch()
	archTools, err := allTools.Match(coretools.Filter{Arch: arch})
	if err == coretools.ErrNoMatches {
		return nil, errors.Errorf(
			"need agent binaries for arch %s, only found %s",
			arch, allTools.Arches(),
		)
	} else if err != nil {
		return nil, errors.Trace(err)
	}
	return archTools, nil
}
520436
func (agent *Agent) install(ctx context.Context) error {
	exe, err := os.Executable()
	if err != nil {
		return err
	}

	substitutions := map[string]string{
		"Agent":          exe,
		"Server":         agent.server,
		"ServiceAccount": agent.serviceAccount,
		"User":           agent.swarmingUser,
	}
	content, err := substituteAsset(ctx, agent.agentAutoStartTemplate, substitutions)
	if err != nil {
		return err
	}
	path, err := substitute(ctx, agent.agentAutoStartPath, substitutions)
	if err != nil {
		return err
	}

	_, err = os.Stat(path)
	if err == nil || os.IsExist(err) {
		bytes, err := ioutil.ReadFile(path)
		if err != nil {
			return err
		}
		if string(bytes) == content {
			logging.Infof(ctx, "Already installed: %s.", path)
			return nil
		}
		logging.Infof(ctx, "Reinstalling: %s.", path)
		if err = agent.strategy.stop(ctx); err != nil {
			return err
		}
	} else {
		logging.Infof(ctx, "Installing: %s.", path)
	}
	if err = ioutil.WriteFile(path, []byte(content), 0644); err != nil {
		return err
	}
	return agent.strategy.start(ctx, path)
}
959089
func AgentDone(logger loggo.Logger, err error) error {
	err = errors.Cause(err)
	switch err {
	case jworker.ErrTerminateAgent, jworker.ErrRebootMachine, jworker.ErrShutdownMachine:
		// These errors are swallowed here because we want to exit
		// the agent process without error, to avoid the init system
		// restarting us.
		err = nil
	}
	if ug, ok := err.(*upgrader.UpgradeReadyError); ok {
		if err := ug.ChangeAgentTools(); err != nil {
			// Return and let the init system deal with the restart.
			err = errors.Annotate(err, "cannot change agent binaries")
			logger.Infof(err.Error())
			return err
		}
	}
	if err == jworker.ErrRestartAgent {
		logger.Warningf("agent restarting")
	}
	return err
}
309350
func (c *Config) AgentVersion() (version.Number, bool) {
	if v, ok := c.defined[AgentVersionKey].(string); ok {
		n, err := version.Parse(v)
		if err != nil {
			panic(err) // We should have checked it earlier.
		}
		return n, true
	}
	return version.Zero, false
}