forked from labring-sigs/sealos-migrate
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
1351 lines (1207 loc) · 39.8 KB
/
main.go
File metadata and controls
1351 lines (1207 loc) · 39.8 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
package main
import (
"bytes"
"context"
"crypto/hmac"
"crypto/sha256"
"database/sql"
"encoding/base64"
"encoding/csv"
"encoding/json"
"errors"
"flag"
"fmt"
"net"
"net/url"
"os"
"os/exec"
"path/filepath"
"strings"
"time"
_ "github.com/lib/pq"
"github.com/modood/table"
)
const (
defaultSealosEnvPath = "/root/.sealos/cloud/sealos.env"
defaultGlobalsPath = "/root/.sealos/cloud/values/globals.yaml"
)
const (
colorReset = "\033[0m"
colorRed = "\033[31m"
colorCyan = "\033[36m"
colorYellow = "\033[33m"
colorPurple = "\033[35m"
colorGreenBold = "\033[1;32m\033[1m"
)
type logger struct{}
// ServiceInfo 服务信息表格结构
type ServiceInfo struct {
Name string
User string
Password string
Version string
PublishAddr string
}
// RegionInfo 区域信息表格结构
type RegionInfo struct {
Key string
Value string
}
func (l logger) timestamp() string {
return time.Now().Format("2006-01-02 15:04:05")
}
func (l logger) errorf(format string, args ...any) {
flag := l.timestamp()
fmt.Printf("%s ERROR [%s] >> %s %s\n", colorRed, flag, fmt.Sprintf(format, args...), colorReset)
os.Exit(1)
}
func (l logger) infof(format string, args ...any) {
flag := l.timestamp()
fmt.Printf("%s INFO [%s] >> %s %s\n", colorCyan, flag, fmt.Sprintf(format, args...), colorReset)
}
func (l logger) warnf(format string, args ...any) {
flag := l.timestamp()
fmt.Printf("%s WARN [%s] >> %s %s\n", colorYellow, flag, fmt.Sprintf(format, args...), colorReset)
}
func (l logger) debugf(format string, args ...any) {
flag := l.timestamp()
fmt.Printf("%s DEBUG [%s] >> %s %s\n", colorPurple, flag, fmt.Sprintf(format, args...), colorReset)
}
func (l logger) printf(format string, args ...any) {
flag := l.timestamp()
fmt.Printf("%s INFO [%s] >> %s %s\n", colorGreenBold, flag, fmt.Sprintf(format, args...), colorReset)
}
func main() {
log := logger{}
flag.Usage = func() {
out := flag.CommandLine.Output()
fmt.Fprintf(out, "用法:\n")
fmt.Fprintf(out, " %s [参数]\n\n", filepath.Base(os.Args[0]))
fmt.Fprintf(out, "说明:\n")
fmt.Fprintf(out, " 默认输出 Sealos Cloud 相关服务信息,并可生成 ns-admin 登录链接。\n")
fmt.Fprintf(out, " 也支持通过单独参数仅输出某个配置值。\n\n")
fmt.Fprintf(out, "参数:\n")
flag.PrintDefaults()
fmt.Fprintf(out, "\n示例:\n")
fmt.Fprintf(out, " %s -cloud-domain\n", filepath.Base(os.Args[0]))
fmt.Fprintf(out, " %s -global-db-internal\n", filepath.Base(os.Args[0]))
fmt.Fprintf(out, " %s -global-db-external\n", filepath.Base(os.Args[0]))
fmt.Fprintf(out, " %s -region-id\n", filepath.Base(os.Args[0]))
fmt.Fprintf(out, " %s -cluster-id\n", filepath.Base(os.Args[0]))
fmt.Fprintf(out, " %s -jwt-global\n", filepath.Base(os.Args[0]))
fmt.Fprintf(out, " %s -password-salt\n", filepath.Base(os.Args[0]))
fmt.Fprintf(out, " %s -regin-info\n", filepath.Base(os.Args[0]))
fmt.Fprintf(out, " %s -region-info\n", filepath.Base(os.Args[0]))
fmt.Fprintf(out, " %s -only-ns-admin -ns-admin-user-id admin\n", filepath.Base(os.Args[0]))
}
sealosEnvPath := flag.String("sealos-env", defaultSealosEnvPath, "sealos.env 文件路径")
onlyNsAdmin := flag.Bool("only-ns-admin", false, "仅生成 ns-admin 登录链接")
skipNsAdmin := flag.Bool("skip-ns-admin", false, "跳过 ns-admin 登录链接生成")
nsAdminUserID := flag.String("ns-admin-user-id", "admin", "ns-admin 登录用户 ID")
nsAdminUserUID := flag.String("ns-admin-user-uid", "", "ns-admin 登录用户 UID(可为空自动查)")
nsAdminNamespace := flag.String("ns-admin-namespace", "admin-system", "ns-admin configmap 所在命名空间")
nsAdminConfigMap := flag.String("ns-admin-configmap", "admin-sealos-admin", "ns-admin configmap 名称")
printCloudDomain := flag.Bool("cloud-domain", false, "仅输出 sealos-config 中的 cloudDomain")
printGlobalDBInternal := flag.Bool("global-db-internal", false, "仅输出内网全局数据库地址")
printGlobalDBExternal := flag.Bool("global-db-external", false, "仅输出外网全局数据库地址")
printRegionID := flag.Bool("region-id", false, "仅输出区域 ID")
printClusterID := flag.Bool("cluster-id", false, "仅输出集群 ID(kube-system namespace UID 前八位)")
printJWTGlobal := flag.Bool("jwt-global", false, "仅输出 desktop auth jwt.global")
printPasswordSalt := flag.Bool("password-salt", false, "仅输出 desktop auth passwordSalt")
printReginInfo := flag.Bool("regin-info", false, "以表格输出 cluster-id、region-id、cloud-domain、jwt-global、password-salt、global-db-external")
printRegionInfo := flag.Bool("region-info", false, "以表格输出 cluster-id、region-id、cloud-domain、jwt-global、password-salt、global-db-external(regin-info 别名)")
flag.Parse()
if _, err := exec.LookPath("kubectl"); err != nil {
log.errorf("kubectl 未安装或不在 PATH 中")
}
if *printJWTGlobal && *printPasswordSalt {
log.errorf("参数冲突: -jwt-global 和 -password-salt 仅支持单个参数输出,请分别执行")
}
if *printCloudDomain || *printGlobalDBInternal || *printGlobalDBExternal || *printRegionID || *printClusterID || *printJWTGlobal || *printPasswordSalt || *printReginInfo || *printRegionInfo {
if *printReginInfo || *printRegionInfo {
jwtGlobal, passwordSalt, err := getDesktopAuthSecrets()
if err != nil {
log.errorf("获取 desktop auth 配置失败: %v", err)
}
clusterID, err := getClusterID()
if err != nil {
log.errorf("获取集群 ID 失败: %v", err)
}
regionID, err := getSealosConfigValue("regionUID")
if err != nil {
log.errorf("获取区域 ID 失败: %v", err)
}
internalURI, err := getSealosConfigValue("databaseGlobalCockroachdbURI")
if err != nil {
log.errorf("获取内网全局数据库地址失败: %v", err)
}
cloudDomain, err := getSealosConfigValue("cloudDomain")
if err != nil {
log.errorf("获取 cloudDomain 失败: %v", err)
}
globalDBExternal, err := buildExternalDatabaseURI(internalURI, cloudDomain)
if err != nil {
log.errorf("生成外网全局数据库地址失败: %v", err)
}
infos := []RegionInfo{
{Key: "cloud-domain", Value: cloudDomain},
{Key: "cluster-id", Value: clusterID},
{Key: "region-id", Value: regionID},
{Key: "jwt-global", Value: jwtGlobal},
{Key: "password-salt", Value: passwordSalt},
{Key: "global-db-external", Value: globalDBExternal},
}
table.Output(infos)
return
}
if *printCloudDomain {
value, err := getSealosConfigValue("cloudDomain")
if err != nil {
log.errorf("获取 cloudDomain 失败: %v", err)
}
fmt.Println(value)
}
if *printGlobalDBInternal {
value, err := getSealosConfigValue("databaseGlobalCockroachdbURI")
if err != nil {
log.errorf("获取内网全局数据库地址失败: %v", err)
}
fmt.Println(value)
}
if *printGlobalDBExternal {
internalURI, err := getSealosConfigValue("databaseGlobalCockroachdbURI")
if err != nil {
log.errorf("获取内网全局数据库地址失败: %v", err)
}
cloudDomain, err := getSealosConfigValue("cloudDomain")
if err != nil {
log.errorf("获取 cloudDomain 失败: %v", err)
}
value, err := buildExternalDatabaseURI(internalURI, cloudDomain)
if err != nil {
log.errorf("生成外网全局数据库地址失败: %v", err)
}
fmt.Println(value)
}
if *printRegionID {
value, err := getSealosConfigValue("regionUID")
if err != nil {
log.errorf("获取区域 ID 失败: %v", err)
}
fmt.Println(value)
}
if *printClusterID {
value, err := getClusterID()
if err != nil {
log.errorf("获取集群 ID 失败: %v", err)
}
fmt.Println(value)
}
if *printJWTGlobal || *printPasswordSalt {
jwtGlobal, passwordSalt, err := getDesktopAuthSecrets()
if err != nil {
log.errorf("获取 desktop auth 配置失败: %v", err)
}
if *printJWTGlobal {
fmt.Println(jwtGlobal)
}
if *printPasswordSalt {
fmt.Println(passwordSalt)
}
}
return
}
log.infof("Sealos Cloud")
sealosEnv, err := loadEnvFile(*sealosEnvPath)
if err != nil {
log.errorf("Sealos cloud not found %s. Please install sealos cloud first.", *sealosEnvPath)
}
log.infof("Loading configuration from %s", *sealosEnvPath)
sealosCloudDomain := firstNonEmpty(sealosEnv["SEALOS_V2_CLOUD_DOMAIN"], sealosEnv["SEALOS_CLOUD_DOMAIN"])
sealosCloudPort := firstNonEmpty(sealosEnv["SEALOS_V2_CLOUD_PORT"], sealosEnv["SEALOS_CLOUD_PORT"])
k8sVersion, err := getKubernetesVersion()
if err != nil {
log.warnf("获取 Kubernetes 版本失败: %v", err)
}
sealosCloudVersion, err := getSealosCloudVersion()
if err != nil {
log.warnf("获取 Sealos Cloud 版本失败: %v", err)
}
if !*onlyNsAdmin {
// 收集所有服务信息
var services []ServiceInfo
services = append(services, minioInfo(sealosCloudDomain)...)
services = append(services, grafanaInfo(sealosCloudDomain)...)
services = append(services, vmInfo(sealosCloudDomain)...)
services = append(services, vlogsInfo(sealosCloudDomain)...)
services = append(services, hamiInfo()...) // 添加 HAMI 信息
services = append(services, finishInfo(sealosCloudDomain, sealosCloudPort, k8sVersion, sealosCloudVersion)...)
services = append(services, aiproxyInfo(sealosCloudDomain)...) // 添加 AIProxy 信息
services = append(services, cockroachInfo(sealosCloudDomain)...) // 添加 CockroachDB 信息
// 输出表格
if len(services) > 0 {
log.printf("")
table.Output(services)
} else {
log.warnf("未找到任何服务信息")
}
// 单独输出证书信息
tlsTips(log, sealosCloudDomain)
}
if !*skipNsAdmin {
userID := strings.TrimSpace(*nsAdminUserID)
if userID == "" {
userID = "admin"
}
link, err := generateNsAdminLink(*nsAdminNamespace, *nsAdminConfigMap, userID, *nsAdminUserUID)
if err != nil {
if *onlyNsAdmin {
log.errorf("生成 ns-admin 登录链接失败: %v", err)
} else {
log.warnf("生成 ns-admin 登录链接失败: %v", err)
}
} else {
log.infof("ns-admin 登录链接:")
log.printf("%s", link)
}
}
}
func loadEnvFile(path string) (map[string]string, error) {
data, err := os.ReadFile(filepath.Clean(path))
if err != nil {
return nil, err
}
envs := map[string]string{}
lines := strings.Split(string(data), "\n")
for _, line := range lines {
line = strings.TrimSpace(line)
if line == "" || strings.HasPrefix(line, "#") {
continue
}
if strings.HasPrefix(line, "export ") {
line = strings.TrimSpace(strings.TrimPrefix(line, "export "))
}
parts := strings.SplitN(line, "=", 2)
if len(parts) != 2 {
continue
}
key := strings.TrimSpace(parts[0])
val := strings.TrimSpace(parts[1])
val = strings.Trim(val, `"'`)
envs[key] = val
}
return envs, nil
}
func firstNonEmpty(values ...string) string {
for _, value := range values {
if value != "" {
return value
}
}
return ""
}
func getSealosConfigValue(key string) (string, error) {
value, err := runCommand("kubectl", "get", "configmap", "sealos-config", "-n", "sealos-system",
"-o", fmt.Sprintf("jsonpath={.data.%s}", key))
if err != nil {
return "", err
}
if strings.TrimSpace(value) == "" {
return "", fmt.Errorf("sealos-config 中的 %s 为空", key)
}
return value, nil
}
func buildExternalDatabaseURI(internalURI, cloudDomain string) (string, error) {
parsed, err := url.Parse(internalURI)
if err != nil {
return "", err
}
if strings.TrimSpace(cloudDomain) == "" {
return "", fmt.Errorf("cloudDomain 为空")
}
parsed.Host = fmt.Sprintf("%s:%d", cloudDomain, 36257)
return parsed.String(), nil
}
func getClusterID() (string, error) {
uid, err := runCommand("kubectl", "get", "ns", "kube-system", "-o", "jsonpath={.metadata.uid}")
if err != nil {
return "", err
}
uid = strings.TrimSpace(uid)
if len(uid) < 8 {
return "", fmt.Errorf("kube-system namespace UID 长度不足: %q", uid)
}
return uid[:8], nil
}
func runCommand(name string, args ...string) (string, error) {
cmd := exec.Command(name, args...)
var out bytes.Buffer
var stderr bytes.Buffer
cmd.Stdout = &out
cmd.Stderr = &stderr
if err := cmd.Run(); err != nil {
if stderr.Len() > 0 {
return "", fmt.Errorf("%v: %s", err, strings.TrimSpace(stderr.String()))
}
return "", err
}
return strings.TrimSpace(out.String()), nil
}
func runShell(command string) (string, error) {
return runCommand("sh", "-c", command)
}
func getKubernetesVersion() (string, error) {
output, err := runCommand("kubectl", "version", "-o", "json")
if err != nil {
return "", err
}
var payload struct {
ServerVersion struct {
GitVersion string `json:"gitVersion"`
} `json:"serverVersion"`
}
if err := json.Unmarshal([]byte(output), &payload); err != nil {
return "", err
}
return strings.TrimPrefix(payload.ServerVersion.GitVersion, "v"), nil
}
func getSealosCloudVersion() (string, error) {
deploys := []string{
"desktop-frontend",
"sealos-desktop",
}
for _, deploy := range deploys {
image, err := runCommand("kubectl", "get", "deployment", deploy, "-n", "sealos",
"-o", "jsonpath={.spec.template.spec.containers[0].image}")
if err == nil && image != "" {
lastColon := strings.LastIndex(image, ":")
if lastColon != -1 && lastColon != len(image)-1 {
return image[lastColon+1:], nil
}
}
}
return "", fmt.Errorf("未找到 Sealos Cloud 版本信息")
}
func finishInfo(domain, port, k8sVersion, sealosCloudVersion string) []ServiceInfo {
var services []ServiceInfo
adminPassword, err := runCommand("kubectl", "get", "cm", "sealos-cloud-admin", "-n", "sealos-system",
"-o", "jsonpath={.data.PASSWORD}", "--ignore-not-found")
if err != nil {
adminPassword = ""
}
if strings.TrimSpace(adminPassword) == "" {
adminPassword, err = runCommand("kubectl", "get", "job", "init-job", "-n", "account-system",
"-o", "jsonpath={.spec.template.spec.containers[0].env[?(@.name==\"ADMIN_PASSWORD\")].value}")
if err != nil {
adminPassword = "<获取失败>"
}
}
// 添加主服务信息
services = append(services, ServiceInfo{
Name: "Sealos Cloud",
User: "admin",
Password: adminPassword,
Version: sealosCloudVersion,
PublishAddr: fmt.Sprintf("https://%s:%s", domain, port),
})
// 添加Kubernetes版本信息
services = append(services, ServiceInfo{
Name: "Kubernetes",
User: "-",
Password: "-",
Version: k8sVersion,
PublishAddr: "-",
})
return services
}
func minioInfo(domain string) []ServiceInfo {
var services []ServiceInfo
consoleUser, err := runCommand("kubectl", "get", "cm", "objectstorage-config", "-n", "sealos-system",
"-o", "jsonpath={.data.MINIO_CONSOLE_USER}")
if err != nil {
return services
}
consolePassword, _ := runCommand("kubectl", "get", "cm", "objectstorage-config", "-n", "sealos-system",
"-o", "jsonpath={.data.MINIO_CONSOLE_PASSWORD}")
kbUser, _ := runCommand("kubectl", "get", "cm", "objectstorage-config", "-n", "sealos-system",
"-o", "jsonpath={.data.MINIO_KB_USER}")
kbPassword, _ := runCommand("kubectl", "get", "cm", "objectstorage-config", "-n", "sealos-system",
"-o", "jsonpath={.data.MINIO_KB_PASSWORD}")
testUserPassword, _ := runCommand("kubectl", "get", "cm", "objectstorage-config", "-n", "sealos-system",
"-o", "jsonpath={.data.MINIO_TESTUSER_PASSWORD}")
minioURL := fmt.Sprintf("https://osconsole.%s", domain)
// MinIO Console
services = append(services, ServiceInfo{
Name: "MinIO Console",
User: consoleUser,
Password: consolePassword,
Version: "-",
PublishAddr: minioURL,
})
// MinIO KB
services = append(services, ServiceInfo{
Name: "MinIO KB",
User: kbUser,
Password: kbPassword,
Version: "-",
PublishAddr: minioURL,
})
// MinIO Test User
services = append(services, ServiceInfo{
Name: "MinIO Test",
User: "testuser",
Password: testUserPassword,
Version: "-",
PublishAddr: minioURL,
})
return services
}
func grafanaInfo(domain string) []ServiceInfo {
var services []ServiceInfo
adminPassword, err := runCommand("kubectl", "get", "cm", "grafana-config", "-n", "sealos-system",
"-o", "jsonpath={.data.GF_PASSWORD}")
if err != nil {
return services
}
adminUser, _ := runCommand("kubectl", "get", "cm", "grafana-config", "-n", "sealos-system",
"-o", "jsonpath={.data.GF_USER}")
services = append(services, ServiceInfo{
Name: "Grafana",
User: adminUser,
Password: adminPassword,
Version: "-",
PublishAddr: fmt.Sprintf("https://gggggrafana.%s", domain),
})
return services
}
func vmInfo(domain string) []ServiceInfo {
var services []ServiceInfo
secretName := "vmuser-vm-stack-victoria-metrics-k8s-stack"
ns := "vm"
nameB64, err := runCommand("kubectl", "get", "secrets", secretName, "-n", ns,
"-o", "jsonpath={.data.name}")
if err != nil {
return services
}
passwordB64, _ := runCommand("kubectl", "get", "secrets", secretName, "-n", ns,
"-o", "jsonpath={.data.password}")
usernameB64, _ := runCommand("kubectl", "get", "secrets", secretName, "-n", ns,
"-o", "jsonpath={.data.username}")
name := decodeBase64(nameB64)
username := decodeBase64(usernameB64)
password := decodeBase64(passwordB64)
// 如果三个值都为空,视为整体失败
if name == "" && username == "" && password == "" {
return services
}
// VictoriaMetrics vmui
services = append(services, ServiceInfo{
Name: "VictoriaMetrics VMUI",
User: username,
Password: password,
Version: "-",
PublishAddr: fmt.Sprintf("https://vmmmmauth.%s/vmui", domain),
})
// VictoriaMetrics Agent
services = append(services, ServiceInfo{
Name: "VictoriaMetrics Agent",
User: username,
Password: password,
Version: "-",
PublishAddr: fmt.Sprintf("https://vmmmmagent.%s", domain),
})
return services
}
func vlogsInfo(domain string) []ServiceInfo {
var services []ServiceInfo
sysUser, err := runCommand("kubectl", "get", "configmap", "vlogs-config", "-n", "sealos-system",
"-o", "jsonpath={.data.SELECT_USER}")
if err != nil {
return services
}
sysPassword, _ := runCommand("kubectl", "get", "configmap", "vlogs-config", "-n", "sealos-system",
"-o", "jsonpath={.data.SELECT_PASSWORD}")
userUser, _ := runCommand("kubectl", "get", "configmap", "vlogs-config-user", "-n", "sealos-system",
"-o", "jsonpath={.data.SELECT_USER}")
userPassword, _ := runCommand("kubectl", "get", "configmap", "vlogs-config-user", "-n", "sealos-system",
"-o", "jsonpath={.data.SELECT_PASSWORD}")
// System Logs
services = append(services, ServiceInfo{
Name: "System Logs",
User: sysUser,
Password: sysPassword,
Version: "-",
PublishAddr: fmt.Sprintf("https://vvvvvvlogs.%s", domain),
})
// User Logs
services = append(services, ServiceInfo{
Name: "User Logs",
User: userUser,
Password: userPassword,
Version: "-",
PublishAddr: fmt.Sprintf("https://vvvvvvuserlogs.%s", domain),
})
return services
}
func hamiInfo() []ServiceInfo {
var services []ServiceInfo
// 读取 HAMI webui 配置
webuiAddress, err := runCommand("kubectl", "get", "cm", "hami-webui-config", "-n", "sealos-system",
"-o", "jsonpath={.data.HAMI_WEBUI_ADDRESS}")
if err != nil {
// HAMI 配置不存在,直接返回空数组
return services
}
webuiUser, _ := runCommand("kubectl", "get", "cm", "hami-webui-config", "-n", "sealos-system",
"-o", "jsonpath={.data.HAMI_WEBUI_USER}")
webuiPassword, _ := runCommand("kubectl", "get", "cm", "hami-webui-config", "-n", "sealos-system",
"-o", "jsonpath={.data.HAMI_WEBUI_PASSWORD}")
// 添加 HAMI WebUI 信息到表格
services = append(services, ServiceInfo{
Name: "HAMI WebUI",
User: webuiUser,
Password: webuiPassword,
Version: "-",
PublishAddr: webuiAddress,
})
return services
}
func aiproxyInfo(domain string) []ServiceInfo {
var services []ServiceInfo
// 读取 AIProxy 配置
adminKey, err := runCommand("kubectl", "get", "configmap", "aiproxy-env", "-n", "aiproxy-system",
"-o", "jsonpath={.data.ADMIN_KEY}")
if err != nil {
// AIProxy 配置不存在,直接返回空数组
return services
}
aiproxyURL := fmt.Sprintf("https://aiproxy.%s", domain)
// 添加 AIProxy 信息到表格
services = append(services, ServiceInfo{
Name: "AIProxy",
User: "admin",
Password: adminKey,
Version: "-",
PublishAddr: aiproxyURL,
})
return services
}
func cockroachInfo(domain string) []ServiceInfo {
var services []ServiceInfo
// 读取 CockroachDB URI
uri, err := runCommand("kubectl", "get", "configmap", "sealos-config", "-n", "sealos-system",
"-o", "jsonpath={.data.databaseGlobalCockroachdbURI}")
if err != nil {
// CockroachDB 配置不存在,直接返回空数组
return services
}
// 解析 URI: postgresql://username:password@host:port/database
// 示例: postgresql://root:password@cockroachdb.sealos.svc:26257/defaultdb
parsedURI := uri
if strings.HasPrefix(parsedURI, "postgresql://") {
parsedURI = strings.TrimPrefix(parsedURI, "postgresql://")
}
// 提取用户名和密码
// 格式: username:password@host:port/database
var username, password string
atIndex := strings.Index(parsedURI, "@")
if atIndex != -1 {
// 获取 @ 之前的部分(username:password)
userPassPart := parsedURI[:atIndex]
colonIndex := strings.Index(userPassPart, ":")
if colonIndex != -1 {
username = userPassPart[:colonIndex]
password = userPassPart[colonIndex+1:]
}
}
// 添加 CockroachDB 信息到表格
services = append(services, ServiceInfo{
Name: "CockroachDB",
User: username,
Password: password,
Version: "-",
PublishAddr: fmt.Sprintf("https://cockroachdb.%s", domain),
})
return services
}
func tlsTips(log logger, domain string) {
acmeDNS, err := runCommand("kubectl", "get", "configmap", "cert-config", "-n", "sealos-system",
"-o", "jsonpath={.data.ACMEDNS_FULL_DOMAIN}")
if err != nil {
log.warnf("读取 TLS 配置失败: %v", err)
return
}
certMode, _ := runCommand("kubectl", "get", "configmap", "cert-config", "-n", "sealos-system",
"-o", "jsonpath={.data.CERT_MODE}")
dnsmasqEnabled, _ := runCommand("kubectl", "get", "configmap", "cert-config", "-n", "sealos-system",
"-o", "jsonpath={.data.DNSMASQ_ENABLED}")
log.printf("TLS certificate information (important - please review):")
switch certMode {
case "acmedns":
log.printf("A CNAME record should point %s to the ACME DNS name provided during installation.", domain)
log.printf("Create a CNAME record for '_acme-challenge.%s' pointing to the %s.", domain, acmeDNS)
case "self-signed":
log.printf("No TLS certificate provided — a self-signed certificate will be used by Sealos Cloud.")
log.printf("Browsers and clients will show a warning unless the self-signed certificate is trusted.")
log.printf("To trust the certificate, follow the guide: https://sealos.run/docs/self-hosting/install#信任自签名证书")
case "https":
log.printf("A custom TLS certificate and private key were provided.")
log.printf("Ensure the DNS name %s resolves to this server's IP so the certificate is valid.", domain)
log.printf("If you encounter certificate errors in clients, verify the certificate chain and that the hostname matches.")
case "offline":
log.printf("Offline mode selected — TLS certificates are not managed by Sealos Cloud.")
log.printf("Ensure that the existing certificates on the cluster are valid and trusted by clients.")
// 检查 DNSMasq 是否启用(不区分大小写)
if strings.ToLower(strings.TrimSpace(dnsmasqEnabled)) != "true" {
manualDomain := domain
log.printf("DNSMasq is disabled. Please configure DNS records for %s, *.%s, and update.code.visualstudio.com.", manualDomain, manualDomain)
}
log.printf("All offline files have been copied to the NGINX location.")
// 获取本地IP
localIP, err := getLocalIP()
if err != nil {
log.warnf("获取本地IP失败: %v", err)
localIP = "<your-server-ip>"
}
log.printf("Please visit: http://%s:32000 to verify offline resources are accessible.", localIP)
default:
log.errorf("Unknown CERT_MODE: %s", certMode)
}
}
// getLocalIP 获取本机IP地址
func getLocalIP() (string, error) {
// 尝试使用 hostname -I 命令获取IP
output, err := runCommand("hostname", "-I")
if err != nil {
// 如果 hostname -I 失败,尝试使用 ip route get 1
output, err = runShell("ip route get 1 | awk '{print $7}' | head -1")
if err != nil {
// 如果都失败,尝试使用 ifconfig
output, err = runShell("ifconfig | grep 'inet ' | grep -v 127.0.0.1 | awk '{print $2}' | head -1")
if err != nil {
return "", fmt.Errorf("无法获取本地IP地址")
}
}
}
// hostname -I 可能返回多个IP,取第一个
parts := strings.Fields(output)
if len(parts) == 0 {
return "", fmt.Errorf("未找到有效的IP地址")
}
return parts[0], nil
}
func decodeBase64(value string) string {
decoded, err := base64.StdEncoding.DecodeString(value)
if err != nil {
return value
}
return string(decoded)
}
func generateNsAdminLink(namespace, configMap, userID, userUID string) (string, error) {
envContent, err := runCommand("kubectl", "get", "cm", configMap, "-n", namespace,
"-o", "jsonpath={.data['.env']}")
envMap := map[string]string{}
if err == nil && envContent != "" {
envMap = parseEnvContent(envContent)
}
tokenPrefix := envMap["TOKEN_URL_PREFIX"]
secret := envMap["GENERATE_TOKEN"]
globalDBURI := firstNonEmpty(envMap["GLOBAL_COCKROACHDB_URI"], envMap["globalCockroachdbURI"])
if tokenPrefix == "" || secret == "" {
confignames := []string{
"desktop-frontend-config",
"sealos-desktop-config",
}
for _, cfgName := range confignames {
cfgContent, cfgErr := runCommand("kubectl", "get", "cm", cfgName, "-n", "sealos",
"-o", "jsonpath={.data.config\\.yaml}", "--ignore-not-found")
if cfgErr == nil && cfgContent != "" {
domain, jwtGlobal, _, dbURI := parseDesktopFrontendConfig(cfgContent)
if tokenPrefix == "" && domain != "" {
tokenPrefix = fmt.Sprintf("https://%s/switchRegion?token=", domain)
}
if secret == "" && jwtGlobal != "" {
secret = jwtGlobal
}
if globalDBURI == "" && dbURI != "" {
globalDBURI = dbURI
}
if tokenPrefix != "" && secret != "" {
break
}
}
}
}
if tokenPrefix == "" || secret == "" {
return "", fmt.Errorf("TOKEN_URL_PREFIX 或 GENERATE_TOKEN 为空")
}
resolvedUID := strings.TrimSpace(userUID)
if resolvedUID == "" {
if globalDBURI == "" {
return "", fmt.Errorf("未提供用户 UID,且无法获取 GLOBAL_COCKROACHDB_URI")
}
var err error
resolvedUID, err = lookupUserUID(globalDBURI, userID)
if err != nil {
return "", err
}
}
token, err := buildJWT(userID, resolvedUID, secret)
if err != nil {
return "", err
}
return tokenPrefix + token, nil
}
func parseEnvContent(content string) map[string]string {
envs := map[string]string{}
lines := strings.Split(content, "\n")
for _, line := range lines {
line = strings.TrimSpace(line)
if line == "" || strings.HasPrefix(line, "#") {
continue
}
parts := strings.SplitN(line, "=", 2)
if len(parts) != 2 {
continue
}
key := strings.TrimSpace(parts[0])
val := strings.TrimSpace(parts[1])
val = strings.Trim(val, `"'`)
envs[key] = val
}
return envs
}
type yamlKey struct {
indent int
key string
}
func parseDesktopFrontendConfig(content string) (string, string, string, string) {
var domain string
var jwtGlobal string
var passwordSalt string
var dbURI string
lines := strings.Split(content, "\n")
stack := make([]yamlKey, 0, 8)
for _, rawLine := range lines {
line := strings.TrimRight(rawLine, " \t\r")
trimmed := strings.TrimSpace(line)
if trimmed == "" || strings.HasPrefix(trimmed, "#") {
continue
}
indent := leadingSpaces(rawLine)
parts := strings.SplitN(trimmed, ":", 2)
key := strings.TrimSpace(parts[0])
value := ""
if len(parts) > 1 {
value = strings.TrimSpace(parts[1])
}
for len(stack) > 0 && indent <= stack[len(stack)-1].indent {
stack = stack[:len(stack)-1]
}
if value == "" {
stack = append(stack, yamlKey{indent: indent, key: key})
continue
}
value = strings.Trim(value, `"'`)
path := buildPath(stack, key)
if path == "cloud.domain" && domain == "" {
domain = value
}
if path == "desktop.auth.jwt.global" && jwtGlobal == "" {
jwtGlobal = value
}
if (path == "desktop.auth.idp.password.salt") && passwordSalt == "" {
passwordSalt = value
}
if path == "database.globalCockroachdbURI" && dbURI == "" {
dbURI = value
}
}
return domain, jwtGlobal, passwordSalt, dbURI
}
func getDesktopAuthSecrets() (string, string, error) {
confignames := []string{
"desktop-frontend-config",
"sealos-desktop-config",
}
for _, cfgName := range confignames {
cfgContent, cfgErr := runCommand("kubectl", "get", "cm", cfgName, "-n", "sealos",
"-o", "jsonpath={.data.config\\.yaml}", "--ignore-not-found")
if cfgErr != nil || cfgContent == "" {
continue
}
_, jwtGlobal, passwordSalt, _ := parseDesktopFrontendConfig(cfgContent)
if jwtGlobal != "" || passwordSalt != "" {
return jwtGlobal, passwordSalt, nil
}
}
return "", "", fmt.Errorf("未找到 desktop auth jwt.global 或 passwordSalt")
}
func leadingSpaces(line string) int {
count := 0
for _, ch := range line {
if ch != ' ' && ch != '\t' {
break
}
count++
}
return count
}
func buildPath(stack []yamlKey, leaf string) string {
if len(stack) == 0 {
return leaf
}
parts := make([]string, 0, len(stack)+1)
for _, item := range stack {
parts = append(parts, item.key)
}
parts = append(parts, leaf)
return strings.Join(parts, ".")
}
func lookupUserUID(dbURI, userID string) (string, error) {
resolvedURI, useDirectQuery, err := resolveLookupUserDBURI(dbURI)
if err != nil {
return "", err
}
if useDirectQuery {
return lookupUserUIDDirect(resolvedURI, userID)
}
query := fmt.Sprintf("SELECT id, uid FROM \"User\" WHERE id='%s' LIMIT 1;", escapeSQLLiteral(userID))
podName, err := findCockroachPod()
if err != nil {
return "", err
}
localURL, urlErr := rewriteCockroachURLForLocalhost(resolvedURI)
if urlErr != nil {
return "", urlErr
}
output, err := runCommand(
"kubectl",
"exec",
"-n",
"sealos",
podName,
"-c",
"db",
"--",
"cockroach",
"sql",
"--certs-dir=/cockroach/cockroach-certs",
"--url",
localURL,
"--format=csv",
"-e",