-
Notifications
You must be signed in to change notification settings - Fork 19
/
utils.go
201 lines (180 loc) · 5.58 KB
/
utils.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
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
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
package main
import (
"bytes"
"fmt"
"hash/maphash"
"io"
"log"
"math/rand"
"os"
"regexp"
"runtime"
"strconv"
"strings"
"time"
)
type Logger struct {
Level string
}
func NewLogger(level string) *Logger {
return &Logger{
Level: strings.ToLower(level),
}
}
func (l *Logger) SetLogLevel(level string) {
l.Level = strings.ToLower(level)
}
func (l *Logger) SetOutput(w io.Writer) {
log.SetOutput(w)
}
func getGoroutineID() uint64 {
b := make([]byte, 64)
b = b[:runtime.Stack(b, false)]
b = bytes.TrimPrefix(b, []byte("goroutine "))
b = b[:bytes.IndexByte(b, ' ')]
n, _ := strconv.ParseUint(string(b), 10, 64)
return n
}
func toPrintOrNotToPrint(currentMessageLogLevel string, loggerLogLevel string) bool {
// this will be the most prevalent log level of messages,
// so let's keep it on top
// to make things faster
if currentMessageLogLevel == "debug" && loggerLogLevel != "debug" {
return false // do not print debug log message
}
// don't print any logs
if loggerLogLevel == "silent" {
return false
}
if currentMessageLogLevel == "warn" && loggerLogLevel == "error" {
return false // do not print debug log message
}
if currentMessageLogLevel == "info" && (loggerLogLevel == "error" || loggerLogLevel == "warn") {
return false // do not print debug log message
}
return true
}
func (l *Logger) Log(level, msg string) {
if level != "debug" && level != "info" && level != "warn" && level != "error" {
panic(fmt.Sprintf("Unsupported log level: %v", level))
}
if !toPrintOrNotToPrint(level, l.Level) {
return
}
pc := make([]uintptr, 15)
n := runtime.Callers(2, pc)
frames := runtime.CallersFrames(pc[:n])
frame, _ := frames.Next()
coloredMsg := msg
// info has 1 letter less than debug, so let's add a space in the beginning of a line
prettyLogLevel := strings.ToUpper(level)
if prettyLogLevel == "INFO" {
prettyLogLevel = " INFO"
}
if prettyLogLevel == "WARN" {
prettyLogLevel = " WARN"
coloredMsg = orange(msg)
}
if prettyLogLevel == "ERROR" {
coloredMsg = red(msg)
}
log.Printf("[%2d] %s: (%s) %s", getGoroutineID(), prettyLogLevel, frame.Function, coloredMsg)
}
func red(text string) string {
return "\033[31m" + text + "\033[0m"
}
func green(text string) string {
return "\033[32m" + text + "\033[0m"
}
func orange(text string) string {
return "\033[33m" + text + "\033[0m"
}
// Returns an identificator that can be reused later in many places,
// e.g. as some file name or as docker container name.
// e.g. dojo-myproject-2019-01-09_10-39-06-98498093
// It may not contain upper case letters or else "docker inspect" complains with the error:
// invalid reference format: repository name must be lowercase.
func getRunID(test string) string {
if test != "true" {
currentDirectory, err := os.Getwd()
if err != nil {
panic(err)
}
return getRunIDGenerateFromCurrentDir(currentDirectory)
} else {
return "testdojorunid"
}
}
func getRunIDGenerateFromCurrentDir(currentDirectory string) string {
currentDirectorySplit := strings.Split(currentDirectory, "/")
currentDirectoryLastPart := currentDirectorySplit[len(currentDirectorySplit)-1]
currentTime := time.Now().Format("2006-01-02_15-04-05")
// run ID must contain a random number. Using time is insufficient, because e.g. 2 CI agents may be started
// in the same second for the same project.
// https://stackoverflow.com/a/73251027
r := rand.New(rand.NewSource(int64(new(maphash.Hash).Sum64())))
randomNumber := r.Int()
runID := fmt.Sprintf("dojo-%s-%v-%v", currentDirectoryLastPart, currentTime, randomNumber)
// replace all the upper case letters to lower case letters, this is to support the case when
// the currentDirectory contains capital letters and docker-compose project names do not welcome
// capital letters
runID = strings.ToLower(runID)
//runID = strings.ReplaceAll(runID, " ", "")
// remove any special characters
runID = regexp.MustCompile(`[^a-zA-Z0-9\-]+`).ReplaceAllString(runID, "")
return runID
}
func cmdInfoToString(cmd string, stdout string, stderr string, exitStatus int) string {
if stdout == "" {
stdout = "<empty string>"
} else {
stdout = strings.TrimSuffix(stdout, "\n")
}
if stderr == "" {
stderr = "<empty string>"
} else {
stderr = strings.TrimSuffix(stderr, "\n")
}
return fmt.Sprintf(`Command: %s
Exit status: %v
StdOut: %s
StdErr: %s
`,
cmd, exitStatus, stdout, stderr)
}
func removeWhiteSpaces(str string) string {
return strings.Join(strings.Fields(str), "")
}
type ContainerInfo struct {
ID string
Name string
Status string
ExitCode string
Exists bool
Logs string
}
// Returns: container ID, status , whether or not a container exists, error
func getContainerInfo(shellService ShellServiceInterface, containerNameOrID string) (*ContainerInfo, error) {
if containerNameOrID == "" {
panic("containerNameOrID was empty")
}
// https://docs.docker.com/engine/api/v1.21/
cmd := fmt.Sprintf("docker inspect --format='{{.Id}} {{.Name}} {{.State.Status}} {{.State.ExitCode}}' %s", containerNameOrID)
stdout, stderr, exitStatus, _ := shellService.RunGetOutput(cmd, true)
if exitStatus != 0 {
if strings.Contains(stdout, "No such object") || strings.Contains(stderr, "No such object") {
return &ContainerInfo{Exists: false}, nil
}
cmdInfo := cmdInfoToString(cmd, stdout, stderr, exitStatus)
return &ContainerInfo{}, fmt.Errorf("Unexpected exit status:\n%s", cmdInfo)
}
status := strings.TrimSuffix(stdout, "\n")
outputArr := strings.Split(status, " ")
return &ContainerInfo{
ID: outputArr[0],
Name: strings.TrimPrefix(outputArr[1], "/"),
Status: outputArr[2],
ExitCode: outputArr[3],
Exists: true,
}, nil
}