You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

user_business_analysis.go 54 kB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480
  1. package models
  2. import (
  3. "fmt"
  4. "sort"
  5. "strconv"
  6. "time"
  7. "code.gitea.io/gitea/modules/log"
  8. "code.gitea.io/gitea/modules/timeutil"
  9. "xorm.io/builder"
  10. "xorm.io/xorm"
  11. )
  12. const (
  13. PAGE_SIZE = 2000
  14. BATCH_INSERT_SIZE = 50
  15. )
  16. type UserBusinessAnalysisAll struct {
  17. ID int64 `xorm:"pk"`
  18. CountDate int64 `xorm:"pk"`
  19. //action :ActionMergePullRequest // 11
  20. CodeMergeCount int `xorm:"NOT NULL DEFAULT 0"`
  21. //action :ActionCommitRepo // 5
  22. CommitCount int `xorm:"NOT NULL DEFAULT 0"`
  23. //action :ActionCreateIssue // 10
  24. IssueCount int `xorm:"NOT NULL DEFAULT 0"`
  25. //comment table current date
  26. CommentCount int `xorm:"NOT NULL DEFAULT 0"`
  27. //watch table current date
  28. FocusRepoCount int `xorm:"NOT NULL DEFAULT 0"`
  29. //star table current date
  30. StarRepoCount int `xorm:"NOT NULL DEFAULT 0"`
  31. //follow table
  32. WatchedCount int `xorm:"NOT NULL DEFAULT 0"`
  33. // user table
  34. GiteaAgeMonth int `xorm:"NOT NULL DEFAULT 0"`
  35. //
  36. CommitCodeSize int `xorm:"NOT NULL DEFAULT 0"`
  37. //attachement table
  38. CommitDatasetSize int `xorm:"NOT NULL DEFAULT 0"`
  39. //0
  40. CommitModelCount int `xorm:"NOT NULL DEFAULT 0"`
  41. //issue, issueassignees
  42. SolveIssueCount int `xorm:"NOT NULL DEFAULT 0"`
  43. //baike
  44. EncyclopediasCount int `xorm:"NOT NULL DEFAULT 0"`
  45. //user
  46. RegistDate timeutil.TimeStamp `xorm:"NOT NULL"`
  47. //repo
  48. CreateRepoCount int `xorm:"NOT NULL DEFAULT 0"`
  49. //login count, from elk
  50. LoginCount int `xorm:"NOT NULL DEFAULT 0"`
  51. //openi index
  52. OpenIIndex float64 `xorm:"NOT NULL DEFAULT 0"`
  53. //user
  54. Email string `xorm:"NOT NULL"`
  55. //user
  56. Name string `xorm:"NOT NULL"`
  57. DataDate string `xorm:"NULL"`
  58. //cloudbraintask
  59. CloudBrainTaskNum int `xorm:"NOT NULL DEFAULT 0"`
  60. GpuDebugJob int `xorm:"NOT NULL DEFAULT 0"`
  61. NpuDebugJob int `xorm:"NOT NULL DEFAULT 0"`
  62. GpuTrainJob int `xorm:"NOT NULL DEFAULT 0"`
  63. NpuTrainJob int `xorm:"NOT NULL DEFAULT 0"`
  64. NpuInferenceJob int `xorm:"NOT NULL DEFAULT 0"`
  65. GpuBenchMarkJob int `xorm:"NOT NULL DEFAULT 0"`
  66. CloudBrainRunTime int `xorm:"NOT NULL DEFAULT 0"`
  67. CommitDatasetNum int `xorm:"NOT NULL DEFAULT 0"`
  68. UserIndex float64 `xorm:"NOT NULL DEFAULT 0"`
  69. UserLocation string `xorm:"NULL"`
  70. }
  71. type UserBusinessAnalysis struct {
  72. ID int64 `xorm:"pk"`
  73. CountDate int64 `xorm:"pk"`
  74. //action :ActionMergePullRequest // 11
  75. CodeMergeCount int `xorm:"NOT NULL DEFAULT 0"`
  76. //action :ActionCommitRepo // 5
  77. CommitCount int `xorm:"NOT NULL DEFAULT 0"`
  78. //action :ActionCreateIssue // 6
  79. IssueCount int `xorm:"NOT NULL DEFAULT 0"`
  80. //comment table current date
  81. CommentCount int `xorm:"NOT NULL DEFAULT 0"`
  82. //watch table current date
  83. FocusRepoCount int `xorm:"NOT NULL DEFAULT 0"`
  84. //star table current date
  85. StarRepoCount int `xorm:"NOT NULL DEFAULT 0"`
  86. //follow table
  87. WatchedCount int `xorm:"NOT NULL DEFAULT 0"`
  88. // user table
  89. GiteaAgeMonth int `xorm:"NOT NULL DEFAULT 0"`
  90. //
  91. CommitCodeSize int `xorm:"NOT NULL DEFAULT 0"`
  92. //attachement table
  93. CommitDatasetSize int `xorm:"NOT NULL DEFAULT 0"`
  94. //0
  95. CommitModelCount int `xorm:"NOT NULL DEFAULT 0"`
  96. //issue, issueassignees
  97. SolveIssueCount int `xorm:"NOT NULL DEFAULT 0"`
  98. //baike
  99. EncyclopediasCount int `xorm:"NOT NULL DEFAULT 0"`
  100. //user
  101. RegistDate timeutil.TimeStamp `xorm:"NOT NULL"`
  102. //repo
  103. CreateRepoCount int `xorm:"NOT NULL DEFAULT 0"`
  104. //login count, from elk
  105. LoginCount int `xorm:"NOT NULL DEFAULT 0"`
  106. //openi index
  107. OpenIIndex float64 `xorm:"NOT NULL DEFAULT 0"`
  108. //user
  109. Email string `xorm:"NOT NULL"`
  110. //user
  111. Name string `xorm:"NOT NULL"`
  112. DataDate string `xorm:"NULL"`
  113. CloudBrainTaskNum int `xorm:"NOT NULL DEFAULT 0"`
  114. GpuDebugJob int `xorm:"NOT NULL DEFAULT 0"`
  115. NpuDebugJob int `xorm:"NOT NULL DEFAULT 0"`
  116. GpuTrainJob int `xorm:"NOT NULL DEFAULT 0"`
  117. NpuTrainJob int `xorm:"NOT NULL DEFAULT 0"`
  118. NpuInferenceJob int `xorm:"NOT NULL DEFAULT 0"`
  119. GpuBenchMarkJob int `xorm:"NOT NULL DEFAULT 0"`
  120. CloudBrainRunTime int `xorm:"NOT NULL DEFAULT 0"`
  121. CommitDatasetNum int `xorm:"NOT NULL DEFAULT 0"`
  122. UserIndex float64 `xorm:"NOT NULL DEFAULT 0"`
  123. UserLocation string `xorm:"NULL"`
  124. }
  125. type UserBusinessAnalysisQueryOptions struct {
  126. ListOptions
  127. UserName string
  128. SortType string
  129. StartTime int64
  130. EndTime int64
  131. IsAll bool
  132. }
  133. type UserBusinessAnalysisList []*UserBusinessAnalysis
  134. func (ulist UserBusinessAnalysisList) Swap(i, j int) { ulist[i], ulist[j] = ulist[j], ulist[i] }
  135. func (ulist UserBusinessAnalysisList) Len() int { return len(ulist) }
  136. func (ulist UserBusinessAnalysisList) Less(i, j int) bool {
  137. return ulist[i].ID > ulist[j].ID
  138. }
  139. func getLastCountDate() int64 {
  140. statictisSess := xStatistic.NewSession()
  141. defer statictisSess.Close()
  142. statictisSess.Limit(1, 0)
  143. userBusinessAnalysisList := make([]*UserBusinessAnalysis, 0)
  144. if err := statictisSess.Table("user_business_analysis").OrderBy("count_date desc").Limit(1, 0).
  145. Find(&userBusinessAnalysisList); err == nil {
  146. for _, userRecord := range userBusinessAnalysisList {
  147. return userRecord.CountDate - 10000
  148. }
  149. } else {
  150. log.Info("query error." + err.Error())
  151. }
  152. currentTimeNow := time.Now()
  153. pageStartTime := time.Date(currentTimeNow.Year(), currentTimeNow.Month(), currentTimeNow.Day(), 0, 0, 0, 0, currentTimeNow.Location())
  154. return pageStartTime.Unix()
  155. }
  156. func QueryMetrics(start int64, end int64) ([]*UserMetrics, int64) {
  157. statictisSess := xStatistic.NewSession()
  158. defer statictisSess.Close()
  159. userMetricsList := make([]*UserMetrics, 0)
  160. if err := statictisSess.Table(new(UserMetrics)).Where("count_date >" + fmt.Sprint(start) + " and count_date<" + fmt.Sprint(end)).OrderBy("count_date desc").
  161. Find(&userMetricsList); err != nil {
  162. return nil, 0
  163. }
  164. return userMetricsList, int64(len(userMetricsList))
  165. }
  166. func QueryRankList(key string, tableName string, limit int) ([]*UserBusinessAnalysisAll, int64) {
  167. statictisSess := xStatistic.NewSession()
  168. defer statictisSess.Close()
  169. userBusinessAnalysisAllList := make([]*UserBusinessAnalysisAll, 0)
  170. if err := statictisSess.Table(tableName).OrderBy(key+" desc,id desc").Limit(limit, 0).
  171. Find(&userBusinessAnalysisAllList); err != nil {
  172. return nil, 0
  173. }
  174. return userBusinessAnalysisAllList, int64(len(userBusinessAnalysisAllList))
  175. }
  176. func QueryUserStaticDataByTableName(start int, pageSize int, tableName string, queryObj interface{}, userName string) ([]*UserBusinessAnalysisAll, int64) {
  177. statictisSess := xStatistic.NewSession()
  178. defer statictisSess.Close()
  179. var cond = builder.NewCond()
  180. if len(userName) > 0 {
  181. cond = cond.And(
  182. builder.Like{"name", userName},
  183. )
  184. }
  185. allCount, err := statictisSess.Where(cond).Count(queryObj)
  186. if err != nil {
  187. log.Info("query error." + err.Error())
  188. return nil, 0
  189. }
  190. log.Info("query return total:" + fmt.Sprint(allCount))
  191. userBusinessAnalysisAllList := make([]*UserBusinessAnalysisAll, 0)
  192. if err := statictisSess.Table(tableName).Where(cond).OrderBy("user_index desc,id desc").Limit(pageSize, start).
  193. Find(&userBusinessAnalysisAllList); err != nil {
  194. return nil, 0
  195. }
  196. return userBusinessAnalysisAllList, allCount
  197. }
  198. func QueryUserStaticDataAll(opts *UserBusinessAnalysisQueryOptions) ([]*UserBusinessAnalysisAll, int64) {
  199. log.Info("query startTime =" + fmt.Sprint(opts.StartTime) + " endTime=" + fmt.Sprint(opts.EndTime) + " isAll=" + fmt.Sprint(opts.IsAll))
  200. statictisSess := xStatistic.NewSession()
  201. defer statictisSess.Close()
  202. allCount, err := statictisSess.Count(new(UserBusinessAnalysisAll))
  203. if err != nil {
  204. log.Info("query error." + err.Error())
  205. return nil, 0
  206. }
  207. log.Info("query return total:" + fmt.Sprint(allCount))
  208. pageSize := PAGE_SIZE
  209. totalPage := int(allCount) / pageSize
  210. userBusinessAnalysisReturnList := make([]*UserBusinessAnalysisAll, 0)
  211. for i := 0; i <= int(totalPage); i++ {
  212. userBusinessAnalysisAllList := make([]*UserBusinessAnalysisAll, 0)
  213. if err := statictisSess.Table("user_business_analysis_all").OrderBy("id desc").Limit(pageSize, i*pageSize).
  214. Find(&userBusinessAnalysisAllList); err != nil {
  215. return nil, 0
  216. }
  217. log.Info("query " + fmt.Sprint(i+1) + " result size=" + fmt.Sprint(len(userBusinessAnalysisAllList)))
  218. for _, userRecord := range userBusinessAnalysisAllList {
  219. userBusinessAnalysisReturnList = append(userBusinessAnalysisReturnList, userRecord)
  220. }
  221. }
  222. log.Info("return size=" + fmt.Sprint(len(userBusinessAnalysisReturnList)))
  223. return userBusinessAnalysisReturnList, allCount
  224. }
  225. func QueryUserStaticDataPage(opts *UserBusinessAnalysisQueryOptions) ([]*UserBusinessAnalysis, int64) {
  226. log.Info("query startTime =" + fmt.Sprint(opts.StartTime) + " endTime=" + fmt.Sprint(opts.EndTime) + " isAll=" + fmt.Sprint(opts.IsAll))
  227. statictisSess := xStatistic.NewSession()
  228. defer statictisSess.Close()
  229. currentTimeNow := time.Now()
  230. pageStartTime := getLastCountDate()
  231. pageEndTime := time.Date(currentTimeNow.Year(), currentTimeNow.Month(), currentTimeNow.Day(), 23, 59, 59, 0, currentTimeNow.Location()).Unix()
  232. var cond = builder.NewCond()
  233. if len(opts.UserName) > 0 {
  234. cond = cond.And(
  235. builder.Like{"name", opts.UserName},
  236. )
  237. }
  238. cond = cond.And(
  239. builder.Gte{"count_date": pageStartTime},
  240. )
  241. cond = cond.And(
  242. builder.Lte{"count_date": pageEndTime},
  243. )
  244. count, err := statictisSess.Where(cond).Count(new(UserBusinessAnalysis))
  245. if err != nil {
  246. log.Info("query error." + err.Error())
  247. return nil, 0
  248. }
  249. if opts.Page >= 0 && opts.PageSize > 0 {
  250. var start int
  251. if opts.Page == 0 {
  252. start = 0
  253. } else {
  254. start = (opts.Page - 1) * opts.PageSize
  255. }
  256. statictisSess.Limit(opts.PageSize, start)
  257. }
  258. userBusinessAnalysisList := make([]*UserBusinessAnalysis, 0)
  259. if err := statictisSess.Table("user_business_analysis").Where(cond).OrderBy("id desc").
  260. Find(&userBusinessAnalysisList); err != nil {
  261. return nil, 0
  262. }
  263. resultMap := make(map[int64]*UserBusinessAnalysis)
  264. if len(userBusinessAnalysisList) > 0 {
  265. var newAndCond = builder.NewCond()
  266. var newOrCond = builder.NewCond()
  267. for _, userRecord := range userBusinessAnalysisList {
  268. newOrCond = newOrCond.Or(
  269. builder.Eq{"id": userRecord.ID},
  270. )
  271. }
  272. newAndCond = newAndCond.And(
  273. newOrCond,
  274. )
  275. if !opts.IsAll {
  276. newAndCond = newAndCond.And(
  277. builder.Gte{"count_date": opts.StartTime},
  278. )
  279. newAndCond = newAndCond.And(
  280. builder.Lte{"count_date": opts.EndTime},
  281. )
  282. }
  283. allCount, err := statictisSess.Where(newAndCond).Count(new(UserBusinessAnalysis))
  284. if err != nil {
  285. log.Info("query error." + err.Error())
  286. return nil, 0
  287. }
  288. pageSize := 1000
  289. totalPage := int(allCount) / pageSize
  290. for i := 0; i <= int(totalPage); i++ {
  291. userBusinessAnalysisList = make([]*UserBusinessAnalysis, 0)
  292. if err := statictisSess.Table("user_business_analysis").Where(newAndCond).OrderBy("count_date desc").Limit(pageSize, i*pageSize).
  293. Find(&userBusinessAnalysisList); err != nil {
  294. return nil, 0
  295. }
  296. log.Info("query result size=" + fmt.Sprint(len(userBusinessAnalysisList)))
  297. for _, userRecord := range userBusinessAnalysisList {
  298. if _, ok := resultMap[userRecord.ID]; !ok {
  299. resultMap[userRecord.ID] = userRecord
  300. } else {
  301. resultMap[userRecord.ID].CodeMergeCount += userRecord.CodeMergeCount
  302. resultMap[userRecord.ID].CommitCount += userRecord.CommitCount
  303. resultMap[userRecord.ID].IssueCount += userRecord.IssueCount
  304. resultMap[userRecord.ID].CommentCount += userRecord.CommentCount
  305. resultMap[userRecord.ID].FocusRepoCount += userRecord.FocusRepoCount
  306. resultMap[userRecord.ID].StarRepoCount += userRecord.StarRepoCount
  307. resultMap[userRecord.ID].WatchedCount += userRecord.WatchedCount
  308. resultMap[userRecord.ID].CommitCodeSize += userRecord.CommitCodeSize
  309. resultMap[userRecord.ID].CommitDatasetSize += userRecord.CommitDatasetSize
  310. resultMap[userRecord.ID].CommitDatasetNum += userRecord.CommitDatasetNum
  311. resultMap[userRecord.ID].CommitModelCount += userRecord.CommitModelCount
  312. resultMap[userRecord.ID].SolveIssueCount += userRecord.SolveIssueCount
  313. resultMap[userRecord.ID].EncyclopediasCount += userRecord.EncyclopediasCount
  314. resultMap[userRecord.ID].CreateRepoCount += userRecord.CreateRepoCount
  315. resultMap[userRecord.ID].LoginCount += userRecord.LoginCount
  316. }
  317. }
  318. }
  319. }
  320. userBusinessAnalysisReturnList := UserBusinessAnalysisList{}
  321. for _, v := range resultMap {
  322. userBusinessAnalysisReturnList = append(userBusinessAnalysisReturnList, v)
  323. }
  324. sort.Sort(userBusinessAnalysisReturnList)
  325. log.Info("return size=" + fmt.Sprint(len(userBusinessAnalysisReturnList)))
  326. return userBusinessAnalysisReturnList, count
  327. }
  328. func refreshUserStaticTable(wikiCountMap map[string]int, tableName string, pageStartTime time.Time, pageEndTime time.Time, userMetrics map[string]int) {
  329. sess := x.NewSession()
  330. defer sess.Close()
  331. statictisSess := xStatistic.NewSession()
  332. defer statictisSess.Close()
  333. log.Info("truncate all data from table: " + tableName)
  334. statictisSess.Exec("TRUNCATE TABLE " + tableName)
  335. log.Info("pageStartTime:" + pageStartTime.Format("2006-01-02 15:04:05"))
  336. log.Info("pageEndTime time:" + pageEndTime.Format("2006-01-02 15:04:05"))
  337. start_unix := pageStartTime.Unix()
  338. end_unix := pageEndTime.Unix()
  339. currentTimeNow := time.Now()
  340. startTime := currentTimeNow.AddDate(0, 0, -1)
  341. CodeMergeCountMap := queryPullRequest(start_unix, end_unix)
  342. CommitCountMap := queryCommitAction(start_unix, end_unix, 5)
  343. IssueCountMap := queryCreateIssue(start_unix, end_unix)
  344. CommentCountMap := queryComment(start_unix, end_unix)
  345. FocusRepoCountMap := queryWatch(start_unix, end_unix)
  346. StarRepoCountMap := queryStar(start_unix, end_unix)
  347. WatchedCountMap := queryFollow(start_unix, end_unix)
  348. CommitCodeSizeMap := queryCommitCodeSize(start_unix, end_unix)
  349. CommitDatasetSizeMap, CommitDatasetNumMap := queryDatasetSize(start_unix, end_unix)
  350. SolveIssueCountMap := querySolveIssue(start_unix, end_unix)
  351. CreateRepoCountMap := queryUserCreateRepo(start_unix, end_unix)
  352. LoginCountMap := queryLoginCount(start_unix, end_unix)
  353. OpenIIndexMap := queryUserRepoOpenIIndex(startTime.Unix(), end_unix)
  354. CloudBrainTaskMap, CloudBrainTaskItemMap := queryCloudBrainTask(start_unix, end_unix)
  355. AiModelManageMap := queryUserModel(start_unix, end_unix)
  356. DataDate := currentTimeNow.Format("2006-01-02") + " 00:01"
  357. cond := "type != 1 and is_active=true"
  358. count, err := sess.Where(cond).Count(new(User))
  359. if err != nil {
  360. log.Info("query user error. return.")
  361. return
  362. }
  363. ParaWeight := getParaWeight()
  364. var indexTotal int64
  365. indexTotal = 0
  366. insertCount := 0
  367. userIndexMap := make(map[int64]float64, 0)
  368. maxUserIndex := 0.0
  369. minUserIndex := 100000000.0
  370. dateRecordBatch := make([]UserBusinessAnalysisAll, 0)
  371. for {
  372. sess.Select("`user`.*").Table("user").Where(cond).OrderBy("id asc").Limit(PAGE_SIZE, int(indexTotal))
  373. userList := make([]*User, 0)
  374. sess.Find(&userList)
  375. for _, userRecord := range userList {
  376. var dateRecordAll UserBusinessAnalysisAll
  377. dateRecordAll.ID = userRecord.ID
  378. dateRecordAll.Email = userRecord.Email
  379. dateRecordAll.RegistDate = userRecord.CreatedUnix
  380. dateRecordAll.Name = userRecord.Name
  381. dateRecordAll.GiteaAgeMonth = subMonth(currentTimeNow, userRecord.CreatedUnix.AsTime())
  382. dateRecordAll.DataDate = DataDate
  383. dateRecordAll.UserLocation = userRecord.Location
  384. dateRecordAll.CodeMergeCount = getMapValue(dateRecordAll.ID, CodeMergeCountMap)
  385. dateRecordAll.CommitCount = getMapValue(dateRecordAll.ID, CommitCountMap)
  386. dateRecordAll.IssueCount = getMapValue(dateRecordAll.ID, IssueCountMap)
  387. dateRecordAll.CommentCount = getMapValue(dateRecordAll.ID, CommentCountMap)
  388. dateRecordAll.FocusRepoCount = getMapValue(dateRecordAll.ID, FocusRepoCountMap)
  389. dateRecordAll.StarRepoCount = getMapValue(dateRecordAll.ID, StarRepoCountMap)
  390. dateRecordAll.WatchedCount = getMapValue(dateRecordAll.ID, WatchedCountMap)
  391. dateRecordAll.CommitCodeSize = getMapValue(dateRecordAll.ID, CommitCodeSizeMap)
  392. dateRecordAll.CommitDatasetSize = getMapValue(dateRecordAll.ID, CommitDatasetSizeMap)
  393. dateRecordAll.CommitDatasetNum = getMapValue(dateRecordAll.ID, CommitDatasetNumMap)
  394. dateRecordAll.SolveIssueCount = getMapValue(dateRecordAll.ID, SolveIssueCountMap)
  395. dateRecordAll.EncyclopediasCount = getMapKeyStringValue(dateRecordAll.Name, wikiCountMap)
  396. dateRecordAll.CreateRepoCount = getMapValue(dateRecordAll.ID, CreateRepoCountMap)
  397. dateRecordAll.LoginCount = getMapValue(dateRecordAll.ID, LoginCountMap)
  398. if _, ok := OpenIIndexMap[dateRecordAll.ID]; !ok {
  399. dateRecordAll.OpenIIndex = 0
  400. } else {
  401. dateRecordAll.OpenIIndex = OpenIIndexMap[dateRecordAll.ID]
  402. }
  403. dateRecordAll.CloudBrainTaskNum = getMapValue(dateRecordAll.ID, CloudBrainTaskMap)
  404. dateRecordAll.GpuDebugJob = getMapKeyStringValue(fmt.Sprint(dateRecordAll.ID)+"_GpuDebugJob", CloudBrainTaskItemMap)
  405. dateRecordAll.NpuDebugJob = getMapKeyStringValue(fmt.Sprint(dateRecordAll.ID)+"_NpuDebugJob", CloudBrainTaskItemMap)
  406. dateRecordAll.GpuTrainJob = getMapKeyStringValue(fmt.Sprint(dateRecordAll.ID)+"_GpuTrainJob", CloudBrainTaskItemMap)
  407. dateRecordAll.NpuTrainJob = getMapKeyStringValue(fmt.Sprint(dateRecordAll.ID)+"_NpuTrainJob", CloudBrainTaskItemMap)
  408. dateRecordAll.NpuInferenceJob = getMapKeyStringValue(fmt.Sprint(dateRecordAll.ID)+"_NpuInferenceJob", CloudBrainTaskItemMap)
  409. dateRecordAll.GpuBenchMarkJob = getMapKeyStringValue(fmt.Sprint(dateRecordAll.ID)+"_GpuBenchMarkJob", CloudBrainTaskItemMap)
  410. dateRecordAll.CommitModelCount = getMapValue(dateRecordAll.ID, AiModelManageMap)
  411. dateRecordAll.UserIndex = getUserIndexFromAnalysisAll(dateRecordAll, ParaWeight)
  412. userIndexMap[dateRecordAll.ID] = dateRecordAll.UserIndex
  413. if maxUserIndex < dateRecordAll.UserIndex {
  414. maxUserIndex = dateRecordAll.UserIndex
  415. }
  416. if minUserIndex > dateRecordAll.UserIndex {
  417. minUserIndex = dateRecordAll.UserIndex
  418. }
  419. dateRecordBatch = append(dateRecordBatch, dateRecordAll)
  420. if len(dateRecordBatch) >= BATCH_INSERT_SIZE {
  421. insertTable(dateRecordBatch, tableName, statictisSess)
  422. insertCount += BATCH_INSERT_SIZE
  423. if err != nil {
  424. log.Info("insert all data failed." + err.Error())
  425. }
  426. dateRecordBatch = make([]UserBusinessAnalysisAll, 0)
  427. }
  428. if tableName == "user_business_analysis_all" {
  429. if dateRecordAll.UserIndex > 0 || dateRecordAll.LoginCount > 0 {
  430. userMetrics["TotalHasActivityUser"] = getMapKeyStringValue("TotalHasActivityUser", userMetrics) + 1
  431. }
  432. }
  433. }
  434. indexTotal += PAGE_SIZE
  435. if indexTotal >= count {
  436. break
  437. }
  438. }
  439. if len(dateRecordBatch) > 0 {
  440. insertTable(dateRecordBatch, tableName, statictisSess)
  441. insertCount += len(dateRecordBatch)
  442. if err != nil {
  443. log.Info("insert all data failed." + err.Error())
  444. }
  445. }
  446. //normalization
  447. for k, v := range userIndexMap {
  448. tmpResult := (v - minUserIndex) / (maxUserIndex - minUserIndex)
  449. updateUserIndex(tableName, statictisSess, k, tmpResult)
  450. }
  451. log.Info("refresh data finished.tableName=" + tableName + " total record:" + fmt.Sprint(insertCount))
  452. }
  453. func updateUserIndex(tableName string, statictisSess *xorm.Session, userId int64, userIndex float64) {
  454. updateSql := "UPDATE public." + tableName + " set user_index=" + fmt.Sprint(userIndex) + " where id=" + fmt.Sprint(userId)
  455. statictisSess.Exec(updateSql)
  456. }
  457. func insertTable(dateRecords []UserBusinessAnalysisAll, tableName string, statictisSess *xorm.Session) {
  458. insertBatchSql := "INSERT INTO public." + tableName +
  459. "(id, count_date, code_merge_count, commit_count, issue_count, comment_count, focus_repo_count, star_repo_count, watched_count, gitea_age_month, commit_code_size, commit_dataset_size, " +
  460. "commit_model_count, solve_issue_count, encyclopedias_count, regist_date, create_repo_count, login_count, open_i_index, email, name, data_date,cloud_brain_task_num,gpu_debug_job,npu_debug_job,gpu_train_job,npu_train_job,npu_inference_job,gpu_bench_mark_job,cloud_brain_run_time,commit_dataset_num,user_index,user_location) " +
  461. "VALUES"
  462. for i, record := range dateRecords {
  463. insertBatchSql += "(" + fmt.Sprint(record.ID) + ", " + fmt.Sprint(record.CountDate) + ", " + fmt.Sprint(record.CodeMergeCount) + ", " + fmt.Sprint(record.CommitCount) +
  464. ", " + fmt.Sprint(record.IssueCount) + ", " + fmt.Sprint(record.CommentCount) + ", " + fmt.Sprint(record.FocusRepoCount) + ", " + fmt.Sprint(record.StarRepoCount) +
  465. ", " + fmt.Sprint(record.WatchedCount) + ", " + fmt.Sprint(record.GiteaAgeMonth) + ", " + fmt.Sprint(record.CommitCodeSize) + ", " + fmt.Sprint(record.CommitDatasetSize) +
  466. ", " + fmt.Sprint(record.CommitModelCount) + ", " + fmt.Sprint(record.SolveIssueCount) + ", " + fmt.Sprint(record.EncyclopediasCount) + ", " + fmt.Sprint(record.RegistDate) +
  467. ", " + fmt.Sprint(record.CreateRepoCount) + ", " + fmt.Sprint(record.LoginCount) + ", " + fmt.Sprint(record.OpenIIndex) + ", '" + record.Email + "', '" + record.Name + "', '" + record.DataDate + "'," + fmt.Sprint(record.CloudBrainTaskNum) + "," + fmt.Sprint(record.GpuDebugJob) + "," + fmt.Sprint(record.NpuDebugJob) + "," + fmt.Sprint(record.GpuTrainJob) + "," + fmt.Sprint(record.NpuTrainJob) + "," + fmt.Sprint(record.NpuInferenceJob) + "," + fmt.Sprint(record.GpuBenchMarkJob) + "," + fmt.Sprint(record.CloudBrainRunTime) + "," + fmt.Sprint(record.CommitDatasetNum) + "," + fmt.Sprint(record.UserIndex) + ",'" + record.UserLocation + "')"
  468. if i < (len(dateRecords) - 1) {
  469. insertBatchSql += ","
  470. }
  471. }
  472. statictisSess.Exec(insertBatchSql)
  473. }
  474. func RefreshUserStaticAllTabel(wikiCountMap map[string]int, userMetrics map[string]int) {
  475. currentTimeNow := time.Now()
  476. pageStartTime := time.Date(2021, 11, 5, 0, 0, 0, 0, currentTimeNow.Location())
  477. pageEndTime := time.Date(currentTimeNow.Year(), currentTimeNow.Month(), currentTimeNow.Day(), 23, 59, 59, 0, currentTimeNow.Location())
  478. refreshUserStaticTable(wikiCountMap, "user_business_analysis_all", pageStartTime, pageEndTime, userMetrics)
  479. log.Info("refresh all data finished.")
  480. pageStartTime = time.Date(currentTimeNow.Year(), 1, 1, 0, 0, 0, 0, currentTimeNow.Location())
  481. refreshUserStaticTable(wikiCountMap, "user_business_analysis_current_year", pageStartTime, pageEndTime, userMetrics)
  482. thisMonth := time.Date(currentTimeNow.Year(), currentTimeNow.Month(), 1, 0, 0, 0, 0, currentTimeNow.Location())
  483. refreshUserStaticTable(wikiCountMap, "user_business_analysis_current_month", thisMonth, pageEndTime, userMetrics)
  484. offset := int(time.Monday - currentTimeNow.Weekday())
  485. if offset > 0 {
  486. offset = -6
  487. }
  488. pageStartTime = time.Date(currentTimeNow.Year(), currentTimeNow.Month(), currentTimeNow.Day(), 0, 0, 0, 0, time.Local).AddDate(0, 0, offset)
  489. refreshUserStaticTable(wikiCountMap, "user_business_analysis_current_week", pageStartTime, pageEndTime, userMetrics)
  490. pageStartTime = time.Date(currentTimeNow.Year(), currentTimeNow.Month(), currentTimeNow.Day(), 0, 0, 0, 0, time.Local).AddDate(0, 0, -30)
  491. refreshUserStaticTable(wikiCountMap, "user_business_analysis_last30_day", pageStartTime, pageEndTime, userMetrics)
  492. pageStartTime = time.Date(currentTimeNow.Year(), currentTimeNow.Month(), currentTimeNow.Day(), 0, 0, 0, 0, time.Local).AddDate(0, 0, -1)
  493. pageEndTime = time.Date(currentTimeNow.Year(), currentTimeNow.Month(), currentTimeNow.Day(), 23, 59, 59, 0, currentTimeNow.Location()).AddDate(0, 0, -1)
  494. refreshUserStaticTable(wikiCountMap, "user_business_analysis_yesterday", pageStartTime, pageEndTime, userMetrics)
  495. pageStartTime = thisMonth.AddDate(0, -1, 0)
  496. pageEndTime = time.Date(currentTimeNow.Year(), currentTimeNow.Month(), 1, 23, 59, 59, 0, currentTimeNow.Location()).AddDate(0, 0, -1)
  497. refreshUserStaticTable(wikiCountMap, "user_business_analysis_last_month", pageStartTime, pageEndTime, userMetrics)
  498. }
  499. func CounDataByDateAndReCount(wikiCountMap map[string]int, startTime time.Time, endTime time.Time, isReCount bool) error {
  500. log.Info("start to count other user info data")
  501. sess := x.NewSession()
  502. defer sess.Close()
  503. currentTimeNow := time.Now()
  504. log.Info("current time:" + currentTimeNow.Format("2006-01-02 15:04:05"))
  505. start_unix := startTime.Unix()
  506. log.Info("DB query time:" + startTime.Format("2006-01-02 15:04:05"))
  507. end_unix := endTime.Unix()
  508. CountDate := time.Date(currentTimeNow.Year(), currentTimeNow.Month(), currentTimeNow.Day(), 0, 1, 0, 0, currentTimeNow.Location())
  509. if isReCount {
  510. CountDate = time.Date(startTime.Year(), startTime.Month(), startTime.Day(), 0, 1, 0, 0, currentTimeNow.Location())
  511. }
  512. DataDate := startTime.Format("2006-01-02")
  513. CodeMergeCountMap := queryPullRequest(start_unix, end_unix)
  514. CommitCountMap := queryCommitAction(start_unix, end_unix, 5)
  515. IssueCountMap := queryCreateIssue(start_unix, end_unix)
  516. CommentCountMap := queryComment(start_unix, end_unix)
  517. FocusRepoCountMap := queryWatch(start_unix, end_unix)
  518. StarRepoCountMap := queryStar(start_unix, end_unix)
  519. WatchedCountMap := queryFollow(start_unix, end_unix)
  520. CommitCodeSizeMap, err := GetAllUserKPIStats()
  521. if err != nil {
  522. log.Info("query commit code errr.")
  523. } else {
  524. log.Info("query commit code size, len=" + fmt.Sprint(len(CommitCodeSizeMap)))
  525. }
  526. CommitDatasetSizeMap, CommitDatasetNumMap := queryDatasetSize(start_unix, end_unix)
  527. SolveIssueCountMap := querySolveIssue(start_unix, end_unix)
  528. CreateRepoCountMap := queryUserCreateRepo(start_unix, end_unix)
  529. LoginCountMap := queryLoginCount(start_unix, end_unix)
  530. OpenIIndexMap := queryUserRepoOpenIIndex(start_unix, end_unix)
  531. CloudBrainTaskMap, CloudBrainTaskItemMap := queryCloudBrainTask(start_unix, end_unix)
  532. AiModelManageMap := queryUserModel(start_unix, end_unix)
  533. statictisSess := xStatistic.NewSession()
  534. defer statictisSess.Close()
  535. cond := "type != 1 and is_active=true"
  536. count, err := sess.Where(cond).Count(new(User))
  537. if err != nil {
  538. log.Info("query user error. return.")
  539. return err
  540. }
  541. ParaWeight := getParaWeight()
  542. userMetrics := make(map[string]int)
  543. var indexTotal int64
  544. indexTotal = 0
  545. for {
  546. sess.Select("`user`.*").Table("user").Where(cond).OrderBy("id asc").Limit(PAGE_SIZE, int(indexTotal))
  547. userList := make([]*User, 0)
  548. sess.Find(&userList)
  549. for i, userRecord := range userList {
  550. var dateRecord UserBusinessAnalysis
  551. dateRecord.ID = userRecord.ID
  552. log.Info("i=" + fmt.Sprint(i) + " userName=" + userRecord.Name)
  553. dateRecord.CountDate = CountDate.Unix()
  554. statictisSess.Delete(&dateRecord)
  555. dateRecord.Email = userRecord.Email
  556. dateRecord.RegistDate = userRecord.CreatedUnix
  557. dateRecord.Name = userRecord.Name
  558. dateRecord.GiteaAgeMonth = subMonth(currentTimeNow, userRecord.CreatedUnix.AsTime())
  559. dateRecord.DataDate = DataDate
  560. dateRecord.CodeMergeCount = getMapValue(dateRecord.ID, CodeMergeCountMap)
  561. dateRecord.CommitCount = getMapValue(dateRecord.ID, CommitCountMap)
  562. dateRecord.IssueCount = getMapValue(dateRecord.ID, IssueCountMap)
  563. dateRecord.CommentCount = getMapValue(dateRecord.ID, CommentCountMap)
  564. dateRecord.FocusRepoCount = getMapValue(dateRecord.ID, FocusRepoCountMap)
  565. dateRecord.StarRepoCount = getMapValue(dateRecord.ID, StarRepoCountMap)
  566. dateRecord.WatchedCount = getMapValue(dateRecord.ID, WatchedCountMap)
  567. if _, ok := CommitCodeSizeMap[dateRecord.Email]; !ok {
  568. dateRecord.CommitCodeSize = 0
  569. } else {
  570. dateRecord.CommitCodeSize = int(CommitCodeSizeMap[dateRecord.Email].CommitLines)
  571. }
  572. dateRecord.CommitDatasetSize = getMapValue(dateRecord.ID, CommitDatasetSizeMap)
  573. dateRecord.CommitDatasetNum = getMapValue(dateRecord.ID, CommitDatasetNumMap)
  574. dateRecord.SolveIssueCount = getMapValue(dateRecord.ID, SolveIssueCountMap)
  575. dateRecord.EncyclopediasCount = getMapKeyStringValue(dateRecord.Name, wikiCountMap)
  576. dateRecord.CreateRepoCount = getMapValue(dateRecord.ID, CreateRepoCountMap)
  577. dateRecord.LoginCount = getMapValue(dateRecord.ID, LoginCountMap)
  578. if _, ok := OpenIIndexMap[dateRecord.ID]; !ok {
  579. dateRecord.OpenIIndex = 0
  580. } else {
  581. dateRecord.OpenIIndex = OpenIIndexMap[dateRecord.ID]
  582. }
  583. dateRecord.CloudBrainTaskNum = getMapValue(dateRecord.ID, CloudBrainTaskMap)
  584. dateRecord.GpuDebugJob = getMapKeyStringValue(fmt.Sprint(dateRecord.ID)+"_GpuDebugJob", CloudBrainTaskItemMap)
  585. dateRecord.NpuDebugJob = getMapKeyStringValue(fmt.Sprint(dateRecord.ID)+"_NpuDebugJob", CloudBrainTaskItemMap)
  586. dateRecord.GpuTrainJob = getMapKeyStringValue(fmt.Sprint(dateRecord.ID)+"_GpuTrainJob", CloudBrainTaskItemMap)
  587. dateRecord.NpuTrainJob = getMapKeyStringValue(fmt.Sprint(dateRecord.ID)+"_NpuTrainJob", CloudBrainTaskItemMap)
  588. dateRecord.NpuInferenceJob = getMapKeyStringValue(fmt.Sprint(dateRecord.ID)+"_NpuInferenceJob", CloudBrainTaskItemMap)
  589. dateRecord.GpuBenchMarkJob = getMapKeyStringValue(fmt.Sprint(dateRecord.ID)+"_GpuBenchMarkJob", CloudBrainTaskItemMap)
  590. dateRecord.CloudBrainRunTime = getMapKeyStringValue(fmt.Sprint(dateRecord.ID)+"_CloudBrainRunTime", CloudBrainTaskItemMap)
  591. dateRecord.CommitModelCount = getMapValue(dateRecord.ID, AiModelManageMap)
  592. dateRecord.UserIndex = getUserIndex(dateRecord, ParaWeight)
  593. setUserMetrics(userMetrics, userRecord, start_unix, end_unix, dateRecord)
  594. _, err = statictisSess.Insert(&dateRecord)
  595. if err != nil {
  596. log.Info("insert daterecord failed." + err.Error())
  597. return err
  598. }
  599. }
  600. indexTotal += PAGE_SIZE
  601. if indexTotal >= count {
  602. break
  603. }
  604. }
  605. RefreshUserStaticAllTabel(wikiCountMap, userMetrics)
  606. //insert userMetrics table
  607. var useMetrics UserMetrics
  608. useMetrics.CountDate = CountDate.Unix()
  609. statictisSess.Delete(&useMetrics)
  610. useMetrics.ActivateRegistUser = getMapKeyStringValue("ActivateRegistUser", userMetrics)
  611. useMetrics.HasActivityUser = getMapKeyStringValue("HasActivityUser", userMetrics)
  612. useMetrics.NotActivateRegistUser = getMapKeyStringValue("NotActivateRegistUser", userMetrics)
  613. useMetrics.TotalActivateRegistUser = getMapKeyStringValue("TotalActivateRegistUser", userMetrics)
  614. useMetrics.TotalHasActivityUser = getMapKeyStringValue("TotalHasActivityUser", userMetrics)
  615. statictisSess.Insert(&useMetrics)
  616. return nil
  617. }
  618. func setUserMetrics(userMetrics map[string]int, user *User, start_time int64, end_time int64, dateRecord UserBusinessAnalysis) {
  619. //ActivateRegistUser int `xorm:"NOT NULL DEFAULT 0"`
  620. //NotActivateRegistUser int `xorm:"NOT NULL DEFAULT 0"`
  621. //HasActivityUser int `xorm:"NOT NULL DEFAULT 0"`
  622. //TotalActivateRegistUser int `xorm:"NOT NULL DEFAULT 0"`
  623. //TotalHasActivityUser
  624. regist_time := user.CreatedUnix.AsTime().Unix()
  625. if regist_time >= start_time && regist_time <= end_time {
  626. if user.IsActive {
  627. userMetrics["ActivateRegistUser"] = getMapKeyStringValue("ActivateRegistUser", userMetrics) + 1
  628. } else {
  629. userMetrics["NotActivateRegistUser"] = getMapKeyStringValue("NotActivateRegistUser", userMetrics) + 1
  630. }
  631. }
  632. if user.IsActive {
  633. userMetrics["TotalActivateRegistUser"] = getMapKeyStringValue("TotalActivateRegistUser", userMetrics) + 1
  634. }
  635. if dateRecord.UserIndex > 0 || dateRecord.LoginCount > 0 {
  636. userMetrics["HasActivityUser"] = getMapKeyStringValue("HasActivityUser", userMetrics) + 1
  637. }
  638. }
  639. func getParaWeight() map[string]float64 {
  640. result := make(map[string]float64)
  641. statictisSess := xStatistic.NewSession()
  642. defer statictisSess.Close()
  643. statictisSess.Select("*").Table(new(UserAnalysisPara))
  644. paraList := make([]*UserAnalysisPara, 0)
  645. statictisSess.Find(&paraList)
  646. for _, paraRecord := range paraList {
  647. result[paraRecord.Key] = paraRecord.Value
  648. }
  649. return result
  650. }
  651. func getUserIndexFromAnalysisAll(dateRecord UserBusinessAnalysisAll, ParaWeight map[string]float64) float64 {
  652. var result float64
  653. // PR数 0.20
  654. // commit数 0.20
  655. // 提出任务数 0.20
  656. // 评论数 0.20
  657. // 关注项目数 0.10
  658. // 点赞项目数 0.10
  659. // 登录次数 0.10
  660. result = float64(dateRecord.CodeMergeCount) * getParaWeightValue("CodeMergeCount", ParaWeight, 0.2)
  661. result += float64(dateRecord.CommitCount) * getParaWeightValue("CommitCount", ParaWeight, 0.2)
  662. log.Info("1 result=" + fmt.Sprint(result))
  663. result += float64(dateRecord.IssueCount) * getParaWeightValue("IssueCount", ParaWeight, 0.2)
  664. result += float64(dateRecord.CommentCount) * getParaWeightValue("CommentCount", ParaWeight, 0.2)
  665. result += float64(dateRecord.FocusRepoCount) * getParaWeightValue("FocusRepoCount", ParaWeight, 0.1)
  666. result += float64(dateRecord.StarRepoCount) * getParaWeightValue("StarRepoCount", ParaWeight, 0.1)
  667. result += float64(dateRecord.LoginCount) * getParaWeightValue("LoginCount", ParaWeight, 0.1)
  668. result += float64(dateRecord.WatchedCount) * getParaWeightValue("WatchedCount", ParaWeight, 0.3)
  669. result += float64(dateRecord.CommitCodeSize) * getParaWeightValue("CommitCodeSize", ParaWeight, 0.1)
  670. result += float64(dateRecord.SolveIssueCount) * getParaWeightValue("SolveIssueCount", ParaWeight, 0.2)
  671. result += float64(dateRecord.EncyclopediasCount) * getParaWeightValue("EncyclopediasCount", ParaWeight, 0.1)
  672. result += float64(dateRecord.CreateRepoCount) * getParaWeightValue("CreateRepoCount", ParaWeight, 0.05)
  673. result += float64(dateRecord.CloudBrainTaskNum) * getParaWeightValue("CloudBrainTaskNum", ParaWeight, 0.3)
  674. result += float64(dateRecord.CommitModelCount) * getParaWeightValue("CommitModelCount", ParaWeight, 0.2)
  675. result += dateRecord.OpenIIndex * getParaWeightValue("OpenIIndex", ParaWeight, 0.1)
  676. return result
  677. }
  678. func getUserIndex(dateRecord UserBusinessAnalysis, ParaWeight map[string]float64) float64 {
  679. var result float64
  680. // PR数 0.20
  681. // commit数 0.20
  682. // 提出任务数 0.20
  683. // 评论数 0.20
  684. // 关注项目数 0.10
  685. // 点赞项目数 0.10
  686. // 登录次数 0.10
  687. result = float64(dateRecord.CodeMergeCount) * getParaWeightValue("CodeMergeCount", ParaWeight, 0.2)
  688. result += float64(dateRecord.CommitCount) * getParaWeightValue("CommitCount", ParaWeight, 0.2)
  689. log.Info("2 result=" + fmt.Sprint(result))
  690. result += float64(dateRecord.IssueCount) * getParaWeightValue("IssueCount", ParaWeight, 0.2)
  691. result += float64(dateRecord.CommentCount) * getParaWeightValue("CommentCount", ParaWeight, 0.2)
  692. result += float64(dateRecord.FocusRepoCount) * getParaWeightValue("FocusRepoCount", ParaWeight, 0.1)
  693. result += float64(dateRecord.StarRepoCount) * getParaWeightValue("StarRepoCount", ParaWeight, 0.1)
  694. result += float64(dateRecord.LoginCount) * getParaWeightValue("LoginCount", ParaWeight, 0.1)
  695. result += float64(dateRecord.WatchedCount) * getParaWeightValue("WatchedCount", ParaWeight, 0.3)
  696. result += float64(dateRecord.CommitCodeSize) * getParaWeightValue("CommitCodeSize", ParaWeight, 0.1)
  697. result += float64(dateRecord.SolveIssueCount) * getParaWeightValue("SolveIssueCount", ParaWeight, 0.2)
  698. result += float64(dateRecord.EncyclopediasCount) * getParaWeightValue("EncyclopediasCount", ParaWeight, 0.1)
  699. result += float64(dateRecord.CreateRepoCount) * getParaWeightValue("CreateRepoCount", ParaWeight, 0.05)
  700. result += float64(dateRecord.CloudBrainTaskNum) * getParaWeightValue("CloudBrainTaskNum", ParaWeight, 0.3)
  701. result += float64(dateRecord.CommitModelCount) * getParaWeightValue("CommitModelCount", ParaWeight, 0.2)
  702. result += dateRecord.OpenIIndex * getParaWeightValue("OpenIIndex", ParaWeight, 0.1)
  703. return result
  704. }
  705. func getParaWeightValue(key string, valueMap map[string]float64, defaultValue float64) float64 {
  706. if _, ok := valueMap[key]; !ok {
  707. return defaultValue
  708. } else {
  709. return valueMap[key]
  710. }
  711. }
  712. func getMapKeyStringValue(key string, valueMap map[string]int) int {
  713. if _, ok := valueMap[key]; !ok {
  714. return 0
  715. } else {
  716. return valueMap[key]
  717. }
  718. }
  719. func getMapValue(userId int64, valueMap map[int64]int) int {
  720. if _, ok := valueMap[userId]; !ok {
  721. return 0
  722. } else {
  723. return valueMap[userId]
  724. }
  725. }
  726. func getInt(str string) int {
  727. re, err := strconv.ParseInt(str, 10, 32)
  728. if err != nil {
  729. return 0
  730. }
  731. return int(re)
  732. }
  733. func CounDataByDate(wikiCountMap map[string]int, startTime time.Time, endTime time.Time) {
  734. CounDataByDateAndReCount(wikiCountMap, startTime, endTime, false)
  735. }
  736. func querySolveIssue(start_unix int64, end_unix int64) map[int64]int {
  737. sess := x.NewSession()
  738. defer sess.Close()
  739. resultMap := make(map[int64]int)
  740. cond := "issue.is_closed=true and issue.closed_unix>=" + fmt.Sprint(start_unix) + " and issue.closed_unix<=" + fmt.Sprint(end_unix)
  741. count, err := sess.Table("issue_assignees").Join("inner", "issue", "issue.id=issue_assignees.issue_id").Where(cond).Count(new(IssueAssignees))
  742. if err != nil {
  743. log.Info("query issue error. return.")
  744. return resultMap
  745. }
  746. var indexTotal int64
  747. indexTotal = 0
  748. for {
  749. issueAssigneesList := make([]*IssueAssignees, 0)
  750. sess.Select("issue_assignees.*").Table("issue_assignees").
  751. Join("inner", "issue", "issue.id=issue_assignees.issue_id").
  752. Where(cond).OrderBy("issue_assignees.id asc").Limit(PAGE_SIZE, int(indexTotal))
  753. sess.Find(&issueAssigneesList)
  754. log.Info("query IssueAssignees size=" + fmt.Sprint(len(issueAssigneesList)))
  755. for _, issueAssigneesRecord := range issueAssigneesList {
  756. if _, ok := resultMap[issueAssigneesRecord.AssigneeID]; !ok {
  757. resultMap[issueAssigneesRecord.AssigneeID] = 1
  758. } else {
  759. resultMap[issueAssigneesRecord.AssigneeID] += 1
  760. }
  761. }
  762. indexTotal += PAGE_SIZE
  763. if indexTotal >= count {
  764. break
  765. }
  766. }
  767. return resultMap
  768. }
  769. func queryPullRequest(start_unix int64, end_unix int64) map[int64]int {
  770. sess := x.NewSession()
  771. defer sess.Close()
  772. resultMap := make(map[int64]int)
  773. cond := "pull_request.merged_unix>=" + fmt.Sprint(start_unix) + " and pull_request.merged_unix<=" + fmt.Sprint(end_unix)
  774. count, err := sess.Table("issue").Join("inner", "pull_request", "issue.id=pull_request.issue_id").Where(cond).Count(new(Issue))
  775. if err != nil {
  776. log.Info("query issue error. return.")
  777. return resultMap
  778. }
  779. var indexTotal int64
  780. indexTotal = 0
  781. for {
  782. issueList := make([]*Issue, 0)
  783. sess.Select("issue.*").Table("issue").Join("inner", "pull_request", "issue.id=pull_request.issue_id").Where(cond).OrderBy("issue.id asc").Limit(PAGE_SIZE, int(indexTotal))
  784. sess.Find(&issueList)
  785. log.Info("query issue(PR) size=" + fmt.Sprint(len(issueList)))
  786. for _, issueRecord := range issueList {
  787. if _, ok := resultMap[issueRecord.PosterID]; !ok {
  788. resultMap[issueRecord.PosterID] = 1
  789. } else {
  790. resultMap[issueRecord.PosterID] += 1
  791. }
  792. }
  793. indexTotal += PAGE_SIZE
  794. if indexTotal >= count {
  795. break
  796. }
  797. }
  798. return resultMap
  799. }
  800. func queryCommitAction(start_unix int64, end_unix int64, actionType int64) map[int64]int {
  801. sess := x.NewSession()
  802. defer sess.Close()
  803. resultMap := make(map[int64]int)
  804. cond := "user_id=act_user_id and op_type=" + fmt.Sprint(actionType) + " and created_unix>=" + fmt.Sprint(start_unix) + " and created_unix<=" + fmt.Sprint(end_unix)
  805. count, err := sess.Where(cond).Count(new(Action))
  806. if err != nil {
  807. log.Info("query action error. return.")
  808. return resultMap
  809. }
  810. var indexTotal int64
  811. indexTotal = 0
  812. for {
  813. sess.Select("id,user_id,op_type,act_user_id").Table("action").Where(cond).OrderBy("id asc").Limit(PAGE_SIZE, int(indexTotal))
  814. actionList := make([]*Action, 0)
  815. sess.Find(&actionList)
  816. log.Info("query action size=" + fmt.Sprint(len(actionList)))
  817. for _, actionRecord := range actionList {
  818. if _, ok := resultMap[actionRecord.UserID]; !ok {
  819. resultMap[actionRecord.UserID] = 1
  820. } else {
  821. resultMap[actionRecord.UserID] += 1
  822. }
  823. }
  824. indexTotal += PAGE_SIZE
  825. if indexTotal >= count {
  826. break
  827. }
  828. }
  829. return resultMap
  830. }
  831. func queryCreateIssue(start_unix int64, end_unix int64) map[int64]int {
  832. sess := x.NewSession()
  833. defer sess.Close()
  834. resultMap := make(map[int64]int)
  835. cond := "is_pull=false and created_unix>=" + fmt.Sprint(start_unix) + " and created_unix<=" + fmt.Sprint(end_unix)
  836. count, err := sess.Where(cond).Count(new(Issue))
  837. if err != nil {
  838. log.Info("query Issue error. return.")
  839. return resultMap
  840. }
  841. var indexTotal int64
  842. indexTotal = 0
  843. for {
  844. sess.Select("id,poster_id").Table("issue").Where(cond).OrderBy("id asc").Limit(PAGE_SIZE, int(indexTotal))
  845. issueList := make([]*Issue, 0)
  846. sess.Find(&issueList)
  847. log.Info("query issue size=" + fmt.Sprint(len(issueList)))
  848. for _, issueRecord := range issueList {
  849. if _, ok := resultMap[issueRecord.PosterID]; !ok {
  850. resultMap[issueRecord.PosterID] = 1
  851. } else {
  852. resultMap[issueRecord.PosterID] += 1
  853. }
  854. }
  855. indexTotal += PAGE_SIZE
  856. if indexTotal >= count {
  857. break
  858. }
  859. }
  860. return resultMap
  861. }
  862. func queryComment(start_unix int64, end_unix int64) map[int64]int {
  863. sess := x.NewSession()
  864. defer sess.Close()
  865. cond := "created_unix>=" + fmt.Sprint(start_unix) + " and created_unix<=" + fmt.Sprint(end_unix)
  866. resultMap := make(map[int64]int)
  867. count, err := sess.Where(cond).Count(new(Comment))
  868. if err != nil {
  869. log.Info("query Comment error. return.")
  870. return resultMap
  871. }
  872. var indexTotal int64
  873. indexTotal = 0
  874. for {
  875. sess.Select("id,type,poster_id").Table("comment").Where(cond).OrderBy("id asc").Limit(PAGE_SIZE, int(indexTotal))
  876. commentList := make([]*Comment, 0)
  877. sess.Find(&commentList)
  878. log.Info("query Comment size=" + fmt.Sprint(len(commentList)))
  879. for _, commentRecord := range commentList {
  880. if _, ok := resultMap[commentRecord.PosterID]; !ok {
  881. resultMap[commentRecord.PosterID] = 1
  882. } else {
  883. resultMap[commentRecord.PosterID] += 1
  884. }
  885. }
  886. indexTotal += PAGE_SIZE
  887. if indexTotal >= count {
  888. break
  889. }
  890. }
  891. return resultMap
  892. }
  893. func queryWatch(start_unix int64, end_unix int64) map[int64]int {
  894. sess := x.NewSession()
  895. defer sess.Close()
  896. cond := " created_unix>=" + fmt.Sprint(start_unix) + " and created_unix<=" + fmt.Sprint(end_unix)
  897. resultMap := make(map[int64]int)
  898. count, err := sess.Where(cond).Count(new(Watch))
  899. if err != nil {
  900. log.Info("query issue error. return.")
  901. return resultMap
  902. }
  903. var indexTotal int64
  904. indexTotal = 0
  905. for {
  906. watchList := make([]*Watch, 0)
  907. sess.Select("id,user_id,repo_id").Table("watch").Where(cond).OrderBy("id asc").Limit(PAGE_SIZE, int(indexTotal))
  908. sess.Find(&watchList)
  909. log.Info("query Watch size=" + fmt.Sprint(len(watchList)))
  910. for _, watchRecord := range watchList {
  911. if _, ok := resultMap[watchRecord.UserID]; !ok {
  912. resultMap[watchRecord.UserID] = 1
  913. } else {
  914. resultMap[watchRecord.UserID] += 1
  915. }
  916. }
  917. indexTotal += PAGE_SIZE
  918. if indexTotal >= count {
  919. break
  920. }
  921. }
  922. return resultMap
  923. }
  924. func queryStar(start_unix int64, end_unix int64) map[int64]int {
  925. sess := x.NewSession()
  926. defer sess.Close()
  927. cond := " created_unix>=" + fmt.Sprint(start_unix) + " and created_unix<=" + fmt.Sprint(end_unix)
  928. resultMap := make(map[int64]int)
  929. count, err := sess.Where(cond).Count(new(Star))
  930. if err != nil {
  931. log.Info("query star error. return.")
  932. return resultMap
  933. }
  934. var indexTotal int64
  935. indexTotal = 0
  936. for {
  937. sess.Select("id,uid,repo_id").Table("star").Where(cond).OrderBy("id asc").Limit(PAGE_SIZE, int(indexTotal))
  938. starList := make([]*Star, 0)
  939. sess.Find(&starList)
  940. log.Info("query Star size=" + fmt.Sprint(len(starList)))
  941. for _, starRecord := range starList {
  942. if _, ok := resultMap[starRecord.UID]; !ok {
  943. resultMap[starRecord.UID] = 1
  944. } else {
  945. resultMap[starRecord.UID] += 1
  946. }
  947. }
  948. indexTotal += PAGE_SIZE
  949. if indexTotal >= count {
  950. break
  951. }
  952. }
  953. return resultMap
  954. }
  955. func queryFollow(start_unix int64, end_unix int64) map[int64]int {
  956. sess := x.NewSession()
  957. defer sess.Close()
  958. resultMap := make(map[int64]int)
  959. cond := " created_unix>=" + fmt.Sprint(start_unix) + " and created_unix<=" + fmt.Sprint(end_unix)
  960. count, err := sess.Where(cond).Count(new(Follow))
  961. if err != nil {
  962. log.Info("query follow error. return.")
  963. return resultMap
  964. }
  965. var indexTotal int64
  966. indexTotal = 0
  967. for {
  968. sess.Select("id,user_id,follow_id").Table("follow").Where(cond).OrderBy("id asc").Limit(PAGE_SIZE, int(indexTotal))
  969. followList := make([]*Follow, 0)
  970. sess.Find(&followList)
  971. log.Info("query Follow size=" + fmt.Sprint(len(followList)))
  972. for _, followRecord := range followList {
  973. if _, ok := resultMap[followRecord.FollowID]; !ok {
  974. resultMap[followRecord.FollowID] = 1
  975. } else {
  976. resultMap[followRecord.FollowID] += 1
  977. }
  978. }
  979. indexTotal += PAGE_SIZE
  980. if indexTotal >= count {
  981. break
  982. }
  983. }
  984. return resultMap
  985. }
  986. func queryDatasetSize(start_unix int64, end_unix int64) (map[int64]int, map[int64]int) {
  987. sess := x.NewSession()
  988. defer sess.Close()
  989. resultSizeMap := make(map[int64]int)
  990. resultNumMap := make(map[int64]int)
  991. cond := " created_unix>=" + fmt.Sprint(start_unix) + " and created_unix<=" + fmt.Sprint(end_unix)
  992. count, err := sess.Where(cond).Count(new(Attachment))
  993. if err != nil {
  994. log.Info("query attachment error. return.")
  995. return resultSizeMap, resultNumMap
  996. }
  997. var indexTotal int64
  998. indexTotal = 0
  999. for {
  1000. sess.Select("id,uploader_id,size").Table("attachment").Where(cond).OrderBy("id asc").Limit(PAGE_SIZE, int(indexTotal))
  1001. attachmentList := make([]*Attachment, 0)
  1002. sess.Find(&attachmentList)
  1003. log.Info("query Attachment size=" + fmt.Sprint(len(attachmentList)))
  1004. for _, attachRecord := range attachmentList {
  1005. if _, ok := resultSizeMap[attachRecord.UploaderID]; !ok {
  1006. resultSizeMap[attachRecord.UploaderID] = int(attachRecord.Size / (1024 * 1024)) //MB
  1007. resultNumMap[attachRecord.UploaderID] = 1
  1008. } else {
  1009. resultSizeMap[attachRecord.UploaderID] += int(attachRecord.Size / (1024 * 1024)) //MB
  1010. resultNumMap[attachRecord.UploaderID] += 1
  1011. }
  1012. }
  1013. indexTotal += PAGE_SIZE
  1014. if indexTotal >= count {
  1015. break
  1016. }
  1017. }
  1018. return resultSizeMap, resultNumMap
  1019. }
  1020. func queryUserCreateRepo(start_unix int64, end_unix int64) map[int64]int {
  1021. sess := x.NewSession()
  1022. defer sess.Close()
  1023. resultMap := make(map[int64]int)
  1024. cond := "is_fork=false and created_unix>=" + fmt.Sprint(start_unix) + " and created_unix<=" + fmt.Sprint(end_unix)
  1025. count, err := sess.Where(cond).Count(new(Repository))
  1026. if err != nil {
  1027. log.Info("query Repository error. return.")
  1028. return resultMap
  1029. }
  1030. var indexTotal int64
  1031. indexTotal = 0
  1032. for {
  1033. sess.Select("id,owner_id,name").Table("repository").Where(cond).OrderBy("id asc").Limit(PAGE_SIZE, int(indexTotal))
  1034. repoList := make([]*Repository, 0)
  1035. sess.Find(&repoList)
  1036. log.Info("query Repository size=" + fmt.Sprint(len(repoList)))
  1037. for _, repoRecord := range repoList {
  1038. if _, ok := resultMap[repoRecord.OwnerID]; !ok {
  1039. resultMap[repoRecord.OwnerID] = 1
  1040. } else {
  1041. resultMap[repoRecord.OwnerID] += 1
  1042. }
  1043. }
  1044. indexTotal += PAGE_SIZE
  1045. if indexTotal >= count {
  1046. break
  1047. }
  1048. }
  1049. return resultMap
  1050. }
  1051. func queryUserRepoOpenIIndex(start_unix int64, end_unix int64) map[int64]float64 {
  1052. statictisSess := xStatistic.NewSession()
  1053. defer statictisSess.Close()
  1054. statictisSess.Select("id,repo_id,radar_total").Table("repo_statistic").Where("created_unix>=" + fmt.Sprint(start_unix) + " and created_unix<=" + fmt.Sprint(end_unix)).OrderBy("id desc")
  1055. repoStatisticList := make([]*RepoStatistic, 0)
  1056. statictisSess.Find(&repoStatisticList)
  1057. repoOpenIIndexMap := make(map[int64]float64)
  1058. log.Info("query repo_statistic size=" + fmt.Sprint(len(repoStatisticList)))
  1059. for _, repoRecord := range repoStatisticList {
  1060. if _, ok := repoOpenIIndexMap[repoRecord.RepoID]; !ok {
  1061. repoOpenIIndexMap[repoRecord.RepoID] = repoRecord.RadarTotal
  1062. }
  1063. }
  1064. sess := x.NewSession()
  1065. defer sess.Close()
  1066. sess.Select("id,owner_id,name").Table("repository").Where("is_fork=false")
  1067. repoList := make([]*Repository, 0)
  1068. sess.Find(&repoList)
  1069. userMap := make(map[int64]float64)
  1070. log.Info("query Repository size=" + fmt.Sprint(len(repoList)))
  1071. for _, repoRecord := range repoList {
  1072. if _, ok := userMap[repoRecord.OwnerID]; !ok {
  1073. if _, ok := repoOpenIIndexMap[repoRecord.ID]; ok {
  1074. userMap[repoRecord.OwnerID] = repoOpenIIndexMap[repoRecord.ID]
  1075. }
  1076. }
  1077. }
  1078. //query collaboration
  1079. sess.Select("repo_id,user_id,mode").Table("collaboration")
  1080. collaborationList := make([]*Collaboration, 0)
  1081. sess.Find(&collaborationList)
  1082. log.Info("query collaborationList size=" + fmt.Sprint(len(collaborationList)))
  1083. for _, collaborationRecord := range collaborationList {
  1084. if _, ok := userMap[collaborationRecord.UserID]; !ok {
  1085. if _, ok := repoOpenIIndexMap[collaborationRecord.RepoID]; ok {
  1086. userMap[collaborationRecord.UserID] = repoOpenIIndexMap[collaborationRecord.RepoID]
  1087. }
  1088. } else {
  1089. if _, ok := repoOpenIIndexMap[collaborationRecord.RepoID]; ok {
  1090. userMap[collaborationRecord.UserID] += repoOpenIIndexMap[collaborationRecord.RepoID]
  1091. }
  1092. }
  1093. }
  1094. log.Info("user openi index size=" + fmt.Sprint(len(userMap)))
  1095. return userMap
  1096. }
  1097. func queryLoginCount(start_unix int64, end_unix int64) map[int64]int {
  1098. statictisSess := xStatistic.NewSession()
  1099. defer statictisSess.Close()
  1100. resultMap := make(map[int64]int)
  1101. cond := "created_unix>=" + fmt.Sprint(start_unix) + " and created_unix<=" + fmt.Sprint(end_unix)
  1102. count, err := statictisSess.Where(cond).Count(new(UserLoginLog))
  1103. if err != nil {
  1104. log.Info("query UserLoginLog error. return.")
  1105. return resultMap
  1106. }
  1107. var indexTotal int64
  1108. indexTotal = 0
  1109. for {
  1110. statictisSess.Select("id,u_id").Table("user_login_log").Where(cond).OrderBy("id asc").Limit(PAGE_SIZE, int(indexTotal))
  1111. userLoginLogList := make([]*UserLoginLog, 0)
  1112. statictisSess.Find(&userLoginLogList)
  1113. log.Info("query user login size=" + fmt.Sprint(len(userLoginLogList)))
  1114. for _, loginRecord := range userLoginLogList {
  1115. if _, ok := resultMap[loginRecord.UId]; !ok {
  1116. resultMap[loginRecord.UId] = 1
  1117. } else {
  1118. resultMap[loginRecord.UId] += 1
  1119. }
  1120. }
  1121. indexTotal += PAGE_SIZE
  1122. if indexTotal >= count {
  1123. break
  1124. }
  1125. }
  1126. log.Info("user login size=" + fmt.Sprint(len(resultMap)))
  1127. return resultMap
  1128. }
  1129. func queryCommitCodeSize(start_unix int64, end_unix int64) map[int64]int {
  1130. statictisSess := xStatistic.NewSession()
  1131. defer statictisSess.Close()
  1132. resultMap := make(map[int64]int)
  1133. cond := "count_date>=" + fmt.Sprint(start_unix) + " and count_date<=" + fmt.Sprint(end_unix)
  1134. count, err := statictisSess.Where(cond).Count(new(UserBusinessAnalysis))
  1135. if err != nil {
  1136. log.Info("query commit code size error. return.")
  1137. return resultMap
  1138. }
  1139. var indexTotal int64
  1140. indexTotal = 0
  1141. for {
  1142. statictisSess.Select("id,commit_code_size").Table("user_business_analysis").Where(cond).OrderBy("id asc").Limit(PAGE_SIZE, int(indexTotal))
  1143. userBusinessAnalysisList := make([]*UserBusinessAnalysis, 0)
  1144. statictisSess.Find(&userBusinessAnalysisList)
  1145. log.Info("query user login size=" + fmt.Sprint(len(userBusinessAnalysisList)))
  1146. for _, analysisRecord := range userBusinessAnalysisList {
  1147. if _, ok := resultMap[analysisRecord.ID]; !ok {
  1148. resultMap[analysisRecord.ID] = analysisRecord.CommitCodeSize
  1149. } else {
  1150. resultMap[analysisRecord.ID] += analysisRecord.CommitCodeSize
  1151. }
  1152. }
  1153. indexTotal += PAGE_SIZE
  1154. if indexTotal >= count {
  1155. break
  1156. }
  1157. }
  1158. log.Info("user commit code size=" + fmt.Sprint(len(resultMap)))
  1159. return resultMap
  1160. }
  1161. func queryUserModel(start_unix int64, end_unix int64) map[int64]int {
  1162. sess := x.NewSession()
  1163. defer sess.Close()
  1164. resultMap := make(map[int64]int)
  1165. cond := " created_unix>=" + fmt.Sprint(start_unix) + " and created_unix<=" + fmt.Sprint(end_unix)
  1166. count, err := sess.Where(cond).Count(new(AiModelManage))
  1167. if err != nil {
  1168. log.Info("query AiModelManage error. return.")
  1169. return resultMap
  1170. }
  1171. var indexTotal int64
  1172. indexTotal = 0
  1173. for {
  1174. sess.Select("id,user_id").Table("ai_model_manage").Where(cond).OrderBy("id asc").Limit(PAGE_SIZE, int(indexTotal))
  1175. aiModelList := make([]*AiModelManage, 0)
  1176. sess.Find(&aiModelList)
  1177. log.Info("query AiModelManage size=" + fmt.Sprint(len(aiModelList)))
  1178. for _, aiModelRecord := range aiModelList {
  1179. if _, ok := resultMap[aiModelRecord.UserId]; !ok {
  1180. resultMap[aiModelRecord.UserId] = 1
  1181. } else {
  1182. resultMap[aiModelRecord.UserId] += 1
  1183. }
  1184. }
  1185. indexTotal += PAGE_SIZE
  1186. if indexTotal >= count {
  1187. break
  1188. }
  1189. }
  1190. return resultMap
  1191. }
  1192. func queryCloudBrainTask(start_unix int64, end_unix int64) (map[int64]int, map[string]int) {
  1193. sess := x.NewSession()
  1194. defer sess.Close()
  1195. resultMap := make(map[int64]int)
  1196. resultItemMap := make(map[string]int)
  1197. cond := " created_unix>=" + fmt.Sprint(start_unix) + " and created_unix<=" + fmt.Sprint(end_unix)
  1198. count, err := sess.Where(cond).Count(new(Cloudbrain))
  1199. if err != nil {
  1200. log.Info("query cloudbrain error. return.")
  1201. return resultMap, resultItemMap
  1202. }
  1203. var indexTotal int64
  1204. indexTotal = 0
  1205. for {
  1206. sess.Select("id,job_type,user_id,duration,train_job_duration,type").Table("cloudbrain").Where(cond).OrderBy("id asc").Limit(PAGE_SIZE, int(indexTotal))
  1207. cloudTaskList := make([]*Cloudbrain, 0)
  1208. sess.Find(&cloudTaskList)
  1209. log.Info("query cloudbrain size=" + fmt.Sprint(len(cloudTaskList)))
  1210. for _, cloudTaskRecord := range cloudTaskList {
  1211. if _, ok := resultMap[cloudTaskRecord.UserID]; !ok {
  1212. resultMap[cloudTaskRecord.UserID] = 1
  1213. } else {
  1214. resultMap[cloudTaskRecord.UserID] += 1
  1215. }
  1216. setMapKey("CloudBrainRunTime", cloudTaskRecord.UserID, int(cloudTaskRecord.Duration), resultItemMap)
  1217. if cloudTaskRecord.Type == 1 { //npu
  1218. if cloudTaskRecord.JobType == "TRAIN" {
  1219. setMapKey("NpuTrainJob", cloudTaskRecord.UserID, 1, resultItemMap)
  1220. } else if cloudTaskRecord.JobType == "INFERENCE" {
  1221. setMapKey("NpuInferenceJob", cloudTaskRecord.UserID, 1, resultItemMap)
  1222. } else {
  1223. setMapKey("NpuDebugJob", cloudTaskRecord.UserID, 1, resultItemMap)
  1224. }
  1225. } else { //type=0 gpu
  1226. if cloudTaskRecord.JobType == "TRAIN" {
  1227. setMapKey("GpuTrainJob", cloudTaskRecord.UserID, 1, resultItemMap)
  1228. } else if cloudTaskRecord.JobType == "BENCHMARK" {
  1229. setMapKey("GpuBenchMarkJob", cloudTaskRecord.UserID, 1, resultItemMap)
  1230. } else {
  1231. setMapKey("GpuDebugJob", cloudTaskRecord.UserID, 1, resultItemMap)
  1232. }
  1233. }
  1234. }
  1235. indexTotal += PAGE_SIZE
  1236. if indexTotal >= count {
  1237. break
  1238. }
  1239. }
  1240. return resultMap, resultItemMap
  1241. }
  1242. func setMapKey(key string, userId int64, value int, resultItemMap map[string]int) {
  1243. newKey := fmt.Sprint(userId) + "_" + key
  1244. if _, ok := resultItemMap[newKey]; !ok {
  1245. resultItemMap[newKey] = value
  1246. } else {
  1247. resultItemMap[newKey] += value
  1248. }
  1249. }
  1250. func subMonth(t1, t2 time.Time) (month int) {
  1251. y1 := t1.Year()
  1252. y2 := t2.Year()
  1253. m1 := int(t1.Month())
  1254. m2 := int(t2.Month())
  1255. d1 := t1.Day()
  1256. d2 := t2.Day()
  1257. yearInterval := y1 - y2
  1258. // 如果 d1的 月-日 小于 d2的 月-日 那么 yearInterval-- 这样就得到了相差的年数
  1259. if m1 < m2 || m1 == m2 && d1 < d2 {
  1260. yearInterval--
  1261. }
  1262. // 获取月数差值
  1263. monthInterval := (m1 + 12) - m2
  1264. if d1 < d2 {
  1265. monthInterval--
  1266. }
  1267. monthInterval %= 12
  1268. month = yearInterval*12 + monthInterval
  1269. if month == 0 {
  1270. month = 1
  1271. }
  1272. return month
  1273. }