-
Notifications
You must be signed in to change notification settings - Fork 52
/
Copy pathmain.go
424 lines (367 loc) · 14.8 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
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
package main
import (
"context"
"flag"
"fmt"
embeddedPostgres "github.com/aquametalabs/embedded-postgres"
"github.com/jackc/pgx/v4/pgxpool"
"github.com/lib/pq"
"log"
"net/http"
"os"
"os/exec"
"os/signal"
"path/filepath"
"syscall"
"time"
)
func main() {
log.Print(` __ `)
log.Print(`_____ ________ _______ _____ _____/ |______ `)
log.Print(`\__ \ / ____/ | \__ \ / \_/ __ \ __\__ \ `)
log.Print(` / __ \< <_| | | // __ \| Y Y \ ___/| | / __ \_`)
log.Print(`(____ /\__ |____/(____ /__|_| /\___ >__| (____ /`)
log.Print(` \/ |__| \/ \/ \/ \/ `)
log.Print(` [ version 0.4.0 ] `)
// log.SetPrefix("[💧 aquameta 💧] ")
log.Print("Aquameta server... ENGAGE!")
workingDirectory, err := filepath.Abs(filepath.Dir(os.Args[0]))
var epg embeddedPostgres.EmbeddedPostgres
//
// trap ctrl-c
//
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt, syscall.SIGINT, syscall.SIGTERM)
go func() {
for sig := range c {
if epg.IsStarted() {
log.Print("Stopping PostgreSQL")
epg.Stop()
}
log.Fatalf("SIG %s - Good day.", sig)
}
}()
//
// load config
//
var configFile = flag.String("c", "", "configuration file")
flag.Parse()
config, err := getConfig(*configFile)
if err != nil {
log.Printf("Could not load boot configuration file: %s", err)
log.Print("Usage:")
flag.PrintDefaults()
log.Fatal("Quitting.")
/*
log.Printf("Loading default Bootloader configuration instead from %s", bootloaderConfigFile)
blconfig, err := getConfig(bootloaderConfigFile); if err != nil {
log.Fatalf("Could not load bootloader config %s: %s", bootloaderConfigFile, err)
}
config = blconfig
*/
}
//
// setup embedded database
//
if config.Database.Mode == "embedded" {
//
// initialize epg w/ config settings
//
// TODO: NewDatabase() should be called NewPGServer() or some such... refactor epg
epg = *embeddedPostgres.NewDatabase(embeddedPostgres.DefaultConfig().
Username(config.Database.Role).
Password(config.Database.Password).
// Host
Port(config.Database.Port).
Database(config.Database.DatabaseName).
Version(embeddedPostgres.V12).
RuntimePath(config.Database.EmbeddedPostgresRuntimePath).
StartTimeout(45 * time.Second))
// has an embedded postgres already been installed?
log.Printf("Checking for existing embedded server at %s", config.Database.EmbeddedPostgresRuntimePath)
epgFilesExist := true
if _, err := os.Stat(config.Database.EmbeddedPostgresRuntimePath); os.IsNotExist(err) {
// TODO: we probably want some more robust inspection of the directory.
// Check that it has the binary, and a data directory, and generally looks sane.
// If it doesn't, QUIT! (Do NOT install the db here, it might be some other directory
// that would get overwritten.
log.Printf("Embedded PostgreSQL server found at %s.", config.Database.EmbeddedPostgresRuntimePath)
epgFilesExist = false
}
// if directory doesn't exist, generate an embedded database there
if !epgFilesExist {
log.Printf("Embedded PostgreSQL server not found at %s. Installing...", config.Database.EmbeddedPostgresRuntimePath)
if err := epg.Install(); err != nil {
log.Fatalf("Unable to install PostgreSQL: %v", err)
}
log.Printf("PostgreSQL server installed at %s", config.Database.EmbeddedPostgresRuntimePath)
}
//
// start the epg database daemon
//
log.Printf("Starting PostgreSQL server from %s...", config.Database.EmbeddedPostgresRuntimePath)
if err := epg.Start(); err != nil {
log.Fatalf("Unable to start PostgreSQL: %v", err)
}
log.Print("PostgreSQL server started.")
defer func() {
log.Print("Stopping PostgreSQL Server...")
if err := epg.Stop(); err != nil {
log.Fatalf("Database halt failed: %v", err)
} else {
log.Print("Database stopped")
}
}()
//
// CREATE DATABASE
//
if !epgFilesExist {
if err := epg.CreateDatabase(); err != nil {
// TODO: create epg.DatabaseExists() method
// log.Fatalf("Unable to create database: %v", err)
} else {
log.Print("PostgreSQL server installed to %s", config.Database.EmbeddedPostgresRuntimePath)
}
}
}
//
// connect to database
//
connectionString := fmt.Sprintf("postgresql://%s:%s@%s:%d/%s", config.Database.Role, config.Database.Password, config.Database.Host, config.Database.Port, config.Database.DatabaseName)
log.Printf("Database: %s", connectionString)
dbpool, err := pgxpool.Connect(context.Background(), connectionString)
if err != nil {
log.Fatalf("Unable to connect to database: %v", err)
}
log.Print("Connected to database.")
defer dbpool.Close()
//
// pg_settings
//
// CLI switch here: if --debug, else ...
settingsQueries := [...]string{
fmt.Sprintf("set log_min_messages='notice'"), // { notice, warning, error, ...}
fmt.Sprintf("set log_statement='all'"),
fmt.Sprintf("set statement_timeout=0"),
}
for i := 0; i < len(settingsQueries); i++ {
_, err := dbpool.Exec(context.Background(), settingsQueries[i])
if err != nil {
epg.Stop()
log.Fatalf("Unable to update settings: %v", err)
}
}
log.Print("PostgreSQL settings have been set.")
//
// - install aquameta extensions
//
var ct int
dbQuery := fmt.Sprintf("select count(*) as ct from pg_catalog.pg_extension where extname in ('meta','meta_triggers','bundle','event','endpoint','ide','documentation','widget','semantics')")
err = dbpool.QueryRow(context.Background(), dbQuery).Scan(&ct)
log.Print("Checking for Aquameta installation....")
if ct != 9 {
//
// install aquameta extensions
//
log.Print("Aquameta is not installed on this database. Installing...")
if config.Database.Mode == "embedded" {
exec.Command("/bin/sh", "-c", "cp "+workingDirectory+"/extensions/*/*--*.*.*.sql "+config.Database.EmbeddedPostgresRuntimePath+"/share/postgresql/extension/").Run()
exec.Command("/bin/sh", "-c", "cp "+workingDirectory+"/extensions/*/*.control "+config.Database.EmbeddedPostgresRuntimePath+"/share/postgresql/extension/").Run()
log.Print("Extensions copied to PostgreSQL's extensions directory.")
}
installQueries := [...]string{
"create extension if not exists hstore schema public",
"create extension if not exists \"uuid-ossp\" schema public",
"create extension if not exists pgcrypto schema public",
"create extension if not exists postgres_fdw schema public",
"create extension meta version '0.4.0'",
"create extension meta_triggers version '0.4.0'",
"create extension bundle",
"create extension event",
"create extension endpoint",
"create extension widget",
"create extension semantics",
"create extension ide",
"create extension documentation"}
for i := 0; i < len(installQueries); i++ {
log.Print(installQueries[i])
_, err := dbpool.Exec(context.Background(), installQueries[i])
if err != nil {
log.Fatalf("Unable to install extensions: %v", err)
if config.Database.Mode == "embedded" {
epg.Stop()
}
}
}
log.Print("Extensions were successfully installed.")
//
// setup hub remote
//
log.Print("Adding bundle.remote_database for hub...")
hubRemoteQuery := `insert into bundle.remote_database (foreign_server_name, schema_name, connection_string, username, password)
values (
'hub', 'hub',
'dbname ''aquameta'', host ''hub.aquameta.com'', port ''5432''',
'anonymous', 'anonymous'
)`
_, err := dbpool.Query(context.Background(), hubRemoteQuery)
if err != nil {
if config.Database.Mode == "embedded" {
epg.Stop()
}
log.Fatalf("Unable to add bundle.remote_database: %v", err)
}
//
// create superuser
//
log.Print("Setting up permissions...")
superuserQuery := fmt.Sprintf("insert into endpoint.user (email, name, active, role_id) values (%s, %s, true, meta.role_id(%s))",
pq.QuoteLiteral(config.AquametaUser.Email),
pq.QuoteLiteral(config.AquametaUser.Name),
pq.QuoteLiteral(config.Database.Role))
rows, err := dbpool.Query(context.Background(), superuserQuery)
if err != nil {
log.Fatalf("Unable to create superuser: %v", err)
}
rows.Close()
//
// download and install bundles
//
/*
TODO: switch hub install vs local file install, based on CLI
// hub install over network
log.Print("Downloading Aquameta core bundles from hub.aquameta.com...")
bundleQueries := [...]string{
"select bundle.remote_mount(id) from bundle.remote_database",
"select bundle.remote_pull_bundle(r.id, b.id) from bundle.remote_database r, hub.bundle b",
"select bundle.checkout(c.id) from bundle.commit c join bundle.bundle b on b.head_commit_id = c.id;" }
for i := 0; i < len(bundleQueries); i++ {
log.Printf("Setup query: %s", bundleQueries[i])
rows, err := dbpool.Query(context.Background(), bundleQueries[i])
if err != nil {
log.Fatalf("Unable to install Aquameta bundles: %v", err)
}
rows.Close()
}
*/
// install from local filesystem
// TODO: Do this by inspecting the bundles directory?
log.Print("Installing core bundles from source")
coreBundles := [...]string{
"org.aquameta.core.bootloader",
// "org.aquameta.core.bundle",
"org.aquameta.core.endpoint",
"org.aquameta.core.ide",
"org.aquameta.core.mimetypes",
"org.aquameta.core.semantics",
"org.aquameta.core.widget",
"org.aquameta.games.snake",
"org.aquameta.ui.fsm",
"org.aquameta.ui.layout",
"org.aquameta.ui.tags",
}
for i := 0; i < len(coreBundles); i++ {
log.Print(" - "+coreBundles[i])
q := "select bundle.bundle_import_csv('" + workingDirectory + "/bundles/" + coreBundles[i] + "')"
_, err := dbpool.Exec(context.Background(), q)
if err != nil {
if config.Database.Mode == "embedded" {
epg.Stop()
}
log.Fatalf("Unable to install Aquameta bundles: %v", err)
}
_, err = dbpool.Exec(context.Background(), "select bundle.checkout(c.id) from bundle.commit c join bundle.bundle b on b.head_commit_id = c.id where b.name = '" + coreBundles[i] + "'")
if err != nil {
log.Fatalf("Unable to checkout core bundles: %v", err)
}
}
//
// check out core bundles
//
log.Print("Installation complete!")
}
bootloaderHandler := func(w http.ResponseWriter, req *http.Request) {
log.Println(req.Proto, req.Method, req.RequestURI)
// halt
if req.RequestURI == "/bootloader/halt" {
log.Print("Bootloader has requested that I halt, so I will halt.")
if epg.IsStarted() {
log.Print("Stopping PostgreSQL")
epg.Stop()
}
log.Fatal("Good day.")
}
// write config
if req.RequestURI == "/bootloader/configure" {
log.Println("Ok I will write out the specified .conf file to disk")
}
}
//
// attach handlers
//
// TODO: configure these in the database??
http.HandleFunc("/_socket/detach/", websocketDetach)
http.Handle("/socket.io/", websocket(dbpool))
http.HandleFunc("/bootloader/", bootloaderHandler)
http.HandleFunc("/endpoint/", endpoint(dbpool))
http.HandleFunc("/", resource(dbpool))
httpDone := make(chan bool)
fuseDone := make(chan bool)
//
// start http server
//
log.Printf("Starting HTTP server\n\n%s://%s:%s%s\n\n",
config.HTTPServer.Protocol,
config.HTTPServer.IP,
config.HTTPServer.Port,
config.HTTPServer.StartupURL)
go func() {
if config.HTTPServer.Protocol == "http" {
http.ListenAndServe(config.HTTPServer.IP+":"+config.HTTPServer.Port, nil)
} else {
if config.HTTPServer.Protocol == "https" {
// https://github.com/denji/golang-tls
log.Fatal(http.ListenAndServeTLS(
config.HTTPServer.IP+":"+config.HTTPServer.Port,
config.HTTPServer.SSLCertificateFile,
config.HTTPServer.SSLKeyFile,
nil))
} else {
log.Fatal("Unrecognized protocol: " + config.HTTPServer.Protocol)
}
}
httpDone <- true
}()
//
// start pgfs (if OS is supported and it's enabled in config)
//
go pgfs(config, dbpool, fuseDone)
//
// start gui
//
/*
log.Printf("HTTP server started, startup URL:\n\n%s://%s:%s%s\n\n",
config.HTTPServer.Protocol,
config.HTTPServer.IP,
config.HTTPServer.Port,
config.HTTPServer.StartupURL)
w := webview.New(true)
defer w.Destroy()
w.SetTitle("Aquameta Boot Loader")
w.SetSize(800, 500, webview.HintNone)
w.Navigate(config.HTTPServer.Protocol+"://"+config.HTTPServer.IP+":"+config.HTTPServer.Port+"/boot")
w.Run()
*/
select {
case <-httpDone:
println("HTTP server stopped.")
case <-fuseDone:
println("FUSE filesystem stopped.")
}
if config.Database.Mode == "embedded" {
if epg.IsStarted() {
epg.Stop()
}
}
log.Fatal("Good day.")
}