diff --git a/biz/docker/docker_dispose_compose_file.go b/biz/docker/docker_dispose_compose_file.go index a66653c..b9c7ae6 100644 --- a/biz/docker/docker_dispose_compose_file.go +++ b/biz/docker/docker_dispose_compose_file.go @@ -20,183 +20,184 @@ * @Description: */ -package docker - -import ( - "agent/biz/model/device" - "agent/biz/model/disk_initial/model" - "agent/config" - "agent/res" - "fmt" - math_rand "math/rand" - "strings" - "time" - - "agent/utils/logger" - - "github.com/dungeonsnd/gocom/file/fileutil" -) - -func replacePlaceholderInComposeFile(f string) error { - logger.AppLogger().Debugf("replacePlaceholderInComposeFile, f:%v", f) - - btid := device.GetDeviceInfo().Btid - - b, err := fileutil.ReadFromFile(f) - if err != nil { - logger.AppLogger().Debugf("replacePlaceholderInComposeFile, failed ReadFromFile f:%v", f) - return err - } - s := string(b) - logger.AppLogger().Debugf("replacePlaceholderInComposeFile, %v", f) - s = strings.ReplaceAll(s, config.Config.Box.Loki.Placeholder, btid) - // logger.AppLogger().Debugf("replacePlaceholderInComposeFile, after Replace placeholder %v new content: %v", f, s) - newContent := []byte(s) - err = fileutil.WriteToFile(f, newContent, true) - if err != nil { - logger.AppLogger().Warnf("replacePlaceholderInComposeFile, failed WriteToFile %v", f) - return err - } - logger.AppLogger().Debugf("replacePlaceholderInComposeFile, succ WriteToFile %v", f) - return nil -} - -func disposeComposeFile() { - f := config.Config.Docker.CustomComposeFile - logger.AppLogger().Debugf("disposeComposeFile, f:%v", f) - replacePlaceholderInComposeFile(f) - if fileutil.IsFileExist(f) { - logger.AppLogger().Infof("DisposeComposeFile, %v exist", f) - b, err := fileutil.ReadFromFile(f) - if err != nil { - logger.AppLogger().Warnf("failed ReadFromFile, file:%v, err:%v", f, err) - } else { - err1 := fileutil.WriteToFile(config.Config.Docker.ComposeFile, - b, true) - if err1 != nil { - logger.AppLogger().Warnf("failed WriteToFile, file:%v, err1:%v", config.Config.Docker.ComposeFile, err1) - } - } - } else { - logger.AppLogger().Warnf("DisposeComposeFile, %v not exist", f) - } - - err := ProcessVolumes(config.Config.Docker.ComposeFile, model.GetFileStoragePath()) - if err != nil { - logger.AppLogger().Warnf("failed ProcessVolumes, file:%v, err1:%v", config.Config.Docker.ComposeFile, err) - } -} - -func writeDefaultDockerComposeFile() { - // rpm 安装时已经不释放了,所以须在程序里释放。升级时已经有该文件了,所以启动时根据配置项释放程序中内置的。 - if fileutil.IsFileNotExist(config.Config.Docker.CustomComposeFile) { - // logger.AppLogger().Debugf("writeDefaultDockerComposeFile, %v not exist", config.Config.Docker.CustomComposeFile) - - composeFileContent := res.GetContentDockerCompose() - composeFileContent = replaceRandomPasswordAndPortPlaceholder(composeFileContent) - fileutil.WriteToFile(config.Config.Docker.CustomComposeFile, composeFileContent, true) - } else { - // logger.AppLogger().Debugf("writeDefaultDockerComposeFile, %v exist", config.Config.Docker.CustomComposeFile) - - if config.Config.OverwriteDockerCompose { - composeFileContent := res.GetContentDockerCompose() - composeFileContent = replaceRandomPasswordAndPortPlaceholder(composeFileContent) - fileutil.WriteToFile(config.Config.Docker.CustomComposeFile, composeFileContent, true) - } - } -} - -func writeUpgradeComposeFile() { - f := config.Config.Docker.UpgradeComposeFile - logger.AppLogger().Debugf("dispose upgrade ComposeFile, f:%v", f) - composeFileContent := res.GetContentUpgradeComposeFile() - err := fileutil.WriteToFile(f, composeFileContent, true) - if err != nil { - logger.AppLogger().Errorf("write upgrade ComposeFile err:%v", err) - return - } -} - -func replaceRandomPasswordAndPortPlaceholder(composeFileContent []byte) []byte { - logger.AppLogger().Debugf("replaceRandomPasswordAndPortPlaceholder") - - randstr := "" - if fileutil.IsFileExist(config.Config.Box.RandDockercomposePassword) { - - b, err := fileutil.ReadFromFile(config.Config.Box.RandDockercomposePassword) - if err != nil { - logger.AppLogger().Errorf("replaceRandomPasswordAndPortPlaceholder, ReadFromFile %v err: %v", - config.Config.Box.RandDockercomposePassword, err) - } else { - randstr = string(b) - } - } - if len(randstr) < 2 { - // 替换成随机密码 - randstr = rand(16) - err := fileutil.WriteToFile(config.Config.Box.RandDockercomposePassword, []byte(randstr), true) - if err != nil { - logger.AppLogger().Errorf("replaceRandomPasswordAndPortPlaceholder, WriteToFile %v err: %v", - config.Config.Box.RandDockercomposePassword, err) - } - } - logger.AppLogger().Debugf("replaceRandomPasswordAndPortPlaceholder, randstr:%v", randstr) - composeFileContent = []byte(strings.ReplaceAll(string(composeFileContent), "placeholder_mysecretpassword", randstr)) - - randRedisPort := "" - if fileutil.IsFileExist(config.Config.Box.RandDockercomposeRedisPort) { - - b, err := fileutil.ReadFromFile(config.Config.Box.RandDockercomposeRedisPort) - if err != nil { - logger.AppLogger().Errorf("replaceRandomPasswordAndPortPlaceholder, ReadFromFile %v err: %v", - config.Config.Box.RandDockercomposeRedisPort, err) - } else { - randRedisPort = string(b) - if err != nil { - logger.AppLogger().Errorf("replaceRandomPasswordAndPortPlaceholder, strconv.Atoi %v err: %v", - string(b), err) - } - } - } - if len(randRedisPort) < 2 { - // 替换成随机端口号 - randRedisPort = randInt(19000, 19999) // redis 端口号在一个区间内随机生成 - err := fileutil.WriteToFile(config.Config.Box.RandDockercomposeRedisPort, []byte(randRedisPort), true) - if err != nil { - logger.AppLogger().Errorf("replaceRandomPasswordAndPortPlaceholder, WriteToFile %v err: %v", - config.Config.Box.RandDockercomposeRedisPort, err) - } - } - - i := strings.Index(string(composeFileContent), "placeholder_6379") - logger.AppLogger().Debugf("replaceRandomPasswordAndPortPlaceholder, randRedisPort:%v, strings.Index return :%v", randRedisPort, i) - - composeFileContent = []byte(strings.ReplaceAll(string(composeFileContent), "placeholder_6379", randRedisPort)) - - // 更新自身连接 redis 的配置。 - addrSplit := strings.Split(config.Config.Redis.Addr, ":") - if len(addrSplit) > 1 { - config.UpdateRedisConfig(addrSplit[0]+":6379", randstr) - } else { - config.UpdateRedisConfig("127.0.0.1:"+randRedisPort, randstr) - } - - return composeFileContent -} - -func rand(length int) string { - str := "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" - bytes := []byte(str) - result := []byte{} - r := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - for i := 0; i < length; i++ { - result = append(result, bytes[r.Intn(len(bytes))]) - } - return string(result) -} - -func randInt(min int, max int) string { - math_rand.Seed(time.Now().UnixNano()) - r := math_rand.Intn(max-min) + min - return fmt.Sprintf("%v", r) -} + package docker + + import ( + "agent/biz/model/device" + "agent/biz/model/disk_initial/model" + "agent/config" + "agent/res" + "fmt" + math_rand "math/rand" + "strings" + "time" + + "agent/utils/logger" + + "github.com/dungeonsnd/gocom/file/fileutil" + ) + + func replacePlaceholderInComposeFile(f string) error { + logger.AppLogger().Debugf("replacePlaceholderInComposeFile, f:%v", f) + + btid := device.GetDeviceInfo().Btid + + b, err := fileutil.ReadFromFile(f) + if err != nil { + logger.AppLogger().Debugf("replacePlaceholderInComposeFile, failed ReadFromFile f:%v", f) + return err + } + s := string(b) + logger.AppLogger().Debugf("replacePlaceholderInComposeFile, %v", f) + s = strings.ReplaceAll(s, config.Config.Box.Loki.Placeholder, btid) + // logger.AppLogger().Debugf("replacePlaceholderInComposeFile, after Replace placeholder %v new content: %v", f, s) + newContent := []byte(s) + err = fileutil.WriteToFile(f, newContent, true) + if err != nil { + logger.AppLogger().Warnf("replacePlaceholderInComposeFile, failed WriteToFile %v", f) + return err + } + logger.AppLogger().Debugf("replacePlaceholderInComposeFile, succ WriteToFile %v", f) + return nil + } + + func disposeComposeFile() { + f := config.Config.Docker.CustomComposeFile + logger.AppLogger().Debugf("disposeComposeFile, f:%v", f) + replacePlaceholderInComposeFile(f) + if fileutil.IsFileExist(f) { + logger.AppLogger().Infof("DisposeComposeFile, %v exist", f) + b, err := fileutil.ReadFromFile(f) + if err != nil { + logger.AppLogger().Warnf("failed ReadFromFile, file:%v, err:%v", f, err) + } else { + err1 := fileutil.WriteToFile(config.Config.Docker.ComposeFile, + b, true) + if err1 != nil { + logger.AppLogger().Warnf("failed WriteToFile, file:%v, err1:%v", config.Config.Docker.ComposeFile, err1) + } + } + } else { + logger.AppLogger().Warnf("DisposeComposeFile, %v not exist", f) + } + + err := ProcessVolumes(config.Config.Docker.ComposeFile, model.GetFileStoragePath()) + if err != nil { + logger.AppLogger().Warnf("failed ProcessVolumes, file:%v, err1:%v", config.Config.Docker.ComposeFile, err) + } + } + + func writeDefaultDockerComposeFile() { + // rpm 安装时已经不释放了,所以须在程序里释放。升级时已经有该文件了,所以启动时根据配置项释放程序中内置的。 + if fileutil.IsFileNotExist(config.Config.Docker.CustomComposeFile) { + fmt.Printf("writeDefaultDockerComposeFile, %v not exist\n", config.Config.Docker.CustomComposeFile) + + composeFileContent := res.GetContentDockerCompose() + composeFileContent = replaceRandomPasswordAndPortPlaceholder(composeFileContent) + fileutil.WriteToFile(config.Config.Docker.CustomComposeFile, composeFileContent, true) + } else { + fmt.Printf("writeDefaultDockerComposeFile, %v exist\n", config.Config.Docker.CustomComposeFile) + + if config.Config.OverwriteDockerCompose { + composeFileContent := res.GetContentDockerCompose() + composeFileContent = replaceRandomPasswordAndPortPlaceholder(composeFileContent) + fileutil.WriteToFile(config.Config.Docker.CustomComposeFile, composeFileContent, true) + } + } + } + + func writeUpgradeComposeFile() { + f := config.Config.Docker.UpgradeComposeFile + logger.AppLogger().Debugf("dispose upgrade ComposeFile, f:%v", f) + composeFileContent := res.GetContentUpgradeComposeFile() + err := fileutil.WriteToFile(f, composeFileContent, true) + if err != nil { + logger.AppLogger().Errorf("write upgrade ComposeFile err:%v", err) + return + } + } + + func replaceRandomPasswordAndPortPlaceholder(composeFileContent []byte) []byte { + logger.AppLogger().Debugf("replaceRandomPasswordAndPortPlaceholder") + + randstr := "" + if fileutil.IsFileExist(config.Config.Box.RandDockercomposePassword) { + + b, err := fileutil.ReadFromFile(config.Config.Box.RandDockercomposePassword) + if err != nil { + logger.AppLogger().Errorf("replaceRandomPasswordAndPortPlaceholder, ReadFromFile %v err: %v", + config.Config.Box.RandDockercomposePassword, err) + } else { + randstr = string(b) + } + } + if len(randstr) < 2 { + // 替换成随机密码 + randstr = rand(16) + err := fileutil.WriteToFile(config.Config.Box.RandDockercomposePassword, []byte(randstr), true) + if err != nil { + logger.AppLogger().Errorf("replaceRandomPasswordAndPortPlaceholder, WriteToFile %v err: %v", + config.Config.Box.RandDockercomposePassword, err) + } + } + logger.AppLogger().Debugf("replaceRandomPasswordAndPortPlaceholder, randstr:%v", randstr) + composeFileContent = []byte(strings.ReplaceAll(string(composeFileContent), "placeholder_mysecretpassword", randstr)) + + randRedisPort := "" + if fileutil.IsFileExist(config.Config.Box.RandDockercomposeRedisPort) { + + b, err := fileutil.ReadFromFile(config.Config.Box.RandDockercomposeRedisPort) + if err != nil { + logger.AppLogger().Errorf("replaceRandomPasswordAndPortPlaceholder, ReadFromFile %v err: %v", + config.Config.Box.RandDockercomposeRedisPort, err) + } else { + randRedisPort = string(b) + if err != nil { + logger.AppLogger().Errorf("replaceRandomPasswordAndPortPlaceholder, strconv.Atoi %v err: %v", + string(b), err) + } + } + } + if len(randRedisPort) < 2 { + // 替换成随机端口号 + randRedisPort = randInt(19000, 19999) // redis 端口号在一个区间内随机生成 + err := fileutil.WriteToFile(config.Config.Box.RandDockercomposeRedisPort, []byte(randRedisPort), true) + if err != nil { + logger.AppLogger().Errorf("replaceRandomPasswordAndPortPlaceholder, WriteToFile %v err: %v", + config.Config.Box.RandDockercomposeRedisPort, err) + } + } + + i := strings.Index(string(composeFileContent), "placeholder_6379") + logger.AppLogger().Debugf("replaceRandomPasswordAndPortPlaceholder, randRedisPort:%v, strings.Index return :%v", randRedisPort, i) + + composeFileContent = []byte(strings.ReplaceAll(string(composeFileContent), "placeholder_6379", randRedisPort)) + + // 更新自身连接 redis 的配置。 + addrSplit := strings.Split(config.Config.Redis.Addr, ":") + if len(addrSplit) > 1 { + config.UpdateRedisConfig(addrSplit[0]+":6379", randstr) + } else { + config.UpdateRedisConfig("127.0.0.1:"+randRedisPort, randstr) + } + + return composeFileContent + } + + func rand(length int) string { + str := "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" + bytes := []byte(str) + result := []byte{} + r := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) + for i := 0; i < length; i++ { + result = append(result, bytes[r.Intn(len(bytes))]) + } + return string(result) + } + + func randInt(min int, max int) string { + math_rand.Seed(time.Now().UnixNano()) + r := math_rand.Intn(max-min) + min + return fmt.Sprintf("%v", r) + } + \ No newline at end of file diff --git a/biz/model/device/key.go b/biz/model/device/key.go index f4b9393..566f443 100644 --- a/biz/model/device/key.go +++ b/biz/model/device/key.go @@ -122,7 +122,7 @@ func InitDeviceKeyNormal() { logger.AppLogger().Debugf("InitdeviceKey, devicePriKeyBytes length=%v", len(devicePublicKey)) logger.AppLogger().Debugf("InitdeviceKey, devicePublicKey length=%v", len(devicePublicKey)) - logger.AppLogger().Debugf("InitdeviceKey, devicePublicKey=%v", devicePublicKey) + // logger.AppLogger().Debugf("InitdeviceKey, devicePublicKey=%v", devicePublicKey) } func GetDevicePriKey() []byte { diff --git a/biz/service/bind/com/progress/progress.go b/biz/service/bind/com/progress/progress.go index 64d9932..248f86c 100644 --- a/biz/service/bind/com/progress/progress.go +++ b/biz/service/bind/com/progress/progress.go @@ -20,8 +20,13 @@ import ( "agent/biz/model/dto" "agent/biz/model/dto/bind/com/progress" "agent/biz/service/base" + "agent/config" "agent/utils/logger" + "agent/utils/tools" "fmt" + "os" + "strings" + "time" ) type ComProgressService struct { @@ -32,13 +37,37 @@ type ComProgressService struct { func (svc *ComProgressService) Process() dto.BaseRspStr { logger.AppLogger().Debugf("ComProgressService Process") svc.PairedInfo = clientinfo.GetAdminPairedInfo() - dockerStatus := docker.GetDockerStatus() if svc.PairedInfo.AlreadyBound() { err := fmt.Errorf("pairedStatus:%+v", svc.PairedInfo.Status()) return dto.BaseRspStr{Code: dto.AgentCodeAlreadyPairedStr, Message: err.Error()} } + + singleDockerModeEnv := os.Getenv(config.Config.Box.RunInDocker.AoSpaceSingleDockerModeEnv) + logger.AppLogger().Debugf("ComProgressService Process, singleDockerModeEnv:%v", singleDockerModeEnv) + if strings.EqualFold(singleDockerModeEnv, "true") { + go svc.startSpacePrograms() + time.Sleep(12 * time.Second) + rsp := &progress.ProgressRsp{ComStatus: docker.ContainersStarted, Progress: 100} + svc.Rsp = rsp + return svc.BaseService.Process() + } + + dockerStatus := docker.GetDockerStatus() rsp := &progress.ProgressRsp{ComStatus: dockerStatus, Progress: docker.GetStartingProgress()} svc.Rsp = rsp return svc.BaseService.Process() } + +func (svc *ComProgressService) startSpacePrograms() error { + cmd := "bash" + scripts := []string{"/usr/local/bin/start.sh"} + logger.AppLogger().Debugf("startSpacePrograms, will RunCmd script: %v %v", cmd, strings.Join(scripts, " ")) + _, stdout, err := tools.RunCmd(cmd, scripts) + if err != nil { + logger.AppLogger().Warnf("%v %v, stdout:%v, err:%v", cmd, strings.Join(scripts, " "), stdout, err) + } else { + logger.AppLogger().Debugf("%v %v succ", cmd, strings.Join(scripts, " ")) + } + return err +} diff --git a/biz/service/bind/init/init.go b/biz/service/bind/init/init.go index 10fe395..95f08ac 100644 --- a/biz/service/bind/init/init.go +++ b/biz/service/bind/init/init.go @@ -38,7 +38,7 @@ type InitService struct { func (svc *InitService) Process() dto.BaseRspStr { logger.AppLogger().Debugf("InitService Process") req := svc.Req.(*bindinit.InitReq) - // logger.AppLogger().Debugf("InitService Process, req:%+v", req) + logger.AppLogger().Debugf("InitService Process, req:%+v", req) if req != nil && len(req.ClientUuid) > 0 && len(req.ClientVersion) > 0 { clientinfo.SetClientVersion(req.ClientUuid, req.ClientVersion) } @@ -97,6 +97,8 @@ func (svc *InitService) Process() dto.BaseRspStr { rsp.InitialEstimateTimeSec = int(config.Config.Box.InitialEstimateTimeSecRunInDocker) } + logger.AppLogger().Debugf("ServiceInit, rsp.DeviceAbility:%+v", rsp.DeviceAbility) + svc.Rsp = rsp return svc.BaseService.Process() } diff --git a/biz/service/bind/space/create/create.go b/biz/service/bind/space/create/create.go index ac9d1e4..448e866 100644 --- a/biz/service/bind/space/create/create.go +++ b/biz/service/bind/space/create/create.go @@ -32,6 +32,8 @@ import ( "agent/utils/retry" "encoding/base64" "fmt" + "os" + "strings" "time" ) @@ -58,7 +60,7 @@ func (svc *SpaceCreateService) Process() dto.BaseRspStr { rsp := &create.CreateRsp{} req := svc.Req.(*create.CreateReq) - // logger.AppLogger().Debugf("SpaceCreateService Process, req:%+v", req) + logger.AppLogger().Debugf("SpaceCreateService Process, req:%+v", req) logger.AppLogger().Debugf("SpaceCreateService Process, pairedInfo:%+v", svc.PairedInfo) logger.AppLogger().Debugf("SpaceCreateService, rebind:%+v", svc.PairedInfo.Rebind()) @@ -125,10 +127,13 @@ func (svc *SpaceCreateService) Process() dto.BaseRspStr { logger.AppLogger().Debugf("callGateway, microServerRsp:%v", microServerRsp) // TODO: update did doc history - // ... - // 启动/停止转发服务 - svc.startOrStopContainers() - logger.AppLogger().Debugf("startOrStopContainers") + + singleDockerModeEnv := os.Getenv(config.Config.Box.RunInDocker.AoSpaceSingleDockerModeEnv) + if !strings.EqualFold(singleDockerModeEnv, "true") { + // 启动/停止转发服务 + svc.startOrStopContainers() + logger.AppLogger().Debugf("startOrStopContainers") + } svc.Rsp = rsp @@ -163,7 +168,7 @@ func (svc *SpaceCreateService) registerDevice(req *create.CreateReq) (*dto.BaseR } func (svc *SpaceCreateService) callGateway(req *create.CreateReq) (call.MicroServerRsp, error) { - // logger.AppLogger().Debugf("callGateway, req:%+v ", req) + logger.AppLogger().Debugf("callGateway, req:%+v ", req) var microServerRsp call.MicroServerRsp diff --git a/biz/web/http_server.go b/biz/web/http_server.go index bcad528..7be91ed 100644 --- a/biz/web/http_server.go +++ b/biz/web/http_server.go @@ -18,6 +18,8 @@ import ( "agent/biz/docker" "agent/biz/web/routers" "agent/config" + "os" + "strings" "github.com/gin-gonic/gin" @@ -41,8 +43,13 @@ func Start() { go externalWebServer.Start() - docker.SubscribeAsyncDockerNetwork(func(status int) { - // start internal web server + // start internal web server + if strings.EqualFold(os.Getenv(config.Config.Box.RunInDocker.AoSpaceSingleDockerModeEnv), "true") { go internalWebServer.Start() - }) + } else { + docker.SubscribeAsyncDockerNetwork(func(status int) { + go internalWebServer.Start() + }) + } + } diff --git a/config/config.go b/config/config.go index 503081e..c7da998 100644 --- a/config/config.go +++ b/config/config.go @@ -15,10 +15,10 @@ package config import ( - "agent/deps/logger" hardware_util "agent/utils/hardware" "flag" "fmt" + "os" "strings" "testing" "time" @@ -35,7 +35,7 @@ var runInDocker bool // 以下配置项尽量都包含默认值. 让用户零配置启动. // 系统OS镜像构建时,没有复制默认的 yml 配置文件. 原因是这里已经设置了默认值,不想在项目组重复设置默认值. -type configSt struct { +var Config = struct { DebugMode bool `default:"false"` // 调试模式。会控制是否打开 swagger 等。 OverwriteDockerCompose bool `default:"true"` // 启动时是否覆盖 docker-compose.yml。"true" 表示覆盖。 EnableSecurityChip bool `default:"true"` // 是否启用加密芯片。 @@ -89,11 +89,10 @@ type configSt struct { AoLogDirCheckCronExp string `default:"0 0 4 * *"` // 所有程序日志目录定时检测的 cron 表达式. 比如 0 0 4 * * 表示每天 4时 0分 0秒执行一次逻辑。 Path string `default:"/opt/logs/system-agent/"` Filename string `default:"system-agent"` - MaxAge uint32 `default:"7"` // 文件最多保留多少天后被覆盖. - RotationSize int64 `default:"10"` // 多少MBytes生成新文件. - RotationCount uint32 `default:"20"` // 多少个文件之后覆盖最早的文件. - Level uint32 `default:"6"` // InfoLevel=4, DebugLevel=5, logrus.TraceLevel=6 . 暂时没用到. - LevelString string `default:"info"` // 默认info. debug, info, warn, error, dpanic, panic, fatal + MaxAge uint32 `default:"7"` // 文件最多保留多少天后被覆盖. + RotationSize int64 `default:"10"` // 多少MBytes生成新文件. + RotationCount uint32 `default:"20"` // 多少个文件之后覆盖最早的文件. + Level uint32 `default:"6"` // InfoLevel=4, DebugLevel=5, logrus.TraceLevel=6 . 暂时没用到. } EnableKeyboard bool `default:"false"` @@ -196,8 +195,9 @@ type configSt struct { } RunInDocker struct { - AoSpaceDataDirEnv string `default:"AOSPACE_DATADIR"` // 数据存储目录 - RunNetworkModeEnv string `default:"RUN_NETWORK_MODE"` // docker-compose 中的 nginx 网络配置键名称 + AoSpaceDataDirEnv string `default:"AOSPACE_DATADIR"` // 数据存储目录 + RunNetworkModeEnv string `default:"RUN_NETWORK_MODE"` // docker-compose 中的 nginx 网络配置键名称 + AoSpaceSingleDockerModeEnv string `default:"AOSPACE_SINGLE_DOCKER_MODE"` } Cert struct { @@ -411,9 +411,7 @@ type configSt struct { Password string `default:"mysecretpassword"` DBIndex int `default:"0"` } -} - -var Config configSt +}{} var ConfFile = "/etc/ao-space/system-agent.yml" // 默认配置文件 var ConfFileCustom1 = "/opt/tmp/system-agent.yml" // 用户自定义配置文件 @@ -439,8 +437,6 @@ func init() { AutoReloadInterval: time.Second * 15, AutoReloadCallback: func(config interface{}) { // fmt.Printf("config file changed:\n%+v\n", config) - cfg := config.(*configSt) - logger.SetLevel(cfg.Log.LevelString) }}).Load(&Config, ConfFileCustom1, *flagConfFile) Config.Version = v @@ -502,30 +498,32 @@ func modifyConfigWhenRunInDocker() { // fmt.Printf("Config.Box.SnNumberStoreFile: %v \n", Config.Box.SnNumberStoreFile) // 调用地址修改 - // aospace-all-in-one - Config.EnvDefaultVal.SYSTEM_AGENT_URL_DEVICE_INFO = "http://aospace-all-in-one:5680/agent/v1/api/device/info" - Config.EnvDefaultVal.SYSTEM_AGENT_URL_BASE = "http://aospace-all-in-one:5680/agent/v1/api" - // DockerLocalListenAddr - Config.Web.DockerLocalListenAddr = "aospace-all-in-one:5680" - addr := []*string{&Config.AliveChecker.GateWay.UrlGateway, - &Config.GateWay.Revoke.Url, - &Config.GateWay.APIRoot.Url, - &Config.Account.User.Url, - &Config.Account.Member.Url, - &Config.Account.AdminCreate.Url, - &Config.Account.SpaceAdmin.Url, - &Config.Account.NetworkChannelInfo.Url, - &Config.Account.NetworkChannelWan.Url, - &Config.Account.AdminSetPassword.Url, - &Config.Account.AdminPasswordCheck.Url, - &Config.Account.AdminRevoke.Url, - &Config.Account.AdminInitial.Url, - &Config.Account.Migrate.Url, - &Config.Redis.Addr, - &Config.GateWay.SwitchPlatform.Url} - for _, v := range addr { - *v = strings.ReplaceAll(*v, "localhost:8080", "aospace-gateway:8080") - *v = strings.ReplaceAll(*v, "127.0.0.1:6379", "aospace-redis:6379") + if !strings.EqualFold(os.Getenv(Config.Box.RunInDocker.AoSpaceSingleDockerModeEnv), "true") { + // aospace-all-in-one + Config.EnvDefaultVal.SYSTEM_AGENT_URL_DEVICE_INFO = "http://aospace-all-in-one:5680/agent/v1/api/device/info" + Config.EnvDefaultVal.SYSTEM_AGENT_URL_BASE = "http://aospace-all-in-one:5680/agent/v1/api" + // DockerLocalListenAddr + Config.Web.DockerLocalListenAddr = "aospace-all-in-one:5680" + addr := []*string{&Config.AliveChecker.GateWay.UrlGateway, + &Config.GateWay.Revoke.Url, + &Config.GateWay.APIRoot.Url, + &Config.Account.User.Url, + &Config.Account.Member.Url, + &Config.Account.AdminCreate.Url, + &Config.Account.SpaceAdmin.Url, + &Config.Account.NetworkChannelInfo.Url, + &Config.Account.NetworkChannelWan.Url, + &Config.Account.AdminSetPassword.Url, + &Config.Account.AdminPasswordCheck.Url, + &Config.Account.AdminRevoke.Url, + &Config.Account.AdminInitial.Url, + &Config.Account.Migrate.Url, + &Config.Redis.Addr, + &Config.GateWay.SwitchPlatform.Url} + for _, v := range addr { + *v = strings.ReplaceAll(*v, "localhost:8080", "aospace-gateway:8080") + *v = strings.ReplaceAll(*v, "127.0.0.1:6379", "aospace-redis:6379") + } } // All diff --git a/main.go b/main.go index 6f3c2b0..89e2903 100644 --- a/main.go +++ b/main.go @@ -19,92 +19,105 @@ * @LastEditTime: 2022-06-06 11:28:46 * @Description: */ -package main - -import ( - "agent/biz/alivechecker" - "agent/biz/disk_space_monitor/log_dir_monitor" - "agent/biz/docker" - "agent/config" - - "agent/biz/model/clientinfo" - "agent/biz/model/device" - "agent/biz/model/did/leveldb" - "agent/biz/service/platform" - "agent/biz/service/upgrade" - "agent/biz/web" - "agent/utils/logger" - "fmt" - "os" - "os/signal" - "syscall" - - serviceswithplatform "agent/biz/service/switch-platform" - // _ "net/http/pprof" -) - -func main() { - - logger.SetLogPath(config.Config.Log.Path) - logger.SetLogConfig(int(config.Config.Log.RotationSize), - int(config.Config.Log.RotationCount), - int(config.Config.Log.MaxAge), false) - logger.PrecreateAllLoggers() - logger.SetLevel(config.Config.Log.LevelString) - - config.Version = Version - config.VersionNumber = VersionNumber - - logger.AppLogger().Infof("================[%v Started] [system-agent version:%v]================", - os.Args[0], config.Version+"-"+config.VersionNumber) - if err := AgentCmd.Execute(); err != nil { - fmt.Println(err) - os.Exit(1) - } - device.InitDeviceInfo() - device.InitDeviceKey() - clientinfo.InitClientInfo() - go platform.InitPlatformAbility() - serviceswithplatform.RetryUnfinishedStatus() - upgrade.CronForUpgrade() - // 启动 web/http api 服务 - web.Start() - - // 启动 docker 微服务创建或启动 - docker.Start() - alivechecker.Start() - - // 检测是否需要发送升级推送 - go upgrade.CheckUpgradeSucc() - - // 日志目录监控 - log_dir_monitor.Start() - - if err := leveldb.OpenDB(); err != nil { - fmt.Printf("\nFailed leveldb.OpenDB, err:%v\n", err) - os.Exit(0) - } - - quitChan := make(chan os.Signal) - signal.Notify(quitChan, syscall.SIGHUP, syscall.SIGINT, syscall.SIGTERM, - syscall.SIGQUIT, syscall.SIGUSR1, syscall.SIGUSR2) - - for s := range quitChan { - switch s { - case syscall.SIGHUP, syscall.SIGINT, syscall.SIGTERM, syscall.SIGQUIT: - fmt.Printf("signal %v\n", s) - GracefullExit() - case syscall.SIGUSR1: - // fmt.Println("usr1 signal", s) - case syscall.SIGUSR2: - // fmt.Println("usr2 signal", s) - default: - // fmt.Println("other signal", s) - } - } - -} - -func GracefullExit() { - os.Exit(0) -} + package main + + import ( + "agent/biz/alivechecker" + "agent/biz/disk_space_monitor/log_dir_monitor" + "agent/biz/docker" + "agent/config" + "strings" + + "agent/biz/model/clientinfo" + "agent/biz/model/device" + "agent/biz/model/did/leveldb" + "agent/biz/service/platform" + "agent/biz/service/upgrade" + "agent/biz/web" + "agent/utils/logger" + "fmt" + "os" + "os/signal" + "syscall" + + serviceswithplatform "agent/biz/service/switch-platform" + // _ "net/http/pprof" + ) + + func main() { + + logger.SetLogPath(config.Config.Log.Path) + logger.SetLogConfig(int(config.Config.Log.RotationSize), + int(config.Config.Log.RotationCount), + int(config.Config.Log.MaxAge), false) + logger.PrecreateAllLoggers() + + config.Version = Version + config.VersionNumber = VersionNumber + + logger.AppLogger().Infof("================[%v Started] [system-agent version:%v]================", + os.Args[0], config.Version+"-"+config.VersionNumber) + + fmt.Printf("AoLogDirBase:%+v\n", config.Config.Log.AoLogDirBase) + fmt.Printf("singleDockerModeEnv:%+v\n", os.Getenv(config.Config.Box.RunInDocker.AoSpaceSingleDockerModeEnv)) + + if err := AgentCmd.Execute(); err != nil { + fmt.Println(err) + os.Exit(1) + } + device.InitDeviceInfo() + device.InitDeviceKey() + clientinfo.InitClientInfo() + + if !strings.EqualFold(os.Getenv(config.Config.Box.RunInDocker.AoSpaceSingleDockerModeEnv), "true") { + go platform.InitPlatformAbility() + serviceswithplatform.RetryUnfinishedStatus() + upgrade.CronForUpgrade() + } + + // 启动 web/http api 服务 + web.Start() + + // 启动 docker 微服务创建或启动 + if !strings.EqualFold(os.Getenv(config.Config.Box.RunInDocker.AoSpaceSingleDockerModeEnv), "true") { + docker.Start() + } + alivechecker.Start() + + // 检测是否需要发送升级推送 + if !strings.EqualFold(os.Getenv(config.Config.Box.RunInDocker.AoSpaceSingleDockerModeEnv), "true") { + go upgrade.CheckUpgradeSucc() + } + + // 日志目录监控 + log_dir_monitor.Start() + + if err := leveldb.OpenDB(); err != nil { + fmt.Printf("\nFailed leveldb.OpenDB, err:%v\n", err) + os.Exit(0) + } + + quitChan := make(chan os.Signal) + signal.Notify(quitChan, syscall.SIGHUP, syscall.SIGINT, syscall.SIGTERM, + syscall.SIGQUIT, syscall.SIGUSR1, syscall.SIGUSR2) + + for s := range quitChan { + switch s { + case syscall.SIGHUP, syscall.SIGINT, syscall.SIGTERM, syscall.SIGQUIT: + fmt.Printf("signal %v\n", s) + GracefullExit() + case syscall.SIGUSR1: + // fmt.Println("usr1 signal", s) + case syscall.SIGUSR2: + // fmt.Println("usr2 signal", s) + default: + // fmt.Println("other signal", s) + } + } + + } + + func GracefullExit() { + os.Exit(0) + } + \ No newline at end of file diff --git a/script/build_linux-riscv64_bywin.bat b/script/build_linux-riscv64_bywin.bat new file mode 100644 index 0000000..ea0fce0 --- /dev/null +++ b/script/build_linux-riscv64_bywin.bat @@ -0,0 +1,25 @@ +rem Copyright (c) 2022 Institute of Software, Chinese Academy of Sciences (ISCAS) +rem +rem Licensed under the Apache License, Version 2.0 (the "License"); +rem you may not use this file except in compliance with the License. +rem You may obtain a copy of the License at +rem +rem http://www.apache.org/licenses/LICENSE-2.0 +rem +rem Unless required by applicable law or agreed to in writing, software +rem distributed under the License is distributed on an "AS IS" BASIS, +rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +rem See the License for the specific language governing permissions and +rem limitations under the License. + + +@REM go get -u github.com/swaggo/swag/cmd/swag @REM 下载的版本较新,CI 机器 go 版本 go 1.15.7-3,可能会 CI 编译失败!!!! + +@REM swag init -g biz/web/routers/router.go @REM 去掉本行注释,可以重新生成 swagger 文档。 + +set CGO_ENABLED=0 +set GOOS=linux +set GOARCH=riscv64 + +go build -ldflags "-s -w -X 'main.Version=aospace-agent-opensource' -X 'main.VersionNumber=0.9.0'" -gcflags="-N -l" -o build/system-agent +echo "build finished" diff --git a/utils/deviceid/sn.go b/utils/deviceid/sn.go index 0c33b1b..8c72f5e 100644 --- a/utils/deviceid/sn.go +++ b/utils/deviceid/sn.go @@ -38,6 +38,7 @@ type SnInfo struct { func GetSnNumber(snNumberStoreFile string) (string, error) { if fileutil.IsFileExist(snNumberStoreFile) { + // fmt.Printf("GetSnNumber,%v exist\n", snNumberStoreFile) if content, err := fileutil.ReadFromFile(snNumberStoreFile); err != nil { fmt.Printf("GetSnNumber, ReadFromFile err: %v\n", err) return "", err @@ -45,11 +46,13 @@ func GetSnNumber(snNumberStoreFile string) (string, error) { return string(content), nil } } else if strings.EqualFold(currentChip(), RPI) || strings.EqualFold(currentChip(), RK3568Dev) { + fmt.Printf("GetSnNumber,%v not exist, so current hardware is chip:%v\n", snNumberStoreFile, currentChip()) return "", fmt.Errorf("unsupported on this hardware platform") } else { + fmt.Printf("GetSnNumber,%v not exist, so current hardware is rk's production\n", snNumberStoreFile) sn, err := getVendorSnNumber() if err != nil { - // fmt.Printf("GetSnNumber, getVendorSnNumber err: %v\n", err) + fmt.Printf("GetSnNumber, getVendorSnNumber err: %v\n", err) return "", err } else { return sn, nil // 二代正式板 diff --git a/utils/hardware/hardware.go b/utils/hardware/hardware.go index 3efd378..9756353 100644 --- a/utils/hardware/hardware.go +++ b/utils/hardware/hardware.go @@ -59,10 +59,10 @@ func RunningInDocker() bool { envkey := "AOSPACE_DATADIR" dataDir := os.Getenv(envkey) if len(dataDir) > 0 { - // fmt.Printf("RunningInDocker, dataDir:%v\n", dataDir) + fmt.Printf("RunningInDocker, dataDir:%v\n", dataDir) return true } else { - // fmt.Printf("RunningInDocker==false, dataDir:%v\n", dataDir) + fmt.Printf("RunningInDocker==false, dataDir:%v\n", dataDir) return false } }