-
Notifications
You must be signed in to change notification settings - Fork 51
/
main.go
468 lines (401 loc) · 13.6 KB
/
main.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
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
/*
Copyright 2019 The Cloud-Barista Authors.
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 is the starting point of CB-Tumblebug
package main
import (
"bufio"
"context"
"encoding/csv"
"fmt"
"os"
"os/user"
"strconv"
"strings"
"sync"
"time"
"github.com/cloud-barista/cb-tumblebug/src/core/common/logger"
"github.com/cloud-barista/cb-tumblebug/src/core/model"
"github.com/cloud-barista/cb-tumblebug/src/kvstore/etcd"
"github.com/cloud-barista/cb-tumblebug/src/kvstore/kvstore"
"github.com/rs/zerolog/log"
//_ "github.com/go-sql-driver/mysql"
"github.com/fsnotify/fsnotify"
_ "github.com/mattn/go-sqlite3"
"github.com/spf13/viper"
"github.com/cloud-barista/cb-tumblebug/src/core/common"
"github.com/cloud-barista/cb-tumblebug/src/core/infra"
restServer "github.com/cloud-barista/cb-tumblebug/src/api/rest/server"
"xorm.io/xorm"
"xorm.io/xorm/names"
)
// init for main
func init() {
model.SystemReady = false
model.SelfEndpoint = common.NVL(os.Getenv("TB_SELF_ENDPOINT"), "localhost:1323")
model.SpiderRestUrl = common.NVL(os.Getenv("TB_SPIDER_REST_URL"), "http://localhost:1024/spider")
model.DragonflyRestUrl = common.NVL(os.Getenv("TB_DRAGONFLY_REST_URL"), "http://localhost:9090/dragonfly")
model.TerrariumRestUrl = common.NVL(os.Getenv("TB_TERRARIUM_REST_URL"), "http://localhost:8055/terrarium")
model.DBUrl = common.NVL(os.Getenv("TB_SQLITE_URL"), "localhost:3306")
model.DBDatabase = common.NVL(os.Getenv("TB_SQLITE_DATABASE"), "cb_tumblebug")
model.DBUser = common.NVL(os.Getenv("TB_SQLITE_USER"), "cb_tumblebug")
model.DBPassword = common.NVL(os.Getenv("TB_SQLITE_PASSWORD"), "cb_tumblebug")
model.AutocontrolDurationMs = common.NVL(os.Getenv("TB_AUTOCONTROL_DURATION_MS"), "10000")
model.DefaultNamespace = common.NVL(os.Getenv("TB_DEFAULT_NAMESPACE"), "default")
model.DefaultCredentialHolder = common.NVL(os.Getenv("TB_DEFAULT_CREDENTIALHOLDER"), "admin")
// Etcd
model.EtcdEndpoints = common.NVL(os.Getenv("TB_ETCD_ENDPOINTS"), "localhost:2379")
// load the latest configuration from DB (if exist)
log.Info().Msg("[Update system environment]")
common.UpdateGlobalVariable(model.StrDragonflyRestUrl)
common.UpdateGlobalVariable(model.StrSpiderRestUrl)
common.UpdateGlobalVariable(model.TerrariumRestUrl)
common.UpdateGlobalVariable(model.StrAutocontrolDurationMs)
// Initialize the logger
logLevel := common.NVL(os.Getenv("TB_LOGLEVEL"), "debug")
logWriter := common.NVL(os.Getenv("TB_LOGWRITER"), "both")
logFilePath := common.NVL(os.Getenv("TB_LOGFILE_PATH"), "./log/tumblebug.log")
logMaxSizeStr := common.NVL(os.Getenv("TB_LOGFILE_MAXSIZE"), "10")
logMaxSize, _ := strconv.Atoi(logMaxSizeStr)
logMaxBackupsStr := common.NVL(os.Getenv("TB_LOGFILE_MAXBACKUPS"), "3")
logMaxBackups, _ := strconv.Atoi(logMaxBackupsStr)
logMaxAgeStr := common.NVL(os.Getenv("TB_LOGFILE_MAXAGE"), "3")
logMaxAge, _ := strconv.Atoi(logMaxAgeStr)
logCompressStr := common.NVL(os.Getenv("TB_LOGFILE_COMPRESS"), "false")
logCompress := (logCompressStr == "true")
logger := logger.NewLogger(logger.Config{
LogLevel: logLevel,
LogWriter: logWriter,
LogFilePath: logFilePath,
MaxSize: logMaxSize,
MaxBackups: logMaxBackups,
MaxAge: logMaxAge,
Compress: logCompress,
})
// Set the global logger
log.Logger = *logger
// load config
//masterConfigInfos = confighandler.GetMasterConfigInfos()
//Setup database (meta_db/dat/cbtumblebug.s3db)
log.Info().Msg("[Setup SQL Database]")
err := os.MkdirAll("../meta_db/dat/", os.ModePerm)
if err != nil {
log.Error().Err(err).Msg("")
}
//err = common.OpenSQL("../meta_db/dat/cbtumblebug.s3db") // commented out to move to use XORM
model.ORM, err = xorm.NewEngine("sqlite3", "../meta_db/dat/cbtumblebug.s3db")
if err != nil {
log.Error().Err(err).Msg("")
} else {
log.Info().Msg("Database access info set successfully")
}
//model.ORM.SetMapper(names.SameMapper{})
model.ORM.SetTableMapper(names.SameMapper{})
model.ORM.SetColumnMapper(names.SameMapper{})
// "CREATE Table IF NOT EXISTS spec(...)"
//err = common.CreateSpecTable() // commented out to move to use XORM
err = model.ORM.Sync2(new(model.TbSpecInfo))
if err != nil {
log.Error().Err(err).Msg("")
} else {
log.Info().Msg("Table spec set successfully..")
}
// "CREATE Table IF NOT EXISTS image(...)"
//err = common.CreateImageTable() // commented out to move to use XORM
err = model.ORM.Sync2(new(model.TbImageInfo))
if err != nil {
log.Error().Err(err).Msg("")
} else {
log.Info().Msg("Table image set successfully..")
}
err = model.ORM.Sync2(new(model.TbCustomImageInfo))
if err != nil {
log.Error().Err(err).Msg("")
} else {
log.Info().Msg("Table customImage set successfully..")
}
err = addIndexes()
if err != nil {
log.Error().Err(err).Msg("Cannot add indexes to the tables (ORM)")
}
setConfig()
_, err = common.GetNs(model.DefaultNamespace)
if err != nil {
if model.DefaultNamespace != "" {
defaultNS := model.NsReq{Name: model.DefaultNamespace, Description: "Default Namespace"}
_, err := common.CreateNs(&defaultNS)
if err != nil {
log.Error().Err(err).Msg("")
panic(err)
}
} else {
log.Error().Msg("Default namespace is not set")
panic("Default namespace is not set, please set TB_DEFAULT_NAMESPACE in setup.env or environment variable")
}
}
}
// setConfig get cloud settings from a config file
func setConfig() {
fileName := "cloud_conf"
viper.AddConfigPath(".")
viper.AddConfigPath("./conf/")
viper.AddConfigPath("../conf/")
viper.SetConfigName(fileName)
viper.SetConfigType("yaml")
err := viper.ReadInConfig()
if err != nil {
log.Error().Err(err).Msg("")
panic(fmt.Errorf("fatal error reading cloud_conf: %w", err))
}
log.Info().Msg(viper.ConfigFileUsed())
err = viper.Unmarshal(&common.RuntimeConf)
if err != nil {
log.Error().Err(err).Msg("")
panic(err)
}
// Load cloudinfo
cloudInfoViper := viper.New()
fileName = "cloudinfo"
cloudInfoViper.AddConfigPath(".")
cloudInfoViper.AddConfigPath("./assets/")
cloudInfoViper.AddConfigPath("../assets/")
cloudInfoViper.SetConfigName(fileName)
cloudInfoViper.SetConfigType("yaml")
err = cloudInfoViper.ReadInConfig()
if err != nil {
panic(fmt.Errorf("fatal error reading cloudinfo config file: %w", err))
}
log.Info().Msg(cloudInfoViper.ConfigFileUsed())
err = cloudInfoViper.Unmarshal(&common.RuntimeCloudInfo)
if err != nil {
log.Error().Err(err).Msg("")
panic(err)
}
// make all map keys lowercase
common.AdjustKeysToLowercase(&common.RuntimeCloudInfo)
// fmt.Printf("%+v\n", common.RuntimeCloudInfo)
common.PrintCloudInfoTable(common.RuntimeCloudInfo)
//
// Load k8sclusterinfo
//
k8sClusterInfoViper := viper.New()
fileName = "k8sclusterinfo"
k8sClusterInfoViper.AddConfigPath(".")
k8sClusterInfoViper.AddConfigPath("./assets/")
k8sClusterInfoViper.AddConfigPath("../assets/")
k8sClusterInfoViper.SetConfigName(fileName)
k8sClusterInfoViper.SetConfigType("yaml")
err = k8sClusterInfoViper.ReadInConfig()
if err != nil {
panic(fmt.Errorf("fatal error reading cloudinfo config file: %w", err))
}
log.Info().Msg(k8sClusterInfoViper.ConfigFileUsed())
err = k8sClusterInfoViper.Unmarshal(&common.RuntimeK8sClusterInfo)
if err != nil {
log.Error().Err(err).Msg("")
panic(err)
}
//
// Wait until CB-Spider is ready
//
maxAttempts := 60 // (3 mins)
attempt := 0
for attempt < maxAttempts {
if common.CheckSpiderReady() == nil {
log.Info().Msg("CB-Spider is now ready. Initializing CB-Tumblebug...")
break
}
log.Info().Msgf("CB-Spider at %s is not ready. Attempt %d/%d", model.SpiderRestUrl, attempt+1, maxAttempts)
time.Sleep(3 * time.Second)
attempt++
}
if attempt == maxAttempts {
panic("Failed to confirm CB-Spider readiness within the allowed time. \nCheck the connection to CB-Spider.")
}
// Setup etcd and kvstore
var etcdAuthEnabled bool
var etcdUsername string
var etcdPassword string
etcdAuthEnabled = os.Getenv("TB_ETCD_AUTH_ENABLED") == "true"
if etcdAuthEnabled {
etcdUsername = os.Getenv("TB_ETCD_USERNAME")
etcdPassword = os.Getenv("TB_ETCD_PASSWORD")
}
etcdEndpoints := strings.Split(model.EtcdEndpoints, ",")
ctx := context.Background()
config := etcd.Config{
Endpoints: etcdEndpoints,
DialTimeout: 5 * time.Second,
}
if etcdAuthEnabled && etcdUsername != "" && etcdPassword != "" {
config.Username = etcdUsername
config.Password = etcdPassword
}
// Wait until etcd is ready
var etcdStore kvstore.Store
var err2 error
etcdMaxAttempts := 10 // (50 sec)
etcdAttempt := 1
for ; etcdAttempt <= etcdMaxAttempts; etcdAttempt++ {
etcdStore, err2 = etcd.NewEtcdStore(ctx, config)
if err2 == nil {
log.Info().Msg("etcd is now available.")
break
}
log.Warn().Err(err2).Msgf("etcd at %s is not ready. Attempt %d/%d", model.EtcdEndpoints, etcdAttempt, maxAttempts)
time.Sleep(5 * time.Second)
}
if err2 != nil {
log.Fatal().Err(err2).Msg("failed to initialize etcd")
}
err2 = kvstore.InitializeStore(etcdStore)
if err2 != nil {
log.Fatal().Err(err2).Msg("")
}
log.Info().Msg("kvstore is initialized successfully. Initializing CB-Tumblebug...")
// Register all cloud info
err = common.RegisterAllCloudInfo()
if err != nil {
log.Error().Err(err).Msg("Failed to register cloud info")
panic(err)
}
// Load credentials
usr, err := user.Current()
if err != nil {
log.Error().Err(err).Msg("")
}
credPath := usr.HomeDir + "/.cloud-barista"
credViper := viper.New()
fileName = "credentials"
credViper.AddConfigPath(credPath)
credViper.SetConfigName(fileName)
credViper.SetConfigType("yaml")
err = credViper.ReadInConfig()
if err != nil {
log.Info().Msg("Local credentials file not found. Continue.")
} else {
log.Info().Msg(credViper.ConfigFileUsed())
err = credViper.Unmarshal(&common.RuntimeCredential)
if err != nil {
log.Error().Err(err).Msg("")
panic(err)
}
// common.PrintCredentialInfo(common.RuntimeCredential)
}
// err = common.RegisterAllCloudInfo()
// if err != nil {
// log.Error().Err(err).Msg("Failed to register credentials")
// panic(err)
// }
// const mrttArrayXMax = 300
// const mrttArrayYMax = 300
// common.RuntimeLatancyMap = make([][]string, mrttArrayXMax)
// cloudlatencymap.csv
file, fileErr := os.Open("../assets/cloudlatencymap.csv")
defer file.Close()
if fileErr != nil {
log.Error().Err(fileErr).Msg("")
panic(fileErr)
}
rdr := csv.NewReader(bufio.NewReader(file))
common.RuntimeLatancyMap, _ = rdr.ReadAll()
for i, v := range common.RuntimeLatancyMap {
if i == 0 {
continue
}
if v[0] == "" {
break
}
common.RuntimeLatancyMapIndex[v[0]] = i
}
//fmt.Printf("RuntimeLatancyMap: %v\n\n", common.RuntimeLatancyMap)
//fmt.Printf("[RuntimeLatancyMapIndex]\n %v\n", common.RuntimeLatancyMapIndex)
}
// addIndexes adds indexes to the tables for faster search
func addIndexes() error {
_, err := model.ORM.Exec("CREATE INDEX IF NOT EXISTS idx_namespace ON TbSpecInfo (Namespace)")
if err != nil {
return err
}
_, err = model.ORM.Exec("CREATE INDEX IF NOT EXISTS idx_vcpu ON TbSpecInfo (VCPU)")
if err != nil {
return err
}
_, err = model.ORM.Exec("CREATE INDEX IF NOT EXISTS idx_memorygib ON TbSpecInfo (MemoryGiB)")
if err != nil {
return err
}
_, err = model.ORM.Exec("CREATE INDEX IF NOT EXISTS idx_cspspecname ON TbSpecInfo (CspSpecName)")
if err != nil {
return err
}
_, err = model.ORM.Exec("CREATE INDEX IF NOT EXISTS idx_costperhour ON TbSpecInfo (CostPerHour)")
if err != nil {
return err
}
return nil
}
// Main Body
// @title CB-Tumblebug REST API
// @version latest
// @description CB-Tumblebug is an open source system for managing multi-cloud infrastructure consisting of resources from multiple cloud service providers. (Cloud-Barista)
// @termsOfService https://github.com/cloud-barista/cb-tumblebug/blob/main/README.md
// @contact.name API Support
// @contact.url https://github.com/cloud-barista/cb-tumblebug/issues/new/choose
// @license.name Apache 2.0
// @license.url http://www.apache.org/licenses/LICENSE-2.0.html
// @BasePath /tumblebug
// @securityDefinitions.basic BasicAuth
// @securityDefinitions.apikey Bearer
// @in header
// @name Authorization
// @description Type "Bearer" followed by a space and JWT token ([TBD] Get token in http://xxx.xxx.xxx.xxx:xxx/auth)
func main() {
//Ticker for MCI Orchestration Policy
log.Info().Msg("[Initiate Multi-Cloud Orchestration]")
autoControlDuration, _ := strconv.Atoi(model.AutocontrolDurationMs) //ms
ticker := time.NewTicker(time.Millisecond * time.Duration(autoControlDuration))
go func() {
for t := range ticker.C {
//display ticker if you need (remove '_ = t')
_ = t
//fmt.Println("- Orchestration Controller ", t.Format("2006-01-02 15:04:05"))
infra.OrchestrationController()
}
}()
defer ticker.Stop()
go func() {
viper.WatchConfig()
viper.OnConfigChange(func(e fsnotify.Event) {
log.Info().Msgf("Config file changed: %s", e.Name)
err := viper.ReadInConfig()
if err != nil { // Handle errors reading the config file
log.Error().Err(err).Msg("")
panic(fmt.Errorf("fatal error config file: %w", err))
}
err = viper.Unmarshal(&common.RuntimeConf)
if err != nil {
log.Error().Err(err).Msg("")
panic(err)
}
})
}()
// Launch API servers (REST)
wg := new(sync.WaitGroup)
wg.Add(1)
// Start REST Server
go func() {
restServer.RunServer()
wg.Done()
}()
wg.Wait()
}