-
Notifications
You must be signed in to change notification settings - Fork 11
/
main.go
218 lines (176 loc) · 5.28 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
//go:generate bash -c "mkdir -p codegen && go run github.com/deepmap/oapi-codegen/cmd/[email protected] -generate types,server,spec -package codegen api/message_bus/openapi.yaml > codegen/message_bus_api.go"
package main
import (
"context"
_ "embed"
"flag"
"fmt"
"net"
"net/http"
"net/url"
"os"
"path/filepath"
"strings"
"time"
"github.com/IceWhaleTech/CasaOS-Common/external"
"github.com/IceWhaleTech/CasaOS-Common/model"
"github.com/IceWhaleTech/CasaOS-Common/utils/file"
util_http "github.com/IceWhaleTech/CasaOS-Common/utils/http"
"github.com/IceWhaleTech/CasaOS-Common/utils/logger"
"github.com/IceWhaleTech/CasaOS-MessageBus/codegen"
"github.com/IceWhaleTech/CasaOS-MessageBus/common"
"github.com/IceWhaleTech/CasaOS-MessageBus/config"
"github.com/IceWhaleTech/CasaOS-MessageBus/repository"
"github.com/IceWhaleTech/CasaOS-MessageBus/route"
"github.com/IceWhaleTech/CasaOS-MessageBus/service"
"github.com/coreos/go-systemd/daemon"
"go.uber.org/zap"
)
const localhost = "127.0.0.1"
var (
commit = "private build"
date = "private build"
//go:embed api/index.html
_docHTML string
//go:embed api/message_bus/openapi.yaml
_docYAML string
//go:embed build/sysroot/etc/casaos/message-bus.conf.sample
_confSample string
unixSocketPath = "/tmp/message-bus.sock"
)
func main() {
// arguments
configFlag := flag.String("c", "", "config file path")
versionFlag := flag.Bool("v", false, "version")
flag.Parse()
if *versionFlag {
fmt.Printf("v%s\n", common.MessageBusVersion)
os.Exit(0)
}
println("git commit:", commit)
println("build date:", date)
// initialization
config.InitSetup(*configFlag, _confSample)
logger.LogInit(config.AppInfo.LogPath, config.AppInfo.LogSaveName, config.AppInfo.LogFileExt)
// repository
if err := file.IsNotExistMkDir(config.CommonInfo.RuntimePath); err != nil {
panic(err)
}
databaseFilePath := filepath.Join(config.CommonInfo.RuntimePath, "message-bus.db")
persistDatabaseFilePath := filepath.Join(config.AppInfo.DBPath, "db", "message-bus.db")
repository, err := repository.NewDatabaseRepository(databaseFilePath, persistDatabaseFilePath)
if err != nil {
panic(err)
}
defer repository.Close()
// service
services := service.NewServices(&repository)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
services.Start(&ctx)
go services.YSKService.Start(true)
// route
swagger, err := codegen.GetSwagger()
if err != nil {
panic(err)
}
apiRouter, err := route.NewAPIRouter(swagger, &services)
if err != nil {
panic(err)
}
docRouter, err := route.NewDocRouter(swagger, _docHTML, _docYAML)
if err != nil {
panic(err)
}
mux := &util_http.HandlerMultiplexer{
HandlerMap: map[string]http.Handler{
"v2": apiRouter,
"doc": docRouter,
},
}
// http listener
listener, err := net.Listen("tcp", net.JoinHostPort(localhost, "0"))
if err != nil {
panic(err)
}
// remove unix socket file. don't need check whether it exists or not
os.Remove(unixSocketPath)
// socket listener
socketListener, err := net.Listen("unix", unixSocketPath)
if err != nil {
panic(err)
}
// register at gateway
u, err := url.Parse(swagger.Servers[0].URL)
if err != nil {
panic(err)
}
apiPath := strings.TrimRight(u.Path, "/")
apiPaths := []string{apiPath, "/doc" + apiPath}
gatewayManagement, err := external.NewManagementService(config.CommonInfo.RuntimePath)
if err != nil {
panic(err)
}
for _, apiPath := range apiPaths {
err = gatewayManagement.CreateRoute(&model.Route{
Path: apiPath,
Target: "http://" + listener.Addr().String(),
})
if err != nil {
panic(err)
}
}
// write address file
addressFilePath, err := writeAddressFile(config.CommonInfo.RuntimePath, external.MessageBusAddressFilename, "http://"+listener.Addr().String())
if err != nil {
panic(err)
}
// notify systemd
if supported, err := daemon.SdNotify(false, daemon.SdNotifyReady); err != nil {
logger.Error("Failed to notify systemd that message bus service is ready", zap.Error(err))
} else if supported {
logger.Info("Notified systemd that message bus service is ready")
} else {
logger.Info("This process is not running as a systemd service.")
}
// start http server
logger.Info("MessageBus service is listening...", zap.Any("address", listener.Addr().String()), zap.String("filepath", addressFilePath))
server := &http.Server{
Handler: mux,
ReadHeaderTimeout: 5 * time.Second,
}
socketServer := &http.Server{
Handler: mux,
ReadHeaderTimeout: 5 * time.Second,
}
httpServerErrChan := make(chan error, 1)
socketServerErrChan := make(chan error, 1)
go func() {
err := server.Serve(listener)
httpServerErrChan <- err
}()
go func() {
err := socketServer.Serve(socketListener)
socketServerErrChan <- err
}()
select {
case err := <-httpServerErrChan:
if err != nil {
logger.Info("MessageBus service is stopped", zap.Error(err))
panic(err)
}
case err := <-socketServerErrChan:
if err != nil {
logger.Info("MessageBus socket service is stopped", zap.Error(err))
panic(err)
}
}
}
func writeAddressFile(runtimePath string, filename string, address string) (string, error) {
err := os.MkdirAll(runtimePath, 0o755)
if err != nil {
return "", err
}
filepath := filepath.Join(runtimePath, filename)
return filepath, os.WriteFile(filepath, []byte(address), 0o600)
}