File: generate_syslog.go

package info (click to toggle)
nerdlog 1.10.0-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 4,296 kB
  • sloc: sh: 1,004; makefile: 85
file content (490 lines) | stat: -rw-r--r-- 11,840 bytes parent folder | download
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
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
package sysloggen

import (
	"fmt"
	"math/rand"
	"os"
	"time"

	"github.com/juju/errors"
)

var facilities = []string{
	"kern", "user", "mail", "daemon", "auth", "syslog",
	"lpr", "news", "uucp", "cron", "authpriv", "ftp",
}

var severities = []string{
	"emerg", "alert", "crit", "err", "warning", "notice", "info", "debug",
}

var messages = []string{
	"Connection established",
	"User login successful",
	"Disk space low",
	"System rebooted",
	"Configuration updated",
	"Unauthorized access attempt",
	"Service started",
	"File not found",
	"Network interface down",
	"Memory usage high",
	"Process terminated",
	"CPU temperature critical",
	"New device connected",
	"Package installation completed",
	"Database query failed",
	"Service stopped",
	"Error reading file",
	"Permission denied",
	"Disk write error",
	"Failed login attempt",
	"Configuration load failed",
	"Authentication failure",
	"Server shutting down",
	"Session expired",
	"Process started",
	"Timeout occurred",
	"Network unreachable",
	"Port unreachable",
	"Insufficient privileges",
	"DNS resolution failed",
	"Database connection error",
	"Configuration reload successful",
	"File system full",
	"System performance degraded",
	"Kernel panic",
	"Backup completed",
	"Backup failed",
	"File copied successfully",
	"Process crashed",
	"Memory leak detected",
	"New update available",
	"Update failed",
	"Service restart requested",
	"Database schema updated",
	"Invalid input detected",
	"Request timed out",
	"Resource allocation failed",
	"Firewall rule added",
	"Firewall rule deleted",
	"User session started",
	"User session ended",
	"Disk format completed",
	"SSH connection established",
	"SSH connection closed",
	"Unexpected error occurred",
	"Request successfully processed",
	"Service restart completed",
	"Cache cleared",
	"Cache update completed",
	"Configuration applied successfully",
	"Service health check failed",
	"System running low on resources",
	"File system check completed",
	"Software version updated",
	"Memory usage normal",
	"Disk usage critical",
	"Network congestion detected",
	"Network speed reduced",
	"Service unavailable",
	"Hardware failure detected",
	"Service dependency failure",
	"System time updated",
	"Invalid credentials provided",
	"Login attempt locked out",
	"User account disabled",
	"User account enabled",
	"Service request queued",
	"Service request completed",
	"User permissions updated",
	"Certificate expiration warning",
	"Application crash reported",
	"Security patch applied",
	"Backup restoration completed",
	"Maintenance mode enabled",
	"Maintenance mode disabled",
	"Security alert raised",
	"Security breach detected",
	"Resource utilization warning",
	"High CPU usage detected",
	"High memory usage detected",
	"Disk error occurred",
	"Data corruption detected",
	"API request failed",
	"API response received",
	"File checksum mismatch",
	"Hardware upgrade completed",
	"System configuration backed up",
	"User session timed out",
	"System configuration restored",
	"Service initialization failed",
	"Server started successfully",
	"Server stopped unexpectedly",
	"Logging level changed",
	"Error handling request",
	"Out of memory error",
	"Service dependency initialized",
	"Scheduled task executed",
	"Scheduled task failed",
	"User authentication successful",
	"User authentication failed",
	"Session token expired",
	"File upload completed",
	"File download started",
	"File upload failed",
	"File download failed",
	"File transfer completed",
	"File transfer failed",
	"System clock synchronized",
	"System time drift detected",
	"Software upgrade completed",
	"System reboot required",
	"Disk space reclaimed",
	"IP address conflict detected",
	"Application configuration error",
	"System health check completed",
	"System health check failed",
	"Log file rotated",
	"Log file archived",
	"User password changed",
	"Invalid password attempt",
	"SMTP server connection error",
	"Database migration completed",
	"Database migration failed",
	"Network link restored",
	"Network interface reset",
}

func randomElement(list []string) string {
	return list[rand.Intn(len(list))]
}

