// FullStatus gives the information needed for juju status over the api
182079
func (c *Client) FullStatus(args params.StatusParams) (params.FullStatus, error) {
	if err := c.checkCanRead(); err != nil {
		return params.FullStatus{}, err
	}

	var noStatus params.FullStatus
	var context statusContext

	m, err := c.api.stateAccessor.Model()
	if err != nil {
		return noStatus, errors.Annotate(err, "cannot get model")
	}
	context.presence.Presence = c.api.presence.ModelPresence(m.UUID())
	cfg, err := m.Config()
	if err != nil {
		return noStatus, errors.Annotate(err, "cannot obtain current model config")
	}
	context.providerType = cfg.Type()

	if context.model, err = c.api.stateAccessor.Model(); err != nil {
		return noStatus, errors.Annotate(err, "could not fetch model")
	}
	if context.status, err = context.model.LoadModelStatus(); err != nil {
		return noStatus, errors.Annotate(err, "could not load model status values")
	}
	if context.allAppsUnitsCharmBindings, err =
		fetchAllApplicationsAndUnits(c.api.stateAccessor, context.model); err != nil {
		return noStatus, errors.Annotate(err, "could not fetch applications and units")
	}
	if context.consumerRemoteApplications, err =
		fetchConsumerRemoteApplications(c.api.stateAccessor); err != nil {
		return noStatus, errors.Annotate(err, "could not fetch remote applications")
	}
	// Only admins can see offer details.
	if err := c.checkIsAdmin(); err == nil {
		if context.offers, err =
			fetchOffers(c.api.stateAccessor, context.allAppsUnitsCharmBindings.applications); err != nil {
			return noStatus, errors.Annotate(err, "could not fetch application offers")
		}
	}
	if context.machines, err = fetchMachines(c.api.stateAccessor, nil); err != nil {
		return noStatus, errors.Annotate(err, "could not fetch machines")
	}
	// These may be empty when machines have not finished deployment.
	if context.ipAddresses, context.spaces, context.linkLayerDevices, err =
		fetchNetworkInterfaces(c.api.stateAccessor); err != nil {
		return noStatus, errors.Annotate(err, "could not fetch IP addresses and link layer devices")
	}
	if context.relations, context.relationsById, err = fetchRelations(c.api.stateAccessor); err != nil {
		return noStatus, errors.Annotate(err, "could not fetch relations")
	}
	if len(context.allAppsUnitsCharmBindings.applications) > 0 {
		if context.leaders, err = c.api.leadershipReader.Leaders(); err != nil {
			return noStatus, errors.Annotate(err, "could not fetch leaders")
		}
	}
	if context.controllerTimestamp, err = c.api.stateAccessor.ControllerTimestamp(); err != nil {
		return noStatus, errors.Annotate(err, "could not fetch controller timestamp")
	}

	logger.Tracef("Applications: %v", context.allAppsUnitsCharmBindings.applications)
	logger.Tracef("Remote applications: %v", context.consumerRemoteApplications)
	logger.Tracef("Offers: %v", context.offers)
	logger.Tracef("Relations: %v", context.relations)

	if len(args.Patterns) > 0 {
		predicate := BuildPredicateFor(args.Patterns)

		// First, attempt to match machines. Any units on those
		// machines are implicitly matched.
		matchedMachines := make(set.Strings)
		for _, machineList := range context.machines {
			for _, m := range machineList {
				matches, err := predicate(m)
				if err != nil {
					return noStatus, errors.Annotate(
						err, "could not filter machines",
					)
				}
				if matches {
					matchedMachines.Add(m.Id())
				}
			}
		}

		// Filter units
		matchedSvcs := make(set.Strings)
		unitChainPredicate := UnitChainPredicateFn(predicate, context.unitByName)
		// It's possible that we will discover a unit that matches given filter
		// half way through units collection. In that case, it may be that the machine
		// for that unit has other applications' units on it that have already been examined
		// prior. This means that we may miss these other application(s).
		// This behavior has been inconsistent since we get units in a map where
		// the order is not guaranteed.
		// To cater for this scenario, we need to gather all units
		// in a temporary collection keyed on machine to allow for the later
		// pass. This fixes situations similar to inconsistencies
		// observed in lp#1592872.
		machineUnits := map[string][]string{}
		for _, unitMap := range context.allAppsUnitsCharmBindings.units {
			for name, unit := range unitMap {
				machineId, err := unit.AssignedMachineId()
				if err != nil {
					machineId = ""
				} else if matchedMachines.Contains(machineId) {
					// Unit is on a matching machine.
					matchedSvcs.Add(unit.ApplicationName())
					continue
				}
				if machineId != "" {
					machineUnits[machineId] = append(machineUnits[machineId], unit.ApplicationName())
				}

				// Always start examining at the top-level. This
				// prevents a situation where we filter a subordinate
				// before we discover its parent is a match.
				if !unit.IsPrincipal() {
					continue
				} else if matches, err := unitChainPredicate(unit); err != nil {
					return noStatus, errors.Annotate(err, "could not filter units")
				} else if !matches {
					delete(unitMap, name)
					continue
				}
				matchedSvcs.Add(unit.ApplicationName())
				if machineId != "" {
					matchedMachines.Add(machineId)
				}
			}
		}
		for _, m := range matchedMachines.SortedValues() {
			for _, a := range machineUnits[m] {
				if !matchedSvcs.Contains(a) {
					matchedSvcs.Add(a)
				}
			}
		}

		// Filter applications
		for appName, app := range context.allAppsUnitsCharmBindings.applications {
			matches, err := predicate(app)
			if err != nil {
				return noStatus, errors.Annotate(err, "could not filter applications")
			}

			// There are matched units for this application
			// or the application matched the given criteria.
			deleted := false
			if !matchedSvcs.Contains(appName) && !matches {
				delete(context.allAppsUnitsCharmBindings.applications, appName)
				deleted = true
			}

			// Filter relations:
			// Remove relations for applications that were deleted and
			// for the applications that did not match the
			// given criteria.
			if deleted || !matches {
				// delete relations for this app
				if relations, ok := context.relations[appName]; ok {
					for _, r := range relations {
						delete(context.relationsById, r.Id())
					}
					delete(context.relations, appName)
				}
			}
		}
		// TODO(wallyworld) - filter remote applications

		// Filter machines
		for status, machineList := range context.machines {
			matched := make([]*state.Machine, 0, len(machineList))
			for _, m := range machineList {
				machineContainers, err := m.Containers()
				if err != nil {
					return noStatus, err
				}
				machineContainersSet := set.NewStrings(machineContainers...)

				if matchedMachines.Contains(m.Id()) || !matchedMachines.Intersection(machineContainersSet).IsEmpty() {
					// The machine is matched directly, or contains a unit
					// or container that matches.
					logger.Tracef("machine %s is hosting something.", m.Id())
					matched = append(matched, m)
					continue
				}
			}
			context.machines[status] = matched
		}
	}

	modelStatus, err := c.modelStatus()
	if err != nil {
		return noStatus, errors.Annotate(err, "cannot determine model status")
	}
	return params.FullStatus{
		Model:               modelStatus,
		Machines:            context.processMachines(),
		Applications:        context.processApplications(),
		RemoteApplications:  context.processRemoteApplications(),
		Offers:              context.processOffers(),
		Relations:           context.processRelations(),
		ControllerTimestamp: context.controllerTimestamp,
	}, nil
}
377399
func CheckErrorStatus(code int, res *http.Response) error {
	err := CheckError(res)
	if err != nil {
		return err
	}

	if res.StatusCode != code {
		return fmt.Errorf("unexpected status code: %s", res.Status)
	}

	return nil
}
15225
func (e LoggedInError) ToStatus() (s keybase1.Status) {
	s.Code = SCAlreadyLoggedIn
	s.Name = "ALREADY_LOGGED_IN"
	s.Desc = "Already logged in as a different user"
	return
}
264826
func (r *ReporterKBPKI) NotifySyncStatus(ctx context.Context,
	status *keybase1.FSPathSyncStatus) {
	select {
	case r.notifySyncBuffer <- status:
	default:
		r.vlog.CLogf(
			ctx, libkb.VLog1, "ReporterKBPKI: notify sync buffer full, "+
				"dropping %+v", status)
	}
}
1201337
func (client *Client) PaginateRunstatusServices(ctx context.Context, page RunstatusPage, callback func(*RunstatusService, error) bool) { // nolint: dupl
	if page.ServicesURL == "" {
		callback(nil, fmt.Errorf("empty Services URL for %#v", page))
		return
	}

	servicesURL := page.ServicesURL
	for servicesURL != "" {
		resp, err := client.runstatusRequest(ctx, servicesURL, nil, "GET")
		if err != nil {
			callback(nil, err)
			return
		}

		var ss *RunstatusServiceList
		if err := json.Unmarshal(resp, &ss); err != nil {
			callback(nil, err)
			return
		}

		for i := range ss.Services {
			if err := ss.Services[i].FakeID(); err != nil {
				log.Printf("bad fake ID for %#v, %s", ss.Services[i], err)
			}

			if cont := callback(&ss.Services[i], nil); !cont {
				return
			}
		}

		servicesURL = ss.Next
	}
}
1027486
func CheckErrorStatus(code int, res *http.Response, isPlatformError ...bool) error {
	err := CheckError(res)
	if len(isPlatformError) > 0 && isPlatformError[0] {
		err = CheckError(res, true)
	}
	if err != nil {
		return err
	}

	if res.StatusCode != code {
		return fmt.Errorf("unexpected status code: %s", res.Status)
	}

	return nil
}
331131
func (u LoginRequiredError) ToStatus() (s keybase1.Status) {
	s.Code = SCLoginRequired
	s.Name = "LOGIN_REQUIRED"
	s.Desc = u.Context
	return
}
528860
func (e *Endpoint) policyStatus() models.EndpointPolicyEnabled {
	policyEnabled := models.EndpointPolicyEnabledNone
	switch {
	case e.realizedPolicy.IngressPolicyEnabled && e.realizedPolicy.EgressPolicyEnabled:
		policyEnabled = models.EndpointPolicyEnabledBoth
	case e.realizedPolicy.IngressPolicyEnabled:
		policyEnabled = models.EndpointPolicyEnabledIngress
	case e.realizedPolicy.EgressPolicyEnabled:
		policyEnabled = models.EndpointPolicyEnabledEgress
	}
	return policyEnabled
}
1085028
func (u *UniterAPI) RelationsStatus(args params.Entities) (params.RelationUnitStatusResults, error) {
	result := params.RelationUnitStatusResults{
		Results: make([]params.RelationUnitStatusResult, len(args.Entities)),
	}
	if len(args.Entities) == 0 {
		return result, nil
	}
	canRead, err := u.accessUnit()
	if err != nil {
		return params.RelationUnitStatusResults{}, err
	}

	oneRelationUnitStatus := func(rel *state.Relation, unit *state.Unit) (params.RelationUnitStatus, error) {
		rus := params.RelationUnitStatus{
			RelationTag: rel.Tag().String(),
			Suspended:   rel.Suspended(),
		}
		ru, err := rel.Unit(unit)
		if err != nil {
			return params.RelationUnitStatus{}, errors.Trace(err)
		}
		inScope, err := ru.InScope()
		if err != nil {
			return params.RelationUnitStatus{}, errors.Trace(err)
		}
		rus.InScope = inScope
		return rus, nil
	}

	relationResults := func(unit *state.Unit) ([]params.RelationUnitStatus, error) {
		var ruStatus []params.RelationUnitStatus
		app, err := unit.Application()
		if err != nil {
			return nil, errors.Trace(err)
		}
		relations, err := app.Relations()
		for _, rel := range relations {
			rus, err := oneRelationUnitStatus(rel, unit)
			if err != nil {
				return nil, errors.Trace(err)
			}
			ruStatus = append(ruStatus, rus)
		}
		return ruStatus, nil
	}

	for i, entity := range args.Entities {
		tag, err := names.ParseUnitTag(entity.Tag)
		if err != nil {
			result.Results[i].Error = common.ServerError(common.ErrPerm)
			continue
		}
		err = common.ErrPerm
		if canRead(tag) {
			var unit *state.Unit
			unit, err = u.getUnit(tag)
			if err == nil {
				result.Results[i].RelationResults, err = relationResults(unit)
			}
		}
		result.Results[i].Error = common.ServerError(err)
	}
	return result, nil
}
1159979
func (sa *scriptAddress) SyncStatus() SyncStatus {
	switch {
	case sa.flags.unsynced && !sa.flags.partialSync:
		return Unsynced(sa.firstBlock)
	case sa.flags.unsynced && sa.flags.partialSync:
		return PartialSync(sa.partialSyncHeight)
	default:
		return FullSync{}
	}
}
739586
func NewUserStatus(httpResponse *http.Response) (*UserStatus, error) {
	statusResponse := &UserStatus{HTTPResponse: httpResponse}

	defer closeResponseBody(httpResponse)

	body, err := ioutil.ReadAll(httpResponse.Body)
	if err != nil {
		Logger.Println("Error reading from API:", err)
		return statusResponse, err
	}

	err = json.Unmarshal(body, statusResponse)
	if err != nil {
		Logger.Println("Error parsing JSON:", err)
		return statusResponse, err
	}

	statusResponse.ID = strconv.Itoa(statusResponse.StatusData.ID)
	return statusResponse, nil
}
1122111
func (e ServerErrorConflictPrevRoot) ToStatus() (s keybase1.Status) {
	s.Code = StatusCodeServerErrorConflictPrevRoot
	s.Name = "CONFLICT_PREV_ROOT"
	s.Desc = e.Error()
	return
}
492587
func (e ServerErrorNonceNonExistent) ToStatus() (s keybase1.Status) {
	s.Code = StatusCodeServerErrorNonceNonExistent
	s.Name = "BLOCK_NONCENONEXISTENT"
	s.Desc = e.Msg
	return
}
627414
func (e ServerErrorThrottle) ToStatus() (s keybase1.Status) {
	s.Code = StatusCodeServerErrorThrottle
	s.Name = "THROTTLE"
	s.Desc = e.Err.Error()
	if e.SuggestedRetryIn != nil {
		s.Fields = append(s.Fields, keybase1.StringKVPair{
			Key:   "suggestedRetryInMS",
			Value: strconv.FormatInt(int64((*e.SuggestedRetryIn)/time.Millisecond), 10),
		})
	}
	return
}
366800
func (c *ApiController) GetWorkersAllStatus() {
	log.Info("Get all workers with status")

	status, _ := c.GetInt(":status")
	workers := models.GetAllWorkersWithStatus(status)

	c.Data["json"] = workers
	c.ServeJson()
}
1286119
func hasStatusEnabled(subresources *apiextensions.CustomResourceSubresources) bool {
	if subresources != nil && subresources.Status != nil {
		return true
	}
	return false
}
46615
func NewGetStatus(ctx *middleware.Context, handler GetStatusHandler) *GetStatus {
	return &GetStatus{Context: ctx, Handler: handler}
}