/
status.go
107 lines (94 loc) · 2.77 KB
/
status.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
100
101
102
103
104
105
106
107
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"time"
)
type StatusReport []StatusItem
type StatusItem struct {
Version float64 `json:"version"`
TimestampUTC string `json:"timestampUTC"`
Status Status `json:"status"`
}
type StatusType string
const (
StatusTransitioning StatusType = "transitioning"
StatusError StatusType = "error"
StatusSuccess StatusType = "success"
)
type Status struct {
Operation string `json:"operation"`
ConfigurationAppliedTimeUTC string `json:"configurationAppliedTime"`
Status StatusType `json:"status"`
FormattedMessage FormattedMessage `json:"formattedMessage"`
SubstatusList []SubstatusItem `json:"substatus,omitempty"`
}
type FormattedMessage struct {
Lang string `json:"lang"`
Message string `json:"message"`
}
type SubstatusItem struct {
Name string `json:"name"`
Status StatusType `json:"status"`
FormattedMessage FormattedMessage `json:"formattedMessage"`
}
func NewStatus(t StatusType, operation, message string) StatusReport {
now := time.Now().UTC().Format(time.RFC3339)
return []StatusItem{
{
Version: 1.0,
TimestampUTC: now,
Status: Status{
Operation: operation,
ConfigurationAppliedTimeUTC: now,
Status: t,
FormattedMessage: FormattedMessage{
Lang: "en",
Message: message},
},
},
}
}
func (r StatusReport) AddSubstatus(t StatusType, name, message string) {
if len(r) > 0 {
r[0].Status.SubstatusList = []SubstatusItem{
{
Name: name,
Status: t,
FormattedMessage: FormattedMessage{
Lang: "en",
Message: message,
},
},
}
}
}
func (r StatusReport) marshal() ([]byte, error) {
return json.MarshalIndent(r, "", "\t")
}
// Save persists the status message to the specified status folder using the
// sequence number. The operation consists of writing to a temporary file in the
// same folder and moving it to the final destination for atomicity.
func (r StatusReport) Save(statusFolder string, seqNum int) error {
fn := fmt.Sprintf("%d.status", seqNum)
path := filepath.Join(statusFolder, fn)
tmpFile, err := ioutil.TempFile(statusFolder, fn)
if err != nil {
return fmt.Errorf("status: failed to create temporary file: %v", err)
}
tmpFile.Close()
b, err := r.marshal()
if err != nil {
return fmt.Errorf("status: failed to marshal into json: %v", err)
}
if err := ioutil.WriteFile(tmpFile.Name(), b, 0644); err != nil {
return fmt.Errorf("status: failed to path=%s error=%v", tmpFile.Name(), err)
}
if err := os.Rename(tmpFile.Name(), path); err != nil {
return fmt.Errorf("status: failed to move to path=%s error=%v", path, err)
}
return nil
}