summaryrefslogtreecommitdiff
path: root/util/state.go
blob: 29fca945d154ef1e938ed57383e4a08b987c9a99 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
package util

import (
	"errors"
	"github.com/shirou/gopsutil/process"
	"github.com/spiral/roadrunner"
)

// State provides information about specific worker.
type State struct {
	// Pid contains process id.
	Pid int `json:"pid"`

	// Status of the worker.
	Status string `json:"status"`

	// Number of worker executions.
	NumJobs int64 `json:"numExecs"`

	// Created is unix nano timestamp of worker creation time.
	Created int64 `json:"created"`

	// MemoryUsage holds the information about worker memory usage in bytes.
	// Values might vary for different operating systems and based on RSS.
	MemoryUsage uint64 `json:"memoryUsage"`
}

// WorkerState creates new worker state definition.
func WorkerState(w *roadrunner.Worker) (*State, error) {
	p, _ := process.NewProcess(int32(*w.Pid))
	i, err := p.MemoryInfo()
	if err != nil {
		return nil, err
	}

	return &State{
		Pid:         *w.Pid,
		Status:      w.State().String(),
		NumJobs:     w.State().NumExecs(),
		Created:     w.Created.UnixNano(),
		MemoryUsage: i.RSS,
	}, nil
}

// ServerState returns list of all worker states of a given rr server.
func ServerState(rr *roadrunner.Server) ([]*State, error) {
	if rr == nil {
		return nil, errors.New("rr server is not running")
	}

	result := make([]*State, 0)
	for _, w := range rr.Workers() {
		state, err := WorkerState(w)
		if err != nil {
			return nil, err
		}

		result = append(result, state)
	}

	return result, nil
}