This repository has been archived by the owner on Apr 4, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 4
/
main.go
271 lines (235 loc) · 7.97 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
// Copyright 2014-2016 Fraunhofer Institute for Applied Information Technology FIT
package main
import (
"flag"
"fmt"
"log"
"net"
"net/http"
"os"
"os/signal"
"syscall"
"github.com/codegangsta/negroni"
"github.com/gorilla/context"
"github.com/justinas/alice"
_ "github.com/linksmart/go-sec/auth/keycloak/obtainer"
_ "github.com/linksmart/go-sec/auth/keycloak/validator"
"github.com/linksmart/go-sec/auth/validator"
"github.com/linksmart/thing-directory/catalog"
"github.com/linksmart/thing-directory/notification"
"github.com/linksmart/thing-directory/wot"
"github.com/rs/cors"
uuid "github.com/satori/go.uuid"
)
const LINKSMART = `
╦ ╦ ╔╗╔ ╦╔═ ╔═╗ ╔╦╗ ╔═╗ ╦═╗ ╔╦╗
║ ║ ║║║ ╠╩╗ ╚═╗ ║║║ ╠═╣ ╠╦╝ ║
╩═╝ ╩ ╝╚╝ ╩ ╩ ╚═╝ ╩ ╩ ╩ ╩ ╩╚═ ╩
`
const (
SwaggerUISchemeLess = "linksmart.github.io/swagger-ui/dist"
Spec = "https://raw.githubusercontent.com/linksmart/thing-directory/{version}/apidoc/openapi-spec.yml"
SourceCodeRepo = "https://github.com/linksmart/thing-directory"
)
var (
confPath = flag.String("conf", "conf/thing-directory.json", "Configuration file path")
version = flag.Bool("version", false, "Print the API version")
Version string // set with build flags
BuildNumber string // set with build flags
)
func main() {
flag.Parse()
if *version {
fmt.Println(Version)
return
}
fmt.Print(LINKSMART)
log.Printf("Starting Thing Directory")
defer log.Println("Stopped.")
if Version != "" {
log.Printf("Version: %s", Version)
}
if BuildNumber != "" {
log.Printf("Build Number: %s", BuildNumber)
}
config, err := loadConfig(*confPath)
if err != nil {
panic("Error reading config file:" + err.Error())
}
log.Printf("Loaded config file: %s", *confPath)
if config.ServiceID == "" {
config.ServiceID = uuid.NewV4().String()
log.Printf("Service ID not set. Generated new UUID: %s", config.ServiceID)
}
if len(config.Validation.JSONSchemas) > 0 {
err = wot.LoadJSONSchemas(config.Validation.JSONSchemas)
if err != nil {
panic("error loading validation JSON Schemas: " + err.Error())
}
log.Printf("Loaded JSON Schemas: %v", config.Validation.JSONSchemas)
} else {
log.Printf("Warning: No configuration for JSON Schemas. TDs will not be validated.")
}
// Setup API storage
var storage catalog.Storage
switch config.Storage.Type {
case catalog.BackendLevelDB:
storage, err = catalog.NewLevelDBStorage(config.Storage.DSN, nil)
if err != nil {
panic("Failed to start LevelDB storage:" + err.Error())
}
defer storage.Close()
default:
panic("Could not create catalog API storage. Unsupported type:" + config.Storage.Type)
}
controller, err := catalog.NewController(storage)
if err != nil {
panic("Failed to start the controller:" + err.Error())
}
defer controller.Stop()
// Create catalog API object
api := catalog.NewHTTPAPI(controller, Version)
// Start notification
var eventQueue notification.EventQueue
switch config.Storage.Type {
case catalog.BackendLevelDB:
eventQueue, err = notification.NewLevelDBEventQueue(config.Storage.DSN+"/sse", nil, 1000)
if err != nil {
panic("Failed to start LevelDB storage for SSE events:" + err.Error())
}
defer eventQueue.Close()
default:
panic("Could not create SSE storage. Unsupported type:" + config.Storage.Type)
}
notificationController := notification.NewController(eventQueue)
notifAPI := notification.NewSSEAPI(notificationController, Version)
defer notificationController.Stop()
controller.AddSubscriber(notificationController)
nRouter, err := setupHTTPRouter(&config.HTTP, api, notifAPI)
if err != nil {
panic(err)
}
// Start listener
addr := fmt.Sprintf("%s:%d", config.HTTP.BindAddr, config.HTTP.BindPort)
listener, err := net.Listen("tcp", addr)
if err != nil {
panic(err)
}
go func() {
if config.HTTP.TLSConfig.Enabled {
log.Printf("HTTP/TLS server listening on %v", addr)
log.Fatalf("Error starting HTTP/TLS Server: %s", http.ServeTLS(listener, nRouter, config.HTTP.TLSConfig.CertFile, config.HTTP.TLSConfig.KeyFile))
} else {
log.Printf("HTTP server listening on %v", addr)
log.Fatalf("Error starting HTTP Server: %s", http.Serve(listener, nRouter))
}
}()
// Publish service using DNS-SD
if config.DNSSD.Publish.Enabled {
shutdown, err := registerDNSSDService(config)
if err != nil {
log.Printf("Failed to register DNS-SD service: %s", err)
}
defer shutdown()
}
// Register in the LinkSmart Service Catalog
if config.ServiceCatalog.Enabled {
unregisterService, err := registerInServiceCatalog(config)
if err != nil {
panic("Error registering service:" + err.Error())
}
// Unregister from the Service Catalog
defer func() {
err := unregisterService()
if err != nil {
log.Printf("Error unregistering service from catalog: %s", err)
}
}()
}
log.Println("Ready!")
// Ctrl+C / Kill handling
handler := make(chan os.Signal, 1)
signal.Notify(handler, syscall.SIGINT, syscall.SIGTERM)
<-handler
log.Println("Shutting down...")
}
func setupHTTPRouter(config *HTTPConfig, api *catalog.HTTPAPI, notifAPI *notification.SSEAPI) (*negroni.Negroni, error) {
corsHandler := cors.New(cors.Options{
AllowedOrigins: []string{"*"},
AllowedMethods: []string{
http.MethodHead,
http.MethodGet,
http.MethodPost,
http.MethodPut,
http.MethodPatch,
http.MethodDelete,
},
AllowedHeaders: []string{"*"},
AllowCredentials: false,
ExposedHeaders: []string{"*"},
})
commonHandlers := alice.New(
context.ClearHandler,
corsHandler.Handler,
)
// Append auth handler if enabled
if config.Auth.Enabled {
// Setup ticket validator
v, err := validator.Setup(
config.Auth.Provider,
config.Auth.ProviderURL,
config.Auth.ClientID,
config.Auth.BasicEnabled,
&config.Auth.Authz)
if err != nil {
return nil, err
}
commonHandlers = commonHandlers.Append(v.Handler)
}
// Configure http api router
r := newRouter()
r.get("/", commonHandlers.ThenFunc(indexHandler))
r.options("/{path:.*}", commonHandlers.ThenFunc(optionsHandler))
// OpenAPI Proxy for Swagger "try it out" feature
r.get("/openapi-spec-proxy", commonHandlers.ThenFunc(apiSpecProxy))
r.get("/openapi-spec-proxy/{basepath:.+}", commonHandlers.ThenFunc(apiSpecProxy))
// Deprecated: use /things and /search instead
// TD CRUD, listing, filtering
r.get("/td", commonHandlers.ThenFunc(api.GetMany))
r.get("/td-chunked", commonHandlers.ThenFunc(api.GetAll))
r.post("/td", commonHandlers.ThenFunc(api.Post))
r.get("/td/{id:.+}", commonHandlers.ThenFunc(api.Get))
r.put("/td/{id:.+}", commonHandlers.ThenFunc(api.Put))
r.patch("/td/{id:.+}", commonHandlers.ThenFunc(api.Patch))
r.delete("/td/{id:.+}", commonHandlers.ThenFunc(api.Delete))
// CRUDL
r.post("/things", commonHandlers.ThenFunc(api.Post)) // create anonymous
r.put("/things/{id:.+}", commonHandlers.ThenFunc(api.Put)) // create or update
r.get("/things/{id:.+}", commonHandlers.ThenFunc(api.Get)) // retrieve
r.patch("/things/{id:.+}", commonHandlers.ThenFunc(api.Patch)) // partially update
r.delete("/things/{id:.+}", commonHandlers.ThenFunc(api.Delete)) // delete
r.get("/things", commonHandlers.ThenFunc(api.GetAll)) // listing
// search
r.get("/search/jsonpath", commonHandlers.ThenFunc(api.SearchJSONPath))
r.get("/search/xpath", commonHandlers.ThenFunc(api.SearchXPath))
// TD validation
r.get("/validation", commonHandlers.ThenFunc(api.GetValidation))
//TD notification
r.get("/events", commonHandlers.ThenFunc(notifAPI.SubscribeEvent))
r.get("/events/{type}", commonHandlers.ThenFunc(notifAPI.SubscribeEvent))
logger := negroni.NewLogger()
logFlags := log.LstdFlags
if evalEnv(EnvDisableLogTime) {
logFlags = 0
}
logger.ALogger = log.New(os.Stdout, "", logFlags)
logger.SetFormat("{{.Method}} {{.Request.URL}} {{.Request.Proto}} {{.Status}} {{.Duration}}")
// Configure the middleware
n := negroni.New(
negroni.NewRecovery(),
logger,
)
// Mount router
n.UseHandler(r)
return n, nil
}