-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinit.go
More file actions
658 lines (565 loc) · 19.4 KB
/
init.go
File metadata and controls
658 lines (565 loc) · 19.4 KB
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
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
package main
import (
"crypto/rand"
"fmt"
"net"
"os"
"path/filepath"
"sort"
"strconv"
"strings"
"github.com/manifoldco/promptui"
"github.com/spf13/cobra"
)
var initCmd = &cobra.Command{
Use: "init",
Short: "Initialize Apito CLI system configuration",
Long: `Initialize and validate Apito CLI system configuration, check ports, and set up required environment variables.`,
Run: func(cmd *cobra.Command, args []string) {
initializeSystem()
},
}
var initUpdateCmd = &cobra.Command{
Use: "update",
Short: "Update system .env with new default keys",
Long: `Merges missing default env keys into ~/.apito/bin/.env. Use after upgrading the CLI when new env vars are introduced. Prints what was added, or "Nothing to change." if already up to date.`,
Run: func(cmd *cobra.Command, args []string) {
runInitUpdate()
},
}
func init() {
initCmd.AddCommand(initUpdateCmd)
}
func runInitUpdate() {
homeDir, err := os.UserHomeDir()
if err != nil {
print_error("Failed to get home directory: " + err.Error())
return
}
envPath, err := getEnvPath()
if err != nil {
print_error("Failed to resolve .env path: " + err.Error())
return
}
if _, err := os.Stat(envPath); os.IsNotExist(err) {
print_error("No system .env found at ~/.apito/bin/.env. Run 'apito init' first.")
return
}
existing, err := ReadEnv()
if err != nil {
print_error("Failed to read .env: " + err.Error())
return
}
runMode := "docker"
if cfg, cfgErr := loadCLIConfig(); cfgErr == nil && cfg.Mode != "" {
runMode = cfg.Mode
}
defaultConfig := getDefaultEnvConfig(runMode, homeDir)
var added []string
for k, v := range defaultConfig {
if _, ok := existing[k]; !ok {
existing[k] = v
added = append(added, k)
}
}
if len(added) == 0 {
print_status("Nothing to change.")
return
}
if err := WriteEnv(existing); err != nil {
print_error("Failed to write .env: " + err.Error())
return
}
sort.Strings(added)
print_success("Updated ~/.apito/bin/.env")
for _, k := range added {
print_status(" Added: " + k)
}
}
func initializeSystem() {
print_step("🚀 Initializing Apito CLI System")
fmt.Println()
// Prepare core directories
if err := ensureBaseDirs(); err != nil {
print_error("Failed to prepare directories: " + err.Error())
return
}
// Choose run mode (Docker vs Manual) and persist if confirmed
print_status("Step 0: Select run mode (Docker recommended)...")
mode, err := selectAndPersistRunMode()
if err != nil {
print_error("Failed to set run mode: " + err.Error())
return
}
print_success("Run mode: " + mode)
fmt.Println()
// Step 0.5: Fetch and store latest component versions (Docker mode only)
if mode == "docker" {
print_status("Step 0.5: Checking for latest component versions...")
if err := ensureComponentVersions(); err != nil {
print_warning("Could not fetch latest versions: " + err.Error())
print_status("Will use 'latest' tags for Docker images")
} else {
print_success("Component versions configured")
}
// Regenerate docker-compose.yml with updated versions
print_status("Updating docker-compose.yml with component versions...")
if _, err := writeComposeFile(); err != nil {
print_warning("Could not update docker-compose.yml: " + err.Error())
} else {
print_success("docker-compose.yml updated with component versions")
}
fmt.Println()
}
// Step 1: Check and create ~/.apito directory
print_status("Step 1: Checking Apito directory...")
if err := ensureApitoDirectory(); err != nil {
print_error("Failed to create Apito directory: " + err.Error())
return
}
print_success("Apito directory ready")
fmt.Println()
// Step 2: Check and create .config file
print_status("Step 2: Checking system configuration...")
if err := ensureDefaultEnvironmentConfig(mode); err != nil {
print_error("Failed to create system configuration: " + err.Error())
return
}
print_success("System configuration ready")
fmt.Println()
// Step 2.5: Optional database setup (Docker mode only)
if mode == "docker" {
print_status("Step 2.5: Database setup (optional)...")
print_status("Database setup will be handled by 'apito start --db system' or 'apito start --db project'")
print_status("You can set up databases when starting services")
} else {
print_status("Database setup will be handled by 'apito start --db system' or 'apito start --db project'")
}
fmt.Println()
// Step 3: Validate system database configuration
print_status("Step 3: Validating system database configuration...")
if err := validateSystemDatabase(); err != nil {
print_error("System database validation failed: " + err.Error())
return
}
print_success("System database configuration validated")
fmt.Println()
// Step 4: Validate environment configuration
print_status("Step 4: Validating environment configuration...")
if err := validateEnvironmentConfig(); err != nil {
print_error("Environment configuration validation failed: " + err.Error())
return
}
print_success("Environment configuration validated")
fmt.Println()
// Step 5: Check port availability
print_status("Step 5: Checking port availability...")
if err := checkPortAvailability(); err != nil {
print_warning("Port availability check failed: " + err.Error())
} else {
print_success("Port availability check passed")
}
fmt.Println()
print_success("🎉 Apito CLI system initialization completed successfully!")
print_status("You can now start apito studio using : apito start")
}
func ensureApitoDirectory() error {
homeDir, err := os.UserHomeDir()
if err != nil {
return fmt.Errorf("error finding home directory: %w", err)
}
apitoDir := filepath.Join(homeDir, ".apito")
if _, err := os.Stat(apitoDir); os.IsNotExist(err) {
print_status("Creating Apito directory: " + apitoDir)
if err := os.MkdirAll(apitoDir, 0755); err != nil {
return fmt.Errorf("error creating Apito directory: %w", err)
}
} else {
print_status("Apito directory already exists: " + apitoDir)
}
return nil
}
// getDefaultEnvConfig returns the default env key/value map for ~/.apito/bin/.env.
// runMode is "docker" or "manual"; homeDir is used for manual-mode paths.
func getDefaultEnvConfig(runMode, homeDir string) map[string]string {
defaultDatabaseDir := "/app/db"
var (
cacheDatabasePath string
kvDatabasePath string
queueDatabasePath string
systemDatabasePath string
projectDatabasePath string
defaultSaaSProjectDBPath string
)
if runMode == "docker" {
cacheDatabasePath = "apito_cache.db"
kvDatabasePath = "apito_kv.db"
queueDatabasePath = "apito_queue.db"
systemDatabasePath = "apito_system.db"
projectDatabasePath = "apito_project.db"
defaultSaaSProjectDBPath = "apito_saas_project.db"
} else {
dbDataDir := filepath.Join(homeDir, ".apito", "db")
cacheDatabasePath = filepath.Join(dbDataDir, "apito_cache.db")
kvDatabasePath = filepath.Join(dbDataDir, "apito_kv.db")
queueDatabasePath = filepath.Join(dbDataDir, "apito_queue.db")
systemDatabasePath = filepath.Join(dbDataDir, "apito_system.db")
projectDatabasePath = filepath.Join(dbDataDir, "apito_project.db")
defaultSaaSProjectDBPath = filepath.Join(dbDataDir, "apito_saas_project.db")
}
return map[string]string{
"ENVIRONMENT": "local",
"AUTH_SERVICE_PROVIDER": "local",
"BRANKA_KEY": "",
"COOKIE_DOMAIN": "localhost",
"CORS_ORIGIN": "http://localhost:4000",
"PLUGIN_PATH": "plugins",
"PRIVATE_KEY_PATH": "keys/private.key",
"PUBLIC_KEY_PATH": "keys/public.key",
"SERVE_PORT": "5050",
"TOKEN_TTL": "60",
"APITO_ADMIN_RESET_SECRET": generateSecurePassword(),
"DEFAULT_DATABASE_DIR": defaultDatabaseDir,
"CACHE_DB": "memory",
"CACHE_DB_HOST": cacheDatabasePath,
"CACHE_TTL": "600",
"KV_ENGINE": "coreDB",
"KV_DATABASE": kvDatabasePath,
"QUEUE_ENGINE": "coreDB",
"QUEUE_DATABASE": queueDatabasePath,
"SYSTEM_DB_ENGINE": "coreDB",
"SYSTEM_DB_NAME": systemDatabasePath,
"PROJECT_DB_ENGINE": "coreDB",
"PROJECT_DB_NAME": projectDatabasePath,
"DEFAULT_SAAS_PROJECT_DB_NAME": defaultSaaSProjectDBPath,
}
}
func ensureDefaultEnvironmentConfig(runMode string) error {
homeDir, err := os.UserHomeDir()
if err != nil {
return fmt.Errorf("error finding home directory: %w", err)
}
if runMode == "" {
if cfg, cfgErr := loadCLIConfig(); cfgErr == nil && cfg.Mode != "" {
runMode = cfg.Mode
}
}
if runMode == "" {
runMode = "docker"
}
apitoBinDir := filepath.Join(homeDir, ".apito", "bin")
if err := os.MkdirAll(apitoBinDir, 0755); err != nil {
return fmt.Errorf("error creating bin directory: %w", err)
}
configFile := filepath.Join(apitoBinDir, ".env")
// If .env exists as a directory (Docker creates it when bind-mount target is missing),
// remove it so we can create a proper file.
if info, err := os.Stat(configFile); err == nil && info.IsDir() {
if err := os.RemoveAll(configFile); err != nil {
return fmt.Errorf("error removing .env directory (was created by Docker): %w", err)
}
print_status("Removed .env directory, creating configuration file...")
}
// Check if config file exists
if _, err := os.Stat(configFile); os.IsNotExist(err) {
print_status("Creating system configuration file...")
defaultConfig := getDefaultEnvConfig(runMode, homeDir)
if err := saveEnvConfig(apitoBinDir, defaultConfig); err != nil {
return fmt.Errorf("error creating system config: %w", err)
}
print_success("System configuration file created")
} else {
print_status("System configuration file already exists")
}
return nil
}
// ensureEnvFileReady guarantees ~/.apito/bin/.env exists as a file (not a directory).
// Docker creates bind-mount targets as directories when they don't exist; this repairs that.
// Call before any Docker operation that mounts .env.
func ensureEnvFileReady() error {
homeDir, err := os.UserHomeDir()
if err != nil {
return fmt.Errorf("error finding home directory: %w", err)
}
apitoBinDir := filepath.Join(homeDir, ".apito", "bin")
envPath := filepath.Join(apitoBinDir, ".env")
if err := os.MkdirAll(apitoBinDir, 0755); err != nil {
return fmt.Errorf("error creating bin directory: %w", err)
}
if info, err := os.Stat(envPath); err == nil && info.IsDir() {
if err := os.RemoveAll(envPath); err != nil {
return fmt.Errorf("error removing .env directory: %w", err)
}
}
return ensureDefaultEnvironmentConfig("docker")
}
func validateSystemDatabase() error {
homeDir, err := os.UserHomeDir()
if err != nil {
return fmt.Errorf("error finding home directory: %w", err)
}
config, err := getConfig(filepath.Join(homeDir, ".apito", "bin"))
if err != nil {
return fmt.Errorf("error reading system config: %w", err)
}
dbEngine := config["APITO_SYSTEM_DB_ENGINE"]
if dbEngine == "" {
dbEngine = "coreDB"
}
print_status("System database engine: " + dbEngine)
// If using external database, validate configuration
if dbEngine != "coreDB" {
requiredFields := []string{"SYSTEM_DB_HOST", "SYSTEM_DB_PORT", "SYSTEM_DB_USER", "SYSTEM_DB_PASSWORD", "SYSTEM_DB_NAME"}
missingFields := []string{}
for _, field := range requiredFields {
if config[field] == "" {
missingFields = append(missingFields, field)
}
}
if len(missingFields) > 0 {
print_warning("Missing system database configuration fields: " + strings.Join(missingFields, ", "))
print_status("Please configure the following database settings:")
if err := promptForDatabaseConfig(config, "SYSTEM"); err != nil {
return fmt.Errorf("error configuring system database: %w", err)
}
}
}
return nil
}
func validateEnvironmentConfig() error {
homeDir, err := os.UserHomeDir()
if err != nil {
return fmt.Errorf("error finding home directory: %w", err)
}
config, err := getConfig(filepath.Join(homeDir, ".apito", "bin"))
if err != nil {
return fmt.Errorf("error reading system config: %w", err)
}
// Check mandatory environment variables
mandatoryFields := []string{"ENVIRONMENT", "CORS_ORIGIN", "COOKIE_DOMAIN"}
missingFields := []string{}
for _, field := range mandatoryFields {
if config[field] == "" {
missingFields = append(missingFields, field)
}
}
// Handle BRANKA_KEY separately - generate if missing
if config["BRANKA_KEY"] == "" {
print_status("Generating BRANKA_KEY...")
config["BRANKA_KEY"] = generateBrankaKey()
print_success("BRANKA_KEY generated successfully")
// Save the generated key to the same location we read from (bin directory)
if err := saveEnvConfig(filepath.Join(homeDir, ".apito", "bin"), config); err != nil {
return fmt.Errorf("error saving generated BRANKA_KEY: %w", err)
}
}
if len(missingFields) > 0 {
print_warning("Missing mandatory environment configuration: " + strings.Join(missingFields, ", "))
print_status("Please configure the following environment settings:")
if err := promptForEnvironmentConfig(config); err != nil {
return fmt.Errorf("error configuring environment: %w", err)
}
}
return nil
}
func promptForDatabaseConfig(config map[string]string, prefix string) error {
print_status("Configuring " + prefix + " database settings...")
// Database host
prompt := promptui.Prompt{
Label: prefix + " Database Host",
Default: config[prefix+"_DB_HOST"],
}
dbHost, err := prompt.Run()
if err != nil {
return fmt.Errorf("prompt failed: %w", err)
}
config[prefix+"_DB_HOST"] = dbHost
// Database port
prompt = promptui.Prompt{
Label: prefix + " Database Port",
Default: config[prefix+"_DB_PORT"],
}
dbPort, err := prompt.Run()
if err != nil {
return fmt.Errorf("prompt failed: %w", err)
}
config[prefix+"_DB_PORT"] = dbPort
// Database user
prompt = promptui.Prompt{
Label: prefix + " Database User",
Default: config[prefix+"_DB_USER"],
}
dbUser, err := prompt.Run()
if err != nil {
return fmt.Errorf("prompt failed: %w", err)
}
config[prefix+"_DB_USER"] = dbUser
// Database password
prompt = promptui.Prompt{
Label: prefix + " Database Password",
Mask: '*',
Default: config[prefix+"_DB_PASSWORD"],
}
dbPassword, err := prompt.Run()
if err != nil {
return fmt.Errorf("prompt failed: %w", err)
}
config[prefix+"_DB_PASSWORD"] = dbPassword
// Database name
prompt = promptui.Prompt{
Label: prefix + " Database Name",
Default: config[prefix+"_DB_NAME"],
}
dbName, err := prompt.Run()
if err != nil {
return fmt.Errorf("prompt failed: %w", err)
}
config[prefix+"_DB_NAME"] = dbName
// Save configuration
homeDir, err := os.UserHomeDir()
if err != nil {
return fmt.Errorf("error finding home directory: %w", err)
}
if err := saveEnvConfig(filepath.Join(homeDir, ".apito", "bin"), config); err != nil {
return fmt.Errorf("error saving configuration: %w", err)
}
print_success(prefix + " database configuration saved")
return nil
}
func promptForEnvironmentConfig(config map[string]string) error {
print_status("Configuring environment settings...")
// Environment
envOptions := []string{"local", "development", "staging", "production"}
currentEnv := config["ENVIRONMENT"]
if currentEnv == "" {
currentEnv = "local"
}
prompt := promptui.Select{
Label: "Environment",
Items: envOptions,
}
_, env, err := prompt.Run()
if err != nil {
return fmt.Errorf("prompt failed: %w", err)
}
config["ENVIRONMENT"] = env
// CORS Origin
promptInput := promptui.Prompt{
Label: "CORS Origin (e.g., http://localhost:3000, https://yourdomain.com)",
Default: config["CORS_ORIGIN"],
}
corsOrigin, err := promptInput.Run()
if err != nil {
return fmt.Errorf("prompt failed: %w", err)
}
config["CORS_ORIGIN"] = corsOrigin
// Cookie Domain
promptInput = promptui.Prompt{
Label: "Cookie Domain (e.g., localhost, yourdomain.com)",
Default: config["COOKIE_DOMAIN"],
}
cookieDomain, err := promptInput.Run()
if err != nil {
return fmt.Errorf("prompt failed: %w", err)
}
config["COOKIE_DOMAIN"] = cookieDomain
// Note: BRANKA_KEY is auto-generated if not provided
// Save configuration
homeDir, err := os.UserHomeDir()
if err != nil {
return fmt.Errorf("error finding home directory: %w", err)
}
if err := saveEnvConfig(filepath.Join(homeDir, ".apito", "bin"), config); err != nil {
return fmt.Errorf("error saving configuration: %w", err)
}
print_success("Environment configuration saved")
return nil
}
// generateBrankaKey produces exactly 32 bytes for AES-256, matching engine requirements
// (branca token, project key manager). Uses crypto/rand for secure generation.
func generateBrankaKey() string {
const charset = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*()_+-=[]{}|;:,.<>?"
const keyLength = 32
bytes := make([]byte, keyLength)
if _, err := rand.Read(bytes); err != nil {
// Fallback: deterministic but ensures 32 bytes (avoid panic in engine)
for i := range bytes {
bytes[i] = charset[i%len(charset)]
}
}
result := make([]byte, keyLength)
for i := range result {
result[i] = charset[int(bytes[i])%len(charset)]
}
return string(result)
}
// ensureComponentVersions checks for latest versions and prompts for updates
func ensureComponentVersions() error {
cfg, err := loadCLIConfig()
if err != nil {
return fmt.Errorf("failed to load config: %w", err)
}
// Check for updates (compares current vs latest)
updates, err := checkForComponentUpdates()
if err != nil {
return fmt.Errorf("failed to check for updates: %w", err)
}
// If no current versions set, automatically use latest without prompting
if cfg.EngineVersion == "" && cfg.ConsoleVersion == "" {
print_status("No versions configured, fetching latest versions...")
// Fetch and set engine version
if engineVersion, err := getLatestEngineVersion(); err == nil {
cfg.EngineVersion = engineVersion
print_success(fmt.Sprintf("Engine version set to %s", engineVersion))
} else {
print_warning(fmt.Sprintf("Could not fetch engine version: %v", err))
}
// Fetch and set console version
if consoleVersion, err := getLatestConsoleVersion(); err == nil {
cfg.ConsoleVersion = consoleVersion
print_success(fmt.Sprintf("Console version set to %s", consoleVersion))
} else {
print_warning(fmt.Sprintf("Could not fetch console version: %v", err))
}
// Save config
if err := saveCLIConfig(cfg); err != nil {
return fmt.Errorf("failed to save config: %w", err)
}
return nil
}
// If versions exist and updates are available, prompt user
if len(updates) > 0 {
componentsToUpdate := promptForComponentUpdates(updates)
if len(componentsToUpdate) > 0 {
for _, component := range componentsToUpdate {
update := updates[component]
// Update config.yml
if err := updateComponentVersion(component, update.LatestVersion); err != nil {
print_error(fmt.Sprintf("Failed to update config for %s: %v", component, err))
continue
}
print_success(fmt.Sprintf("Updated %s to %s", component, update.LatestVersion))
}
} else {
print_status("Keeping current versions")
}
} else {
print_success("All components are up to date")
}
return nil
}
func checkPortAvailability() error {
ports := []int{5050, 4000}
for _, port := range ports {
address := ":" + strconv.Itoa(port)
listener, err := net.Listen("tcp", address)
if err != nil {
print_warning(fmt.Sprintf("Port %d is already in use", port))
print_status(fmt.Sprintf("Please ensure port %d is available for Apito to run properly", port))
} else {
listener.Close()
print_status(fmt.Sprintf("Port %d is available", port))
}
}
return nil
}