all repos — erl @ c8ab7c849959313a035bf9e448d110e794190a4f

Execute Reload Loop

state/state.go (view raw)

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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
package state

import (
	"log"

	"alin.ovh/erl/command"
)

type State int

const (
	NotStarted State = iota
	Running
	Exited
)

func (s State) String() string {
	switch s {
	case NotStarted:
		return "NotStarted"
	case Running:
		return "Running"
	case Exited:
		return "Exited"
	default:
		return "Unknown"
	}
}

type Event int

const (
	Start Event = iota
	Signal
	Exit
	Restart
)

func (e Event) String() string {
	switch e {
	case Start:
		return "Start"
	case Signal:
		return "Shutdown"
	case Exit:
		return "Stopped"
	case Restart:
		return "Restart"
	default:
		return "Unknown"
	}
}

type Action func()

type StateMachine struct {
	log          *log.Logger
	currentState State
	transitions  map[State]map[Event]State
	actions      map[State]map[Event]Action
}

func New(cmd command.Command, log *log.Logger) *StateMachine {
	sm := &StateMachine{
		log:          log,
		currentState: NotStarted,
		transitions:  make(map[State]map[Event]State),
		actions:      make(map[State]map[Event]Action),
	}

	sm.transitions[NotStarted] = map[Event]State{
		Start: Running,
	}
	sm.transitions[Running] = map[Event]State{
		Signal:  Exited,
		Exit:    Exited,
		Restart: Running,
	}
	sm.transitions[Exited] = map[Event]State{
		Start:   Running,
		Restart: Running,
	}

	wait := func(cmd command.Command) {
		err := cmd.Wait()
		if err != nil {
			log.Printf("Error waiting for command: %v\n", err)
		}
		sm.SendEvent(Exit)
	}
	start := func() {
		err := cmd.Start()
		if err != nil {
			log.Printf("Failed to start command: %v", err)
		}

		go wait(cmd)
	}
	stop := func() {
		err := cmd.Stop()
		if err != nil {
			log.Printf("Error stopping command: %v\n", err)
		}
	}
	restart := func() {
		stop()
		start()
	}

	sm.actions[NotStarted] = map[Event]Action{
		Start: start,
	}
	sm.actions[Running] = map[Event]Action{
		Signal:  stop,
		Restart: restart,
	}
	sm.actions[Exited] = map[Event]Action{
		Start:   start,
		Restart: start,
	}

	return sm
}

func (sm *StateMachine) SendEvent(ev Event) {
	currentState := sm.currentState
	if nextState, ok := sm.transitions[currentState][ev]; ok {
		sm.currentState = nextState
		if action, ok := sm.actions[currentState][ev]; ok {
			action()
		}
	}
}