forked from sofixa/nomad_follower
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathservice.go
121 lines (101 loc) · 2.38 KB
/
service.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
package main
import (
"log"
"os"
"strconv"
"time"
nomadApi "github.com/hashicorp/nomad/api"
"gopkg.in/natefinch/lumberjack.v2"
)
var DEFAULT_CIRCUIT_BREAK = 60 * time.Second
var DEFAULT_LOG_FILE = "nomad.log"
var DEFAULT_SAVE_FILE = "nomad-follower.json"
var DEFAULT_SKIP_LOG_TAG = "disable_loki_logs"
var MAX_LOG_SIZE = 50
var MAX_LOG_BACKUPS = 1
var MAX_LOG_AGE = 1
var NOMAD_MAX_WAIT = 5 * time.Minute
var ALLOC_REFRESH_TICK = time.Second * 30
var DEFAULT_VERBOSITY = INFO
func main() {
var verbosity LogLevel
verbose := os.Getenv("VERBOSE")
i, err := strconv.Atoi(verbose)
if err != nil {
verbosity = DEFAULT_VERBOSITY
} else {
verbosity = LogLevel(i)
}
logger := Logger{verbosity: verbosity}
logFile := os.Getenv("LOG_FILE")
if logFile == "" {
logFile = DEFAULT_LOG_FILE
}
saveFile := os.Getenv("SAVE_FILE")
if saveFile == "" {
saveFile = DEFAULT_SAVE_FILE
}
skipLogTag := os.Getenv("SKIP_LOG_TAG")
if skipLogTag == "" {
skipLogTag = DEFAULT_SKIP_LOG_TAG
}
createLogFile(logFile, logger)
fileLogger := log.New(&lumberjack.Logger{
Filename: logFile,
MaxSize: MAX_LOG_SIZE,
MaxBackups: MAX_LOG_BACKUPS,
MaxAge: MAX_LOG_AGE,
}, "", 0)
config := nomadApi.DefaultConfig()
config.WaitTime = NOMAD_MAX_WAIT
var nomadConfig NomadConfig
nomadTokenBackend := os.Getenv("NOMAD_TOKEN_BACKEND")
if nomadTokenBackend == "" {
nomadConfig = NewNomadEnvAuth(config, logger)
} else {
nomadConfig = NewNomadRenewableAuth(
config,
nil,
nomadTokenBackend,
DEFAULT_CIRCUIT_BREAK,
logger,
)
}
af, err := NewAllocationFollower(nomadConfig, logger, skipLogTag)
if err != nil {
logger.Errorf("main", "Error creating Allocation Follower: %s", err)
return
}
outChan := af.Start(ALLOC_REFRESH_TICK, saveFile)
if af != nil {
for {
select {
case message, ok := <-outChan:
if ok {
fileLogger.Println(message)
} else {
logger.Info("main", "Allocation Follower fatal error, exiting.")
return
}
}
}
}
}
func createLogFile(logFile string, logger Logger) {
// detect if file exists
var _, err = os.Stat(logFile)
// create file if not exists
if os.IsNotExist(err) {
var file, err = os.Create(logFile)
if err != nil {
logger.Infof(
"createLogFile",
"Error creating log file Error: %v",
err,
)
return
}
defer file.Close()
}
logger.Infof("createLogFile", "Created log file: %s", logFile)
}