// ToStatus implements the ExportableError interface for ServerErrorBadRequest.
516460
func (e ServerErrorBadRequest) ToStatus() (s keybase1.Status) {
	s.Code = StatusCodeServerErrorBadRequest
	s.Name = "BAD_REQUEST"
	s.Desc = e.Reason
	return
}
1208504
func (s *MigrationService) MigrationStatus(ctx context.Context, org string, id int64) (*Migration, *Response, error) {
	u := fmt.Sprintf("orgs/%v/migrations/%v", org, id)

	req, err := s.client.NewRequest("GET", u, nil)
	if err != nil {
		return nil, nil, err
	}

	// TODO: remove custom Accept header when this API fully launches.
	req.Header.Set("Accept", mediaTypeMigrationsPreview)

	m := &Migration{}
	resp, err := s.client.Do(ctx, req, m)
	if err != nil {
		return nil, resp, err
	}

	return m, resp, nil
}
1122111
func (e ServerErrorConflictPrevRoot) ToStatus() (s keybase1.Status) {
	s.Code = StatusCodeServerErrorConflictPrevRoot
	s.Name = "CONFLICT_PREV_ROOT"
	s.Desc = e.Error()
	return
}
803204
func osStatusError(s C.OSStatus) error {
	if s == C.errSecSuccess {
		return nil
	}

	return osStatus(s)
}
791844
func FromStatusCode(err error, statusCode int) error {
	if err == nil {
		return err
	}
	switch statusCode {
	case http.StatusNotFound:
		err = NotFound(err)
	case http.StatusBadRequest:
		err = InvalidParameter(err)
	case http.StatusConflict:
		err = Conflict(err)
	case http.StatusUnauthorized:
		err = Unauthorized(err)
	case http.StatusServiceUnavailable:
		err = Unavailable(err)
	case http.StatusForbidden:
		err = Forbidden(err)
	case http.StatusNotModified:
		err = NotModified(err)
	case http.StatusNotImplemented:
		err = NotImplemented(err)
	case http.StatusInternalServerError:
		if !IsSystem(err) && !IsUnknown(err) && !IsDataLoss(err) && !IsDeadline(err) && !IsCancelled(err) {
			err = System(err)
		}
	default:
		logrus.WithFields(logrus.Fields{
			"module":      "api",
			"status_code": fmt.Sprintf("%d", statusCode),
		}).Debugf("FIXME: Got an status-code for which error does not match any expected type!!!: %d", statusCode)

		switch {
		case statusCode >= 200 && statusCode < 400:
			// it's a client error
		case statusCode >= 400 && statusCode < 500:
			err = InvalidParameter(err)
		case statusCode >= 500 && statusCode < 600:
			err = System(err)
		default:
			err = Unknown(err)
		}
	}
	return err
}
492587
func (e ServerErrorNonceNonExistent) ToStatus() (s keybase1.Status) {
	s.Code = StatusCodeServerErrorNonceNonExistent
	s.Name = "BLOCK_NONCENONEXISTENT"
	s.Desc = e.Msg
	return
}
205666
func (h *Host) AccountsStatus() (interface{}, []camtypes.StatusError) {
	h.didInit.Wait()
	var s []accountStatus
	var errs []camtypes.StatusError
	for _, impName := range h.importers {
		imp := h.imp[impName]
		accts, _ := imp.Accounts()
		for _, ia := range accts {
			as := accountStatus{
				Type: impName,
				Href: ia.AccountURL(),
				Name: ia.AccountLinkSummary(),
			}
			ia.mu.Lock()
			if ia.current != nil {
				as.StartedUnixSec = ia.lastRunStart.Unix()
			}
			if !ia.lastRunDone.IsZero() {
				as.LastFinishedUnixSec = ia.lastRunDone.Unix()
			}
			if ia.lastRunErr != nil {
				as.LastError = ia.lastRunErr.Error()
				errs = append(errs, camtypes.StatusError{
					Error: ia.lastRunErr.Error(),
					URL:   ia.AccountURL(),
				})
			}
			ia.mu.Unlock()
			s = append(s, as)
		}
	}
	return s, errs
}
1097147
func (server *ResilientServer) CacheStatus() *ResilientServerCacheStatus {
	result := &ResilientServerCacheStatus{}
	server.mutex.Lock()

	for _, entry := range server.srvKeyspaceNamesCache {
		entry.mutex.Lock()

		result.SrvKeyspaceNames = append(result.SrvKeyspaceNames, &SrvKeyspaceNamesCacheStatus{
			Cell:           entry.cell,
			Value:          entry.value,
			ExpirationTime: entry.insertionTime.Add(server.cacheTTL),
			LastQueryTime:  entry.lastQueryTime,
			LastError:      entry.lastError,
			LastErrorCtx:   entry.lastErrorCtx,
		})
		entry.mutex.Unlock()
	}

	for _, entry := range server.srvKeyspaceCache {
		entry.mutex.RLock()

		expirationTime := time.Now().Add(server.cacheTTL)
		if entry.watchState != watchStateRunning {
			expirationTime = entry.lastValueTime.Add(server.cacheTTL)
		}

		result.SrvKeyspaces = append(result.SrvKeyspaces, &SrvKeyspaceCacheStatus{
			Cell:           entry.cell,
			Keyspace:       entry.keyspace,
			Value:          entry.value,
			ExpirationTime: expirationTime,
			LastErrorTime:  entry.lastErrorTime,
			LastError:      entry.lastError,
			LastErrorCtx:   entry.lastErrorCtx,
		})
		entry.mutex.RUnlock()
	}

	server.mutex.Unlock()

	// do the sorting without the mutex
	sort.Sort(result.SrvKeyspaceNames)
	sort.Sort(result.SrvKeyspaces)

	return result
}
1126300
func getCoresFromStatus(adminCoresStatus *AdminCoresStatus) []string {
	serverCores := []string{}
	for coreName := range adminCoresStatus.Status {
		serverCores = append(serverCores, coreName)
	}
	return serverCores
}
81536
func (e NoSuchUserError) ToStatus() keybase1.Status {
	return keybase1.Status{
		Name: "NotFound",
		Code: int(keybase1.StatusCode_SCNotFound),
		Desc: e.Error(),
	}
}
1286495
func FromStatus(s *status.Status) *platform.Error {
	if s == nil || s.Code() == codes.OK {
		return nil
	}

	msg := s.Message()
	var perr platform.Error
	if err := json.Unmarshal([]byte(msg), &perr); err != nil {
		return &platform.Error{
			Err:  errors.New(msg),
			Code: platform.EInternal,
		}
	}

	return &perr
}
678334
func (c KeyExistsError) ToStatus() (s keybase1.Status) {
	s.Code = SCKeyInUse
	s.Name = "KEY_IN_USE"
	if c.Key != nil {
		s.Desc = c.Key.String()
	}
	return
}
639693
func (m *Migrator) getMigrationStatuses() error {
	for _, migration := range m.migrations {
		row := m.DB.QueryRow(m.dbAdapter.GetMigrationSql(), migration.Id)
		var mid uint64
		err := row.Scan(&mid)
		if err == sql.ErrNoRows {
			continue
		}
		if err != nil {
			m.logger.Printf(
				"Error getting migration status for %s: %v",
				migration.Name,
				err,
			)
			return err
		}
		migration.Status = Active
	}
	return nil
}
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
}
1191936
func (e ServerErrorMaxRefExceeded) ToStatus() (s keybase1.Status) {
	s.Code = StatusCodeServerErrorMaxRefExceeded
	s.Name = "BLOCK_MAXREFEXCEEDED"
	s.Desc = e.Msg
	return
}
1166328
func v4WriteStatusFunc(stream io.Writer) func(status *apierrors.StatusError) error {
	return func(status *apierrors.StatusError) error {
		bs, err := json.Marshal(status.Status())
		if err != nil {
			return err
		}
		_, err = stream.Write(bs)
		return err
	}
}
570243
func (e ServerErrorBlockArchived) ToStatus() (s keybase1.Status) {
	s.Code = StatusCodeServerErrorBlockArchived
	s.Name = "BLOCK_ARCHIVED"
	s.Desc = e.Msg
	return
}