-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
107 lines (90 loc) · 2.47 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
package main
import (
"fmt"
"math/rand"
"net"
"net/http"
"os"
"time"
"github.com/iver-wharf/wharf-core/pkg/cacertutil"
"github.com/iver-wharf/wharf-core/pkg/logger"
"github.com/iver-wharf/wharf-core/pkg/logger/consolepretty"
"github.com/soheilhy/cmux"
"gorm.io/gorm"
"github.com/iver-wharf/wharf-api/v5/docs"
)
var log = logger.NewScoped("WHARF")
// @title Wharf main API
// @description Wharf backend API that manages data storage for projects,
// @description builds, providers, etc.
// @license.name MIT
// @license.url https://github.com/iver-wharf/wharf-api/blob/master/LICENSE
// @contact.name Iver Wharf API support
// @contact.url https://github.com/iver-wharf/wharf-api/issues
// @contact.email wharf@iver.se
// @basePath /api
// @query.collection.format multi
func main() {
logger.AddOutput(logger.LevelDebug, consolepretty.Default)
var (
config Config
err error
)
if err = loadEmbeddedVersionFile(); err != nil {
log.Error().WithError(err).Message("Failed to read embedded version.yaml file.")
os.Exit(1)
}
if config, err = loadConfig(); err != nil {
fmt.Println("Failed to read config:", err)
os.Exit(1)
}
docs.SwaggerInfo.Version = AppVersion.Version
if config.CA.CertsFile != "" {
client, err := cacertutil.NewHTTPClientWithCerts(config.CA.CertsFile)
if err != nil {
log.Error().WithError(err).Message("Failed to get net/http.Client with certs")
os.Exit(1)
}
http.DefaultClient = client
}
seed()
db := setupDB(config.DB)
if err := serve(config, db); err != nil {
log.Error().WithError(err).
WithString("address", config.HTTP.BindAddress).
Message("Failed to serve API.")
os.Exit(1)
}
}
func serve(config Config, db *gorm.DB) error {
listener, err := net.Listen("tcp", config.HTTP.BindAddress)
if err != nil {
return err
}
mux := cmux.New(listener)
grpcListener := mux.MatchWithWriters(
cmux.HTTP2MatchHeaderFieldSendSettings("content-type", "application/grpc"))
httpListener := mux.Match(cmux.Any())
go serveGRPC(grpcListener, db)
go serveHTTP(httpListener, config, db)
return mux.Serve()
}
func setupDB(dbConfig DBConfig) *gorm.DB {
db, err := openDatabase(dbConfig)
if err != nil {
log.Error().
WithString("driver", string(dbConfig.Driver)).
WithError(err).
Message("Database error")
os.Exit(2)
}
err = runDatabaseMigrations(db, dbConfig.Driver)
if err != nil {
log.Error().WithError(err).Message("Migration error")
os.Exit(3)
}
return db
}
func seed() {
rand.Seed(time.Now().UTC().UnixNano())
}