func generateSyslogEntry(ts time.Time, layout string, parts SyslogParts) string {
	timestamp := ts.Format(layout)
	hostname := "myhost"

	if parts.Tag == "" {
		parts.Tag = randomElement(facilities)
	}

	if parts.Severity == "" {
		parts.Severity = randomElement(severities)
	}

	if parts.Pid == 0 {
		parts.Pid = rand.Intn(9000) + 100
	}

	if parts.Message == "" {
		parts.Message = randomElement(messages)
	}

	return fmt.Sprintf(
		"%s %s %s[%d]: <%s> %s",
		timestamp, hostname, parts.Tag, parts.Pid, parts.Severity, parts.Message,
	)
}

func randomStep(params *DelayCfg, lastDelay, curDelayDelta time.Duration) time.Duration {
	min := -100 * int64(time.Millisecond)
	max := 100 * int64(time.Millisecond)
	curDelayDelta += time.Duration(rand.Int63n(max-min) + min)
	//curDelayDelta += -time.Duration(rand.Int63n(max))
	//_ = min

	ret := lastDelay + curDelayDelta
	if ret < time.Duration(params.MinDelayMS)*time.Millisecond {
		ret = time.Duration(params.MinDelayMS) * time.Millisecond
	}
	if ret > time.Duration(params.MaxDelayMS)*time.Millisecond {
		//ret = time.Duration(params.MaxDelayMS) * time.Millisecond
	}

	return ret

	//min := int64(params.MinDelayMS) * int64(time.Millisecond)
	//max := int64(params.MaxDelayMS) * int64(time.Millisecond)
	//return time.Duration(rand.Int63n(max-min) + min)
}

type Params struct {
	// If TimeLayout is empty, "Jan _2 15:04:05" will be used.
	TimeLayout string

	StartTime     time.Time
	SecondLogTime time.Time

	// LogBasename is a name like "mylog", can be "/path/to/mylog" as well.
	// The first (older) log will have the ".1" appended to it.
	LogBasename string

	// NumLogs specifies the max amount of logs to generate. If 0, we never stop
	// generating logs, and once caught up with the current time (time.Now()), it
	// switches to the real-time mode and continues there forever, waiting for
	// appropriate durations before printing every line.
	NumLogs int

	MinDelayMS int
	MaxDelayMS int

	RandomSeed int

	// SkipIfPrevLogSizeIs and SkipIfLastLogSizeIs are an optimization:
	// if the log files already exist and are of these exact sizes, don't
	// generate anything.
	SkipIfPrevLogSizeIs int64
	SkipIfLastLogSizeIs int64

	Spikes []Spike
}

type DelayCfg struct {
	MinDelayMS int
	MaxDelayMS int
}

type SpikePhase struct {
	// If EndTime is zero, the phase will never end
	EndTime time.Time

	MinDelayMS int
	MaxDelayMS int

	Trend func(phasePercentage float64, minDelayMS, maxDelayMS int) DelayCfg
}

type SyslogParts struct {
	Tag      string
	Severity string
	Pid      int
	Message  string
}

type Spike struct {
	StartTime time.Time
	// All of SyslogParts fields are optional; what is not specified, will be random
	SyslogParts SyslogParts
	Phases      []SpikePhase
}

type streamCtx struct {
	spikeCfg Spike

	lastDelay     time.Duration
	curDelayDelta time.Duration

	nextMsgTime time.Time
}

