forked from GoogleCloudPlatform/scion
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.go
More file actions
2348 lines (2075 loc) · 80.2 KB
/
Copy pathserver.go
File metadata and controls
2348 lines (2075 loc) · 80.2 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
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2026 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package cmd
import (
"context"
"crypto/rand"
"encoding/base64"
"encoding/json"
"fmt"
"io"
"log"
"log/slog"
"net"
"net/http"
"net/url"
"os"
"os/signal"
"path/filepath"
goruntime "runtime"
"strings"
"sync"
"syscall"
"time"
"github.com/GoogleCloudPlatform/scion/pkg/agent"
"github.com/GoogleCloudPlatform/scion/pkg/agent/state"
"github.com/GoogleCloudPlatform/scion/pkg/api"
"github.com/GoogleCloudPlatform/scion/pkg/apiclient"
"github.com/GoogleCloudPlatform/scion/pkg/broker"
"github.com/GoogleCloudPlatform/scion/pkg/brokercredentials"
"github.com/GoogleCloudPlatform/scion/pkg/config"
"github.com/GoogleCloudPlatform/scion/pkg/daemon"
"github.com/GoogleCloudPlatform/scion/pkg/ent/entc"
"github.com/GoogleCloudPlatform/scion/pkg/harness"
"github.com/GoogleCloudPlatform/scion/pkg/hub"
"github.com/GoogleCloudPlatform/scion/pkg/messages"
"github.com/GoogleCloudPlatform/scion/pkg/runtime"
"github.com/GoogleCloudPlatform/scion/pkg/runtimebroker"
"github.com/GoogleCloudPlatform/scion/pkg/secret"
"github.com/GoogleCloudPlatform/scion/pkg/storage"
"github.com/GoogleCloudPlatform/scion/pkg/store"
"github.com/GoogleCloudPlatform/scion/pkg/store/entadapter"
"github.com/GoogleCloudPlatform/scion/pkg/store/sqlite"
"github.com/GoogleCloudPlatform/scion/pkg/util"
"github.com/GoogleCloudPlatform/scion/pkg/util/logging"
"github.com/spf13/cobra"
)
// GlobalGroveName is the special name for the default grove when hub and runtime-broker run together
const GlobalGroveName = "global"
var (
serverConfigPath string
hubPort int
hubHost string
enableHub bool
enableRuntimeBroker bool
runtimeBrokerPort int
dbURL string
enableDevAuth bool
enableDebug bool
storageBucket string
storageDir string
// Template cache settings for Runtime Broker
templateCacheDir string
templateCacheMax int64
// Testing flag to simulate remote broker behavior when running co-located
simulateRemoteBroker bool
// Auto-provide flag for runtime broker
serverAutoProvide bool
// Admin emails for bootstrapping - comma-separated list
adminEmails string
// Web frontend flags
enableWeb bool
webPort int
webAssetsDir string
webSessionSecret string
webBaseURL string
// Server daemon flags
serverStartForeground bool
// Production mode flag
productionMode bool
)
const (
// serverDaemonComponent is the component name used for server daemon PID/log files.
serverDaemonComponent = "server"
)
// serverCmd represents the server command
var serverCmd = &cobra.Command{
Use: "server",
Short: "Manage the Scion server components",
Long: `Commands for managing the Scion server components.
By default, the server runs in workstation mode: all components are enabled,
dev-auth is on, and the server binds to 127.0.0.1 (loopback only). This is
the zero-configuration path for single-user, local development.
For production deployments, use --production to require explicit component
selection and bind to 0.0.0.0 by default.
The server provides:
- Hub API: Central registry for groves, agents, and templates (standalone: port 9810)
- Runtime Broker API: Agent lifecycle management on compute nodes (port 9800)
- Web Frontend: Browser-based UI (port 8080)
In combined mode, the Hub API is mounted on the web server's port (default 8080)
and the standalone Hub listener is not started.`,
}
// serverStartCmd represents the server start command
var serverStartCmd = &cobra.Command{
Use: "start",
Short: "Start the Scion server components",
Long: `Start the Scion server.
By default, the server runs in workstation mode: all components (Hub, Broker,
Web) are enabled, dev-auth is on, auto-provide is enabled, and the server
binds to 127.0.0.1 (loopback only). Just run 'scion server start' to get a
fully functional local server with no flags needed.
The server starts as a background daemon by default. Use --foreground to run
in the current terminal session (useful for systemd/launchd integration).
For production deployments, use --production to switch to explicit mode where
no components are enabled by default and the server binds to 0.0.0.0.
Explicit flags always override workstation defaults. For example,
'scion server start --host 0.0.0.0' uses workstation mode but binds to
all interfaces.
Configuration can be provided via:
- Config file (--config flag or ~/.scion/server.yaml)
- Environment variables (SCION_SERVER_* prefix)
- Command-line flags
Examples:
# Start in workstation mode (all components, dev-auth, loopback)
scion server start
# Start in foreground (for systemd/launchd)
scion server start --foreground
# Workstation mode but expose on all interfaces
scion server start --host 0.0.0.0
# Production mode with explicit components
scion server start --production --enable-hub --enable-runtime-broker --enable-web
# Production mode, Hub with Web Frontend only
scion server start --production --enable-hub --enable-web`,
RunE: runServerStartOrDaemon,
}
// serverStopCmd stops the server daemon
var serverStopCmd = &cobra.Command{
Use: "stop",
Short: "Stop the Scion server daemon",
Long: `Stop the Scion server daemon.
This command stops the server if it's running as a daemon.
If the server is running in foreground mode, use Ctrl+C to stop it.
Examples:
# Stop the server daemon
scion server stop`,
RunE: runServerStop,
}
// serverRestartCmd restarts the server daemon
var serverRestartCmd = &cobra.Command{
Use: "restart",
Short: "Restart the Scion server daemon",
Long: `Restart the Scion server daemon.
This command stops the currently running server daemon and starts a new one
using the current scion binary. This is useful after installing a new version
of scion to pick up the updated binary.
If the server is not running as a daemon, this command will return an error.
Examples:
# Restart the server daemon
scion server restart`,
RunE: runServerRestart,
}
// serverStatusCmd shows the current server status
var serverStatusCmd = &cobra.Command{
Use: "status",
Short: "Show Scion server status",
Long: `Show the current status of the Scion server.
This command displays:
- Whether the server is running (daemon or foreground)
- Daemon PID and log file location
- Component health status (Hub, Runtime Broker, Web)
Examples:
# Show server status
scion server status
# Show server status in JSON format
scion server status --json`,
RunE: runServerStatus,
}
var serverStatusJSON bool
// serverInstallCmd generates a service file for the current platform
var serverInstallCmd = &cobra.Command{
Use: "install",
Short: "Generate a system service file for Scion server",
Long: `Generate a systemd (Linux) or launchd (macOS) service file for running
the Scion server as a managed system service.
The generated file uses --foreground mode so the service manager handles
lifecycle, logging, and restart. Workstation mode defaults apply unless
--production is specified.
On Linux, generates a systemd unit file.
On macOS, generates a launchd plist file.
Examples:
# Generate a service file (prints to stdout)
scion server install
# Install directly on Linux (systemd user service)
scion server install > ~/.config/systemd/user/scion-server.service
systemctl --user daemon-reload
systemctl --user enable --now scion-server
# Install directly on macOS (launchd user agent)
scion server install > ~/Library/LaunchAgents/io.scion.server.plist
launchctl load ~/Library/LaunchAgents/io.scion.server.plist`,
RunE: runServerInstall,
}
var serverInstallProduction bool
// portStatus represents the result of checking a port.
type portStatus struct {
inUse bool
isScionServer bool
}
// checkPort checks if a port is already bound and if it's a scion server.
func checkPort(host string, port int) portStatus {
addr := fmt.Sprintf("%s:%d", host, port)
ln, err := net.Listen("tcp", addr)
if err == nil {
ln.Close()
return portStatus{inUse: false}
}
// Port is in use - check if it's a scion server by hitting the health endpoint
client := &http.Client{Timeout: 2 * time.Second}
resp, err := client.Get(fmt.Sprintf("http://%s/healthz", addr))
if err != nil {
return portStatus{inUse: true, isScionServer: false}
}
defer resp.Body.Close()
// Check if the response looks like a scion health response
var health struct {
Status string `json:"status"`
Version string `json:"version"`
Uptime string `json:"uptime"`
}
if err := json.NewDecoder(resp.Body).Decode(&health); err != nil {
return portStatus{inUse: true, isScionServer: false}
}
// If we got valid health response fields, it's a scion server
if health.Status != "" && health.Uptime != "" {
return portStatus{inUse: true, isScionServer: true}
}
return portStatus{inUse: true, isScionServer: false}
}
// runServerStartOrDaemon handles the server start command. By default it launches
// the server as a background daemon. When --foreground is set, it runs directly.
func runServerStartOrDaemon(cmd *cobra.Command, args []string) error {
if serverStartForeground {
return runServerStart(cmd, args)
}
// Daemon mode
globalDir, err := config.GetGlobalDir()
if err != nil {
return fmt.Errorf("failed to get global directory: %w", err)
}
// Check if already running
running, pid, _ := daemon.StatusComponent(serverDaemonComponent, globalDir)
if running {
return fmt.Errorf("server is already running (PID: %d)\n\nUse 'scion server stop' to stop it, or check the log at %s",
pid, daemon.GetLogPathComponent(serverDaemonComponent, globalDir))
}
// Check if production mode is set in config (settings.yaml server.mode)
if !cmd.Flags().Changed("production") {
if mode := config.LoadServerMode(); mode == "production" {
productionMode = true
}
}
// Apply workstation defaults when not in production mode.
// Workstation mode enables all components, dev-auth, auto-provide,
// and binds to loopback (127.0.0.1) for single-user security.
if !productionMode {
if !cmd.Flags().Changed("enable-hub") {
enableHub = true
}
if !cmd.Flags().Changed("enable-runtime-broker") {
enableRuntimeBroker = true
}
if !cmd.Flags().Changed("enable-web") {
enableWeb = true
}
if !cmd.Flags().Changed("dev-auth") {
enableDevAuth = true
}
if !cmd.Flags().Changed("auto-provide") {
serverAutoProvide = true
}
if !cmd.Flags().Changed("host") {
hubHost = "127.0.0.1"
}
}
// Check if at least one component is enabled
if !enableHub && !enableRuntimeBroker && !enableWeb {
return fmt.Errorf("no server components enabled; use --enable-hub, --enable-runtime-broker, or --enable-web")
}
// Find the scion executable
executable, err := os.Executable()
if err != nil {
return fmt.Errorf("failed to find scion executable: %w", err)
}
// Build args for the daemon process — pass through all flags
daemonArgs := []string{"server", "start", "--foreground"}
if productionMode {
daemonArgs = append(daemonArgs, "--production")
}
if enableHub {
daemonArgs = append(daemonArgs, "--enable-hub")
}
if enableRuntimeBroker {
daemonArgs = append(daemonArgs, "--enable-runtime-broker")
}
if enableWeb {
daemonArgs = append(daemonArgs, "--enable-web")
}
if enableDevAuth {
daemonArgs = append(daemonArgs, "--dev-auth")
}
if enableDebug {
daemonArgs = append(daemonArgs, "--debug")
}
if serverAutoProvide {
daemonArgs = append(daemonArgs, "--auto-provide")
}
daemonArgs = append(daemonArgs, fmt.Sprintf("--host=%s", hubHost))
if cmd.Flags().Changed("port") {
daemonArgs = append(daemonArgs, fmt.Sprintf("--port=%d", hubPort))
}
if cmd.Flags().Changed("runtime-broker-port") {
daemonArgs = append(daemonArgs, fmt.Sprintf("--runtime-broker-port=%d", runtimeBrokerPort))
}
if cmd.Flags().Changed("web-port") {
daemonArgs = append(daemonArgs, fmt.Sprintf("--web-port=%d", webPort))
}
if cmd.Flags().Changed("config") {
daemonArgs = append(daemonArgs, fmt.Sprintf("--config=%s", serverConfigPath))
}
if cmd.Flags().Changed("db") {
daemonArgs = append(daemonArgs, fmt.Sprintf("--db=%s", dbURL))
}
if cmd.Flags().Changed("storage-bucket") {
daemonArgs = append(daemonArgs, fmt.Sprintf("--storage-bucket=%s", storageBucket))
}
if cmd.Flags().Changed("storage-dir") {
daemonArgs = append(daemonArgs, fmt.Sprintf("--storage-dir=%s", storageDir))
}
if globalMode {
daemonArgs = append(daemonArgs, "--global")
}
// Start daemon
mode := "workstation"
if productionMode {
mode = "production"
}
fmt.Printf("Starting server as daemon (%s mode)...\n", mode)
if err := daemon.StartComponent(serverDaemonComponent, executable, daemonArgs, globalDir); err != nil {
return fmt.Errorf("failed to start daemon: %w", err)
}
// Save the daemon args for restart
if err := daemon.SaveArgs(serverDaemonComponent, globalDir, daemonArgs); err != nil {
fmt.Fprintf(os.Stderr, "Warning: failed to save daemon args: %v\n", err)
}
// Verify it started
time.Sleep(500 * time.Millisecond)
running, pid, err = daemon.StatusComponent(serverDaemonComponent, globalDir)
if !running {
return fmt.Errorf("daemon failed to start. Check log at: %s", daemon.GetLogPathComponent(serverDaemonComponent, globalDir))
}
fmt.Printf("Server started (PID: %d)\n", pid)
fmt.Printf("Log file: %s\n", daemon.GetLogPathComponent(serverDaemonComponent, globalDir))
fmt.Printf("PID file: %s\n", daemon.GetPIDPathComponent(serverDaemonComponent, globalDir))
fmt.Println()
// Print quickstart info for workstation mode
if !productionMode {
printWorkstationQuickstart(globalDir, hubHost, webPort, enableWeb, enableDevAuth)
}
fmt.Println("Use 'scion server stop' to stop the daemon.")
fmt.Println("Use 'scion server status' to check status.")
return nil
}
func runServerStop(cmd *cobra.Command, args []string) error {
globalDir, err := config.GetGlobalDir()
if err != nil {
return fmt.Errorf("failed to get global directory: %w", err)
}
running, pid, _ := daemon.StatusComponent(serverDaemonComponent, globalDir)
if !running {
return fmt.Errorf("server daemon is not running")
}
fmt.Printf("Stopping server daemon (PID: %d)...\n", pid)
if err := daemon.StopComponent(serverDaemonComponent, globalDir); err != nil {
return fmt.Errorf("failed to stop daemon: %w", err)
}
// Verify it stopped
time.Sleep(500 * time.Millisecond)
running, _, _ = daemon.StatusComponent(serverDaemonComponent, globalDir)
if running {
return fmt.Errorf("daemon may still be running. Check with 'scion server status'")
}
fmt.Println("Server daemon stopped.")
return nil
}
func runServerRestart(cmd *cobra.Command, args []string) error {
globalDir, err := config.GetGlobalDir()
if err != nil {
return fmt.Errorf("failed to get global directory: %w", err)
}
running, pid, _ := daemon.StatusComponent(serverDaemonComponent, globalDir)
if !running {
return fmt.Errorf("server daemon is not running.\n\nUse 'scion server start' to start it.")
}
// Stop the daemon
fmt.Printf("Stopping server daemon (PID: %d)...\n", pid)
if err := daemon.StopComponent(serverDaemonComponent, globalDir); err != nil {
return fmt.Errorf("failed to stop daemon: %w", err)
}
// Wait for the process to exit
if err := daemon.WaitForExitComponent(serverDaemonComponent, globalDir, 10*time.Second); err != nil {
return fmt.Errorf("failed to stop server: %w", err)
}
fmt.Println("Server daemon stopped.")
// Find the current scion executable
executable, err := os.Executable()
if err != nil {
return fmt.Errorf("failed to find scion executable: %w", err)
}
// Load saved args from previous start, or fall back to reconstructing from flags.
daemonArgs, err := daemon.LoadArgs(serverDaemonComponent, globalDir)
if err != nil {
fmt.Fprintf(os.Stderr, "Warning: failed to load saved args: %v\n", err)
}
if daemonArgs == nil {
// No saved args — reconstruct from current flags (legacy behavior).
daemonArgs = []string{"server", "start", "--foreground"}
if enableHub || enableRuntimeBroker || enableWeb {
if enableHub {
daemonArgs = append(daemonArgs, "--enable-hub")
}
if enableRuntimeBroker {
daemonArgs = append(daemonArgs, "--enable-runtime-broker")
}
if enableWeb {
daemonArgs = append(daemonArgs, "--enable-web")
}
}
if enableDevAuth {
daemonArgs = append(daemonArgs, "--dev-auth")
}
if enableDebug {
daemonArgs = append(daemonArgs, "--debug")
}
}
fmt.Println("Starting server with new binary...")
if err := daemon.StartComponent(serverDaemonComponent, executable, daemonArgs, globalDir); err != nil {
return fmt.Errorf("failed to start daemon: %w", err)
}
// Verify it started
time.Sleep(500 * time.Millisecond)
running, pid, _ = daemon.StatusComponent(serverDaemonComponent, globalDir)
if !running {
return fmt.Errorf("daemon failed to start. Check log at: %s", daemon.GetLogPathComponent(serverDaemonComponent, globalDir))
}
fmt.Printf("Server restarted (PID: %d)\n", pid)
fmt.Printf("Log file: %s\n", daemon.GetLogPathComponent(serverDaemonComponent, globalDir))
fmt.Println()
return nil
}
type serverStatusInfo struct {
DaemonRunning bool `json:"daemonRunning"`
DaemonPID int `json:"daemonPid,omitempty"`
LogFile string `json:"logFile,omitempty"`
PIDFile string `json:"pidFile,omitempty"`
HubRunning bool `json:"hubRunning,omitempty"`
BrokerRunning bool `json:"brokerRunning,omitempty"`
WebRunning bool `json:"webRunning,omitempty"`
}
func runServerStatus(cmd *cobra.Command, args []string) error {
globalDir, err := config.GetGlobalDir()
if err != nil {
return fmt.Errorf("failed to get global directory: %w", err)
}
status := serverStatusInfo{}
// Check daemon status
running, pid, _ := daemon.StatusComponent(serverDaemonComponent, globalDir)
status.DaemonRunning = running
status.DaemonPID = pid
if running {
status.LogFile = daemon.GetLogPathComponent(serverDaemonComponent, globalDir)
status.PIDFile = daemon.GetPIDPathComponent(serverDaemonComponent, globalDir)
}
// Probe health endpoints to check component status
client := &http.Client{Timeout: 2 * time.Second}
// Check web/hub on default web port (8080)
if resp, err := client.Get("http://127.0.0.1:8080/healthz"); err == nil {
resp.Body.Close()
if resp.StatusCode == http.StatusOK {
status.WebRunning = true
status.HubRunning = true // Hub is mounted on web when both are enabled
}
}
// Check standalone hub on default hub port (9810) if not found on web port
if !status.HubRunning {
if resp, err := client.Get("http://127.0.0.1:9810/healthz"); err == nil {
resp.Body.Close()
if resp.StatusCode == http.StatusOK {
status.HubRunning = true
}
}
}
// Check broker on default broker port (9800)
if resp, err := client.Get("http://127.0.0.1:9800/healthz"); err == nil {
resp.Body.Close()
if resp.StatusCode == http.StatusOK {
status.BrokerRunning = true
}
}
if serverStatusJSON {
enc := json.NewEncoder(os.Stdout)
enc.SetIndent("", " ")
return enc.Encode(status)
}
// Human-readable output
fmt.Println("Scion Server Status")
if status.DaemonRunning {
fmt.Printf(" Daemon: running (PID: %d)\n", status.DaemonPID)
fmt.Printf(" Log file: %s\n", status.LogFile)
fmt.Printf(" PID file: %s\n", status.PIDFile)
} else {
fmt.Println(" Daemon: not running")
}
fmt.Println()
fmt.Println("Components:")
if status.HubRunning {
fmt.Println(" Hub API: running")
} else {
fmt.Println(" Hub API: not detected")
}
if status.BrokerRunning {
fmt.Println(" Runtime Broker: running")
} else {
fmt.Println(" Runtime Broker: not detected")
}
if status.WebRunning {
fmt.Println(" Web Frontend: running")
} else {
fmt.Println(" Web Frontend: not detected")
}
return nil
}
func runServerStart(cmd *cobra.Command, args []string) error {
// Initialize logging
useGCP := os.Getenv("SCION_LOG_GCP") == "true"
if os.Getenv("K_SERVICE") != "" {
// Auto-enable GCP logging on Cloud Run
useGCP = true
}
// Disable GCP logging in workstation mode unless explicitly enabled
if !productionMode && os.Getenv("SCION_LOG_GCP") == "" {
useGCP = false
}
// Determine component name based on flags
component := "scion-server"
if enableHub && !enableRuntimeBroker {
component = "scion-hub"
} else if !enableHub && enableRuntimeBroker {
component = "scion-broker"
}
// Initialize OTel logging if configured
ctx := context.Background()
logProvider, logCleanup, err := logging.InitOTelLogging(ctx, logging.OTelConfig{})
if err != nil {
log.Printf("Warning: failed to initialize OTel logging: %v", err)
}
if logCleanup != nil {
defer logCleanup()
}
// Initialize direct Cloud Logging if enabled
var cloudHandler slog.Handler
if logging.IsCloudLoggingEnabled() {
logLevel := logging.ResolveLogLevel(enableDebug)
cfg := logging.CloudLoggingConfig{
Component: component,
}
ch, cloudLogCleanup, cloudErr := logging.NewCloudHandler(ctx, cfg, logLevel)
if cloudErr != nil {
log.Printf("Warning: failed to initialize Cloud Logging: %v", cloudErr)
} else {
cloudHandler = ch
defer cloudLogCleanup()
log.Printf("Cloud Logging enabled (logId=%s, project=%s)", logging.FormatLogID(), logging.FormatProjectID())
}
}
// Setup logging with optional OTel bridge and Cloud Logging handler
logging.SetupWithOTel(component, enableDebug, useGCP, logProvider, cloudHandler)
// Initialize dedicated request logger
reqLogCfg := logging.RequestLoggerConfig{
FilePath: os.Getenv(logging.EnvRequestLogPath),
Component: component,
UseGCP: useGCP,
Foreground: serverStartForeground,
Level: logging.ResolveLogLevel(enableDebug),
}
if ch, ok := cloudHandler.(*logging.CloudHandler); ok && ch != nil {
reqLogCfg.CloudClient = ch.Client()
reqLogCfg.ProjectID = logging.FormatProjectID()
}
requestLogger, reqLogCleanup, err := logging.NewRequestLogger(reqLogCfg)
if err != nil {
slog.Warn("Failed to initialize request logger", "error", err)
requestLogger = slog.New(slog.NewJSONHandler(io.Discard, nil))
}
if reqLogCleanup != nil {
defer reqLogCleanup()
}
// Initialize dedicated message logger for message audit trail
msgLogCfg := logging.MessageLoggerConfig{
Component: component,
UseGCP: useGCP,
Level: logging.ResolveLogLevel(enableDebug),
}
if ch, ok := cloudHandler.(*logging.CloudHandler); ok && ch != nil {
msgLogCfg.CloudClient = ch.Client()
}
messageLogger, msgLogCleanup, err := logging.NewMessageLogger(msgLogCfg)
if err != nil {
slog.Warn("Failed to initialize message logger", "error", err)
messageLogger = nil
}
if msgLogCleanup != nil {
defer msgLogCleanup()
}
// Load configuration
cfg, err := config.LoadGlobalConfig(serverConfigPath)
if err != nil {
return fmt.Errorf("failed to load configuration: %w", err)
}
// Check if production mode is set in config (settings.yaml server.mode).
// The config value is only consulted if --production was not explicitly passed.
if !cmd.Flags().Changed("production") {
if cfg.Mode == "production" {
productionMode = true
}
}
// Apply workstation defaults when not in production mode.
// These are applied before explicit flag overrides so flags always win.
if !productionMode {
if !cmd.Flags().Changed("enable-hub") {
enableHub = true
}
if !cmd.Flags().Changed("enable-runtime-broker") {
enableRuntimeBroker = true
cfg.RuntimeBroker.Enabled = true
}
if !cmd.Flags().Changed("enable-web") {
enableWeb = true
}
if !cmd.Flags().Changed("dev-auth") {
enableDevAuth = true
cfg.Auth.Enabled = true
}
if !cmd.Flags().Changed("auto-provide") {
serverAutoProvide = true
}
if !cmd.Flags().Changed("host") {
cfg.Hub.Host = "127.0.0.1"
cfg.RuntimeBroker.Host = "127.0.0.1"
}
// Force local backends unless explicitly overridden
if !cmd.Flags().Changed("storage-bucket") {
cfg.Storage.Provider = "local"
}
cfg.Secrets.Backend = "local"
}
// Override with command-line flags if specified
if cmd.Flags().Changed("port") {
cfg.Hub.Port = hubPort
}
if cmd.Flags().Changed("host") {
cfg.Hub.Host = hubHost
}
if cmd.Flags().Changed("db") {
cfg.Database.URL = dbURL
}
if cmd.Flags().Changed("enable-hub") {
// If explicitly set, use the flag value
// (enableHub is the variable, it's already set by cobra)
}
if cmd.Flags().Changed("enable-runtime-broker") {
cfg.RuntimeBroker.Enabled = enableRuntimeBroker
}
if cmd.Flags().Changed("runtime-broker-port") {
cfg.RuntimeBroker.Port = runtimeBrokerPort
}
if cmd.Flags().Changed("dev-auth") {
cfg.Auth.Enabled = enableDevAuth
}
// Handle storage configuration
if cmd.Flags().Changed("storage-bucket") {
cfg.Storage.Bucket = storageBucket
}
if cmd.Flags().Changed("storage-dir") {
cfg.Storage.LocalPath = storageDir
}
// Fallback to legacy environment variable if not set elsewhere (production mode only)
if cfg.Storage.Bucket == "" && productionMode {
if val := os.Getenv("SCION_HUB_STORAGE_BUCKET"); val != "" {
cfg.Storage.Bucket = val
if cfg.Storage.Provider == "local" || cfg.Storage.Provider == "" {
cfg.Storage.Provider = "gcs"
}
}
}
// Update local variables from cfg for backward compatibility in initialization logic
storageBucket = cfg.Storage.Bucket
storageDir = cfg.Storage.LocalPath
if storageBucket != "" && (cfg.Storage.Provider == "local" || cfg.Storage.Provider == "") {
cfg.Storage.Provider = "gcs"
}
// Resolve admin mode settings from config and env vars.
// SCION_SERVER_ADMIN_MODE maps to admin.mode due to underscore splitting,
// so we read these env vars directly (consistent with SESSION_SECRET, BASE_URL, etc.).
adminMode := cfg.AdminMode
if v := os.Getenv("SCION_SERVER_ADMIN_MODE"); v != "" {
adminMode = v == "true" || v == "1" || v == "yes"
}
maintenanceMessage := cfg.MaintenanceMessage
if v := os.Getenv("SCION_SERVER_MAINTENANCE_MESSAGE"); v != "" {
maintenanceMessage = v
}
// Ensure global directory exists and settings are initialized.
// This is required for persisting the runtime broker identity.
globalDir, err := config.GetGlobalDir()
if err != nil {
return fmt.Errorf("failed to get global directory: %w", err)
}
if _, err := os.Stat(globalDir); os.IsNotExist(err) {
log.Println("Initializing global scion directory...")
if err := config.InitGlobal(harness.All()); err != nil {
return fmt.Errorf("failed to initialize global config: %w", err)
}
}
// When --global is set, change to the home directory so the server
// operates from the global grove context regardless of where it was launched.
if globalMode {
home, err := os.UserHomeDir()
if err != nil {
return fmt.Errorf("failed to get home directory: %w", err)
}
if err := os.Chdir(home); err != nil {
return fmt.Errorf("failed to change to home directory: %w", err)
}
log.Printf("Global mode: changed working directory to %s", home)
}
// Warn if running from within a project grove instead of the global (~/.scion) grove.
// The server loads templates and settings from the active grove context, so running
// inside a project grove may pick up project-specific (possibly legacy) configuration.
if projectDir, ok := config.FindProjectRoot(); ok {
if projectDir != globalDir {
parentDir := filepath.Dir(projectDir)
fmt.Fprintf(os.Stderr, "\n%s%s WARNING: Server is running from a project grove context (%s)%s\n",
util.Bold, util.Yellow, parentDir, util.Reset)
fmt.Fprintf(os.Stderr, "%s%s The runtime broker will use this grove's templates and settings.%s\n",
util.Bold, util.Yellow, util.Reset)
fmt.Fprintf(os.Stderr, "%s%s For machine-wide operation, run the server from outside any project grove.%s\n\n",
util.Bold, util.Yellow, util.Reset)
}
}
// Check if at least one server is enabled
if !enableHub && !cfg.RuntimeBroker.Enabled && !enableWeb {
return fmt.Errorf("no server components enabled; use --enable-hub, --enable-runtime-broker, or --enable-web")
}
// Check if server ports are already in use
if enableHub && !enableWeb {
// Only check Hub port when running standalone (not mounted on web server).
status := checkPort(cfg.Hub.Host, cfg.Hub.Port)
if status.inUse {
if status.isScionServer {
return fmt.Errorf("a scion server is already running on port %d\nUse 'scion server status' to check or 'scion server stop' to stop it", cfg.Hub.Port)
}
return fmt.Errorf("Hub port %d is already in use by another process", cfg.Hub.Port)
}
}
if cfg.RuntimeBroker.Enabled {
status := checkPort(cfg.RuntimeBroker.Host, cfg.RuntimeBroker.Port)
if status.inUse {
if status.isScionServer {
return fmt.Errorf("a scion server is already running on port %d\nUse 'scion server status' to check or 'scion server stop' to stop it", cfg.RuntimeBroker.Port)
}
return fmt.Errorf("Runtime Broker port %d is already in use by another process", cfg.RuntimeBroker.Port)
}
}
if enableWeb {
webHost := cfg.Hub.Host
if webHost == "" {
webHost = "0.0.0.0"
}
status := checkPort(webHost, webPort)
if status.inUse {
if status.isScionServer {
return fmt.Errorf("a scion server is already running on port %d\nUse 'scion server status' to check or 'scion server stop' to stop it", webPort)
}
return fmt.Errorf("Web Frontend port %d is already in use by another process", webPort)
}
}
// Log server mode
if productionMode {
log.Println("Server mode: production")
} else {
log.Printf("Server mode: workstation (binding to %s)", cfg.Hub.Host)
}
// Log debug mode status
if enableDebug {
log.Println("Debug logging enabled")
// Log OAuth configuration for debugging
logOAuthDebug(cfg)
}
// Setup graceful shutdown
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
sigCh := make(chan os.Signal, 1)
signal.Notify(sigCh, syscall.SIGINT, syscall.SIGTERM)
go func() {
sig := <-sigCh
log.Printf("Received signal %v, shutting down...", sig)
cancel()
}()
var wg sync.WaitGroup
errCh := make(chan error, 3)
// Initialize store (needed for Hub and for global grove registration)
var s store.Store
if enableHub {
switch cfg.Database.Driver {
case "sqlite":
sqliteStore, err := sqlite.New(cfg.Database.URL)
if err != nil {
return fmt.Errorf("failed to open database: %w", err)
}
defer sqliteStore.Close()
// Run legacy migrations
if err := sqliteStore.Migrate(context.Background()); err != nil {
return fmt.Errorf("failed to run migrations: %w", err)
}
// Create Ent client for group operations (uses a separate
// in-process database so Ent-managed tables don't conflict
// with the legacy SQLite schema).
entDSN := cfg.Database.URL + "_ent"
entClient, err := entc.OpenSQLite("file:" + entDSN + "?cache=shared")
if err != nil {
return fmt.Errorf("failed to open ent database: %w", err)
}
if err := entc.AutoMigrate(context.Background(), entClient); err != nil {
entClient.Close()
return fmt.Errorf("failed to run ent migrations: %w", err)
}
// Wrap the SQLite store with the Ent-backed CompositeStore
// so that all group operations use the Ent ORM.
s = entadapter.NewCompositeStore(sqliteStore, entClient)
default:
return fmt.Errorf("unsupported database driver: %s", cfg.Database.Driver)
}
// Verify database connectivity
if err := s.Ping(context.Background()); err != nil {
return fmt.Errorf("database ping failed: %w", err)
}
}
// Variables to track runtime broker info for co-located registration
var brokerID string
var brokerName string
var rt runtime.Runtime
var brokerSettings *config.Settings