This repository has been archived by the owner on Nov 16, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapi.go
99 lines (80 loc) · 2.31 KB
/
api.go
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
package main
import (
"time"
"log"
"container/ring"
)
type Execution struct {
Id int `json:"id"`
Start time.Time `json:"start"`
Finish time.Time `json:"finish"`
Status int `json:"status"`
Log []ExecutionLogMessage `json:"log"`
}
type ExecutionLogMessage struct {
Id int `json:"id"`
Timestamp time.Time `json:"timestamp"`
Message string `json:"message"`
Error bool `json:"error"`
}
type ExecutionStart struct {
Id int `json:"id"`
Start time.Time `json:"start"`
}
type ExecutionFinish struct {
Id int `json:"id"`
Finish time.Time `json:"finish"`
Status int `json:"status"`
}
type ExecutionLog struct {
Execution int `json:"execution"`
Log ExecutionLogMessage `json:"log"`
}
var executionId int = 0
var executions = ring.New(16)
var failedExecutions = ring.New(16)
type Api struct {
stream chan interface{}
}
type ApiReply interface {
Reply(message interface{})
}
func (api *Api) CreateExecution() *Execution {
executionId++
now := time.Now()
exe := &Execution{executionId, now, now, -1, make([]ExecutionLogMessage, 0, 64)}
executions.Value = exe
log.Print("New execution:", exe.Id)
api.stream <- ExecutionStart{exe.Id, exe.Start}
return exe
}
func (api *Api) FinalizeExecution(exe *Execution, status int) {
exe.Status = status
exe.Finish = time.Now()
executions = executions.Next()
if status > 0 {
failedExecutions.Value = exe
failedExecutions = failedExecutions.Next()
}
log.Print("Finalized execution:", exe.Id)
api.stream <- ExecutionFinish{exe.Id, exe.Finish, exe.Status}
}
func (api *Api) ExecutionLog(exe *Execution, log string, error bool) {
message := ExecutionLogMessage{len(exe.Log), time.Now(), log, error}
exe.Log = append(exe.Log, message)
api.stream <- ExecutionLog{exe.Id, message}
}
func (api *Api) Command(command string, replyTo ApiReply) {
if command == "execution-history" {
executions.Do(func(execution interface{}) {
if execution != nil {
replyTo.Reply(*execution.(*Execution))
}
})
failedExecutions.Do(func(execution interface{}) {
if execution != nil {
replyTo.Reply(*execution.(*Execution))
}
})
}
}