c_cloud.go 10.0 KB

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