c_cloud.go 9.8 KB

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