status.go 1.4 KB
Newer Older
O
ob-robot 已提交
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 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78
package http

import (
	"encoding/json"
	"sync/atomic"
)

type State int32

const (
	Unknown  State = 0
	Starting State = 1
	Running  State = 2
	Stopping State = 3
	Stopped  State = 4
)

var stateString = []string{"unknown", "starting", "running", "stopping", "stopped"}

func (s State) String() string {
	return stateString[int(s)]
}

func (s State) MarshalJSON() ([]byte, error) {
	return json.Marshal(s.String())
}

func (s *State) UnmarshalJSON(b []byte) error {
	var str string
	err := json.Unmarshal(b, &str)
	if err != nil {
		return err
	}
	for i := 0; i < len(stateString); i++ {
		if stateString[i] == str {
			*s = State(i)
			return nil
		}
	}
	*s = Unknown
	return nil
}

// Status info api response
type Status struct {
	//service state
	State State `json:"state"`
	//service version
	Version string `json:"version"`
	//service pid
	Pid int `json:"pid"`
	//timestamp when service started
	StartAt int64 `json:"startAt"`
	// Ports process occupied ports
	Ports []int `json:"ports"`
}

type StateHolder struct {
	state State
}

func NewStateHolder(init State) *StateHolder {
	return &StateHolder{
		state: init,
	}
}

func (s *StateHolder) Get() State {
	return State(atomic.LoadInt32((*int32)(&s.state)))
}

func (s *StateHolder) Set(new State) {
	atomic.StoreInt32((*int32)(&s.state), int32(new))
}

func (s *StateHolder) Cas(old, new State) bool {
	return atomic.CompareAndSwapInt32((*int32)(&s.state), int32(old), int32(new))
}