-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathara.go
324 lines (277 loc) · 8.95 KB
/
ara.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
package main
import (
"flag"
"fmt"
"os"
"os/signal"
"runtime/pprof"
"strconv"
"syscall"
"time"
"github.com/getsentry/sentry-go"
"gopkg.in/DataDog/dd-trace-go.v1/ddtrace/tracer"
"gopkg.in/DataDog/dd-trace-go.v1/profiler"
"bitbucket.org/enroute-mobi/ara/api"
"bitbucket.org/enroute-mobi/ara/audit"
"bitbucket.org/enroute-mobi/ara/clock"
"bitbucket.org/enroute-mobi/ara/config"
"bitbucket.org/enroute-mobi/ara/core"
"bitbucket.org/enroute-mobi/ara/logger"
"bitbucket.org/enroute-mobi/ara/model"
"bitbucket.org/enroute-mobi/ara/remote"
"bitbucket.org/enroute-mobi/ara/siri/siri"
"bitbucket.org/enroute-mobi/ara/uuid"
"bitbucket.org/enroute-mobi/ara/version"
)
func main() {
cpuProfile := flag.String("cpuprofile", "", "Write cpu profile to file")
memProfile := flag.String("memprofile", "", "Write memory profile to this file")
uuidPtr := flag.Bool("testuuid", false, "Use the test uuid generator")
clockPtr := flag.String("testclock", "", "Use a fake clock at time given. Format 20060102-1504")
pidPtr := flag.String("pidfile", "", "Write processus pid in given file")
configPtr := flag.String("config", "", "Config directory")
flag.BoolVar(&config.Config.Debug, "debug", false, "Enable debug messages")
flag.BoolVar(&config.Config.Syslog, "syslog", false, "Redirect messages to syslog")
flag.BoolVar(&config.Config.ColorizeLog, "colorizelog", false, "Colorize messages in log")
flag.Parse()
if len(flag.Args()) == 0 {
fmt.Println("Ara", version.Value())
fmt.Println("Usage: ara [-testuuid] [-testclock=<time>] [-pidfile=<filename>]")
fmt.Println(" [-config=<path>] [-debug] [-syslog] [-colorizelog]")
fmt.Println("\tcheck [-requestor-ref=<requestorRef>] <url>")
fmt.Println("\tapi [-listen=<url>]")
fmt.Println("\tmigrate [-path=<path>] <up|down>")
fmt.Println("\tload <file path> <referential_slug>")
os.Exit(1)
}
// Load configuration files
err := config.LoadConfig(*configPtr)
if err != nil {
logger.Log.Panicf("Error while loading configuration: %v", err)
}
if *cpuProfile != "" {
err = enableCpuProfile(*cpuProfile)
if err != nil {
logger.Log.Panicf("Error while configuring cpu profile: %v", err)
}
}
if *memProfile != "" {
err = enableMemoryProfile(*memProfile)
if err != nil {
logger.Log.Panicf("Error while configuring memory profile: %v", err)
}
}
// Configure Sentry
if config.Config.Sentry != "" {
err = sentry.Init(sentry.ClientOptions{
Dsn: config.Config.Sentry,
Release: version.Value(),
Debug: config.Config.Debug,
})
}
logger.Log.Debugf("Ara started with a version : %v", version.Value())
if *uuidPtr {
uuid.SetDefaultUUIDGenerator(uuid.NewFakeUUIDGenerator())
}
if *clockPtr != "" {
testTime, err := time.Parse("20060102-1504", *clockPtr)
if err != nil {
panic(err)
}
clock.SetDefaultClock(clock.NewFakeClockAt(testTime))
}
if *pidPtr != "" {
f, err := os.Create(*pidPtr)
if err != nil {
logger.Log.Printf("Error: Unable to create a file at given path")
os.Exit(2)
}
defer f.Close()
_, err = f.WriteString(strconv.Itoa(os.Getpid()))
if err != nil {
panic(err)
}
}
c := make(chan os.Signal, 1)
signal.Notify(c, syscall.SIGHUP)
go func() {
for sig := range c {
logger.Log.Debugf("Receive sighup signal: %v", sig)
file, err := os.Create("/tmp/stack")
if err != nil {
logger.Log.Panicf("%v", err)
}
pprof.Lookup("goroutine").WriteTo(file, 1)
file.Close()
}
}()
command := flag.Args()[0]
switch command {
case "convert":
convertFlags := flag.NewFlagSet("convert", flag.ExitOnError)
convertFlags.Parse(flag.Args()[1:])
if convertFlags.NArg() < 1 {
logger.Log.Printf("Incorrect use of command convert: not enough aguments")
logger.Log.Printf("usage: ara convert <schema name>")
os.Exit(1)
}
schemaName := convertFlags.Arg(0)
schema := audit.AraBigQuerySchemas[schemaName]
if schema == nil {
logger.Log.Printf("Error: schema %v does no exist", schemaName)
os.Exit(1)
}
jsonSchema, err := schema.ToJSONFields()
if err != nil {
logger.Log.Printf("Error while converting schema to JSON: %v", err)
os.Exit(1)
}
fmt.Println(string(jsonSchema))
os.Exit(0)
case "check":
checkFlags := flag.NewFlagSet("check", flag.ExitOnError)
requestorRefPtr := checkFlags.String("requestor-ref", "Ara", "Specify requestorRef")
checkFlags.Parse(flag.Args()[1:])
err = checkStatus(checkFlags.Arg(0), *requestorRefPtr)
case "api":
apiFlags := flag.NewFlagSet("api", flag.ExitOnError)
serverAddressPtr := apiFlags.String("listen", "localhost:8080", "Specify server port")
apiFlags.Parse(flag.Args()[1:])
if os.Getenv("DD_AGENT_ENV") != "" {
tracer.Start(
tracer.WithService("ara-api"),
tracer.WithEnv(os.Getenv("DD_AGENT_ENV")),
tracer.WithServiceVersion(version.ApplicationName()),
)
defer tracer.Stop()
}
if os.Getenv("DD_PROFILER") == "true" && os.Getenv("DD_AGENT_ENV") != "" {
err := profiler.Start(
profiler.WithService("ara-api"),
profiler.WithEnv(os.Getenv("DD_AGENT_ENV")),
profiler.WithVersion(version.ApplicationName()),
profiler.WithTags("app:ara"),
profiler.WithProfileTypes(
profiler.CPUProfile,
profiler.HeapProfile,
),
)
if err != nil {
logger.Log.Panicf("Error while starting Datadog Profiler: %v", err)
}
defer profiler.Stop()
}
// Init Database
model.Database = model.InitDB(config.Config.DB)
defer model.CloseDB(model.Database)
err = core.CurrentReferentials().Load()
if err != nil {
logger.Log.Panicf("Error while loading Referentials: %v", err)
}
core.CurrentReferentials().Start()
err = api.NewServer(*serverAddressPtr).ListenAndServe()
case "purge":
purgeFlags := flag.NewFlagSet("purge", flag.ExitOnError)
purgeDaysPtr := purgeFlags.Int("days", 1, "Specify number of days to set the purge date")
purgeFlags.Parse(flag.Args()[1:])
// Init Database
model.Database = model.InitDB(config.Config.DB)
defer model.CloseDB(model.Database)
purifier := model.NewPurifier(*purgeDaysPtr)
err = purifier.Purge()
case "migrate":
logger.Log.Debug = true
migrateFlags := flag.NewFlagSet("migrate", flag.ExitOnError)
migrationFilesPtr := migrateFlags.String("path", "db/migrations", "Specify migration files path")
migrateFlags.Parse(flag.Args()[1:])
database := model.InitDB(config.Config.DB)
defer model.CloseDB(database)
err = model.ApplyMigrations(migrateFlags.Arg(0), *migrationFilesPtr, database.Db)
case "load":
loadFlags := flag.NewFlagSet("load", flag.ExitOnError)
forcePtr := loadFlags.Bool("force", false, "Overwrite records in Database")
loadFlags.Parse(flag.Args()[1:])
if loadFlags.NArg() < 2 {
logger.Log.Printf("Incorrect use of command load: not enough aguments")
logger.Log.Printf("usage: ara load [-force] <path> <referential slug>")
os.Exit(2)
}
// Init Database
model.Database = model.InitDB(config.Config.DB)
defer model.CloseDB(model.Database)
err = model.LoadFromCSVFile(loadFlags.Arg(0), loadFlags.Arg(1), *forcePtr)
}
if err != nil {
if _, ok := err.(*siri.SiriError); !ok {
logger.Log.Panicf("Error while running: %v", err)
}
// Siri errors
logger.Log.Printf("%v", err)
os.Exit(2)
}
os.Exit(0)
}
func checkStatus(url string, requestorRef string) error {
client := remote.NewHTTPClient(remote.HTTPClientOptions{Urls: remote.HTTPClientUrls{Url: url}}).SIRIClient()
request := &siri.SIRICheckStatusRequest{
RequestorRef: requestorRef,
RequestTimestamp: clock.DefaultClock().Now(),
MessageIdentifier: "Ara:Message::6ba7b814-9dad-11d1-0-00c04fd430c8:LOC",
}
startTime := time.Now()
xmlResponse, err := client.CheckStatus(request)
if err != nil {
return err
}
responseTime := time.Since(startTime)
// Log
var logMessage []byte
if xmlResponse.Status() {
logMessage = []byte("SIRI OK - status true - ")
} else {
logMessage = []byte("SIRI CRITICAL: status false - ")
if xmlResponse.ErrorType() == "OtherError" {
logMessage = append(logMessage, fmt.Sprintf("%s %d %s - ", xmlResponse.ErrorType(), xmlResponse.ErrorNumber(), xmlResponse.ErrorText())...)
} else {
logMessage = append(logMessage, fmt.Sprintf("%s %s - ", xmlResponse.ErrorType(), xmlResponse.ErrorText())...)
}
}
logMessage = append(logMessage, fmt.Sprintf("%.3f seconds response time", responseTime.Seconds())...)
logger.Log.Printf(string(logMessage))
return nil
}
func enableCpuProfile(file string) error {
f, err := os.Create(file)
if err != nil {
return err
}
pprof.StartCPUProfile(f)
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt)
go func() {
for sig := range c {
logger.Log.Debugf("Receive interrupt signal: %v", sig)
pprof.StopCPUProfile()
f.Close()
os.Exit(0)
}
}()
return nil
}
func enableMemoryProfile(file string) error {
f, err := os.Create(file)
if err != nil {
return err
}
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt)
go func() {
for sig := range c {
logger.Log.Debugf("Receive interrupt signal: %v", sig)
pprof.WriteHeapProfile(f)
f.Close()
os.Exit(0)
}
}()
return nil
}