// TaskStats returns resource usage statistics for the task
338187
func (d *driverPluginClient) TaskStats(ctx context.Context, taskID string, interval time.Duration) (<-chan *cstructs.TaskResourceUsage, error) {
	req := &proto.TaskStatsRequest{
		TaskId:             taskID,
		CollectionInterval: ptypes.DurationProto(interval),
	}
	ctx, _ = joincontext.Join(ctx, d.doneCtx)
	stream, err := d.client.TaskStats(ctx, req)
	if err != nil {
		st := status.Convert(err)
		if len(st.Details()) > 0 {
			if rec, ok := st.Details()[0].(*sproto.RecoverableError); ok {
				return nil, structs.NewRecoverableError(err, rec.Recoverable)
			}
		}
		return nil, err
	}

	ch := make(chan *cstructs.TaskResourceUsage, 1)
	go d.handleStats(ctx, ch, stream)

	return ch, nil
}
757164
func (t *Task) Stats(ctx context.Context) (*types.Any, error) {
	t.mu.Lock()
	defer t.mu.Unlock()
	if t.cg == nil {
		return nil, errors.Wrap(errdefs.ErrNotFound, "cgroup does not exist")
	}
	stats, err := t.cg.Stat(cgroups.IgnoreNotExist)
	if err != nil {
		return nil, err
	}
	return typeurl.MarshalAny(stats)
}
438106
func (w *wizard) networkStats() {
	if len(w.servers) == 0 {
		log.Info("No remote machines to gather stats from")
		return
	}
	// Clear out some previous configs to refill from current scan
	w.conf.ethstats = ""
	w.conf.bootnodes = w.conf.bootnodes[:0]

	// Iterate over all the specified hosts and check their status
	var pend sync.WaitGroup

	stats := make(serverStats)
	for server, pubkey := range w.conf.Servers {
		pend.Add(1)

		// Gather the service stats for each server concurrently
		go func(server string, pubkey []byte) {
			defer pend.Done()

			stat := w.gatherStats(server, pubkey, w.servers[server])

			// All status checks complete, report and check next server
			w.lock.Lock()
			defer w.lock.Unlock()

			delete(w.services, server)
			for service := range stat.services {
				w.services[server] = append(w.services[server], service)
			}
			stats[server] = stat
		}(server, pubkey)
	}
	pend.Wait()

	// Print any collected stats and return
	stats.render()
}
57772
func (_class TaskClass) SetStatus(sessionID SessionRef, self TaskRef, value TaskStatusType) (_err error) {
	_method := "task.set_status"
	_sessionIDArg, _err := convertSessionRefToXen(fmt.Sprintf("%s(%s)", _method, "session_id"), sessionID)
	if _err != nil {
		return
	}
	_selfArg, _err := convertTaskRefToXen(fmt.Sprintf("%s(%s)", _method, "self"), self)
	if _err != nil {
		return
	}
	_valueArg, _err := convertEnumTaskStatusTypeToXen(fmt.Sprintf("%s(%s)", _method, "value"), value)
	if _err != nil {
		return
	}
	_, _err =  _class.client.APICall(_method, _sessionIDArg, _selfArg, _valueArg)
	return
}
1005367
func (d *driverPluginClient) InspectTask(taskID string) (*TaskStatus, error) {
	req := &proto.InspectTaskRequest{TaskId: taskID}

	resp, err := d.client.InspectTask(d.doneCtx, req)
	if err != nil {
		return nil, grpcutils.HandleGrpcErr(err, d.doneCtx)
	}

	status, err := taskStatusFromProto(resp.Task)
	if err != nil {
		return nil, err
	}

	if resp.Driver != nil {
		status.DriverAttributes = resp.Driver.Attributes
	}
	if resp.NetworkOverride != nil {
		status.NetworkOverride = &DriverNetwork{
			PortMap:       map[string]int{},
			IP:            resp.NetworkOverride.Addr,
			AutoAdvertise: resp.NetworkOverride.AutoAdvertise,
		}
		for k, v := range resp.NetworkOverride.PortMap {
			status.NetworkOverride.PortMap[k] = int(v)
		}
	}

	return status, nil
}
1007603
func (r *runtimeVM) ContainerStats(c *Container) (*ContainerStats, error) {
	logrus.Debug("runtimeVM.ContainerStats() start")
	defer logrus.Debug("runtimeVM.ContainerStats() end")

	// Lock the container with a shared lock
	c.opLock.RLock()
	defer c.opLock.RUnlock()

	resp, err := r.task.Stats(r.ctx, &task.StatsRequest{
		ID: c.ID(),
	})
	if err != nil {
		return nil, errdefs.FromGRPC(err)
	}
	if resp == nil {
		return nil, errors.New("Could not retrieve container stats")
	}

	stats, err := typeurl.UnmarshalAny(resp.Stats)
	if err != nil {
		return nil, errors.Wrap(err, "failed to extract container metrics")
	}

	metrics, ok := stats.(*cgroups.Metrics)
	if !ok {
		return nil, errors.Errorf("Unknown stats type %T", stats)
	}

	return metricsToCtrStats(c, metrics), nil
}
416304
func (s *DescribeAuditTaskOutput) SetTaskStatistics(v *TaskStatistics) *DescribeAuditTaskOutput {
	s.TaskStatistics = v
	return s
}
1004275
func (c oauthClient) Task(taskID uint) (wl.Task, error) {
	url := fmt.Sprintf(
		"%s/tasks/%d",
		c.apiURL,
		taskID,
	)

	req, err := c.newGetRequest(url)
	if err != nil {
		return wl.Task{}, err
	}

	resp, err := c.do(req)
	if err != nil {
		return wl.Task{}, err
	}

	if resp.StatusCode != http.StatusOK {
		return wl.Task{}, fmt.Errorf("Unexpected response code %d - expected %d", resp.StatusCode, http.StatusOK)
	}

	task := transportTask{}
	err = json.NewDecoder(resp.Body).Decode(&task)
	if err != nil {
		return wl.Task{}, err
	}
	return taskFromTransport(task)
}
189110
func (m *cgroupManagerImpl) GetResourceStats(name CgroupName) (*ResourceStats, error) {
	cgroupPaths := m.buildCgroupPaths(name)
	stats, err := getStatsSupportedSubsystems(cgroupPaths)
	if err != nil {
		return nil, fmt.Errorf("failed to get stats supported cgroup subsystems for cgroup %v: %v", name, err)
	}
	return toResourceStats(stats), nil
}
1265173
func (c *Client) SessionStats() (stats *SessionStats, err error) {
	if err = c.rpcCall("session-stats", nil, &stats); err != nil {
		err = fmt.Errorf("'session-stats' rpc method failed: %v", err)
	}
	return
}
1321463
func (h *taskHandle) collectStats(ctx context.Context, destCh *usageSender, interval time.Duration) {
	defer destCh.close()

	// backoff and retry used if the docker stats API returns an error
	var backoff time.Duration
	var retry int
	// loops until doneCh is closed
	for {
		if backoff > 0 {
			select {
			case <-time.After(backoff):
			case <-ctx.Done():
				return
			case <-h.doneCh:
				return
			}
		}
		// make a channel for docker stats structs and start a collector to
		// receive stats from docker and emit nomad stats
		// statsCh will always be closed by docker client.
		statsCh := make(chan *docker.Stats)
		go dockerStatsCollector(destCh, statsCh, interval)

		statsOpts := docker.StatsOptions{
			ID:      h.containerID,
			Context: ctx,
			Done:    h.doneCh,
			Stats:   statsCh,
			Stream:  true,
		}

		// Stats blocks until an error has occurred, or doneCh has been closed
		if err := h.client.Stats(statsOpts); err != nil && err != io.ErrClosedPipe {
			// An error occurred during stats collection, retry with backoff
			h.logger.Debug("error collecting stats from container", "error", err)

			// Calculate the new backoff
			backoff = (1 << (2 * uint64(retry))) * statsCollectorBackoffBaseline
			if backoff > statsCollectorBackoffLimit {
				backoff = statsCollectorBackoffLimit
			}
			// Increment retry counter
			retry++
			continue
		}
		// Stats finished either because context was canceled, doneCh was closed
		// or the container stopped. Stop stats collections.
		return
	}
}
78945
func GetTaskStatus(tx *bolt.Tx, id string) (*api.TaskStatus, error) {
	var ts api.TaskStatus
	if err := withTaskBucket(tx, id, func(bkt *bolt.Bucket) error {
		p := bkt.Get(bucketKeyStatus)
		if p == nil {
			return errTaskUnknown
		}

		return proto.Unmarshal(p, &ts)
	}); err != nil {
		return nil, err
	}

	return &ts, nil
}
899679
func (a *Allocations) Stats(args *cstructs.AllocStatsRequest, reply *cstructs.AllocStatsResponse) error {
	defer metrics.MeasureSince([]string{"client", "allocations", "stats"}, time.Now())

	// Check read job permissions
	if aclObj, err := a.c.ResolveToken(args.AuthToken); err != nil {
		return err
	} else if aclObj != nil && !aclObj.AllowNsOp(args.Namespace, acl.NamespaceCapabilityReadJob) {
		return nstructs.ErrPermissionDenied
	}

	clientStats := a.c.StatsReporter()
	aStats, err := clientStats.GetAllocStats(args.AllocID)
	if err != nil {
		return err
	}

	stats, err := aStats.LatestAllocStats(args.Task)
	if err != nil {
		return err
	}

	reply.Stats = stats
	return nil
}
85426
func (s *AuditTaskMetadata) SetTaskStatus(v string) *AuditTaskMetadata {
	s.TaskStatus = &v
	return s
}
96289
func TaskList(args *model.TaskListArgs) (infos []*model.TaskInfo, totalCount int, err error) {
	err = mgr.Do(func(ctx context.Context, cli *client.Client) (err error) {
		var (
			tasks []swarm.Task
			opts  = types.TaskListOptions{
				Filters: filters.NewArgs(),
			}
		)

		if args.PageIndex < 1 {
			args.PageIndex = 1
		}
		if args.PageSize < 1 {
			args.PageSize = math.MaxInt32
		}
		if args.Service != "" {
			opts.Filters.Add("service", args.Service)
		}
		if args.Node != "" {
			opts.Filters.Add("node", args.Node)
		}
		if args.Name != "" {
			opts.Filters.Add("name", args.Name)
		}
		if args.State != "" {
			opts.Filters.Add("desired-state", args.State)
		}

		tasks, err = cli.TaskList(ctx, opts)
		totalCount = len(tasks)
		if err == nil && totalCount > 0 {
			sort.Slice(tasks, func(i, j int) bool {
				return tasks[i].UpdatedAt.After(tasks[j].UpdatedAt)
			})
			start, end := misc.Page(totalCount, args.PageIndex, args.PageSize)
			tasks = tasks[start:end]

			nodes := make(map[string]string)
			for _, t := range tasks {
				if _, ok := nodes[t.NodeID]; !ok {
					if n, _, e := cli.NodeInspectWithRaw(ctx, t.NodeID); e == nil {
						if n.Spec.Name == "" {
							nodes[t.NodeID] = n.Description.Hostname
						} else {
							nodes[t.NodeID] = n.Spec.Name
						}
					} else {
						nodes[t.NodeID] = ""
					}
				}
			}

			infos = make([]*model.TaskInfo, len(tasks))
			for i, t := range tasks {
				infos[i] = model.NewTaskInfo(t, nodes[t.NodeID])
			}
		}
		return
	})
	return
}
630348
func newStatsChanPipe() (*usageSender, <-chan *structs.TaskResourceUsage) {
	destCh := make(chan *cstructs.TaskResourceUsage, 1)
	return &usageSender{
		destCh: destCh,
	}, destCh

}
472602
func (bs *benchmarkServer) getStats(reset bool) *testpb.ServerStats {
	bs.mu.RLock()
	defer bs.mu.RUnlock()
	wallTimeElapsed := time.Since(bs.lastResetTime).Seconds()
	rusageLatest := syscall.GetRusage()
	uTimeElapsed, sTimeElapsed := syscall.CPUTimeDiff(bs.rusageLastReset, rusageLatest)

	if reset {
		bs.lastResetTime = time.Now()
		bs.rusageLastReset = rusageLatest
	}
	return &testpb.ServerStats{
		TimeElapsed: wallTimeElapsed,
		TimeUser:    uTimeElapsed,
		TimeSystem:  sTimeElapsed,
	}
}