-
-
Notifications
You must be signed in to change notification settings - Fork 117
Expand file tree
/
Copy pathmain.go
More file actions
719 lines (603 loc) · 23.2 KB
/
main.go
File metadata and controls
719 lines (603 loc) · 23.2 KB
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
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
package main
import (
"context"
"crypto/tls"
"errors"
"flag"
"fmt"
"github.com/buraksezer/olric"
olricConfig "github.com/buraksezer/olric/config"
"github.com/daptin/daptin/server/auth"
"github.com/daptin/daptin/server/hostswitch"
daptinid "github.com/daptin/daptin/server/id"
"github.com/daptin/daptin/server/task_scheduler"
server2 "github.com/fclairamb/ftpserver/server"
"github.com/go-redis/redis/v8"
jsoniter "github.com/json-iterator/go"
"gopkg.in/natefinch/lumberjack.v2"
"io"
"net"
"net/url"
"path/filepath"
"runtime"
"runtime/pprof"
"strconv"
"strings"
"sync"
"time"
"github.com/GeertJohan/go.rice"
"github.com/artpar/go-guerrilla"
imapServer "github.com/artpar/go-imap/server"
"github.com/daptin/daptin/server"
"github.com/daptin/daptin/server/resource"
"github.com/daptin/daptin/server/statementbuilder"
"github.com/gin-gonic/gin"
"github.com/gocraft/health"
"github.com/jamiealquiza/envy"
"github.com/sadlil/go-trigger"
log "github.com/sirupsen/logrus"
//"io"
"net/http"
"os"
"syscall"
)
// Save the stream as a global variable
var stream = health.NewStream()
var errOlricReadyTimeout = errors.New("olric readiness callback timeout")
func waitForOlricReady(ready <-chan struct{}, startErr <-chan error, timeout time.Duration) error {
timer := time.NewTimer(timeout)
defer timer.Stop()
select {
case <-ready:
return nil
case err := <-startErr:
return err
case <-timer.C:
return errOlricReadyTimeout
}
}
func init() {
goMaxProcs, ok := os.LookupEnv("DAPTIN_GOMAXPROCS")
if !ok || goMaxProcs == "" {
goMaxProcs = "0"
}
goMaxProcsInt, err := strconv.ParseInt(goMaxProcs, 10, 64)
if err != nil {
goMaxProcsInt = 0
}
log.SetFormatter(&log.TextFormatter{
ForceColors: true,
DisableColors: false,
ForceQuote: false,
DisableQuote: false,
EnvironmentOverrideColors: false,
DisableTimestamp: false,
FullTimestamp: true,
TimestampFormat: "2006-01-02 15:04:05",
DisableSorting: false,
SortingFunc: nil,
DisableLevelTruncation: false,
PadLevelText: false,
QuoteEmptyFields: false,
FieldMap: nil,
CallerPrettyfier: nil,
})
jsoniter.RegisterTypeEncoder("daptinid.DaptinReferenceId", &daptinid.DaptinReferenceEncoder{})
log.Debugf("Go Max Procs: %v, Default value was [%v]", goMaxProcsInt, runtime.NumCPU())
runtime.GOMAXPROCS(int(goMaxProcsInt))
// manually set time zone
if tz := os.Getenv("TZ"); tz != "" {
var err error
log.Infof("Setting timezone: %v", tz)
time.Local, err = time.LoadLocation(tz)
if err != nil {
log.Printf("error loading timezone location '%s': %v\n", tz, err)
}
} else {
log.Infof("Setting timezone to UTC since no TZ env variable set")
}
logFileLocation, ok := os.LookupEnv("DAPTIN_LOG_LOCATION")
if !ok || logFileLocation == "" {
return
}
hostname, _ := os.Hostname()
processId := fmt.Sprintf("%v", os.Getpid())
logFileLocation = strings.ReplaceAll(logFileLocation, "${HOSTNAME}", hostname)
logFileLocation = strings.ReplaceAll(logFileLocation, "${PID}", processId)
maxLogFileSize, ok := os.LookupEnv("DAPTIN_LOG_MAX_SIZE")
if !ok {
maxLogFileSize = "10"
}
maxLogFileBackups, ok := os.LookupEnv("DAPTIN_LOG_MAX_BACKUPS")
if !ok {
maxLogFileBackups = "10"
}
maxLogFileAge, ok := os.LookupEnv("DAPTIN_LOG_MAX_AGE")
if !ok {
maxLogFileAge = "7"
}
maxLogFileSizeInt, err := strconv.ParseInt(maxLogFileSize, 10, strconv.IntSize)
if err != nil {
log.Fatalf("invalid max log file size: %v => %v", maxLogFileSize, err)
}
maxLogFileBackupsInt, err := strconv.ParseInt(maxLogFileBackups, 10, strconv.IntSize)
if err != nil {
log.Fatalf("invalid max log file backups: %v => %v", maxLogFileBackups, err)
}
maxLogFileAgeInt, err := strconv.ParseInt(maxLogFileAge, 10, strconv.IntSize)
if err != nil {
log.Fatalf("invalid max log file age: %v => %v", maxLogFileAge, err)
}
lumberjackLogger := &lumberjack.Logger{
// Log file absolute path, os agnostic
Filename: filepath.ToSlash(logFileLocation),
MaxSize: int(maxLogFileSizeInt), // MB
MaxBackups: int(maxLogFileBackupsInt),
MaxAge: int(maxLogFileAgeInt), // days
LocalTime: true,
Compress: false, // disabled by default
}
mwriter := io.MultiWriter(lumberjackLogger, os.Stdout)
log.SetOutput(mwriter)
gin.DefaultWriter = mwriter
gin.DefaultErrorWriter = mwriter
}
// Following variables will be statically linked at the time of compiling
// GitCommit holds short commit hash of source tree
var GitCommit string
// GitBranch holds current branch name the code is built off
var GitBranch string
// GitState shows whether there are uncommitted changes
var GitState string
// GitSummary holds output of git describe --tags --dirty --always
var GitSummary string
// BuildDate holds RFC3339 formatted UTC date (build time)
var BuildDate string
// Version holds contents of ./VERSION file, if exists, or the value passed via the -version option
var Version string
func printVersion() {
fmt.Printf(`
GitCommit: %s
GitBranch: %s
GitState: %s
GitSummary: %s
BuildDate: %s
Version: %s
`, GitCommit, GitBranch, GitState, GitSummary, BuildDate, Version)
}
func main() {
restartLock := sync.Mutex{}
//eventEmitter := &emitter.Emitter{}
var dbType = flag.String("db_type", "sqlite3", "Database to use: sqlite3/mysql/postgres")
var localStoragePath = flag.String("local_storage_path", "./storage", "Path where blob column assets will be stored, set to ; to disable")
var connectionString = flag.String("db_connection_string", "daptin.db", "\n\tSQLite: test.db\n"+
"\tMySql: <username>:<password>@tcp(<hostname>:<port>)/<db_name>\n"+
"\tPostgres: host=<hostname> port=<port> user=<username> password=<password> dbname=<db_name> sslmode=enable/disable")
var webDashboardSource = flag.String("dashboard", "daptinweb", "path to dist folder for daptin web dashboard")
//var assetsSource = flag.String("assets", "assets", "path to folder for assets")
var port_variable = flag.String("port_variable", "DAPTIN_PORT", "ENV port variable name to look for port")
var database_url_variable = flag.String("database_url_variable", "DAPTIN_DB_CONNECTION_STRING", "ENV port variable name to look for connection string")
var port = flag.String("port", ":6336", "daptin port")
var httpsPort = flag.String("https_port", ":6443", "daptin https port")
var runtimeMode = flag.String("runtime", "release", "Runtime for Gin: profile, debug, test, release")
var logLevel = flag.String("log_level", "info", "log level : debug, trace, info, warn, error, fatal")
var profileDumpPath = flag.String("profile_dump_path", "./", "location for dumping cpu/heap data in profile mode")
var profileDumpPeriod = flag.Int("profile_dump_period", 5, "time period in minutes for triggering profile dump")
var olricPeers = flag.String("olric_peers", "", "list of olric peers, comma separated in ip:membership_port")
var olricPort = flag.Int("olric_port", 0, "base port for olric cache (membership = olric_port+1). Default: auto-derived from HTTP port")
var olricSeed = flag.String("olric_seed", "", "hostname to resolve for cluster peer discovery (e.g., daptin-headless.default.svc.cluster.local)")
var olricConfigEnv = flag.String("olric_env", "local", "env value for olric: local/lan/wan, default: lan")
envy.Parse("DAPTIN") // looks for DAPTIN_PORT, DAPTIN_DASHBOARD, DAPTIN_DB_TYPE, DAPTIN_RUNTIME
flag.Parse()
printVersion()
logLevelParsed, err := log.ParseLevel(*logLevel)
if err != nil {
log.Errorf("invalid log level: %s, setting to info", *logLevel)
logLevelParsed = log.InfoLevel
}
log.Infof("Runtime is [%s], logLevel: [%s]", *runtimeMode, *logLevel)
log.SetLevel(logLevelParsed)
profileDumpCount := 0
if *runtimeMode == "profile" {
gin.SetMode("release")
log.Infof("Dumping CPU/Heap Profile at %s every %v Minutes", *profileDumpPath, *profileDumpPeriod)
hostname, _ := os.Hostname()
cpuprofile := fmt.Sprintf("%sdaptin_%s_profile_cpu.%v", *profileDumpPath, hostname, profileDumpCount)
heapprofile := fmt.Sprintf("%sdaptin_%s_profile_heap.%v", *profileDumpPath, hostname, profileDumpCount)
log.Infof("Dumping CPU/Heap Profile at %s, %s", cpuprofile, heapprofile)
cpuFile, err1 := os.Create(cpuprofile)
heapFile, err2 := os.Create(heapprofile)
if err1 != nil || err2 != nil {
log.Errorf("Failed to create file for profile dump: %v - %v", err1, err2)
} else {
var err error
err = pprof.StartCPUProfile(cpuFile)
auth.CheckErr(err, "Failed to start CPU profile: %v", err)
err = pprof.WriteHeapProfile(heapFile)
auth.CheckErr(err, "Failed to start HEAP profile: %v", err)
}
} else {
gin.SetMode(*runtimeMode)
}
stream.AddSink(&health.WriterSink{
Writer: os.Stdout,
})
boxRoot1, err := rice.FindBox("daptinweb")
var boxRoot http.FileSystem
if err != nil || (webDashboardSource != nil && *webDashboardSource != "daptinweb") {
log.Tracef("Dashboard not loading from default path: %v == %v", err, boxRoot1)
log.Infof("Try loading web dashboard from: %v", *webDashboardSource)
boxRoot = http.Dir(*webDashboardSource)
} else {
boxRoot = boxRoot1.HTTPBox()
}
if database_url_variable != nil && *database_url_variable != "DAPTIN_DB_CONNECTION_STRING" {
databaseUrlValue, ok := os.LookupEnv(*database_url_variable)
if ok && len(databaseUrlValue) > 0 {
if strings.Index(databaseUrlValue, "://") > -1 {
log.Printf("connection URL found for database in env variable [%v]", *database_url_variable)
databaseUrlParsed, err := url.Parse(databaseUrlValue)
if err != nil {
log.Printf("Unable to parse database variable value as url, passing it as it is")
connectionString = &databaseUrlValue
} else {
password, _ := databaseUrlParsed.User.Password()
databaseName := strings.Split(databaseUrlParsed.Path, "/")[1]
switch databaseUrlParsed.Scheme {
case "postgresql":
fallthrough
case "postgres":
x := fmt.Sprintf("host=%s port=%s user=%s password=%s dbname=%s sslmode=disable",
databaseUrlParsed.Hostname(), databaseUrlParsed.Port(), databaseUrlParsed.User.Username(), password, databaseName)
connectionString = &x
case "mysql":
x := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s",
databaseUrlParsed.User.Username(), password, databaseUrlParsed.Hostname(), databaseUrlParsed.Port(), databaseName)
connectionString = &x
default:
connectionString = &databaseUrlValue
}
}
} else {
connectionString = &databaseUrlValue
}
if *dbType == "" {
if strings.Index(*connectionString, "dbname=") > -1 {
*dbType = "postgres"
} else if strings.Index(*connectionString, "@tcp") > -1 {
*dbType = "mysql"
}
}
}
}
statementbuilder.InitialiseStatementBuilder(*dbType)
auth.PrepareAuthQueries()
log.Printf("Database connection using: [%v] [%v]", *dbType, *connectionString)
db, err := server.GetDbConnection(*dbType, *connectionString)
if err != nil {
panic(err)
}
db.Stats()
transaction := db.MustBegin()
_ = transaction.Rollback()
log.Printf("connection acquired from database [%s]", *dbType)
portValue := *port
portInt := int64(6336)
if strings.Index(portValue, ".") > -1 {
// port has ip and nothing to do
// get the port from the value, ip:port
portInt, err = strconv.ParseInt(strings.Split(portValue, ":")[1], 10, 32)
if err != nil {
portInt = 6336
}
} else if portValue[0] != ':' {
// port is missing :
portInt, err = strconv.ParseInt(portValue, 10, 32)
portValue = ":" + portValue
}
var hostSwitch hostswitch.HostSwitch
var mailDaemon *guerrilla.Daemon
var taskScheduler task_scheduler.TaskScheduler
var certManager *resource.CertificateManager
var configStore *resource.ConfigStore
var ftpServer *server2.FtpServer
var imapServerInstance *imapServer.Server
var olricDb *olric.EmbeddedClient
if localStoragePath != nil && *localStoragePath != "" {
if _, err := os.Stat(*localStoragePath); err == os.ErrNotExist {
_ = os.Mkdir(*localStoragePath, 0644)
}
}
olricPortValue := *olricPort
if olricPortValue == 0 {
if portInt > 2000 {
olricPortValue = int(portInt - 1000)
} else {
olricPortValue = int(portInt + 1000)
}
}
membershipPort := olricPortValue + 1
olricConfigEnvValue := *olricConfigEnv
olricConfig1 := olricConfig.New(olricConfigEnvValue)
err = olricConfig1.SetupNetworkConfig()
olricConfig1.BindPort = olricPortValue
// MemberlistConfig is already set by olricConfig.New(env) with the correct
// local/lan/wan settings. Do NOT overwrite it with memberlist.DefaultLocalConfig().
olricConfig1.MemberlistConfig.Name = fmt.Sprintf("%v:%v", olricConfig1.MemberlistConfig.BindAddr, olricConfig1.BindPort)
olricConfig1.ReplicaCount = 1
olricConfig1.WriteQuorum = 1
olricConfig1.ReadQuorum = 1
olricConfig1.PartitionCount = 23
olricConfig1.LogLevel = "INFO"
olricConfig1.LogVerbosity = 1
if len(*olricPeers) > 0 {
olricConfig1.Peers = strings.Split(*olricPeers, ",")
}
olricConfig1.LogOutput = os.Stdout
olricConfig1.MemberlistConfig.BindPort = membershipPort
olricReady := make(chan struct{})
var olricReadyOnce sync.Once
olricConfig1.Started = func() {
olricReadyOnce.Do(func() {
close(olricReady)
})
}
// Compute self address before peer resolution so we can filter it out
selfAddr := net.JoinHostPort(olricConfig1.MemberlistConfig.BindAddr, strconv.Itoa(membershipPort))
// Resolve DNS seed to peer addresses
if len(*olricSeed) > 0 {
seedPeers := resolveOlricPeers(*olricSeed, membershipPort, selfAddr)
olricConfig1.Peers = append(olricConfig1.Peers, seedPeers...)
}
// Filter out self from static peers list
var filteredPeers []string
for _, peer := range olricConfig1.Peers {
if peer != selfAddr {
filteredPeers = append(filteredPeers, peer)
}
}
olricConfig1.Peers = filteredPeers
log.Infof("Olric: port=%d, membership=%d, env=%s, peers=%v", olricPortValue, membershipPort, olricConfigEnvValue, olricConfig1.Peers)
emb, err := olric.New(olricConfig1)
if err != nil {
fmt.Printf("Failed to create olric cache: %v", err)
}
// Start Olric and wait for its readiness callback. Start is a blocking
// lifecycle call and should only return on error or shutdown.
olricStartErr := make(chan error, 1)
go func() {
if startErr := emb.Start(); startErr != nil {
resource.CheckErr(startErr, "failed to start cache server")
olricStartErr <- startErr
}
}()
// Keep the previous bounded startup behavior, but use Olric's readiness
// signal instead of waiting for Start to return.
if startErr := waitForOlricReady(olricReady, olricStartErr, 10*time.Second); startErr == nil {
log.Infof("Olric started successfully")
} else if errors.Is(startErr, errOlricReadyTimeout) {
log.Warnf("Olric readiness callback timeout, proceeding anyway")
} else {
resource.CheckErr(startErr, "failed to start cache server before readiness")
}
olricDb = emb.NewEmbeddedClient()
localOlricAddr := olricConfig1.MemberlistConfig.Name
log.Infof("PubSub pinned to local Olric: %s", localOlricAddr)
var membersTopic *olric.PubSub
go func() {
time.Sleep(5 * time.Second)
membersTopic, err := olricDb.NewPubSub(olric.ToAddress(localOlricAddr))
if err != nil || membersTopic == nil {
log.Errorf("failed to create PubSub, skipping member subscription: %v", err)
return
}
sub := membersTopic.Subscribe(context.Background(), "members")
go func(pubsub *redis.PubSub) {
channel := pubsub.Channel()
for msg := range channel {
log.Printf("[402] [%s] Member says: [%v]", msg.Channel, msg.String())
}
}(sub)
resource.CheckErr(err, "Failed to add listener to _members topic")
_, err = membersTopic.Publish(context.Background(), "members",
fmt.Sprintf("Joining from %v", olricConfig1.MemberlistConfig.Name))
resource.CheckErr(err, "Failed to publish message at _members topic")
}()
hostSwitch, mailDaemon, taskScheduler, configStore, certManager,
ftpServer, imapServerInstance, olricDb = server.Main(boxRoot, db, *localStoragePath, olricDb, localOlricAddr)
rhs := RestartHandlerServer{
HostSwitch: &hostSwitch,
}
if *runtimeMode == "profile" {
go func() {
for {
time.Sleep(time.Duration(*profileDumpPeriod) * time.Minute)
profileDumpCount += 1
pprof.StopCPUProfile()
hostname, _ := os.Hostname()
cpuprofile := fmt.Sprintf("%sdaptin_%s_profile_cpu.%v", *profileDumpPath, hostname, profileDumpCount)
heapprofile := fmt.Sprintf("%sdaptin_%s_profile_heap.%v", *profileDumpPath, hostname, profileDumpCount)
log.Infof("Dumping cpu and heap profile at %s, %s", cpuprofile, heapprofile)
cpuFile, err := os.Create(cpuprofile)
heapFile, err := os.Create(heapprofile)
if err != nil {
log.Errorf("Failed to create file [%v] for profile dump: %v", cpuprofile, err)
} else {
err = pprof.StartCPUProfile(cpuFile)
auth.CheckErr(err, "Failed to start CPU profile: %v", err)
err = pprof.WriteHeapProfile(heapFile)
auth.CheckErr(err, "Failed to start HEAP profile: %v", err)
}
}
}()
}
err = trigger.On("restart", func() {
log.Printf("Trigger restart")
restartLock.Lock()
defer restartLock.Unlock()
if membersTopic != nil {
membersTopic.Publish(context.Background(), "members",
fmt.Sprintf("I need to restart: %v", olricConfig1.MemberlistConfig.Name))
}
startTime := time.Now()
log.Printf("Close down services and db connection")
taskScheduler.StopTasks()
if ftpServer != nil {
ftpServer.Stop()
}
if mailDaemon != nil {
mailDaemon.Shutdown()
}
if imapServerInstance != nil {
err = imapServerInstance.Close()
if err != nil {
log.Printf("Failed to close imap server connections: %v", err)
}
}
//err = db.Close()
//resource.CheckErr(err, "Failed to close database connection")
log.Printf("All connections closed")
log.Printf("Create new connections")
//db1, err := server.GetDbConnection(*dbType, *connectionString)
//auth.CheckErr(err, "Failed to create new db connection")
//if err != nil {
// return
//}
//transaction := db1.MustBegin()
//_ = transaction.Rollback()
log.Printf("connection acquired from database [%s]", *dbType)
hostSwitch, mailDaemon, taskScheduler, configStore, certManager,
ftpServer, imapServerInstance, olricDb = server.Main(boxRoot, db, *localStoragePath, olricDb, localOlricAddr)
rhs.HostSwitch = &hostSwitch
secondsToRestart := float64(time.Now().UnixNano()-startTime.UnixNano()) / float64(1000000000)
log.Printf("Restart complete, took %f seconds", secondsToRestart)
if membersTopic != nil {
membersTopic.Publish(context.Background(), "members",
fmt.Sprintf("I am back: %v, took me [%v] seconds to restart", olricConfig1.MemberlistConfig.Name, secondsToRestart))
}
})
resource.CheckErr(err, "Error while adding restart trigger function")
if port_variable != nil && *port_variable != "DAPTIN_PORT" {
portVarString := *port_variable
portVarStringValue, ok := os.LookupEnv(portVarString)
log.Infof("Looking up variable [%s] for port: %v", portVarString, portVarStringValue)
if ok && len(portVarStringValue) > 0 {
if portVarStringValue[0] != ':' {
log.Infof("Port value picked from env is missing colon: %v", portVarStringValue)
portVarStringValue = ":" + portVarStringValue
}
portValue = portVarStringValue
}
}
log.Infof("[ProcessId=%v] Listening at port: %v", syscall.Getpid(), portValue)
transaction, err = db.Beginx()
resource.CheckErr(err, "Failed to begin transaction")
enableHttps, err := configStore.GetConfigValueFor("enable_https", "backend", transaction)
if err != nil {
enableHttps = "false"
_ = configStore.SetConfigValueFor("enable_https", enableHttps, "backend", transaction)
}
hostname, err := configStore.GetConfigValueFor("hostname", "backend", transaction)
backendHostnameCertificate, err := certManager.GetTLSConfig(hostname, true, transaction)
subsitesCertificateMap, err := certManager.GetTLSForEnabledSubsites(transaction)
transaction.Commit()
if err == nil && enableHttps == "true" {
go func() {
keyPairMap := make(map[string]tls.Certificate)
backendCertKeyPair, err := CreateKeyPairFromTLSCertificate(backendHostnameCertificate)
if err != nil {
panic(err)
}
keyPairMap[hostname] = backendCertKeyPair
for subsiteHostname, subsiteCertificate := range subsitesCertificateMap {
certKeyPair, err := CreateKeyPairFromTLSCertificate(subsiteCertificate)
if err != nil {
log.Errorf("Failed to create key pair for subsite [%v]: %v", subsiteHostname, err)
continue
}
keyPairMap[subsiteHostname] = certKeyPair
}
tlsServer := &http.Server{
Addr: *httpsPort,
Handler: &rhs,
TLSConfig: &tls.Config{
GetCertificate: func(info *tls.ClientHelloInfo) (*tls.Certificate, error) {
cert, ok := keyPairMap[info.ServerName]
if ok {
return &cert, nil
}
return nil, fmt.Errorf("certificate not found for hostname [%v]", info.ServerName)
},
},
}
log.Infof("TLS server listening on port %v", *httpsPort)
err1 := tlsServer.ListenAndServeTLS("", "")
if err1 != nil {
log.Errorf("Failed to start TLS server: %v", err1)
}
}()
} else {
log.Warnf("Not starting HTTPS server: %v: %v", hostname, err)
}
log.Infof("Listening at: [%v]", portValue)
err = http.ListenAndServe(portValue, &rhs)
if err != nil {
panic(err)
}
if membersTopic != nil {
membersTopic.Publish(context.Background(), "members",
fmt.Sprintf("I am shutting down: %v", olricConfig1.MemberlistConfig.Name))
}
log.Printf("Why quit now ?")
}
// resolveOlricPeers resolves a DNS hostname to olric peer addresses.
// It retries up to 3 times with 2s delay for environments where DNS
// propagates slowly (K8s headless services, Docker Compose scaling).
func resolveOlricPeers(seed string, membershipPort int, selfAddr string) []string {
const maxRetries = 3
const retryDelay = 2 * time.Second
for attempt := 1; attempt <= maxRetries; attempt++ {
ips, err := net.LookupHost(seed)
if err != nil {
if attempt < maxRetries {
log.Warnf("Failed to resolve olric seed %q (attempt %d/%d): %v, retrying...", seed, attempt, maxRetries, err)
time.Sleep(retryDelay)
continue
}
log.Warnf("Failed to resolve olric seed %q after %d attempts: %v", seed, maxRetries, err)
return nil
}
var peers []string
for _, ip := range ips {
addr := net.JoinHostPort(ip, strconv.Itoa(membershipPort))
if addr != selfAddr {
peers = append(peers, addr)
}
}
if len(peers) == 0 && attempt < maxRetries {
log.Warnf("Olric seed %q resolved but no peers after self-filter (attempt %d/%d), retrying...", seed, attempt, maxRetries)
time.Sleep(retryDelay)
continue
}
log.Infof("Resolved olric seed %q to peers: %v", seed, peers)
return peers
}
return nil
}
func CreateKeyPairFromTLSCertificate(backendHostnameCertificate *resource.TLSCertificate) (tls.Certificate, error) {
certPem := append(backendHostnameCertificate.CertPEM, '\n')
certPem = append(certPem, backendHostnameCertificate.RootCert...)
keyPem := backendHostnameCertificate.PrivatePEMDecrypted
backendCertKeyPair, err := tls.X509KeyPair(certPem, keyPem)
if err != nil {
return tls.Certificate{}, err
}
return backendCertKeyPair, nil
}
// RestartHandlerServer helps in switching the new router with old router with restart is triggered
type RestartHandlerServer struct {
HostSwitch *hostswitch.HostSwitch
}
func (rhs *RestartHandlerServer) ServeHTTP(rew http.ResponseWriter, req *http.Request) {
rhs.HostSwitch.ServeHTTP(rew, req)
}