c_cloud.go 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315
  1. package config
  2. import (
  3. "cicv-data-closedloop/common/config/c_log"
  4. "cicv-data-closedloop/common/util"
  5. "errors"
  6. "gopkg.in/yaml.v3"
  7. "os"
  8. "strings"
  9. "sync"
  10. "time"
  11. )
  12. type MonitorStruct struct {
  13. Url string `yaml:"url"`
  14. }
  15. type PlatformStruct struct {
  16. UrlDeviceAuth string `yaml:"url-device-auth"`
  17. UrlTaskPoll string `yaml:"url-task-poll"`
  18. UrlTask string `yaml:"url-task"`
  19. }
  20. type rosbagStruct struct {
  21. Path string `yaml:"path"`
  22. Envs []string `yaml:"envs"`
  23. }
  24. type HostStruct struct {
  25. Name string `yaml:"name"`
  26. Ip string `yaml:"ip"`
  27. Topics []string `yaml:"topics"`
  28. Rosbag rosbagStruct `yaml:"rosbag"`
  29. }
  30. type RosStruct struct {
  31. MasterAddress string `yaml:"master-address"`
  32. Nodes []string `yaml:"nodes"`
  33. }
  34. type DiskStruct struct {
  35. Name string `yaml:"name"`
  36. Used uint64 `yaml:"used"`
  37. }
  38. type TriggerStruct struct {
  39. Label string `yaml:"label"`
  40. Topics []string `yaml:"topics"`
  41. }
  42. type CollectLimitStruct struct {
  43. Url string `yaml:"url"`
  44. Day int `yaml:"day"`
  45. Week int `yaml:"week"`
  46. Month int `yaml:"month"`
  47. Year int `yaml:"year"`
  48. }
  49. type DataDirStruct struct {
  50. Src string `yaml:"src"`
  51. SrcSub []string `yaml:"src-sub"`
  52. Dest string `yaml:"dest"`
  53. }
  54. type cloudConfig struct {
  55. CollectLimit CollectLimitStruct `yaml:"collect-limit"`
  56. DataDir DataDirStruct `yaml:"data-dir"`
  57. MapBufFiles []string `yaml:"map-buf-files"`
  58. FullCollect bool `yaml:"full-collect"`
  59. ConfigRefreshInterval int `yaml:"config-refresh-interval"` // 配置刷新时间间隔
  60. BagNumber int `yaml:"bag-number"`
  61. TimeWindowSendGap int `yaml:"time-window-send-gap"` // 主节点向从节点发送窗口的最小时间间隔
  62. MapBagPath string `yaml:"map-bag-path"`
  63. TfstaticBagPath string `yaml:"tfstatic-bag-path"`
  64. CostmapBagPath string `yaml:"costmap-bag-path"`
  65. BagDataDir string `yaml:"bag-data-dir"`
  66. BagCopyDir string `yaml:"bag-copy-dir"`
  67. TriggersDir string `yaml:"triggers-dir"`
  68. RpcPort string `yaml:"rpc-port"`
  69. Triggers []TriggerStruct `yaml:"triggers"`
  70. Hosts []HostStruct `yaml:"hosts"`
  71. Ros RosStruct `yaml:"ros"`
  72. Platform PlatformStruct `yaml:"platform"`
  73. Disk DiskStruct `yaml:"disk"`
  74. Monitor MonitorStruct `yaml:"monitor"`
  75. }
  76. //// Request 结构体定义
  77. //type Request struct {
  78. // Type string `json:"type"`
  79. // UUID string `json:"uuid"`
  80. // CommandID string `json:"commandId"`
  81. // Parameter interface{} `json:"parameter"`
  82. //}
  83. //
  84. //// Response 结构体定义
  85. //type Response struct {
  86. // CommandID string `json:"commandId"`
  87. // ErrorCode string `json:"errorCode"`
  88. // Results map[string]string `json:"results"`
  89. // Status string `json:"status"`
  90. // Time int64 `json:"time"`
  91. // Type string `json:"type"`
  92. // UUID string `json:"uuid"`
  93. //}
  94. var (
  95. CloudConfig cloudConfig
  96. CloudConfigMutex sync.RWMutex
  97. )
  98. // InitCloudConfig 初始化业务配置
  99. func InitCloudConfig() {
  100. // history20240401:朴津机器人额外加一个获取sn码
  101. var snCode string
  102. for {
  103. time.Sleep(time.Duration(2) * time.Second)
  104. snCode, err := getSnCode()
  105. if err != nil {
  106. c_log.GlobalLogger.Error("获取sn码失败:", err.Error())
  107. continue
  108. }
  109. LocalConfig.SecretKey = snCode
  110. LocalConfig.EquipmentNo = "pjibot-" + snCode
  111. break
  112. }
  113. c_log.GlobalLogger.Info("本地机器人sn码为:", snCode)
  114. c_log.GlobalLogger.Info("初始化OSS配置文件 - 开始。")
  115. // 获取文件的目录
  116. _ = util.CreateParentDir(LocalConfig.CloudConfigLocalPath)
  117. // 3 ------- 获取 yaml 字符串 -------
  118. cloudConfigObjectKey := LocalConfig.OssBasePrefix + LocalConfig.EquipmentNo + "/" + LocalConfig.CloudConfigFilename
  119. // 判断文件是否存在。如果不存在则使用默认的
  120. isExist, err := OssBucket.IsObjectExist(cloudConfigObjectKey)
  121. if err != nil {
  122. c_log.GlobalLogger.Errorf("判断配置文件是否存在失败,错误信息为:%v", err)
  123. }
  124. if isExist {
  125. c_log.GlobalLogger.Info("使用机器人自定义配置文件:", cloudConfigObjectKey)
  126. } else {
  127. cloudConfigObjectKey = LocalConfig.OssBasePrefix + LocalConfig.CloudConfigFilename // 默认配置文件路径
  128. c_log.GlobalLogger.Info("使用机器人默认配置文件:", cloudConfigObjectKey)
  129. }
  130. for {
  131. OssMutex.Lock()
  132. err := OssBucket.GetObjectToFile(cloudConfigObjectKey, LocalConfig.CloudConfigLocalPath)
  133. OssMutex.Unlock()
  134. if err != nil {
  135. c_log.GlobalLogger.Error("下载 OSS 上的配置文件 "+cloudConfigObjectKey+" 失败,请尽快在 OSS 上传配置文件。", err)
  136. time.Sleep(time.Duration(2) * time.Second)
  137. continue
  138. }
  139. break
  140. }
  141. content, err := os.ReadFile(LocalConfig.CloudConfigLocalPath)
  142. if err != nil {
  143. c_log.GlobalLogger.Error("程序崩溃,配置文件 ", LocalConfig.CloudConfigLocalPath, " 读取失败:", err)
  144. os.Exit(-1)
  145. }
  146. // 4 ------- 解析YAML内容 -------
  147. var newCloudConfig cloudConfig
  148. err = yaml.Unmarshal(content, &newCloudConfig)
  149. if err != nil {
  150. c_log.GlobalLogger.Error("程序崩溃,配置文件 ", LocalConfig.CloudConfigLocalPath, " 解析失败:", err)
  151. os.Exit(-1)
  152. }
  153. // 5 ------- 校验 yaml -------
  154. if checkCloudConfig(newCloudConfig) {
  155. CloudConfigMutex.RLock()
  156. CloudConfig = newCloudConfig
  157. CloudConfigMutex.RUnlock()
  158. } else {
  159. c_log.GlobalLogger.Error("程序崩溃,配置文件格式错误:", newCloudConfig)
  160. os.Exit(-1)
  161. }
  162. c_log.GlobalLogger.Info("初始化OSS配置文件 - 成功。")
  163. util.CreateDir(CloudConfig.BagDataDir)
  164. util.CreateDir(CloudConfig.BagCopyDir)
  165. }
  166. // 更新业务配置
  167. func refreshCloudConfig() {
  168. // 获取文件的目录
  169. _ = util.CreateParentDir(LocalConfig.CloudConfigLocalPath)
  170. // 3 ------- 获取 yaml 字符串 -------
  171. var content []byte
  172. cloudConfigObjectKey := LocalConfig.OssBasePrefix + LocalConfig.EquipmentNo + "/" + LocalConfig.CloudConfigFilename
  173. isExist, err := OssBucket.IsObjectExist(cloudConfigObjectKey)
  174. if err != nil {
  175. c_log.GlobalLogger.Errorf("判断配置文件是否存在失败,错误信息为:%v", err)
  176. return
  177. }
  178. if !isExist {
  179. cloudConfigObjectKey = LocalConfig.OssBasePrefix + LocalConfig.CloudConfigFilename // 默认配置文件路径
  180. }
  181. OssMutex.Lock()
  182. err = OssBucket.GetObjectToFile(cloudConfigObjectKey, LocalConfig.CloudConfigLocalPath)
  183. OssMutex.Unlock()
  184. if err != nil {
  185. c_log.GlobalLogger.Error("下载oss上的配置文件"+cloudConfigObjectKey+"失败。", err)
  186. }
  187. content, err = os.ReadFile(LocalConfig.CloudConfigLocalPath)
  188. if err != nil {
  189. c_log.GlobalLogger.Error("配置文件 ", LocalConfig.CloudConfigLocalPath, " 读取失败:", err)
  190. return
  191. }
  192. // 4 ------- 解析YAML内容 -------
  193. var newCloudConfig cloudConfig
  194. err = yaml.Unmarshal(content, &newCloudConfig)
  195. if err != nil {
  196. c_log.GlobalLogger.Error("配置文件 ", LocalConfig.CloudConfigLocalPath, " 解析失败:", err)
  197. return
  198. }
  199. // 5 ------- 校验 yaml -------
  200. if checkCloudConfig(newCloudConfig) {
  201. CloudConfigMutex.RLock()
  202. CloudConfig = newCloudConfig
  203. CloudConfigMutex.RUnlock()
  204. } else {
  205. c_log.GlobalLogger.Error("配置文件格式错误:", newCloudConfig)
  206. return
  207. }
  208. util.CreateDir(CloudConfig.BagDataDir)
  209. util.CreateDir(CloudConfig.BagCopyDir)
  210. }
  211. // RefreshCloudConfig 轮询oss上的配置文件更新到本地
  212. func RefreshCloudConfig() {
  213. for {
  214. time.Sleep(time.Duration(CloudConfig.ConfigRefreshInterval) * time.Second)
  215. refreshCloudConfig()
  216. }
  217. }
  218. // CheckConfig 校验 cfg.yaml 文件
  219. func checkCloudConfig(check cloudConfig) bool {
  220. if len(check.Hosts) != 1 {
  221. c_log.GlobalLogger.Error("cloud-config.yaml中配置的hosts必须为1。")
  222. os.Exit(-1)
  223. }
  224. return true
  225. }
  226. func getSnCode() (string, error) {
  227. var command []string
  228. command = append(command, "get")
  229. command = append(command, "sn")
  230. _, snOutput, err := util.ExecuteSync(LocalConfig.RosparamPath, command...)
  231. if err != nil {
  232. return "", errors.New("执行获取sn码命令" + util.ToString(command) + "出错:" + util.ToString(err))
  233. }
  234. c_log.GlobalLogger.Info("执行获取sn码命令", command, "成功,结果为:", snOutput)
  235. snCode := strings.Replace(strings.Replace(snOutput, " ", "", -1), "\n", "", -1)
  236. return snCode, nil
  237. }
  238. //// SendWebsocketRequest 发送WebSocket请求并返回sn字段的值
  239. //func SendWebsocketRequest(serverURL, path string, request Request) (string, error) {
  240. // // 构建WebSocket连接URL
  241. // u := url.URL{Scheme: "ws", Host: serverURL, Path: path}
  242. //
  243. // // 创建一个Dialer实例,用于建立WebSocket连接
  244. // dialer := websocket.Dialer{
  245. // ReadBufferSize: 1024,
  246. // WriteBufferSize: 1024,
  247. // // 可选:设置超时等
  248. // HandshakeTimeout: 5 * time.Second,
  249. // }
  250. //
  251. // // 建立WebSocket连接
  252. // conn, _, err := dialer.Dial(u.String(), nil)
  253. // if err != nil {
  254. // return "", fmt.Errorf("dial: %w", err)
  255. // }
  256. // defer conn.Close()
  257. //
  258. // // 将请求JSON编码为字节
  259. // requestJSON, err := json.Marshal(request)
  260. // if err != nil {
  261. // return "", fmt.Errorf("marshal request: %w", err)
  262. // }
  263. //
  264. // // 发送WebSocket消息
  265. // err = conn.WriteMessage(websocket.TextMessage, requestJSON)
  266. // if err != nil {
  267. // return "", fmt.Errorf("write: %w", err)
  268. // }
  269. //
  270. // // 读取WebSocket响应
  271. // _, responseBytes, err := conn.ReadMessage()
  272. // if err != nil {
  273. // return "", fmt.Errorf("read: %w", err)
  274. // }
  275. //
  276. // // 将响应字节解码为JSON
  277. // var response Response
  278. // err = json.Unmarshal(responseBytes, &response)
  279. // if err != nil {
  280. // return "", fmt.Errorf("unmarshal response: %w", err)
  281. // }
  282. //
  283. // // 返回sn字段的值
  284. // return response.Results["sn"], nil
  285. //}