log_ip.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449
  1. package log
  2. import (
  3. "errors"
  4. "fmt"
  5. "github.com/xuri/excelize/v2"
  6. "go.uber.org/zap"
  7. "gorm.io/gorm"
  8. "log-server/global"
  9. "log-server/model/log"
  10. "log-server/model/log/request"
  11. "strconv"
  12. "time"
  13. )
  14. type ServiceIpLog struct {
  15. }
  16. //根据gameId、机器编号分组获取ip
  17. func (s *ServiceIpLog) GetIpLogList(api log.IpLogRequest, info request.PageInfo, order string, desc bool) (list interface{}, total int64, err error) {
  18. limit := info.PageSize
  19. offset := info.PageSize * (info.Page - 1)
  20. db := global.GVA_DB.Model(&log.IpLog{})
  21. var apiList []log.IpLogResponse
  22. startDate := time.Now().Format("2006-01-02")
  23. endDate := time.Now().Format("2006-01-02")
  24. if len(api.Date) == 2 {
  25. startDate = api.Date[0]
  26. endDate = api.Date[1]
  27. }
  28. db = db.Where("create_date >= ? and create_date <= ?", startDate, endDate)
  29. if api.GameId != 0 {
  30. db = db.Where("game_id = ?", api.GameId)
  31. }
  32. if api.PcCode != "" {
  33. db = db.Where("pc_code = ?", api.PcCode)
  34. }
  35. if api.Ip != "" {
  36. db = db.Where("ip = ?", api.Ip)
  37. }
  38. db = db.Select("create_date,pc_code,game_id,count(*) as count_total,count(distinct(ip)) as count_distinct_ip")
  39. db = db.Group("pc_code, game_id, create_date")
  40. //db.Select("count(*)").Count(&countTotal)
  41. //db.Select("count(distinct(ip))").Count(&countDistinctIp)
  42. err = db.Count(&total).Error
  43. if err != nil {
  44. return apiList, total, err
  45. } else {
  46. db = db.Limit(limit).Offset(offset)
  47. if order != "" {
  48. var OrderStr string
  49. // 设置有效排序key 防止sql注入
  50. // 感谢 Tom4t0 提交漏洞信息
  51. orderMap := make(map[string]bool, 4)
  52. orderMap["game_id"] = true
  53. orderMap["count_distinct_ip"] = true
  54. orderMap["count_total"] = true
  55. orderMap["create_date"] = true
  56. if orderMap[order] {
  57. if desc {
  58. OrderStr = order + " desc"
  59. } else {
  60. OrderStr = order
  61. }
  62. } else { // didn't matched any order key in `orderMap`
  63. global.GVA_LOG.Error("获取失败!", zap.Error(err))
  64. return apiList, total, err
  65. }
  66. err = db.Order(OrderStr).Find(&apiList).Error
  67. } else {
  68. err = db.Order("id").Find(&apiList).Error
  69. }
  70. }
  71. //遍历更改日期格式
  72. for i, _ := range apiList {
  73. apiList[i].CreateDate = apiList[i].CreateDate[:10]
  74. }
  75. return apiList, total, err
  76. }
  77. //获取异常租机ip列表
  78. func (s *ServiceIpLog) GetAbnormalIpLogList(api log.AbnormalIpLogRequest, info request.PageInfo, order string, desc bool) (list interface{}, total int64, err error) {
  79. limit := info.PageSize
  80. offset := info.PageSize * (info.Page - 1)
  81. db := global.GVA_DB.Model(&log.AbnormalMachineIp{})
  82. var apiList []log.AbnormalMachineIp
  83. startDate := time.Now().Format("2006-01-02")
  84. endDate := time.Now().Format("2006-01-02")
  85. if len(api.Date) == 2 {
  86. startDate = api.Date[0]
  87. endDate = api.Date[1]
  88. }
  89. db = db.Select("abnormal_machine_ip.*, game_task.task_name, game_task.user")
  90. db = db.Joins("left join game_task on game_task.task_id = abnormal_machine_ip.game_id")
  91. db = db.Where("create_date >= ? and create_date <= ?", startDate, endDate)
  92. if api.GameId != 0 {
  93. db = db.Where("game_id = ?", api.GameId)
  94. }
  95. if api.PcCode != "" {
  96. db = db.Where("pc_code = ?", api.PcCode)
  97. }
  98. if api.Ip != "" {
  99. db = db.Where("ip = ?", api.Ip)
  100. }
  101. err = db.Count(&total).Error
  102. if err != nil {
  103. return apiList, total, err
  104. } else {
  105. db = db.Limit(limit).Offset(offset)
  106. if order != "" {
  107. var OrderStr string
  108. // 设置有效排序key 防止sql注入
  109. // 感谢 Tom4t0 提交漏洞信息
  110. orderMap := make(map[string]bool, 5)
  111. orderMap["game_id"] = true
  112. orderMap["count"] = true
  113. orderMap["create_date"] = true
  114. orderMap["user"] = true
  115. orderMap["task_name"] = true
  116. if orderMap[order] {
  117. if desc {
  118. OrderStr = order + " desc"
  119. } else {
  120. OrderStr = order
  121. }
  122. } else { // didn't matched any order key in `orderMap`
  123. global.GVA_LOG.Error("获取失败!", zap.Error(err))
  124. return apiList, total, err
  125. }
  126. err = db.Order(OrderStr).Find(&apiList).Error
  127. } else {
  128. err = db.Order("id desc").Find(&apiList).Error
  129. }
  130. }
  131. //遍历更改日期格式
  132. for i, _ := range apiList {
  133. apiList[i].CreateDate = apiList[i].CreateDate[:10]
  134. }
  135. return apiList, total, err
  136. }
  137. //获取今日异常租机ip(ip播报使用)
  138. func (s *ServiceIpLog) GetTodayAbnormalIpLogList() (list map[string]string, err error) {
  139. var total int64
  140. var apiList []log.TodayAbnormalMachineIp
  141. pcCodeList := make(map[string]string)
  142. usePcCode := make(map[string]string)
  143. date := time.Now().Format("2006-01-02")
  144. //1个半小时前的时间
  145. effectiveTime := time.Now().Add(-time.Minute * 90).Format("2006-01-02 15:04:05")
  146. db := global.GVA_DB.Table("abnormal_machine_ip as ami")
  147. db = db.Select("ami.*, gt.task_name, gt.user")
  148. db = db.Joins("left join game_task as gt on gt.task_id = ami.game_id")
  149. db = db.Where("create_date", date)
  150. err = db.Count(&total).Error
  151. if total == 0 {
  152. return usePcCode, err
  153. }
  154. if err != nil {
  155. return usePcCode, err
  156. } else {
  157. err = db.Order("id").Find(&apiList).Error
  158. }
  159. //遍历更改日期格式
  160. for i, _ := range apiList {
  161. apiList[i].CreateDate = apiList[i].CreateDate[:10]
  162. //得到{编号【负责人名称类似结构】}
  163. pcCodeList[apiList[i].PcCode] = apiList[i].User
  164. }
  165. //遍历列表中的租机,查询数据库(租机编号,和本日时间),得到记录集合,通过ip作为map的key,判断是否需要播报
  166. //遍历租机编号列表
  167. for k, _ := range pcCodeList {
  168. var ipList []log.IpLogBroadcast
  169. ipSet := make(map[string]int)
  170. db1 := global.GVA_DB.Model(&log.IpLog{}).Select("ip_log.*, game_task.user")
  171. db1 = db1.Joins("left join game_task on game_task.task_id = ip_log.game_id")
  172. db1.Where("create_date = ? and pc_code = ? and ip_log.create_time > ? ", date, k, effectiveTime).Limit(5).Order("id desc").Find(&ipList)
  173. //fmt.Println(ipList)
  174. //fmt.Println(len(ipList))
  175. //样本太少,不做处理
  176. if len(ipList) <= 1 {
  177. return usePcCode, err
  178. }
  179. //遍历ipList,查找
  180. for _, v := range ipList {
  181. ipSet[v.Ip] = 1
  182. //fmt.Println(ipSet)
  183. //fmt.Println(len(ipSet))
  184. }
  185. if len(ipSet) == 1 {
  186. usePcCode[ipList[0].PcCode] = ipList[0].User
  187. }
  188. }
  189. return usePcCode, err
  190. }
  191. //根据gameId获取ip
  192. func (s *ServiceIpLog) GetGameIpList(api log.GameIpRequest, info request.PageInfo, order string, desc bool) (apiList []log.GameIpResponse, total int64, err error) {
  193. limit := info.PageSize
  194. offset := info.PageSize * (info.Page - 1)
  195. db := global.GVA_DB.Model(&log.GameIpResponse{})
  196. startDate := time.Now().Format("2006-01-02")
  197. endDate := time.Now().Format("2006-01-02")
  198. if len(api.Date) == 2 {
  199. startDate = api.Date[0]
  200. endDate = api.Date[1]
  201. }
  202. //筛选负责人
  203. if api.User != "" {
  204. db = db.Where("user = ?", api.User)
  205. }
  206. //筛选日期
  207. db = db.Where("create_date >= ? and create_date <= ?", startDate, endDate)
  208. if api.GameId != 0 {
  209. db = db.Where("game_id = ?", api.GameId)
  210. }
  211. err = db.Count(&total).Error
  212. if err != nil {
  213. return apiList, total, err
  214. } else {
  215. db = db.Limit(limit).Offset(offset)
  216. if order != "" {
  217. var OrderStr string
  218. // 设置有效排序key 防止sql注入
  219. // 感谢 Tom4t0 提交漏洞信息
  220. orderMap := make(map[string]bool, 8)
  221. //orderMap["game_id"] = true
  222. orderMap["count_distinct_ip"] = true
  223. orderMap["count_total"] = true
  224. orderMap["success_ip"] = true
  225. orderMap["task_count"] = true
  226. orderMap["create_date"] = true
  227. orderMap["exceed_three"] = true
  228. orderMap["ip_repetition_rate"] = true
  229. orderMap["average_ip_repetition_rate"] = true
  230. if orderMap[order] {
  231. if desc {
  232. OrderStr = order + " desc"
  233. } else {
  234. OrderStr = order
  235. }
  236. } else { // didn't matched any order key in `orderMap`
  237. global.GVA_LOG.Error("获取失败!", zap.Error(err))
  238. return apiList, total, err
  239. }
  240. err = db.Order(OrderStr).Find(&apiList).Error
  241. } else {
  242. err = db.Order("id").Find(&apiList).Error
  243. }
  244. }
  245. //遍历更改日期格式
  246. for i, _ := range apiList {
  247. apiList[i].CreateDate = apiList[i].CreateDate[:10]
  248. //err = global.GVA_DB.Model(&log.IpLog{}).Select("COUNT(1) as max_count").Where("game_id = ? and create_date = ? and status = 2", apiList[i].GameId, apiList[i].CreateDate).Group("ip").Order("max_count desc").Limit(1).Find(&apiList[i]).Error
  249. //global.GVA_DB.Model(&log.IpLog{}).Select("id,ip,count(*) ").Where("game_id = ? and create_date = ? and status = 2", apiList[i].GameId, apiList[i].CreateDate).Group("ip").Having("count(*) > 4").Count(&apiList[i].ExceedThree)
  250. ////获取平均重复率和ip重复率 并保留小数点后两位
  251. //countDistinctIp := float64(apiList[i].CountDistinctIp)
  252. //successIp := float64(apiList[i].SuccessIp)
  253. //taskCount := float64(apiList[i].TaskCount)
  254. //apiList[i].IpRepetitionRate, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", (countDistinctIp/ successIp) *100), 64)
  255. //if taskCount != 0 {
  256. // apiList[i].AverageIpRepetitionRate, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", (countDistinctIp / taskCount) *100), 64)
  257. //}
  258. }
  259. return apiList, total, err
  260. }
  261. //展示ip
  262. func (s *ServiceIpLog) GetIp(iplog log.IpLogResponse) (list interface{}, total int64, err error) {
  263. var ipList []log.QueryIpList
  264. db := global.GVA_DB.Model(&log.IpLog{}).Select("ip, COUNT(1) as count").Where("game_id = ? and pc_code = ? and create_date = ?", iplog.GameId, iplog.PcCode, iplog.CreateDate).Group("ip")
  265. db.Count(&total)
  266. err = db.Order("count desc").Find(&ipList).Error
  267. return ipList, total, err
  268. }
  269. //gameID分组展示ip
  270. func (s *ServiceIpLog) GetGameIp(ip log.GameIpResponse) (list interface{}, total int64, err error) {
  271. var ipList []log.QueryIpList
  272. db := global.GVA_DB.Model(&log.IpLog{}).Select("ip, COUNT(1) as count").Where("game_id = ? and status = 2 and create_date = ?", ip.GameId, ip.CreateDate).Group("ip")
  273. db.Count(&total)
  274. err = db.Order("count desc").Find(&ipList).Error
  275. return ipList, total, err
  276. }
  277. //获取gameIP列表
  278. func (s *ServiceIpLog) GameIpListExcel(infoList []log.GameIpResponse, filePath string) error {
  279. excel := excelize.NewFile()
  280. excel.SetSheetRow("Sheet1", "A1", &[]string{
  281. "游戏id",
  282. "负责人",
  283. "任务名称",
  284. "上报ip次数",
  285. "任务完成",
  286. "最大ip数",
  287. "异常ip个数",
  288. "成功ip次数",
  289. "ip个数",
  290. "ip重复率",
  291. "平均重复率",
  292. "日期"})
  293. for i, statisticsLog := range infoList {
  294. axis := fmt.Sprintf("A%d", i+2)
  295. excel.SetSheetRow("Sheet1", axis, &[]interface{}{
  296. statisticsLog.GameId,
  297. statisticsLog.User,
  298. statisticsLog.TaskName,
  299. statisticsLog.CountTotal,
  300. statisticsLog.TaskCount,
  301. statisticsLog.MaxCount,
  302. statisticsLog.ExceedThree,
  303. statisticsLog.SuccessIp,
  304. statisticsLog.CountDistinctIp,
  305. statisticsLog.IpRepetitionRate,
  306. statisticsLog.AverageIpRepetitionRate,
  307. statisticsLog.CreateDate[:10],
  308. })
  309. }
  310. err := excel.SaveAs(filePath)
  311. return err
  312. }
  313. //获取异常ip数据
  314. func (s *ServiceIpLog) GetAbnormalIp() (list map[string]string, err error) {
  315. db := global.GVA_DB.Model(&log.GameIpResponse{})
  316. date := time.Now().Format("2006-01-02")
  317. var apiList []log.GameIpResponse
  318. //筛选日期
  319. db = db.Where("create_date = ?", date)
  320. err = db.Order("id").Find(&apiList).Error
  321. var abnormalIpList = map[string]string{}
  322. //遍历更改日期格式
  323. for i, _ := range apiList {
  324. //apiList[i].CreateDate = apiList[i].CreateDate[:10]
  325. if apiList[i].IpRepetitionRate < 30 && apiList[i].CountTotal > 10 {
  326. abnormalIpList[apiList[i].User] = apiList[i].TaskName
  327. }
  328. }
  329. return abnormalIpList, err
  330. }
  331. //更新租机异常ip数据
  332. func (s *ServiceIpLog) UpdateAbnormalMachineIp() (err error) {
  333. //首先获取今天的时间
  334. var abnormalIpList []log.AbnormalMachineIp
  335. date := time.Now().Format("2006-01-02")
  336. //然后查找租机异常ip记录,并且添加至数据库中
  337. db := global.GVA_DB.Table("ip_log").Select("ip, create_date, game_id, pc_code, count(ip) as count")
  338. db = db.Where("create_date", date)
  339. db = db.Group("pc_code, ip, game_id")
  340. err = db.Find(&abnormalIpList).Error
  341. //fmt.Println(abnormalIpList)
  342. if err != nil {
  343. return err
  344. }
  345. //将异常ip存储至abnormal_machine_ip数据库中
  346. for i, _ := range abnormalIpList {
  347. var entity log.AbnormalMachineIp
  348. ip := abnormalIpList[i].Ip
  349. gameId := abnormalIpList[i].GameId
  350. pcCode := abnormalIpList[i].PcCode
  351. createDate := abnormalIpList[i].CreateDate[:10]
  352. count := abnormalIpList[i].Count
  353. //根据count判断,如果count < 9, continue继续做下一条记录的处理
  354. if count < 6 {
  355. continue
  356. }
  357. if !errors.Is(global.GVA_DB.Model(&log.AbnormalMachineIp{}).Where("ip = ? and game_id = ? and pc_code = ? and create_date = ?", ip, gameId, pcCode, createDate).First(&entity).Error, gorm.ErrRecordNotFound) {
  358. //存在相同的ip、租机、gameid、创建日期记录,那么更新数量即可
  359. err = global.GVA_DB.Model(&log.AbnormalMachineIp{}).Where("ip = ? and game_id = ? and pc_code = ? and create_date = ?", ip, gameId, pcCode, createDate).Update("count", count).Error
  360. if err != nil {
  361. return errors.New("更新ip数量失败")
  362. }
  363. continue
  364. }
  365. //如果数据库中没有相同的记录,则创建相对应的记录
  366. err = global.GVA_DB.Model(&log.AbnormalMachineIp{}).Omit("user", "task_name").Create(&abnormalIpList[i]).Error
  367. if err != nil {
  368. return err
  369. }
  370. }
  371. return err
  372. }
  373. //定时更新ip列表数据
  374. func (s *ServiceIpLog) UpdateGameIpList() (err error) {
  375. var total int64
  376. var apiList []log.GameIpResponse
  377. db := global.GVA_DB.Model(&log.IpLog{})
  378. date := time.Now().Format("2006-01-02")
  379. //筛选日期
  380. db = db.Where("ip_log.create_date = ?", date)
  381. //查找总ip上报次数
  382. db = db.Joins("left join"+"(select count(*) as count, game_id, create_date from ip_log where create_date = ? group by game_id, create_date)"+" as late on late.game_id = ip_log.game_id and late.create_date = ip_log.create_date", date)
  383. db = db.Where("ip_log.status = 2")
  384. db = db.Select("ip_log.create_date,ip_log.game_id,late.count as count_total, task_name, user, count(*) as success_ip , retained_complete as task_count, count(distinct(ip)) as count_distinct_ip")
  385. //拼接任务完成表
  386. db = db.Joins("left join game_target_complete as gtc on gtc.task_id = ip_log.game_id and gtc.create_date = ip_log.create_date")
  387. //拼接game_task表获取任务名称和负责人名称
  388. db = db.Joins("left join game_task as gt on gt.task_id = ip_log.game_id")
  389. db = db.Group("ip_log.game_id, ip_log.create_date")
  390. err = db.Count(&total).Error
  391. if err != nil {
  392. return err
  393. }
  394. err = db.Order("ip_log.id").Find(&apiList).Error
  395. //遍历更改日期格式
  396. for i, _ := range apiList {
  397. var entity log.GameIpResponse
  398. apiList[i].CreateDate = apiList[i].CreateDate[:10]
  399. err = global.GVA_DB.Model(&log.IpLog{}).Select("COUNT(1) as max_count").Where("game_id = ? and create_date = ? and status = 2", apiList[i].GameId, apiList[i].CreateDate).Group("ip").Order("max_count desc").Limit(1).Find(&apiList[i]).Error
  400. global.GVA_DB.Model(&log.IpLog{}).Select("id,ip,count(*) ").Where("game_id = ? and create_date = ? and status = 2", apiList[i].GameId, apiList[i].CreateDate).Group("ip").Having("count(*) > 4").Count(&apiList[i].ExceedThree)
  401. //获取平均重复率和ip重复率 并保留小数点后两位
  402. countDistinctIp := float64(apiList[i].CountDistinctIp)
  403. successIp := float64(apiList[i].SuccessIp)
  404. taskCount := float64(apiList[i].TaskCount)
  405. apiList[i].IpRepetitionRate, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", (countDistinctIp/successIp)*100), 64)
  406. if taskCount != 0 {
  407. apiList[i].AverageIpRepetitionRate, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", (countDistinctIp/taskCount)*100), 64)
  408. }
  409. //查找数据库中是否有这条记录(game_id, create_date)
  410. if !errors.Is(global.GVA_DB.Model(&log.GameIpResponse{}).Where("game_id = ? and create_date = ?", apiList[i].GameId, apiList[i].CreateDate).First(&entity).Error, gorm.ErrRecordNotFound) {
  411. //如果有,更新
  412. err = global.GVA_DB.Model(&log.GameIpResponse{}).Where("game_id = ? and create_date = ?", apiList[i].GameId, apiList[i].CreateDate).Save(&apiList[i]).Error
  413. if err != nil {
  414. return errors.New("更新ip列表失败")
  415. }
  416. continue
  417. }
  418. //如果数据库中没有相同的记录,则创建相对应的记录
  419. err = global.GVA_DB.Model(&log.GameIpResponse{}).Create(&apiList[i]).Error
  420. if err != nil {
  421. return err
  422. }
  423. }
  424. return err
  425. }