forked from mendersoftware/mender
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdeployment_logger_test.go
337 lines (270 loc) · 9.2 KB
/
deployment_logger_test.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
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
// Copyright 2019 Northern.tech AS
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package main
import (
"errors"
"fmt"
"io/ioutil"
"math"
"os"
"path"
"strings"
"testing"
"github.com/mendersoftware/log"
"github.com/stretchr/testify/assert"
)
func openLogFileWithContent(file, data string) error {
logF, _ := os.OpenFile(file, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
defer logF.Close()
if _, err := logF.WriteString(data + "\n"); err != nil {
return errors.New("")
}
return nil
}
func logFileContains(file, expected string) bool {
content := make([]byte, 1024)
idF, err := os.Open(file)
if err != nil {
return false
}
defer idF.Close()
if _, err = idF.Read(content); err != nil {
return false
}
return strings.Contains(string(content), expected)
}
func TestFileLogger(t *testing.T) {
logger := NewFileLogger("logfile.log")
defer os.Remove("logfile.log")
if logger.logFileName != "logfile.log" {
t.FailNow()
}
if _, err := os.Stat("logfile.log"); os.IsNotExist(err) {
t.FailNow()
}
if _, err := logger.Write([]byte("some log")); err != nil {
t.FailNow()
}
if !logFileContains("logfile.log", "some log") {
t.FailNow()
}
if err := logger.Deinit(); err != nil {
t.FailNow()
}
// now, once logger is deinitialized, writing logs should return error
if _, err := logger.Write([]byte("some other log")); err == nil {
t.FailNow()
}
}
func TestLogManagerInit(t *testing.T) {
tempDir, _ := ioutil.TempDir("", "logs")
defer os.RemoveAll(tempDir)
logManager := NewDeploymentLogManager(tempDir)
// make sure that logging is disabled by default
if logManager.loggingEnabled == true {
t.FailNow()
}
// check that logger is not instantiated while creating log manager
if logManager.logger != nil {
t.FailNow()
}
if err := logManager.WriteLog([]byte("some log")); err != ErrLoggerNotInitialized {
t.FailNow()
}
}
func TestLogManagerCheckEnableDisable(t *testing.T) {
tempDir, _ := ioutil.TempDir("", "logs")
defer os.RemoveAll(tempDir)
logManager := NewDeploymentLogManager(tempDir)
if err := logManager.Enable("1234-5678"); err != nil {
t.FailNow()
}
if !logManager.loggingEnabled {
t.FailNow()
}
if logManager.logger == nil {
t.FailNow()
}
if err := logManager.Disable(); err != nil || logManager.loggingEnabled {
t.FailNow()
}
// disabling disabled logging
if err := logManager.Disable(); err != nil {
t.FailNow()
}
}
func TestLogManagerCheckLogging(t *testing.T) {
tempDir, _ := ioutil.TempDir("", "logs")
defer os.RemoveAll(tempDir)
logManager := NewDeploymentLogManager(tempDir)
if err := logManager.WriteLog([]byte("log")); err != ErrLoggerNotInitialized {
t.FailNow()
}
if err := logManager.Enable("1111-2222"); err != nil {
t.FailNow()
}
logFileName := fmt.Sprintf(logFileNameScheme, 1, "1111-2222")
logFile := path.Join(tempDir, logFileName)
var toWriteLog = `{"msg":"some log"}`
if err := logManager.WriteLog([]byte(toWriteLog)); err != nil {
t.FailNow()
}
if !logFileContains(logFile, toWriteLog) {
t.FailNow()
}
}
func createFilesToRotate(location string, num int) []string {
fileNames := make([]string, num)
for i := 1; i <= num; i++ {
name := path.Join(location, fmt.Sprintf(logFileNameScheme, i, "1111-2222"))
fileNames = append(fileNames, name)
os.Create(name)
}
return fileNames
}
func removeLogFiles(names []string) {
for _, name := range names {
os.Remove(name)
}
}
func TestLogManagerLogRotation(t *testing.T) {
tempDir, _ := ioutil.TempDir("", "logs")
defer os.RemoveAll(tempDir)
filesToCreate := 10
// create files with indexes from .0001 to .0010
createFilesToRotate(tempDir, filesToCreate)
// add some content to the first file
logFileWithContent := path.Join(tempDir, fmt.Sprintf(logFileNameScheme, 1, "1111-2222"))
logContent := `{"msg":"test"}`
if err := openLogFileWithContent(logFileWithContent, logContent); err != nil {
t.FailNow()
}
logManager := NewDeploymentLogManager(tempDir)
logManager.deploymentID = "1111-2222"
logFiles, err := logManager.getSortedLogFiles()
if len(logFiles) != filesToCreate || err != nil {
t.Fatalf("expected to have %v files; have files: [%v]\n", filesToCreate, logFiles)
}
// do log rotation
logManager.Rotate()
logFiles, err = logManager.getSortedLogFiles()
if len(logFiles) != logManager.maxLogFiles || err != nil {
t.Fatalf("too many files left after rotating; expecting: %v (actual: %v)",
logManager.maxLogFiles, len(logFiles))
}
// test logging with the same deployment id; should not rotate files
logManager.Enable("1111-2222")
logFiles, err = logManager.getSortedLogFiles()
if len(logFiles) != logManager.maxLogFiles || err != nil {
t.Fatalf("should not rotate files as the deployment id did not change")
}
if path.Base(logFiles[len(logFiles)-1]) != fmt.Sprintf(logFileNameScheme, 1, "1111-2222") {
t.Fatalf("invalid name for the last log file; expecting %v (actual: %v)",
fmt.Sprintf(logFileNameScheme, 1, "1111-2222"),
path.Base(logFiles[len(logFiles)-1]))
}
// should not be rotated as deployment ID is the same as the first file
if !logFileContains(logFileWithContent, logContent) {
t.FailNow()
}
logManager.Disable()
// continue logging with different deployment id; should rotate log files
logManager.Enable("2222-3333")
logFiles, err = logManager.getSortedLogFiles()
if len(logFiles) != logManager.maxLogFiles || err != nil {
t.Fatalf("should rotate files as the deployment id changed: %v", logFiles)
}
if path.Base(logFiles[len(logFiles)-1]) != fmt.Sprintf(logFileNameScheme, 1, "2222-3333") {
t.Fatalf("expecting: %v; actual: %v [%v]",
fmt.Sprintf(logFileNameScheme, 1, "2222-3333"), logFiles[len(logFiles)-1], logFiles)
}
// should not be rotated as deployment ID is the same as the first file
logFileWithContent = path.Join(tempDir, fmt.Sprintf(logFileNameScheme, 2, "1111-2222"))
if !logFileContains(logFileWithContent, logContent) {
t.FailNow()
}
logManager.Disable()
}
func TestEnabligLogsNoSpceForStoringLogs(t *testing.T) {
tempDir, _ := ioutil.TempDir("", "logs")
defer os.RemoveAll(tempDir)
logManager := NewDeploymentLogManager(tempDir)
// hope we don't have that much space...
logManager.minLogSizeBytes = math.MaxUint64
if err := logManager.Enable("1111-2222"); err != ErrNotEnoughSpaceForLogs {
t.FailNow()
}
}
func TestDeploymentLoggingHook(t *testing.T) {
tempDir, _ := ioutil.TempDir("", "logs")
defer os.RemoveAll(tempDir)
deploymentLogger := NewDeploymentLogManager(tempDir)
log.AddHook(NewDeploymentLogHook(deploymentLogger))
log.Info("test1")
deploymentLogger.Enable("1111-2222")
logFile := fmt.Sprintf(logFileNameScheme, 1, "1111-2222")
fileLocation := path.Join(tempDir, logFile)
log.Debug("test2")
deploymentLogger.Disable()
log.Info("test3")
// test correct format of log messages
if !logFileContains(fileLocation, `{"level":"debug","message":"test2","timestamp":"`) {
t.FailNow()
}
}
func TestGetLogs(t *testing.T) {
tempDir, _ := ioutil.TempDir("", "logs")
defer os.RemoveAll(tempDir)
deploymentLogger := NewDeploymentLogManager(tempDir)
// test message formatting when have no log file
logs, err := deploymentLogger.GetLogs("non-existing-log-file")
assert.NoError(t, err)
assert.JSONEq(t, `{"messages":[]}`, string(logs))
// test message formating with correct log file
// add some content to the first file
logFileWithContent := path.Join(tempDir, fmt.Sprintf(logFileNameScheme, 1, "1111-2222"))
logContent := `{"msg":"test"}`
err = openLogFileWithContent(logFileWithContent, logContent)
assert.NoError(t, err)
// check if file really exists
_, err = deploymentLogger.findLogsForSpecificID("1111-2222")
assert.NoError(t, err)
logs, err = deploymentLogger.GetLogs("1111-2222")
assert.JSONEq(t, `{"messages":[{"msg":"test"}]}`, string(logs))
// test message formating with empty log file;
// below should create empty log file
deploymentLogger.Enable("1111-3333")
_, err = deploymentLogger.findLogsForSpecificID("1111-3333")
assert.NoError(t, err)
logs, err = deploymentLogger.GetLogs("1111-3333")
assert.JSONEq(t, `{"messages":[]}`, string(logs))
// test broken log entry
logFileWithContent = path.Join(tempDir, fmt.Sprintf(logFileNameScheme, 1, "1111-4444"))
logContent = `{"msg":"test"}
{"msg": "broken
{"msg": "test2"}`
err = openLogFileWithContent(logFileWithContent, logContent)
assert.NoError(t, err)
logs, err = deploymentLogger.GetLogs("1111-4444")
assert.JSONEq(t, `{"messages":[{"msg":"test"}, {"msg": "test2"}]}`, string(logs))
}
func TestFindLogFiles(t *testing.T) {
tempDir, _ := ioutil.TempDir("", "logs")
defer os.RemoveAll(tempDir)
deploymentLogger := NewDeploymentLogManager(tempDir)
logs, err := deploymentLogger.findLogsForSpecificID("non-existing-log-file")
assert.Error(t, err)
assert.True(t, os.IsNotExist(err))
assert.Empty(t, logs)
}