func GenerateSyslog(params Params) error {
	if params.TimeLayout == "" {
		params.TimeLayout = "Jan _2 15:04:05"
	}

	sCtxs := []*streamCtx{
		// Main stream
		&streamCtx{
			spikeCfg: Spike{
				Phases: []SpikePhase{
					SpikePhase{
						MinDelayMS: params.MinDelayMS,
						MaxDelayMS: params.MaxDelayMS,
					},
				},
			},
		},
	}

	for _, spike := range params.Spikes {
		sCtxs = append(sCtxs, &streamCtx{
			spikeCfg: spike,
		})
	}

	type nextDelayAndMsg struct {
		time        time.Time
		syslogParts SyslogParts
	}

	getNextDelayAndMsg := func(curTime time.Time) nextDelayAndMsg {
		// Generate nextMsgTime for all active spikes
		for _, sc := range sCtxs {
			if sc.nextMsgTime.IsZero() {
				if curTime.Before(sc.spikeCfg.StartTime) {
					continue
				}

				phaseStartTime := sc.spikeCfg.StartTime

				if len(sc.spikeCfg.Phases) == 0 {
					panic("no phases")
				}
				var d *DelayCfg
				for _, phase := range sc.spikeCfg.Phases {
					if phase.EndTime.IsZero() || curTime.Before(phase.EndTime) {
						// Found the phase
						percentage := 0.0
						if !phase.EndTime.IsZero() {
							totalDur := phase.EndTime.Sub(phaseStartTime)
							elapsedDur := curTime.Sub(phaseStartTime)
							percentage = float64(elapsedDur) / float64(totalDur) * 100.0
						}

						var curDelayCfg DelayCfg
						if phase.Trend != nil {
							curDelayCfg = phase.Trend(percentage, phase.MinDelayMS, phase.MaxDelayMS)
						} else {
							curDelayCfg = DelayCfg{
								MinDelayMS: phase.MinDelayMS,
								MaxDelayMS: phase.MaxDelayMS,
							}
						}

						d = &curDelayCfg
						break
					}

					phaseStartTime = phase.EndTime
				}

				if d == nil {
					// the spike is over (all phases of it are over)
					continue
				}

				if sc.lastDelay == 0 {
					sc.lastDelay = time.Duration(d.MinDelayMS + (d.MaxDelayMS-d.MinDelayMS)/2)
				}

				dur := randomStep(d, sc.lastDelay, sc.curDelayDelta)
				newDelayDelta := sc.lastDelay - dur

				sc.curDelayDelta = newDelayDelta
				sc.lastDelay = dur
				sc.nextMsgTime = curTime.Add(dur)
			}
		}

		var earliestTime *time.Time
		var syslogParts *SyslogParts
		// Find the earliest time
		for _, sc := range sCtxs {
			if sc.nextMsgTime.IsZero() {
				continue
			}

			if earliestTime == nil || sc.nextMsgTime.Before(*earliestTime) {
				tmpTime := sc.nextMsgTime
				tmpParts := sc.spikeCfg.SyslogParts

				earliestTime = &tmpTime
				syslogParts = &tmpParts

				// Reset it so we'll generate it again next time
				sc.nextMsgTime = time.Time{}
			}
		}

		if earliestTime == nil {
			panic("earliestTime must not be nil at this point, since we have the 'main' spike")
		}

		return nextDelayAndMsg{
			time:        *earliestTime,
			syslogParts: *syslogParts,
		}
	}

	rand.Seed(int64(params.RandomSeed))

	curTime := params.StartTime

	prevlogFname := params.LogBasename + ".1"
	lastlogFname := params.LogBasename

	if params.SkipIfPrevLogSizeIs != 0 && params.SkipIfLastLogSizeIs != 0 {
		var prevlogSize int64
		var lastlogSize int64

		prevlogStat, err := os.Stat(prevlogFname)
		if err == nil {
			prevlogSize = prevlogStat.Size()
		}

		lastlogStat, err := os.Stat(lastlogFname)
		if err == nil {
			lastlogSize = lastlogStat.Size()
		}

		if params.SkipIfPrevLogSizeIs == prevlogSize &&
			params.SkipIfLastLogSizeIs == lastlogSize {
			// Nothing to do
			//fmt.Println("Log files already exist and are of expected sizes, skipping generation")
			return nil
		}
	}

	fmt.Printf("Creating first log file %s\n", prevlogFname)

	file, err := os.Create(prevlogFname)
	if err != nil {
		return errors.Annotatef(err, "creating first log file")
	}
	defer file.Close()

	numLogFile := 0
	numLogsWritten := 0

	isRealtime := false

	for {
		next := getNextDelayAndMsg(curTime)
		if curTime.After(next.time) {
			panic(fmt.Sprintf("curTime %v can't be after next.time %v", curTime, next.time))
		}

		step := next.time.Sub(curTime)
		curTime = curTime.Add(step)

		now := time.Now()
		if params.NumLogs > 0 && numLogsWritten >= params.NumLogs {
			break
		}

		// Real-time transition: we've caught up to current time
		if params.NumLogs == 0 && curTime.After(now) {
			if !isRealtime {
				fmt.Printf("Switching to realtime mode\n")
				isRealtime = true
			}

			time.Sleep(step)
			curTime = time.Now()
		}

		if !curTime.Before(params.SecondLogTime) && numLogFile == 0 {
			numLogFile += 1
			file.Close()

			fmt.Printf("Switching to the next log file %s\n", lastlogFname)

			var err error
			file, err = os.Create(lastlogFname)
			if err != nil {
				return errors.Annotatef(err, "creating second log file")
			}
			defer file.Close()
		}

		logEntry := generateSyslogEntry(curTime, params.TimeLayout, next.syslogParts)
		_, err := file.WriteString(logEntry + "\n")
		if err != nil {
			return errors.Annotatef(err, "writing to log file")
		}

		numLogsWritten++
	}

	return nil
}