utils.go 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232
  1. package util
  2. import (
  3. commonConfig "cicv-data-closedloop/kinglong/common/cfg"
  4. "cicv-data-closedloop/kinglong/common/ent"
  5. "cicv-data-closedloop/kinglong/common/global"
  6. "cicv-data-closedloop/kinglong/common/log"
  7. "fmt"
  8. "os"
  9. "os/exec"
  10. "path/filepath"
  11. "sort"
  12. "strconv"
  13. "strings"
  14. "time"
  15. )
  16. // AppendIfNotExists 向切片中追加元素,如果元素已存在则不添加
  17. func AppendIfNotExists(slice []string, element string) []string {
  18. for _, item := range slice {
  19. if item == element {
  20. return slice // 元素已存在,直接返回原切片
  21. }
  22. }
  23. return append(slice, element) // 元素不存在,追加到切片末尾
  24. }
  25. func AddTimeWindowToTimeWindowProducerQueue(window ent.TimeWindow) {
  26. global.TimeWindowProducerQueueMutex.RLock()
  27. {
  28. global.TimeWindowProducerQueue = append(global.TimeWindowProducerQueue, window)
  29. }
  30. global.TimeWindowProducerQueueMutex.RUnlock()
  31. }
  32. func AddTimeWindowToTimeWindowConsumerQueue(window ent.TimeWindow) {
  33. global.TimeWindowConsumerQueueMutex.RLock()
  34. {
  35. global.TimeWindowConsumerQueue = append(global.TimeWindowConsumerQueue, window)
  36. }
  37. global.TimeWindowConsumerQueueMutex.RUnlock()
  38. }
  39. func RemoveHeadOfdTimeWindowProducerQueue() {
  40. global.TimeWindowProducerQueueMutex.RLock()
  41. {
  42. global.TimeWindowProducerQueue = global.TimeWindowProducerQueue[1:]
  43. }
  44. global.TimeWindowProducerQueueMutex.RUnlock()
  45. }
  46. func RemoveHeaOfdTimeWindowConsumerQueue() {
  47. global.TimeWindowConsumerQueueMutex.RLock()
  48. {
  49. global.TimeWindowConsumerQueue = global.TimeWindowConsumerQueue[1:]
  50. }
  51. global.TimeWindowConsumerQueueMutex.RUnlock()
  52. }
  53. func GetBagTime(bagName string) string {
  54. s1 := strings.Split(bagName, "_")[0]
  55. s1Split := strings.Split(s1, "/")
  56. s2 := s1Split[len(s1Split)-1]
  57. return s2
  58. }
  59. func GetNowTimeCustom() string {
  60. currentTime := time.Now()
  61. formattedTime := currentTime.Format("2006-01-02-15-04-05")
  62. return formattedTime
  63. }
  64. func TimeCustomChange(originalTimeStr string, number int) string {
  65. var newTimeStr string
  66. // 解析时间字符串
  67. layout := "2006-01-02-15-04-05"
  68. originalTime, err := time.Parse(layout, originalTimeStr)
  69. if err != nil {
  70. log.GlobalLogger.Info("无法解析时间字符串:", err)
  71. return newTimeStr
  72. }
  73. // 减少1秒
  74. newTime := originalTime.Add(time.Duration(number) * time.Second)
  75. // 格式化新的时间为指定字符串格式
  76. return newTime.Format(layout)
  77. }
  78. func CalculateDifferenceOfTimeCustom(timeCustom1 string, timeCustom2 string) int {
  79. timeInt1, _ := strconv.Atoi(strings.Replace(timeCustom1, "-", "", -1))
  80. timeInt2, _ := strconv.Atoi(strings.Replace(timeCustom2, "-", "", -1))
  81. return timeInt2 - timeInt1 + 1
  82. }
  83. func TimeCustom1GreaterTimeCustom2(timeCustom1 string, timeCustom2 string) bool {
  84. timeInt1, _ := strconv.Atoi(strings.Replace(timeCustom1, "-", "", -1))
  85. timeInt2, _ := strconv.Atoi(strings.Replace(timeCustom2, "-", "", -1))
  86. return timeInt1 > timeInt2
  87. }
  88. func TimeCustom1GreaterEqualThanTimeCustom2(timeCustom1 string, timeCustom2 string) bool {
  89. timeInt1, _ := strconv.Atoi(strings.Replace(timeCustom1, "-", "", -1))
  90. timeInt2, _ := strconv.Atoi(strings.Replace(timeCustom2, "-", "", -1))
  91. return timeInt1 >= timeInt2
  92. }
  93. func TimeCustom1LessEqualThanTimeCustom2(timeCustom1 string, timeCustom2 string) bool {
  94. timeInt1, _ := strconv.Atoi(strings.Replace(timeCustom1, "-", "", -1))
  95. timeInt2, _ := strconv.Atoi(strings.Replace(timeCustom2, "-", "", -1))
  96. return timeInt1 <= timeInt2
  97. }
  98. // GetDiskUsagePercent 获取磁盘使用率
  99. func GetDiskUsagePercent() float64 {
  100. // 执行 df 命令获取磁盘使用情况
  101. cmd := exec.Command("df", "--total")
  102. output, err := cmd.Output()
  103. if err != nil {
  104. log.GlobalLogger.Info("执行命令失败:", err)
  105. return 0.0
  106. }
  107. // 解析 df 命令输出,计算磁盘占比
  108. lines := strings.Split(string(output), "\n")
  109. for _, line := range lines[1:] {
  110. fields := strings.Fields(line)
  111. if len(fields) >= 6 && fields[0] == "total" {
  112. //filesystem := fields[0]
  113. total, _ := strconv.ParseFloat(strings.TrimSuffix(fields[1], "G"), 64)
  114. used, _ := strconv.ParseFloat(strings.TrimSuffix(fields[2], "G"), 64)
  115. usedPercent := (used / total) * 100
  116. //fmt.Printf("文件系统 %s 已使用 %.2f%%\n", filesystem, usedPercent)
  117. return usedPercent
  118. }
  119. }
  120. return 0.0
  121. }
  122. func ListAbsolutePathAndSort(dir string) []string {
  123. var result []string
  124. if !strings.HasSuffix(dir, "/") {
  125. dir = dir + "/"
  126. }
  127. files, err := os.ReadDir(dir)
  128. if err != nil {
  129. log.GlobalLogger.Info("获取文件列表失败:", err)
  130. return result
  131. }
  132. for _, file := range files {
  133. result = append(result, dir+file.Name())
  134. }
  135. // 根据文件名进行升序排序
  136. sort.Slice(result, func(i, j int) bool {
  137. return filepath.Base(result[i]) < filepath.Base(result[j])
  138. })
  139. return result
  140. }
  141. func GetCopyDir(faultTime string) string {
  142. return commonConfig.CloudConfig.BagCopyDir + faultTime + "/"
  143. }
  144. func MergeSlice(slice1 []string, slice2 []string) []string {
  145. // 遍历第二个切片中的元素,并去重追加到结果切片1中
  146. for _, element := range slice2 {
  147. found := false
  148. for _, item := range slice1 {
  149. if element == item {
  150. found = true
  151. break
  152. }
  153. }
  154. if !found {
  155. slice1 = append(slice1, element)
  156. }
  157. }
  158. return slice1
  159. }
  160. func DeleteFile(path string) {
  161. // 检查文件是否存在
  162. if _, err := os.Stat(path); err == nil {
  163. // 文件存在,执行删除操作
  164. err := os.Remove(path)
  165. if err != nil {
  166. fmt.Printf("删除文件时发生错误:%s\n", err)
  167. return
  168. }
  169. }
  170. }
  171. // GetLastTimeWindow 获取最后一个时间窗口
  172. func GetLastTimeWindow() *ent.TimeWindow {
  173. var lastTimeWindow *ent.TimeWindow // 获取最后一个时间窗口
  174. if len(global.TimeWindowProducerQueue) > 0 {
  175. lastTimeWindow = &global.TimeWindowProducerQueue[len(global.TimeWindowProducerQueue)-1]
  176. }
  177. return lastTimeWindow
  178. }
  179. func RefreshTcpSendTime() {
  180. global.TcpSendTimeMutex.Lock()
  181. global.TcpSendTime = time.Now()
  182. global.TcpSendTimeMutex.Unlock()
  183. }
  184. // SupplyCopyBags 如果 Copy目录下的包不够,则补充一些
  185. func SupplyCopyBags(currentTimeWindow ent.TimeWindow) {
  186. // 如果bag包没有达到length,补充几个
  187. copyBags := ListAbsolutePathWithSuffixAndSort(GetCopyDir(currentTimeWindow.FaultTime), ".bag")
  188. copyBagsLength := len(copyBags)
  189. if copyBagsLength < currentTimeWindow.Length {
  190. time.Sleep(time.Duration(copyBagsLength) * time.Second)
  191. dataBags := ListAbsolutePathWithSuffixAndSort(commonConfig.CloudConfig.BagDataDir, ".bag")
  192. gap := currentTimeWindow.Length - copyBagsLength
  193. log.GlobalLogger.Info("故障 ", currentTimeWindow.FaultTime, "需要补充 ", gap, " 个 bag 包")
  194. for _, bag := range dataBags {
  195. bagTime := GetBagTime(bag)
  196. if TimeCustom1GreaterEqualThanTimeCustom2(bagTime, currentTimeWindow.FaultTime) {
  197. MoveFromDataToCopy(currentTimeWindow.FaultTime, bag)
  198. gap = gap - 1
  199. if gap == 0 {
  200. break
  201. }
  202. }
  203. }
  204. }
  205. }