-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
221 lines (186 loc) · 5.26 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
package main
import (
"context"
"encoding/hex"
"flag"
"fmt"
"io/ioutil"
"net/http"
"os"
"os/signal"
"strings"
"syscall"
"time"
"github.com/RichardKnop/machinery/v1"
machinerycnf "github.com/RichardKnop/machinery/v1/config"
"github.com/aws/aws-sdk-go/aws"
"github.com/dgrijalva/jwt-go"
"github.com/getsentry/sentry-go"
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/postgres"
log "github.com/sirupsen/logrus"
"github.com/spf13/viper"
prefixed "github.com/x-cray/logrus-prefixed-formatter"
bitmarksdk "github.com/bitmark-inc/bitmark-sdk-go"
"github.com/bitmark-inc/bitmark-sdk-go/account"
"github.com/bitmark-inc/spring-app-api/api"
"github.com/bitmark-inc/spring-app-api/logmodule"
"github.com/bitmark-inc/spring-app-api/store"
"github.com/bitmark-inc/spring-app-api/store/dynamodb"
"github.com/bitmark-inc/spring-app-api/store/postgres"
)
var (
server *api.Server
s store.Store
)
func initLog() {
// Log
logLevel, err := log.ParseLevel(viper.GetString("log.level"))
if err != nil {
log.SetLevel(log.DebugLevel)
} else {
log.SetLevel(logLevel)
}
log.SetOutput(os.Stdout)
log.SetFormatter(&prefixed.TextFormatter{
ForceFormatting: true,
FullTimestamp: true,
})
}
func loadConfig(file string) {
// Config from file
viper.SetConfigType("yaml")
if file != "" {
viper.SetConfigFile(file)
}
viper.AddConfigPath("/.config/")
viper.AddConfigPath(".")
err := viper.ReadInConfig()
if err != nil {
fmt.Println("No config file. Read config from env.")
viper.AllowEmptyEnv(false)
}
// Config from env if possible
viper.AutomaticEnv()
viper.SetEnvPrefix("fbm")
viper.SetEnvKeyReplacer(strings.NewReplacer(".", "_"))
}
func main() {
var configFile string
initialCtx, cancelInitialization := context.WithCancel(context.Background())
c := make(chan os.Signal, 2)
signal.Notify(c, os.Interrupt, syscall.SIGTERM)
go func() {
<-c
log.Info("Server is preparing to shutdown")
if initialCtx != nil && cancelInitialization != nil {
log.Info("Cancelling initialization")
cancelInitialization()
<-initialCtx.Done()
}
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
if server != nil {
log.Info("Shutdown mobile api server")
if err := server.Shutdown(ctx); err != nil {
log.Error("Server Shutdown:", err)
}
}
if s != nil {
log.Info("Shuting down db store")
if err := s.Close(ctx); err != nil {
log.Error(err)
}
}
os.Exit(1)
}()
flag.StringVar(&configFile, "c", "./config.yaml", "[optional] path of configuration file")
flag.Parse()
loadConfig(configFile)
initLog()
httpClient := &http.Client{
Timeout: 10 * time.Second,
}
// Sentry
if err := sentry.Init(sentry.ClientOptions{
Dsn: viper.GetString("sentry.dsn"),
AttachStacktrace: true,
Environment: viper.GetString("sentry.environment"),
Dist: viper.GetString("sentry.dist"),
}); err != nil {
log.Error(err)
}
log.WithField("prefix", "init").Info("Initilized sentry")
// Init Bitmark SDK
bitmarksdk.Init(&bitmarksdk.Config{
Network: bitmarksdk.Network(viper.GetString("bitmarksdk.network")),
APIToken: viper.GetString("bitmarksdk.token"),
HTTPClient: httpClient,
})
log.WithField("prefix", "init").Info("Initilized bitmark sdk")
// Load global bitmark account
a, err := account.FromSeed(viper.GetString("account.seed"))
if err != nil {
log.Panic(err)
}
globalAccount := a.(*account.AccountV2)
log.WithField("prefix", "init").Info("Global account: ", globalAccount.AccountNumber())
log.WithField("prefix", "init").Info("Global enc pub key: ", hex.EncodeToString(globalAccount.EncrKey.PublicKeyBytes()))
// Init AWS SDK
awsLogLevel := aws.LogDebugWithRequestErrors
awsConf := &aws.Config{
Region: aws.String(viper.GetString("aws.region")),
Logger: &logmodule.AWSLog{},
LogLevel: &awsLogLevel,
HTTPClient: httpClient,
}
log.WithField("prefix", "init").Info("Initilized aws sdk")
// Load JWT private key
jwtSecretByte, err := ioutil.ReadFile(viper.GetString("jwt.keyfile"))
if err != nil {
log.Panic(err)
}
jwtPrivateKey, err := jwt.ParseRSAPrivateKeyFromPEMWithPassword(jwtSecretByte, viper.GetString("jwt.password"))
if err != nil {
log.Panic(err)
}
log.WithField("prefix", "init").Info("Loaded global jwt key")
// Init db
pgstore, err := postgres.NewPGStore(initialCtx)
if err != nil {
log.Panic(err)
}
s = pgstore
log.WithField("prefix", "init").Info("Initilized db store")
// Init redis
var cnf = &machinerycnf.Config{
Broker: viper.GetString("redis.conn"),
DefaultQueue: "fbm_background",
ResultBackend: viper.GetString("redis.conn"),
}
machineryServer, err := machinery.NewServer(cnf)
if err != nil {
log.Panic(err)
}
dynamodbStore, err := dynamodb.NewDynamoDBStore(awsConf, viper.GetString("aws.dynamodb.table"))
if err != nil {
log.Panic(err)
}
ormDB, err := gorm.Open("postgres", viper.GetString("orm.conn"))
if err != nil {
log.Panic(err)
}
// Init http server
server = api.NewServer(s,
dynamodbStore,
ormDB,
jwtPrivateKey,
awsConf,
globalAccount,
machineryServer)
log.WithField("prefix", "init").Info("Initilized http server")
// Remove initial context
initialCtx = nil
cancelInitialization = nil
log.Fatal(server.Run(":" + viper.GetString("server.port")))
}