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 75 kB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981
  1. package models
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "sort"
  6. "strconv"
  7. "strings"
  8. "time"
  9. "code.gitea.io/gitea/modules/log"
  10. "code.gitea.io/gitea/modules/timeutil"
  11. "xorm.io/builder"
  12. "xorm.io/xorm"
  13. )
  14. const (
  15. PAGE_SIZE = 2000
  16. BATCH_INSERT_SIZE = 50
  17. )
  18. type UserBusinessAnalysisAll struct {
  19. ID int64 `xorm:"pk"`
  20. CountDate int64 `xorm:"pk"`
  21. //action :ActionMergePullRequest // 11
  22. CodeMergeCount int `xorm:"NOT NULL DEFAULT 0"`
  23. //action :ActionCommitRepo // 5
  24. CommitCount int `xorm:"NOT NULL DEFAULT 0"`
  25. //action :ActionCreateIssue // 10
  26. IssueCount int `xorm:"NOT NULL DEFAULT 0"`
  27. //comment table current date
  28. CommentCount int `xorm:"NOT NULL DEFAULT 0"`
  29. //watch table current date
  30. FocusRepoCount int `xorm:"NOT NULL DEFAULT 0"`
  31. //star table current date
  32. StarRepoCount int `xorm:"NOT NULL DEFAULT 0"`
  33. //follow table
  34. WatchedCount int `xorm:"NOT NULL DEFAULT 0"`
  35. // user table
  36. GiteaAgeMonth int `xorm:"NOT NULL DEFAULT 0"`
  37. //
  38. CommitCodeSize int `xorm:"NOT NULL DEFAULT 0"`
  39. //attachement table
  40. CommitDatasetSize int `xorm:"NOT NULL DEFAULT 0"`
  41. //0
  42. CommitModelCount int `xorm:"NOT NULL DEFAULT 0"`
  43. //issue, issueassignees
  44. SolveIssueCount int `xorm:"NOT NULL DEFAULT 0"`
  45. //baike
  46. EncyclopediasCount int `xorm:"NOT NULL DEFAULT 0"`
  47. //user
  48. RegistDate timeutil.TimeStamp `xorm:"NOT NULL"`
  49. //repo
  50. CreateRepoCount int `xorm:"NOT NULL DEFAULT 0"`
  51. //login count, from elk
  52. LoginCount int `xorm:"NOT NULL DEFAULT 0"`
  53. //openi index
  54. OpenIIndex float64 `xorm:"NOT NULL DEFAULT 0"`
  55. //user
  56. Email string `xorm:"NOT NULL"`
  57. //user
  58. Name string `xorm:"NOT NULL"`
  59. DataDate string `xorm:"NULL"`
  60. //cloudbraintask
  61. CloudBrainTaskNum int `xorm:"NOT NULL DEFAULT 0"`
  62. GpuDebugJob int `xorm:"NOT NULL DEFAULT 0"`
  63. NpuDebugJob int `xorm:"NOT NULL DEFAULT 0"`
  64. GpuTrainJob int `xorm:"NOT NULL DEFAULT 0"`
  65. NpuTrainJob int `xorm:"NOT NULL DEFAULT 0"`
  66. NpuInferenceJob int `xorm:"NOT NULL DEFAULT 0"`
  67. GpuBenchMarkJob int `xorm:"NOT NULL DEFAULT 0"`
  68. CloudBrainRunTime int `xorm:"NOT NULL DEFAULT 0"`
  69. CommitDatasetNum int `xorm:"NOT NULL DEFAULT 0"`
  70. UserIndex float64 `xorm:"NOT NULL DEFAULT 0"`
  71. UserIndexPrimitive float64 `xorm:"NOT NULL DEFAULT 0"`
  72. UserLocation string `xorm:"NULL"`
  73. FocusOtherUser int `xorm:"NOT NULL DEFAULT 0"`
  74. CollectDataset int `xorm:"NOT NULL DEFAULT 0"`
  75. CollectedDataset int `xorm:"NOT NULL DEFAULT 0"`
  76. RecommendDataset int `xorm:"NOT NULL DEFAULT 0"`
  77. CollectImage int `xorm:"NOT NULL DEFAULT 0"`
  78. CollectedImage int `xorm:"NOT NULL DEFAULT 0"`
  79. RecommendImage int `xorm:"NOT NULL DEFAULT 0"`
  80. }
  81. type UserBusinessAnalysis struct {
  82. ID int64 `xorm:"pk"`
  83. CountDate int64 `xorm:"pk"`
  84. //action :ActionMergePullRequest // 11
  85. CodeMergeCount int `xorm:"NOT NULL DEFAULT 0"`
  86. //action :ActionCommitRepo // 5
  87. CommitCount int `xorm:"NOT NULL DEFAULT 0"`
  88. //action :ActionCreateIssue // 6
  89. IssueCount int `xorm:"NOT NULL DEFAULT 0"`
  90. //comment table current date
  91. CommentCount int `xorm:"NOT NULL DEFAULT 0"`
  92. //watch table current date
  93. FocusRepoCount int `xorm:"NOT NULL DEFAULT 0"`
  94. //star table current date
  95. StarRepoCount int `xorm:"NOT NULL DEFAULT 0"`
  96. //follow table
  97. WatchedCount int `xorm:"NOT NULL DEFAULT 0"`
  98. // user table
  99. GiteaAgeMonth int `xorm:"NOT NULL DEFAULT 0"`
  100. //
  101. CommitCodeSize int `xorm:"NOT NULL DEFAULT 0"`
  102. //attachement table
  103. CommitDatasetSize int `xorm:"NOT NULL DEFAULT 0"`
  104. //0
  105. CommitModelCount int `xorm:"NOT NULL DEFAULT 0"`
  106. //issue, issueassignees
  107. SolveIssueCount int `xorm:"NOT NULL DEFAULT 0"`
  108. //baike
  109. EncyclopediasCount int `xorm:"NOT NULL DEFAULT 0"`
  110. //user
  111. RegistDate timeutil.TimeStamp `xorm:"NOT NULL"`
  112. //repo
  113. CreateRepoCount int `xorm:"NOT NULL DEFAULT 0"`
  114. //login count, from elk
  115. LoginCount int `xorm:"NOT NULL DEFAULT 0"`
  116. //openi index
  117. OpenIIndex float64 `xorm:"NOT NULL DEFAULT 0"`
  118. //user
  119. Email string `xorm:"NOT NULL"`
  120. //user
  121. Name string `xorm:"NOT NULL"`
  122. DataDate string `xorm:"NULL"`
  123. CloudBrainTaskNum int `xorm:"NOT NULL DEFAULT 0"`
  124. GpuDebugJob int `xorm:"NOT NULL DEFAULT 0"`
  125. NpuDebugJob int `xorm:"NOT NULL DEFAULT 0"`
  126. GpuTrainJob int `xorm:"NOT NULL DEFAULT 0"`
  127. NpuTrainJob int `xorm:"NOT NULL DEFAULT 0"`
  128. NpuInferenceJob int `xorm:"NOT NULL DEFAULT 0"`
  129. GpuBenchMarkJob int `xorm:"NOT NULL DEFAULT 0"`
  130. CloudBrainRunTime int `xorm:"NOT NULL DEFAULT 0"`
  131. CommitDatasetNum int `xorm:"NOT NULL DEFAULT 0"`
  132. UserIndex float64 `xorm:"NOT NULL DEFAULT 0"`
  133. UserIndexPrimitive float64 `xorm:"NOT NULL DEFAULT 0"`
  134. UserLocation string `xorm:"NULL"`
  135. FocusOtherUser int `xorm:"NOT NULL DEFAULT 0"`
  136. CollectDataset int `xorm:"NOT NULL DEFAULT 0"`
  137. CollectedDataset int `xorm:"NOT NULL DEFAULT 0"`
  138. RecommendDataset int `xorm:"NOT NULL DEFAULT 0"`
  139. CollectImage int `xorm:"NOT NULL DEFAULT 0"`
  140. CollectedImage int `xorm:"NOT NULL DEFAULT 0"`
  141. RecommendImage int `xorm:"NOT NULL DEFAULT 0"`
  142. }
  143. type UserBusinessAnalysisQueryOptions struct {
  144. ListOptions
  145. UserName string
  146. SortType string
  147. StartTime int64
  148. EndTime int64
  149. IsAll bool
  150. }
  151. type UserBusinessAnalysisList []*UserBusinessAnalysis
  152. func (ulist UserBusinessAnalysisList) Swap(i, j int) { ulist[i], ulist[j] = ulist[j], ulist[i] }
  153. func (ulist UserBusinessAnalysisList) Len() int { return len(ulist) }
  154. func (ulist UserBusinessAnalysisList) Less(i, j int) bool {
  155. return ulist[i].ID > ulist[j].ID
  156. }
  157. func getLastCountDate() int64 {
  158. statictisSess := xStatistic.NewSession()
  159. defer statictisSess.Close()
  160. statictisSess.Limit(1, 0)
  161. userBusinessAnalysisList := make([]*UserBusinessAnalysis, 0)
  162. if err := statictisSess.Table("user_business_analysis").OrderBy("count_date desc").Limit(1, 0).
  163. Find(&userBusinessAnalysisList); err == nil {
  164. for _, userRecord := range userBusinessAnalysisList {
  165. return userRecord.CountDate - 10000
  166. }
  167. } else {
  168. log.Info("query error." + err.Error())
  169. }
  170. currentTimeNow := time.Now()
  171. pageStartTime := time.Date(currentTimeNow.Year(), currentTimeNow.Month(), currentTimeNow.Day(), 0, 0, 0, 0, currentTimeNow.Location())
  172. return pageStartTime.Unix()
  173. }
  174. func QueryMetricsPage(start int64, end int64) ([]*UserMetrics, int64) {
  175. statictisSess := xStatistic.NewSession()
  176. defer statictisSess.Close()
  177. cond := "count_date >" + fmt.Sprint(start) + " and count_date<" + fmt.Sprint(end)
  178. userMetricsList := make([]*UserMetrics, 0)
  179. //.Limit(pageSize, page*pageSize)
  180. if err := statictisSess.Table(new(UserMetrics)).Where(cond).OrderBy("count_date desc").
  181. Find(&userMetricsList); err != nil {
  182. return nil, 0
  183. }
  184. postUserMetricsList := postDeal(userMetricsList)
  185. return postUserMetricsList, int64(len(postUserMetricsList))
  186. }
  187. func QueryMetrics(start int64, end int64) ([]*UserMetrics, int) {
  188. statictisSess := xStatistic.NewSession()
  189. defer statictisSess.Close()
  190. userMetricsList := make([]*UserMetrics, 0)
  191. if err := statictisSess.Table(new(UserMetrics)).Where("count_date >" + fmt.Sprint(start) + " and count_date<" + fmt.Sprint(end)).OrderBy("count_date desc").
  192. Find(&userMetricsList); err != nil {
  193. return nil, 0
  194. }
  195. postUserMetricsList := postDeal(userMetricsList)
  196. return postUserMetricsList, int(len(postUserMetricsList))
  197. }
  198. func duplicateRemoval(userMetricsList []*UserMetrics) []*UserMetrics {
  199. userMetricsResult := make([]*UserMetrics, 0)
  200. for i := 0; i < len(userMetricsList); i++ {
  201. if i > 0 {
  202. if userMetricsList[i].DataDate == userMetricsList[i-1].DataDate {
  203. continue
  204. }
  205. }
  206. userMetricsResult = append(userMetricsResult, userMetricsList[i])
  207. }
  208. return userMetricsResult
  209. }
  210. func postDeal(userMetricsList []*UserMetrics) []*UserMetrics {
  211. duplicateRemovalUserMetricsList := duplicateRemoval(userMetricsList)
  212. for _, userMetrics := range duplicateRemovalUserMetricsList {
  213. userMetrics.DisplayDate = userMetrics.DataDate
  214. userMetrics.TotalRegistUser = userMetrics.ActivateRegistUser + userMetrics.NotActivateRegistUser
  215. userMetrics.TotalNotActivateRegistUser = userMetrics.TotalUser - userMetrics.TotalActivateRegistUser
  216. }
  217. return duplicateRemovalUserMetricsList
  218. }
  219. func QueryMetricsForAll(start int64, end int64) []*UserMetrics {
  220. statictisSess := xStatistic.NewSession()
  221. defer statictisSess.Close()
  222. userMetricsList := make([]*UserMetrics, 0)
  223. if err := statictisSess.Table(new(UserMetrics)).Where("count_date >" + fmt.Sprint(start) + " and count_date<" + fmt.Sprint(end)).OrderBy("count_date desc").
  224. Find(&userMetricsList); err != nil {
  225. return nil
  226. }
  227. duplicateRemovalUserMetricsList := duplicateRemoval(userMetricsList)
  228. return makeResultForMonth(duplicateRemovalUserMetricsList, len(duplicateRemovalUserMetricsList))
  229. }
  230. func QueryMetricsForYear(start int64, end int64) []*UserMetrics {
  231. allUserInfo, count := QueryMetrics(start, end)
  232. return makeResultForMonth(allUserInfo, count)
  233. }
  234. func makeResultForMonth(allUserInfo []*UserMetrics, count int) []*UserMetrics {
  235. monthMap := make(map[string]*UserMetrics)
  236. if count > 0 {
  237. for _, userMetrics := range allUserInfo {
  238. dateTime := time.Unix(userMetrics.CountDate, 0)
  239. month := fmt.Sprint(dateTime.Year()) + "-" + fmt.Sprint(int(dateTime.Month()))
  240. if _, ok := monthMap[month]; !ok {
  241. monthUserMetrics := &UserMetrics{
  242. DisplayDate: month,
  243. ActivateRegistUser: userMetrics.ActivateRegistUser,
  244. NotActivateRegistUser: userMetrics.NotActivateRegistUser,
  245. TotalUser: userMetrics.TotalUser,
  246. TotalNotActivateRegistUser: userMetrics.TotalUser - userMetrics.TotalActivateRegistUser,
  247. TotalActivateRegistUser: userMetrics.TotalActivateRegistUser,
  248. TotalHasActivityUser: userMetrics.TotalHasActivityUser,
  249. HasActivityUser: userMetrics.HasActivityUser,
  250. DaysForMonth: 1,
  251. TotalRegistUser: userMetrics.ActivateRegistUser + userMetrics.NotActivateRegistUser,
  252. }
  253. monthMap[month] = monthUserMetrics
  254. } else {
  255. value := monthMap[month]
  256. value.ActivateRegistUser += userMetrics.ActivateRegistUser
  257. value.NotActivateRegistUser += userMetrics.NotActivateRegistUser
  258. value.HasActivityUser += userMetrics.HasActivityUser
  259. value.TotalRegistUser += userMetrics.ActivateRegistUser + userMetrics.NotActivateRegistUser
  260. value.ActivateIndex = float64(value.ActivateRegistUser) / float64(value.TotalRegistUser)
  261. value.DaysForMonth += 1
  262. }
  263. }
  264. }
  265. result := make([]*UserMetrics, 0)
  266. for _, value := range monthMap {
  267. result = append(result, value)
  268. }
  269. sort.Slice(result, func(i, j int) bool {
  270. return strings.Compare(result[i].DisplayDate, result[j].DisplayDate) > 0
  271. })
  272. return result
  273. }
  274. func QueryRankList(key string, tableName string, limit int) ([]*UserBusinessAnalysisAll, int64) {
  275. statictisSess := xStatistic.NewSession()
  276. defer statictisSess.Close()
  277. userBusinessAnalysisAllList := make([]*UserBusinessAnalysisAll, 0)
  278. if err := statictisSess.Table(tableName).OrderBy(key+" desc,id desc").Limit(limit, 0).
  279. Find(&userBusinessAnalysisAllList); err != nil {
  280. return nil, 0
  281. }
  282. return userBusinessAnalysisAllList, int64(len(userBusinessAnalysisAllList))
  283. }
  284. func QueryUserStaticDataByTableName(start int, pageSize int, tableName string, queryObj interface{}, userName string) ([]*UserBusinessAnalysisAll, int64) {
  285. statictisSess := xStatistic.NewSession()
  286. defer statictisSess.Close()
  287. var cond = builder.NewCond()
  288. if len(userName) > 0 {
  289. cond = cond.And(
  290. builder.Like{"name", userName},
  291. )
  292. }
  293. allCount, err := statictisSess.Where(cond).Count(queryObj)
  294. if err != nil {
  295. log.Info("query error." + err.Error())
  296. return nil, 0
  297. }
  298. log.Info("query return total:" + fmt.Sprint(allCount))
  299. userBusinessAnalysisAllList := make([]*UserBusinessAnalysisAll, 0)
  300. if err := statictisSess.Table(tableName).Where(cond).OrderBy("user_index desc,id desc").Limit(pageSize, start).
  301. Find(&userBusinessAnalysisAllList); err != nil {
  302. return nil, 0
  303. }
  304. return userBusinessAnalysisAllList, allCount
  305. }
  306. func QueryUserStaticDataAll(opts *UserBusinessAnalysisQueryOptions) ([]*UserBusinessAnalysisAll, int64) {
  307. log.Info("query startTime =" + fmt.Sprint(opts.StartTime) + " endTime=" + fmt.Sprint(opts.EndTime) + " isAll=" + fmt.Sprint(opts.IsAll))
  308. statictisSess := xStatistic.NewSession()
  309. defer statictisSess.Close()
  310. allCount, err := statictisSess.Count(new(UserBusinessAnalysisAll))
  311. if err != nil {
  312. log.Info("query error." + err.Error())
  313. return nil, 0
  314. }
  315. log.Info("query return total:" + fmt.Sprint(allCount))
  316. pageSize := PAGE_SIZE
  317. totalPage := int(allCount) / pageSize
  318. userBusinessAnalysisReturnList := make([]*UserBusinessAnalysisAll, 0)
  319. for i := 0; i <= int(totalPage); i++ {
  320. userBusinessAnalysisAllList := make([]*UserBusinessAnalysisAll, 0)
  321. if err := statictisSess.Table("user_business_analysis_all").OrderBy("id desc").Limit(pageSize, i*pageSize).
  322. Find(&userBusinessAnalysisAllList); err != nil {
  323. return nil, 0
  324. }
  325. log.Info("query " + fmt.Sprint(i+1) + " result size=" + fmt.Sprint(len(userBusinessAnalysisAllList)))
  326. for _, userRecord := range userBusinessAnalysisAllList {
  327. userBusinessAnalysisReturnList = append(userBusinessAnalysisReturnList, userRecord)
  328. }
  329. }
  330. log.Info("return size=" + fmt.Sprint(len(userBusinessAnalysisReturnList)))
  331. return userBusinessAnalysisReturnList, allCount
  332. }
  333. func QueryUserStaticDataPage(opts *UserBusinessAnalysisQueryOptions) ([]*UserBusinessAnalysis, int64) {
  334. log.Info("query startTime =" + fmt.Sprint(opts.StartTime) + " endTime=" + fmt.Sprint(opts.EndTime) + " isAll=" + fmt.Sprint(opts.IsAll))
  335. statictisSess := xStatistic.NewSession()
  336. defer statictisSess.Close()
  337. currentTimeNow := time.Now()
  338. pageStartTime := getLastCountDate()
  339. pageEndTime := time.Date(currentTimeNow.Year(), currentTimeNow.Month(), currentTimeNow.Day(), 23, 59, 59, 0, currentTimeNow.Location()).Unix()
  340. var cond = builder.NewCond()
  341. if len(opts.UserName) > 0 {
  342. cond = cond.And(
  343. builder.Like{"name", opts.UserName},
  344. )
  345. }
  346. cond = cond.And(
  347. builder.Gte{"count_date": pageStartTime},
  348. )
  349. cond = cond.And(
  350. builder.Lte{"count_date": pageEndTime},
  351. )
  352. count, err := statictisSess.Where(cond).Count(new(UserBusinessAnalysis))
  353. if err != nil {
  354. log.Info("query error." + err.Error())
  355. return nil, 0
  356. }
  357. if opts.Page >= 0 && opts.PageSize > 0 {
  358. var start int
  359. if opts.Page == 0 {
  360. start = 0
  361. } else {
  362. start = (opts.Page - 1) * opts.PageSize
  363. }
  364. statictisSess.Limit(opts.PageSize, start)
  365. }
  366. userBusinessAnalysisList := make([]*UserBusinessAnalysis, 0)
  367. if err := statictisSess.Table("user_business_analysis").Where(cond).OrderBy("id desc").
  368. Find(&userBusinessAnalysisList); err != nil {
  369. return nil, 0
  370. }
  371. resultMap := make(map[int64]*UserBusinessAnalysis)
  372. if len(userBusinessAnalysisList) > 0 {
  373. var newAndCond = builder.NewCond()
  374. var newOrCond = builder.NewCond()
  375. for _, userRecord := range userBusinessAnalysisList {
  376. newOrCond = newOrCond.Or(
  377. builder.Eq{"id": userRecord.ID},
  378. )
  379. }
  380. newAndCond = newAndCond.And(
  381. newOrCond,
  382. )
  383. if !opts.IsAll {
  384. newAndCond = newAndCond.And(
  385. builder.Gte{"count_date": opts.StartTime},
  386. )
  387. newAndCond = newAndCond.And(
  388. builder.Lte{"count_date": opts.EndTime},
  389. )
  390. }
  391. allCount, err := statictisSess.Where(newAndCond).Count(new(UserBusinessAnalysis))
  392. if err != nil {
  393. log.Info("query error." + err.Error())
  394. return nil, 0
  395. }
  396. pageSize := 1000
  397. totalPage := int(allCount) / pageSize
  398. for i := 0; i <= int(totalPage); i++ {
  399. userBusinessAnalysisList = make([]*UserBusinessAnalysis, 0)
  400. if err := statictisSess.Table("user_business_analysis").Where(newAndCond).OrderBy("count_date desc").Limit(pageSize, i*pageSize).
  401. Find(&userBusinessAnalysisList); err != nil {
  402. return nil, 0
  403. }
  404. log.Info("query result size=" + fmt.Sprint(len(userBusinessAnalysisList)))
  405. for _, userRecord := range userBusinessAnalysisList {
  406. if _, ok := resultMap[userRecord.ID]; !ok {
  407. resultMap[userRecord.ID] = userRecord
  408. } else {
  409. resultMap[userRecord.ID].CodeMergeCount += userRecord.CodeMergeCount
  410. resultMap[userRecord.ID].CommitCount += userRecord.CommitCount
  411. resultMap[userRecord.ID].IssueCount += userRecord.IssueCount
  412. resultMap[userRecord.ID].CommentCount += userRecord.CommentCount
  413. resultMap[userRecord.ID].FocusRepoCount += userRecord.FocusRepoCount
  414. resultMap[userRecord.ID].StarRepoCount += userRecord.StarRepoCount
  415. resultMap[userRecord.ID].WatchedCount += userRecord.WatchedCount
  416. resultMap[userRecord.ID].CommitCodeSize += userRecord.CommitCodeSize
  417. resultMap[userRecord.ID].CommitDatasetSize += userRecord.CommitDatasetSize
  418. resultMap[userRecord.ID].CommitDatasetNum += userRecord.CommitDatasetNum
  419. resultMap[userRecord.ID].CommitModelCount += userRecord.CommitModelCount
  420. resultMap[userRecord.ID].SolveIssueCount += userRecord.SolveIssueCount
  421. resultMap[userRecord.ID].EncyclopediasCount += userRecord.EncyclopediasCount
  422. resultMap[userRecord.ID].CreateRepoCount += userRecord.CreateRepoCount
  423. resultMap[userRecord.ID].LoginCount += userRecord.LoginCount
  424. }
  425. }
  426. }
  427. }
  428. userBusinessAnalysisReturnList := UserBusinessAnalysisList{}
  429. for _, v := range resultMap {
  430. userBusinessAnalysisReturnList = append(userBusinessAnalysisReturnList, v)
  431. }
  432. sort.Sort(userBusinessAnalysisReturnList)
  433. log.Info("return size=" + fmt.Sprint(len(userBusinessAnalysisReturnList)))
  434. return userBusinessAnalysisReturnList, count
  435. }
  436. func refreshUserStaticTable(wikiCountMap map[string]int, tableName string, pageStartTime time.Time, pageEndTime time.Time, userMetrics map[string]int) {
  437. sess := x.NewSession()
  438. defer sess.Close()
  439. statictisSess := xStatistic.NewSession()
  440. defer statictisSess.Close()
  441. log.Info("truncate all data from table: " + tableName)
  442. statictisSess.Exec("TRUNCATE TABLE " + tableName)
  443. StartTimeNextDay := pageStartTime.AddDate(0, 0, 1)
  444. EndTimeNextDay := pageEndTime.AddDate(0, 0, 1)
  445. log.Info("pageStartTime:" + pageStartTime.Format("2006-01-02 15:04:05") + " nextDay:" + StartTimeNextDay.Format("2006-01-02 15:04:05"))
  446. log.Info("pageEndTime time:" + pageEndTime.Format("2006-01-02 15:04:05") + " nextDay:" + EndTimeNextDay.Format("2006-01-02 15:04:05"))
  447. start_unix := pageStartTime.Unix()
  448. end_unix := pageEndTime.Unix()
  449. currentTimeNow := time.Now()
  450. startTime := currentTimeNow.AddDate(0, 0, -1)
  451. CodeMergeCountMap := queryPullRequest(start_unix, end_unix)
  452. CommitCountMap := queryCommitAction(start_unix, end_unix, 5)
  453. IssueCountMap := queryCreateIssue(start_unix, end_unix)
  454. CommentCountMap := queryComment(start_unix, end_unix)
  455. FocusRepoCountMap := queryWatch(start_unix, end_unix)
  456. StarRepoCountMap := queryStar(start_unix, end_unix)
  457. WatchedCountMap, WatchOtherMap := queryFollow(start_unix, end_unix)
  458. CommitCodeSizeMap := queryCommitCodeSize(StartTimeNextDay.Unix(), EndTimeNextDay.Unix())
  459. CommitDatasetSizeMap, CommitDatasetNumMap := queryDatasetSize(start_unix, end_unix)
  460. SolveIssueCountMap := querySolveIssue(start_unix, end_unix)
  461. CreateRepoCountMap := queryUserCreateRepo(start_unix, end_unix)
  462. LoginCountMap := queryLoginCount(start_unix, end_unix)
  463. OpenIIndexMap := queryUserRepoOpenIIndex(startTime.Unix(), end_unix)
  464. CloudBrainTaskMap, CloudBrainTaskItemMap := queryCloudBrainTask(start_unix, end_unix)
  465. AiModelManageMap := queryUserModel(start_unix, end_unix)
  466. CollectDataset, CollectedDataset := queryDatasetStars(start_unix, end_unix)
  467. RecommendDataset := queryRecommedDataSet(start_unix, end_unix)
  468. CollectImage, CollectedImage := queryImageStars(start_unix, end_unix)
  469. RecommendImage := queryRecommedImage(start_unix, end_unix)
  470. DataDate := currentTimeNow.Format("2006-01-02") + " 00:01"
  471. cond := "type != 1 and is_active=true"
  472. count, err := sess.Where(cond).Count(new(User))
  473. if err != nil {
  474. log.Info("query user error. return.")
  475. return
  476. }
  477. ParaWeight := getParaWeight()
  478. var indexTotal int64
  479. indexTotal = 0
  480. insertCount := 0
  481. userIndexMap := make(map[int64]float64, 0)
  482. maxUserIndex := 0.0
  483. minUserIndex := 100000000.0
  484. dateRecordBatch := make([]UserBusinessAnalysisAll, 0)
  485. for {
  486. sess.Select("`user`.*").Table("user").Where(cond).OrderBy("id asc").Limit(PAGE_SIZE, int(indexTotal))
  487. userList := make([]*User, 0)
  488. sess.Find(&userList)
  489. for _, userRecord := range userList {
  490. var dateRecordAll UserBusinessAnalysisAll
  491. dateRecordAll.ID = userRecord.ID
  492. dateRecordAll.Email = userRecord.Email
  493. dateRecordAll.RegistDate = userRecord.CreatedUnix
  494. dateRecordAll.Name = userRecord.Name
  495. dateRecordAll.GiteaAgeMonth = subMonth(currentTimeNow, userRecord.CreatedUnix.AsTime())
  496. dateRecordAll.DataDate = DataDate
  497. dateRecordAll.UserLocation = userRecord.Location
  498. dateRecordAll.CodeMergeCount = getMapValue(dateRecordAll.ID, CodeMergeCountMap)
  499. dateRecordAll.CommitCount = getMapValue(dateRecordAll.ID, CommitCountMap)
  500. dateRecordAll.IssueCount = getMapValue(dateRecordAll.ID, IssueCountMap)
  501. dateRecordAll.CommentCount = getMapValue(dateRecordAll.ID, CommentCountMap)
  502. dateRecordAll.FocusRepoCount = getMapValue(dateRecordAll.ID, FocusRepoCountMap)
  503. dateRecordAll.FocusOtherUser = getMapValue(dateRecordAll.ID, WatchOtherMap)
  504. dateRecordAll.StarRepoCount = getMapValue(dateRecordAll.ID, StarRepoCountMap)
  505. dateRecordAll.WatchedCount = getMapValue(dateRecordAll.ID, WatchedCountMap)
  506. dateRecordAll.CommitCodeSize = getMapValue(dateRecordAll.ID, CommitCodeSizeMap)
  507. dateRecordAll.CommitDatasetSize = getMapValue(dateRecordAll.ID, CommitDatasetSizeMap)
  508. dateRecordAll.CommitDatasetNum = getMapValue(dateRecordAll.ID, CommitDatasetNumMap)
  509. dateRecordAll.SolveIssueCount = getMapValue(dateRecordAll.ID, SolveIssueCountMap)
  510. dateRecordAll.EncyclopediasCount = getMapKeyStringValue(dateRecordAll.Name, wikiCountMap)
  511. dateRecordAll.CreateRepoCount = getMapValue(dateRecordAll.ID, CreateRepoCountMap)
  512. dateRecordAll.LoginCount = getMapValue(dateRecordAll.ID, LoginCountMap)
  513. if _, ok := OpenIIndexMap[dateRecordAll.ID]; !ok {
  514. dateRecordAll.OpenIIndex = 0
  515. } else {
  516. dateRecordAll.OpenIIndex = OpenIIndexMap[dateRecordAll.ID]
  517. }
  518. dateRecordAll.CloudBrainTaskNum = getMapValue(dateRecordAll.ID, CloudBrainTaskMap)
  519. dateRecordAll.GpuDebugJob = getMapKeyStringValue(fmt.Sprint(dateRecordAll.ID)+"_GpuDebugJob", CloudBrainTaskItemMap)
  520. dateRecordAll.NpuDebugJob = getMapKeyStringValue(fmt.Sprint(dateRecordAll.ID)+"_NpuDebugJob", CloudBrainTaskItemMap)
  521. dateRecordAll.GpuTrainJob = getMapKeyStringValue(fmt.Sprint(dateRecordAll.ID)+"_GpuTrainJob", CloudBrainTaskItemMap)
  522. dateRecordAll.NpuTrainJob = getMapKeyStringValue(fmt.Sprint(dateRecordAll.ID)+"_NpuTrainJob", CloudBrainTaskItemMap)
  523. dateRecordAll.NpuInferenceJob = getMapKeyStringValue(fmt.Sprint(dateRecordAll.ID)+"_NpuInferenceJob", CloudBrainTaskItemMap)
  524. dateRecordAll.GpuBenchMarkJob = getMapKeyStringValue(fmt.Sprint(dateRecordAll.ID)+"_GpuBenchMarkJob", CloudBrainTaskItemMap)
  525. dateRecordAll.CommitModelCount = getMapValue(dateRecordAll.ID, AiModelManageMap)
  526. dateRecordAll.CollectDataset = getMapValue(dateRecordAll.ID, CollectDataset)
  527. dateRecordAll.CollectedDataset = getMapValue(dateRecordAll.ID, CollectedDataset)
  528. dateRecordAll.RecommendDataset = getMapValue(dateRecordAll.ID, RecommendDataset)
  529. dateRecordAll.CollectImage = getMapValue(dateRecordAll.ID, CollectImage)
  530. dateRecordAll.CollectedImage = getMapValue(dateRecordAll.ID, CollectedImage)
  531. dateRecordAll.RecommendImage = getMapValue(dateRecordAll.ID, RecommendImage)
  532. dateRecordAll.UserIndexPrimitive = getUserIndexFromAnalysisAll(dateRecordAll, ParaWeight)
  533. userIndexMap[dateRecordAll.ID] = dateRecordAll.UserIndexPrimitive
  534. if maxUserIndex < dateRecordAll.UserIndexPrimitive {
  535. maxUserIndex = dateRecordAll.UserIndexPrimitive
  536. }
  537. if minUserIndex > dateRecordAll.UserIndexPrimitive {
  538. minUserIndex = dateRecordAll.UserIndexPrimitive
  539. }
  540. dateRecordBatch = append(dateRecordBatch, dateRecordAll)
  541. if len(dateRecordBatch) >= BATCH_INSERT_SIZE {
  542. insertTable(dateRecordBatch, tableName, statictisSess)
  543. insertCount += BATCH_INSERT_SIZE
  544. if err != nil {
  545. log.Info("insert all data failed." + err.Error())
  546. }
  547. dateRecordBatch = make([]UserBusinessAnalysisAll, 0)
  548. }
  549. if tableName == "user_business_analysis_all" {
  550. tValue := getUserActivateAll(dateRecordAll)
  551. if tValue > 0 {
  552. log.Info("dateRecordAll name=" + dateRecordAll.Name + " value=" + fmt.Sprint(tValue))
  553. userMetrics["TotalHasActivityUser"] = getMapKeyStringValue("TotalHasActivityUser", userMetrics) + 1
  554. }
  555. }
  556. }
  557. indexTotal += PAGE_SIZE
  558. if indexTotal >= count {
  559. break
  560. }
  561. }
  562. if len(dateRecordBatch) > 0 {
  563. insertTable(dateRecordBatch, tableName, statictisSess)
  564. insertCount += len(dateRecordBatch)
  565. if err != nil {
  566. log.Info("insert all data failed." + err.Error())
  567. }
  568. }
  569. if tableName == "user_business_analysis_all" {
  570. log.Info("TotalHasActivityUser=" + fmt.Sprint(userMetrics["TotalHasActivityUser"]))
  571. }
  572. //normalization
  573. for k, v := range userIndexMap {
  574. tmpResult := (v - minUserIndex) / (maxUserIndex - minUserIndex)
  575. if tmpResult > 0.99 {
  576. tmpResult = 0.99
  577. }
  578. updateUserIndex(tableName, statictisSess, k, tmpResult)
  579. }
  580. log.Info("refresh data finished.tableName=" + tableName + " total record:" + fmt.Sprint(insertCount))
  581. }
  582. func updateUserIndex(tableName string, statictisSess *xorm.Session, userId int64, userIndex float64) {
  583. updateSql := "UPDATE public." + tableName + " set user_index=" + fmt.Sprint(userIndex*100) + " where id=" + fmt.Sprint(userId)
  584. statictisSess.Exec(updateSql)
  585. }
  586. func insertTable(dateRecords []UserBusinessAnalysisAll, tableName string, statictisSess *xorm.Session) {
  587. insertBatchSql := "INSERT INTO public." + tableName +
  588. "(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, " +
  589. "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,focus_other_user,collect_dataset,collected_dataset,recommend_dataset,collect_image,collected_image,recommend_image,user_index_primitive) " +
  590. "VALUES"
  591. for i, record := range dateRecords {
  592. insertBatchSql += "(" + fmt.Sprint(record.ID) + ", " + fmt.Sprint(record.CountDate) + ", " + fmt.Sprint(record.CodeMergeCount) + ", " + fmt.Sprint(record.CommitCount) +
  593. ", " + fmt.Sprint(record.IssueCount) + ", " + fmt.Sprint(record.CommentCount) + ", " + fmt.Sprint(record.FocusRepoCount) + ", " + fmt.Sprint(record.StarRepoCount) +
  594. ", " + fmt.Sprint(record.WatchedCount) + ", " + fmt.Sprint(record.GiteaAgeMonth) + ", " + fmt.Sprint(record.CommitCodeSize) + ", " + fmt.Sprint(record.CommitDatasetSize) +
  595. ", " + fmt.Sprint(record.CommitModelCount) + ", " + fmt.Sprint(record.SolveIssueCount) + ", " + fmt.Sprint(record.EncyclopediasCount) + ", " + fmt.Sprint(record.RegistDate) +
  596. ", " + 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 + "'," +
  597. fmt.Sprint(record.FocusOtherUser) + "," + fmt.Sprint(record.CollectDataset) + "," + fmt.Sprint(record.CollectedDataset) + "," + fmt.Sprint(record.RecommendDataset) + "," + fmt.Sprint(record.CollectImage) + "," + fmt.Sprint(record.CollectedImage) + "," + fmt.Sprint(record.RecommendImage) + "," + fmt.Sprint(record.UserIndexPrimitive) + ")"
  598. if i < (len(dateRecords) - 1) {
  599. insertBatchSql += ","
  600. }
  601. }
  602. statictisSess.Exec(insertBatchSql)
  603. }
  604. func RefreshUserStaticAllTabel(wikiCountMap map[string]int, userMetrics map[string]int) {
  605. currentTimeNow := time.Now()
  606. pageStartTime := time.Date(2021, 11, 5, 0, 0, 0, 0, currentTimeNow.Location())
  607. pageEndTime := time.Date(currentTimeNow.Year(), currentTimeNow.Month(), currentTimeNow.Day(), 23, 59, 59, 0, currentTimeNow.Location())
  608. refreshUserStaticTable(wikiCountMap, "user_business_analysis_all", pageStartTime, pageEndTime, userMetrics)
  609. log.Info("refresh all data finished.")
  610. pageStartTime = time.Date(currentTimeNow.Year(), 1, 1, 0, 0, 0, 0, currentTimeNow.Location())
  611. refreshUserStaticTable(wikiCountMap, "user_business_analysis_current_year", pageStartTime, pageEndTime, userMetrics)
  612. thisMonth := time.Date(currentTimeNow.Year(), currentTimeNow.Month(), 1, 0, 0, 0, 0, currentTimeNow.Location())
  613. refreshUserStaticTable(wikiCountMap, "user_business_analysis_current_month", thisMonth, pageEndTime, userMetrics)
  614. offset := int(time.Monday - currentTimeNow.Weekday())
  615. if offset > 0 {
  616. offset = -6
  617. }
  618. pageStartTime = time.Date(currentTimeNow.Year(), currentTimeNow.Month(), currentTimeNow.Day(), 0, 0, 0, 0, time.Local).AddDate(0, 0, offset)
  619. refreshUserStaticTable(wikiCountMap, "user_business_analysis_current_week", pageStartTime, pageEndTime, userMetrics)
  620. pageStartTime = time.Date(currentTimeNow.Year(), currentTimeNow.Month(), currentTimeNow.Day(), 0, 0, 0, 0, time.Local).AddDate(0, 0, -30)
  621. refreshUserStaticTable(wikiCountMap, "user_business_analysis_last30_day", pageStartTime, pageEndTime, userMetrics)
  622. pageStartTime = time.Date(currentTimeNow.Year(), currentTimeNow.Month(), currentTimeNow.Day(), 0, 0, 0, 0, time.Local).AddDate(0, 0, -1)
  623. pageEndTime = time.Date(currentTimeNow.Year(), currentTimeNow.Month(), currentTimeNow.Day(), 23, 59, 59, 0, currentTimeNow.Location()).AddDate(0, 0, -1)
  624. refreshUserStaticTable(wikiCountMap, "user_business_analysis_yesterday", pageStartTime, pageEndTime, userMetrics)
  625. pageStartTime = thisMonth.AddDate(0, -1, 0)
  626. pageEndTime = time.Date(currentTimeNow.Year(), currentTimeNow.Month(), 1, 23, 59, 59, 0, currentTimeNow.Location()).AddDate(0, 0, -1)
  627. refreshUserStaticTable(wikiCountMap, "user_business_analysis_last_month", pageStartTime, pageEndTime, userMetrics)
  628. }
  629. func CounDataByDateAndReCount(wikiCountMap map[string]int, startTime time.Time, endTime time.Time, isReCount bool) error {
  630. log.Info("start to count other user info data")
  631. sess := x.NewSession()
  632. defer sess.Close()
  633. currentTimeNow := time.Now()
  634. log.Info("current time:" + currentTimeNow.Format("2006-01-02 15:04:05"))
  635. start_unix := startTime.Unix()
  636. log.Info("DB query time:" + startTime.Format("2006-01-02 15:04:05"))
  637. end_unix := endTime.Unix()
  638. CountDate := time.Date(currentTimeNow.Year(), currentTimeNow.Month(), currentTimeNow.Day(), 0, 1, 0, 0, currentTimeNow.Location())
  639. if isReCount {
  640. CountDate = time.Date(startTime.Year(), startTime.Month(), startTime.Day(), 0, 1, 0, 0, currentTimeNow.Location())
  641. }
  642. DataDate := startTime.Format("2006-01-02")
  643. CodeMergeCountMap := queryPullRequest(start_unix, end_unix)
  644. CommitCountMap := queryCommitAction(start_unix, end_unix, 5)
  645. IssueCountMap := queryCreateIssue(start_unix, end_unix)
  646. CommentCountMap := queryComment(start_unix, end_unix)
  647. FocusRepoCountMap := queryWatch(start_unix, end_unix)
  648. StarRepoCountMap := queryStar(start_unix, end_unix)
  649. WatchedCountMap, WatchOtherMap := queryFollow(start_unix, end_unix)
  650. CommitCodeSizeMap, err := GetAllUserKPIStats()
  651. if err != nil {
  652. log.Info("query commit code errr.")
  653. } else {
  654. log.Info("query commit code size, len=" + fmt.Sprint(len(CommitCodeSizeMap)))
  655. CommitCodeSizeMapJson, _ := json.Marshal(CommitCodeSizeMap)
  656. log.Info("CommitCodeSizeMapJson=" + string(CommitCodeSizeMapJson))
  657. }
  658. CommitDatasetSizeMap, CommitDatasetNumMap := queryDatasetSize(start_unix, end_unix)
  659. SolveIssueCountMap := querySolveIssue(start_unix, end_unix)
  660. CreateRepoCountMap := queryUserCreateRepo(start_unix, end_unix)
  661. LoginCountMap := queryLoginCount(start_unix, end_unix)
  662. OpenIIndexMap := queryUserRepoOpenIIndex(start_unix, end_unix)
  663. CloudBrainTaskMap, CloudBrainTaskItemMap := queryCloudBrainTask(start_unix, end_unix)
  664. AiModelManageMap := queryUserModel(start_unix, end_unix)
  665. CollectDataset, CollectedDataset := queryDatasetStars(start_unix, end_unix)
  666. RecommendDataset := queryRecommedDataSet(start_unix, end_unix)
  667. CollectImage, CollectedImage := queryImageStars(start_unix, end_unix)
  668. RecommendImage := queryRecommedImage(start_unix, end_unix)
  669. statictisSess := xStatistic.NewSession()
  670. defer statictisSess.Close()
  671. cond := "type != 1"
  672. count, err := sess.Where(cond).Count(new(User))
  673. if err != nil {
  674. log.Info("query user error. return.")
  675. return err
  676. }
  677. userNewAddActivity := make(map[int64]map[int64]int64)
  678. ParaWeight := getParaWeight()
  679. userMetrics := make(map[string]int)
  680. var indexTotal int64
  681. indexTotal = 0
  682. for {
  683. sess.Select("`user`.*").Table("user").Where(cond).OrderBy("id asc").Limit(PAGE_SIZE, int(indexTotal))
  684. userList := make([]*User, 0)
  685. sess.Find(&userList)
  686. for i, userRecord := range userList {
  687. var dateRecord UserBusinessAnalysis
  688. dateRecord.ID = userRecord.ID
  689. log.Info("i=" + fmt.Sprint(i) + " userName=" + userRecord.Name)
  690. dateRecord.CountDate = CountDate.Unix()
  691. dateRecord.Email = userRecord.Email
  692. dateRecord.RegistDate = userRecord.CreatedUnix
  693. dateRecord.Name = userRecord.Name
  694. dateRecord.GiteaAgeMonth = subMonth(currentTimeNow, userRecord.CreatedUnix.AsTime())
  695. dateRecord.DataDate = DataDate
  696. dateRecord.CodeMergeCount = getMapValue(dateRecord.ID, CodeMergeCountMap)
  697. dateRecord.CommitCount = getMapValue(dateRecord.ID, CommitCountMap)
  698. dateRecord.IssueCount = getMapValue(dateRecord.ID, IssueCountMap)
  699. dateRecord.CommentCount = getMapValue(dateRecord.ID, CommentCountMap)
  700. dateRecord.FocusRepoCount = getMapValue(dateRecord.ID, FocusRepoCountMap)
  701. dateRecord.StarRepoCount = getMapValue(dateRecord.ID, StarRepoCountMap)
  702. dateRecord.WatchedCount = getMapValue(dateRecord.ID, WatchedCountMap)
  703. dateRecord.FocusOtherUser = getMapValue(dateRecord.ID, WatchOtherMap)
  704. if _, ok := CommitCodeSizeMap[dateRecord.Email]; !ok {
  705. dateRecord.CommitCodeSize = 0
  706. } else {
  707. dateRecord.CommitCodeSize = int(CommitCodeSizeMap[dateRecord.Email].CommitLines)
  708. }
  709. dateRecord.CommitDatasetSize = getMapValue(dateRecord.ID, CommitDatasetSizeMap)
  710. dateRecord.CommitDatasetNum = getMapValue(dateRecord.ID, CommitDatasetNumMap)
  711. dateRecord.SolveIssueCount = getMapValue(dateRecord.ID, SolveIssueCountMap)
  712. dateRecord.EncyclopediasCount = getMapKeyStringValue(dateRecord.Name, wikiCountMap)
  713. dateRecord.CreateRepoCount = getMapValue(dateRecord.ID, CreateRepoCountMap)
  714. dateRecord.LoginCount = getMapValue(dateRecord.ID, LoginCountMap)
  715. if _, ok := OpenIIndexMap[dateRecord.ID]; !ok {
  716. dateRecord.OpenIIndex = 0
  717. } else {
  718. dateRecord.OpenIIndex = OpenIIndexMap[dateRecord.ID]
  719. }
  720. dateRecord.CloudBrainTaskNum = getMapValue(dateRecord.ID, CloudBrainTaskMap)
  721. dateRecord.GpuDebugJob = getMapKeyStringValue(fmt.Sprint(dateRecord.ID)+"_GpuDebugJob", CloudBrainTaskItemMap)
  722. dateRecord.NpuDebugJob = getMapKeyStringValue(fmt.Sprint(dateRecord.ID)+"_NpuDebugJob", CloudBrainTaskItemMap)
  723. dateRecord.GpuTrainJob = getMapKeyStringValue(fmt.Sprint(dateRecord.ID)+"_GpuTrainJob", CloudBrainTaskItemMap)
  724. dateRecord.NpuTrainJob = getMapKeyStringValue(fmt.Sprint(dateRecord.ID)+"_NpuTrainJob", CloudBrainTaskItemMap)
  725. dateRecord.NpuInferenceJob = getMapKeyStringValue(fmt.Sprint(dateRecord.ID)+"_NpuInferenceJob", CloudBrainTaskItemMap)
  726. dateRecord.GpuBenchMarkJob = getMapKeyStringValue(fmt.Sprint(dateRecord.ID)+"_GpuBenchMarkJob", CloudBrainTaskItemMap)
  727. dateRecord.CloudBrainRunTime = getMapKeyStringValue(fmt.Sprint(dateRecord.ID)+"_CloudBrainRunTime", CloudBrainTaskItemMap)
  728. dateRecord.CommitModelCount = getMapValue(dateRecord.ID, AiModelManageMap)
  729. dateRecord.CollectDataset = getMapValue(dateRecord.ID, CollectDataset)
  730. dateRecord.CollectedDataset = getMapValue(dateRecord.ID, CollectedDataset)
  731. dateRecord.RecommendDataset = getMapValue(dateRecord.ID, RecommendDataset)
  732. dateRecord.CollectImage = getMapValue(dateRecord.ID, CollectImage)
  733. dateRecord.CollectedImage = getMapValue(dateRecord.ID, CollectedImage)
  734. dateRecord.RecommendImage = getMapValue(dateRecord.ID, RecommendImage)
  735. dateRecord.UserIndexPrimitive = getUserIndex(dateRecord, ParaWeight)
  736. setUserMetrics(userMetrics, userRecord, start_unix, end_unix, dateRecord)
  737. if getUserActivate(dateRecord) > 0 {
  738. log.Info("has activity." + userRecord.Name)
  739. addUserToMap(userNewAddActivity, userRecord.CreatedUnix, dateRecord.ID)
  740. }
  741. if userRecord.IsActive {
  742. continue
  743. }
  744. statictisSess.Delete(&dateRecord)
  745. _, err = statictisSess.Insert(&dateRecord)
  746. if err != nil {
  747. log.Info("insert daterecord failed." + err.Error())
  748. return err
  749. }
  750. }
  751. indexTotal += PAGE_SIZE
  752. if indexTotal >= count {
  753. break
  754. }
  755. }
  756. RefreshUserStaticAllTabel(wikiCountMap, userMetrics)
  757. //insert userMetrics table
  758. var useMetrics UserMetrics
  759. useMetrics.CountDate = CountDate.Unix()
  760. statictisSess.Delete(&useMetrics)
  761. useMetrics.DataDate = DataDate
  762. useMetrics.ActivateRegistUser = getMapKeyStringValue("ActivateRegistUser", userMetrics)
  763. useMetrics.HasActivityUser = getMapKeyStringValue("HasActivityUser", userMetrics)
  764. useMetrics.RegistActivityUser = 0
  765. useMetrics.NotActivateRegistUser = getMapKeyStringValue("NotActivateRegistUser", userMetrics)
  766. useMetrics.TotalActivateRegistUser = getMapKeyStringValue("TotalActivateRegistUser", userMetrics)
  767. useMetrics.TotalHasActivityUser = getMapKeyStringValue("TotalHasActivityUser", userMetrics)
  768. count, err = sess.Where("type=0").Count(new(User))
  769. if err != nil {
  770. log.Info("query user error. return.")
  771. }
  772. useMetrics.TotalUser = int(count)
  773. if useMetrics.ActivateRegistUser+useMetrics.NotActivateRegistUser == 0 {
  774. useMetrics.ActivateIndex = 0
  775. } else {
  776. useMetrics.ActivateIndex = float64(useMetrics.ActivateRegistUser) / float64(useMetrics.ActivateRegistUser+useMetrics.NotActivateRegistUser)
  777. }
  778. statictisSess.Insert(&useMetrics)
  779. //update new user activity
  780. updateNewUserAcitivity(userNewAddActivity, statictisSess)
  781. return nil
  782. }
  783. func updateNewUserAcitivity(currentUserActivity map[int64]map[int64]int64, statictisSess *xorm.Session) {
  784. for key, value := range currentUserActivity {
  785. useMetrics := &UserMetrics{CountDate: key}
  786. has, err := statictisSess.Get(useMetrics)
  787. if err == nil && has {
  788. userIdArrays := strings.Split(useMetrics.HasActivityUserJson, ",")
  789. for _, userIdStr := range userIdArrays {
  790. userIdInt, err := strconv.ParseInt(userIdStr, 10, 64)
  791. if err == nil {
  792. value[userIdInt] = userIdInt
  793. }
  794. }
  795. userIdArray := ""
  796. for _, tmpValue := range value {
  797. userIdArray += fmt.Sprint(tmpValue) + ","
  798. }
  799. useMetrics.HasActivityUser = len(value)
  800. if len(userIdArray) > 0 {
  801. useMetrics.HasActivityUserJson = userIdArray[0 : len(userIdArray)-1]
  802. }
  803. updateSql := "update public.user_metrics set has_activity_user_json=" + useMetrics.HasActivityUserJson + ",regist_activity_user=" + fmt.Sprint(useMetrics.HasActivityUser) + " where count_date=" + fmt.Sprint(key)
  804. statictisSess.Exec(updateSql)
  805. }
  806. }
  807. }
  808. func addUserToMap(currentUserActivity map[int64]map[int64]int64, registDate timeutil.TimeStamp, userId int64) {
  809. CountDateTime := time.Date(registDate.Year(), registDate.AsTime().Month(), registDate.AsTime().Day(), 0, 1, 0, 0, registDate.AsTime().Location())
  810. CountDate := CountDateTime.Unix()
  811. if _, ok := currentUserActivity[CountDate]; !ok {
  812. userIdMap := make(map[int64]int64, 0)
  813. userIdMap[userId] = userId
  814. currentUserActivity[CountDate] = userIdMap
  815. } else {
  816. currentUserActivity[CountDate][userId] = userId
  817. }
  818. }
  819. func setUserMetrics(userMetrics map[string]int, user *User, start_time int64, end_time int64, dateRecord UserBusinessAnalysis) {
  820. //ActivateRegistUser int `xorm:"NOT NULL DEFAULT 0"`
  821. //NotActivateRegistUser int `xorm:"NOT NULL DEFAULT 0"`
  822. //HasActivityUser int `xorm:"NOT NULL DEFAULT 0"`
  823. //TotalActivateRegistUser int `xorm:"NOT NULL DEFAULT 0"`
  824. //TotalHasActivityUser
  825. regist_time := user.CreatedUnix.AsTime().Unix()
  826. if regist_time >= start_time && regist_time <= end_time {
  827. if user.IsActive {
  828. userMetrics["ActivateRegistUser"] = getMapKeyStringValue("ActivateRegistUser", userMetrics) + 1
  829. } else {
  830. userMetrics["NotActivateRegistUser"] = getMapKeyStringValue("NotActivateRegistUser", userMetrics) + 1
  831. }
  832. }
  833. if user.IsActive {
  834. userMetrics["TotalActivateRegistUser"] = getMapKeyStringValue("TotalActivateRegistUser", userMetrics) + 1
  835. }
  836. if getUserActivate(dateRecord) > 0 {
  837. userMetrics["HasActivityUser"] = getMapKeyStringValue("HasActivityUser", userMetrics) + 1
  838. }
  839. }
  840. func getParaWeight() map[string]float64 {
  841. result := make(map[string]float64)
  842. statictisSess := xStatistic.NewSession()
  843. defer statictisSess.Close()
  844. statictisSess.Select("*").Table(new(UserAnalysisPara))
  845. paraList := make([]*UserAnalysisPara, 0)
  846. statictisSess.Find(&paraList)
  847. for _, paraRecord := range paraList {
  848. result[paraRecord.Key] = paraRecord.Value
  849. }
  850. return result
  851. }
  852. func getUserIndexFromAnalysisAll(dateRecord UserBusinessAnalysisAll, ParaWeight map[string]float64) float64 {
  853. var result float64
  854. // PR数 0.20
  855. // commit数 0.20
  856. // 提出任务数 0.20
  857. // 评论数 0.20
  858. // 关注项目数 0.10
  859. // 点赞项目数 0.10
  860. // 登录次数 0.10
  861. result = float64(dateRecord.CodeMergeCount) * getParaWeightValue("CodeMergeCount", ParaWeight, 0.2)
  862. result += float64(dateRecord.CommitCount) * getParaWeightValue("CommitCount", ParaWeight, 0.2)
  863. log.Info("1 result=" + fmt.Sprint(result))
  864. result += float64(dateRecord.IssueCount) * getParaWeightValue("IssueCount", ParaWeight, 0.2)
  865. result += float64(dateRecord.CommentCount) * getParaWeightValue("CommentCount", ParaWeight, 0.2)
  866. result += float64(dateRecord.FocusRepoCount) * getParaWeightValue("FocusRepoCount", ParaWeight, 0.1)
  867. result += float64(dateRecord.StarRepoCount) * getParaWeightValue("StarRepoCount", ParaWeight, 0.1)
  868. result += float64(dateRecord.LoginCount) * getParaWeightValue("LoginCount", ParaWeight, 0.1)
  869. result += float64(dateRecord.WatchedCount) * getParaWeightValue("WatchedCount", ParaWeight, 0.3)
  870. codeLine := float64(dateRecord.CommitCodeSize)
  871. limitCodeLine := getParaWeightValue("LimitCommitCodeSize", ParaWeight, 1000)
  872. if codeLine >= limitCodeLine {
  873. codeLine = limitCodeLine
  874. }
  875. result += codeLine * getParaWeightValue("CommitCodeSize", ParaWeight, 0.01)
  876. result += float64(dateRecord.SolveIssueCount) * getParaWeightValue("SolveIssueCount", ParaWeight, 0.2)
  877. result += float64(dateRecord.EncyclopediasCount) * getParaWeightValue("EncyclopediasCount", ParaWeight, 0.1)
  878. result += float64(dateRecord.CreateRepoCount) * getParaWeightValue("CreateRepoCount", ParaWeight, 0.05)
  879. result += float64(dateRecord.CloudBrainTaskNum) * getParaWeightValue("CloudBrainTaskNum", ParaWeight, 0.3)
  880. result += float64(dateRecord.CommitModelCount) * getParaWeightValue("CommitModelCount", ParaWeight, 0.2)
  881. result += dateRecord.OpenIIndex * getParaWeightValue("OpenIIndex", ParaWeight, 0.1)
  882. result += float64(dateRecord.CollectDataset) * getParaWeightValue("CollectDataset", ParaWeight, 0.1)
  883. result += float64(dateRecord.CollectedDataset) * getParaWeightValue("CollectedDataset", ParaWeight, 0.1)
  884. result += float64(dateRecord.RecommendDataset) * getParaWeightValue("RecommendDataset", ParaWeight, 0.2)
  885. result += float64(dateRecord.CollectImage) * getParaWeightValue("CollectImage", ParaWeight, 0.1)
  886. result += float64(dateRecord.CollectedImage) * getParaWeightValue("CollectedImage", ParaWeight, 0.1)
  887. result += float64(dateRecord.RecommendImage) * getParaWeightValue("RecommendImage", ParaWeight, 0.2)
  888. return result
  889. }
  890. func getUserActivateAll(dateRecord UserBusinessAnalysisAll) int {
  891. var result int
  892. result += dateRecord.CodeMergeCount
  893. result += dateRecord.CommitCount
  894. result += dateRecord.IssueCount
  895. result += dateRecord.CommentCount
  896. result += dateRecord.FocusRepoCount
  897. result += dateRecord.StarRepoCount
  898. result += dateRecord.SolveIssueCount
  899. result += dateRecord.EncyclopediasCount
  900. result += dateRecord.CreateRepoCount
  901. result += dateRecord.CloudBrainTaskNum
  902. result += dateRecord.CommitModelCount
  903. result += dateRecord.CommitDatasetNum
  904. result += dateRecord.FocusOtherUser
  905. result += dateRecord.CollectDataset
  906. result += dateRecord.CollectImage
  907. result += dateRecord.CommitCodeSize
  908. return result
  909. }
  910. func getUserActivate(dateRecord UserBusinessAnalysis) int {
  911. var result int
  912. result += dateRecord.CodeMergeCount
  913. result += dateRecord.CommitCount
  914. result += dateRecord.IssueCount
  915. result += dateRecord.CommentCount
  916. result += dateRecord.FocusRepoCount
  917. result += dateRecord.StarRepoCount
  918. result += dateRecord.SolveIssueCount
  919. result += dateRecord.EncyclopediasCount
  920. result += dateRecord.CreateRepoCount
  921. result += dateRecord.CloudBrainTaskNum
  922. result += dateRecord.CommitModelCount
  923. result += dateRecord.CommitDatasetNum
  924. result += dateRecord.FocusOtherUser
  925. result += dateRecord.CollectDataset
  926. result += dateRecord.CollectImage
  927. result += dateRecord.CommitCodeSize
  928. return result
  929. }
  930. func getUserIndex(dateRecord UserBusinessAnalysis, ParaWeight map[string]float64) float64 {
  931. var result float64
  932. // PR数 0.20
  933. // commit数 0.20
  934. // 提出任务数 0.20
  935. // 评论数 0.20
  936. // 关注项目数 0.10
  937. // 点赞项目数 0.10
  938. // 登录次数 0.10
  939. result = float64(dateRecord.CodeMergeCount) * getParaWeightValue("CodeMergeCount", ParaWeight, 0.2)
  940. result += float64(dateRecord.CommitCount) * getParaWeightValue("CommitCount", ParaWeight, 0.2)
  941. log.Info("2 result=" + fmt.Sprint(result))
  942. result += float64(dateRecord.IssueCount) * getParaWeightValue("IssueCount", ParaWeight, 0.2)
  943. result += float64(dateRecord.CommentCount) * getParaWeightValue("CommentCount", ParaWeight, 0.2)
  944. result += float64(dateRecord.FocusRepoCount) * getParaWeightValue("FocusRepoCount", ParaWeight, 0.1)
  945. result += float64(dateRecord.StarRepoCount) * getParaWeightValue("StarRepoCount", ParaWeight, 0.1)
  946. result += float64(dateRecord.LoginCount) * getParaWeightValue("LoginCount", ParaWeight, 0.1)
  947. result += float64(dateRecord.WatchedCount) * getParaWeightValue("WatchedCount", ParaWeight, 0.3)
  948. codeLine := float64(dateRecord.CommitCodeSize)
  949. limitCodeLine := getParaWeightValue("LimitCommitCodeSize", ParaWeight, 1000)
  950. if codeLine >= limitCodeLine {
  951. codeLine = limitCodeLine
  952. }
  953. result += codeLine * getParaWeightValue("CommitCodeSize", ParaWeight, 0.01)
  954. result += float64(dateRecord.SolveIssueCount) * getParaWeightValue("SolveIssueCount", ParaWeight, 0.2)
  955. result += float64(dateRecord.EncyclopediasCount) * getParaWeightValue("EncyclopediasCount", ParaWeight, 0.1)
  956. result += float64(dateRecord.CreateRepoCount) * getParaWeightValue("CreateRepoCount", ParaWeight, 0.05)
  957. result += float64(dateRecord.CloudBrainTaskNum) * getParaWeightValue("CloudBrainTaskNum", ParaWeight, 0.3)
  958. result += float64(dateRecord.CommitModelCount) * getParaWeightValue("CommitModelCount", ParaWeight, 0.2)
  959. result += dateRecord.OpenIIndex * getParaWeightValue("OpenIIndex", ParaWeight, 0.1)
  960. result += float64(dateRecord.CollectDataset) * getParaWeightValue("CollectDataset", ParaWeight, 0.1)
  961. result += float64(dateRecord.CollectedDataset) * getParaWeightValue("CollectedDataset", ParaWeight, 0.1)
  962. result += float64(dateRecord.RecommendDataset) * getParaWeightValue("RecommendDataset", ParaWeight, 0.2)
  963. result += float64(dateRecord.CollectImage) * getParaWeightValue("CollectImage", ParaWeight, 0.1)
  964. result += float64(dateRecord.CollectedImage) * getParaWeightValue("CollectedImage", ParaWeight, 0.1)
  965. result += float64(dateRecord.RecommendImage) * getParaWeightValue("RecommendImage", ParaWeight, 0.2)
  966. return result
  967. }
  968. func getParaWeightValue(key string, valueMap map[string]float64, defaultValue float64) float64 {
  969. if _, ok := valueMap[key]; !ok {
  970. return defaultValue
  971. } else {
  972. return valueMap[key]
  973. }
  974. }
  975. func getMapKeyStringValue(key string, valueMap map[string]int) int {
  976. if _, ok := valueMap[key]; !ok {
  977. return 0
  978. } else {
  979. return valueMap[key]
  980. }
  981. }
  982. func getMapValue(userId int64, valueMap map[int64]int) int {
  983. if _, ok := valueMap[userId]; !ok {
  984. return 0
  985. } else {
  986. return valueMap[userId]
  987. }
  988. }
  989. func getInt(str string) int {
  990. re, err := strconv.ParseInt(str, 10, 32)
  991. if err != nil {
  992. return 0
  993. }
  994. return int(re)
  995. }
  996. func CounDataByDate(wikiCountMap map[string]int, startTime time.Time, endTime time.Time) {
  997. CounDataByDateAndReCount(wikiCountMap, startTime, endTime, false)
  998. }
  999. func querySolveIssue(start_unix int64, end_unix int64) map[int64]int {
  1000. sess := x.NewSession()
  1001. defer sess.Close()
  1002. resultMap := make(map[int64]int)
  1003. cond := "issue.is_closed=true and issue.closed_unix>=" + fmt.Sprint(start_unix) + " and issue.closed_unix<=" + fmt.Sprint(end_unix)
  1004. count, err := sess.Table("issue_assignees").Join("inner", "issue", "issue.id=issue_assignees.issue_id").Where(cond).Count(new(IssueAssignees))
  1005. if err != nil {
  1006. log.Info("query issue error. return.")
  1007. return resultMap
  1008. }
  1009. var indexTotal int64
  1010. indexTotal = 0
  1011. for {
  1012. issueAssigneesList := make([]*IssueAssignees, 0)
  1013. sess.Select("issue_assignees.*").Table("issue_assignees").
  1014. Join("inner", "issue", "issue.id=issue_assignees.issue_id").
  1015. Where(cond).OrderBy("issue_assignees.id asc").Limit(PAGE_SIZE, int(indexTotal))
  1016. sess.Find(&issueAssigneesList)
  1017. log.Info("query IssueAssignees size=" + fmt.Sprint(len(issueAssigneesList)))
  1018. for _, issueAssigneesRecord := range issueAssigneesList {
  1019. if _, ok := resultMap[issueAssigneesRecord.AssigneeID]; !ok {
  1020. resultMap[issueAssigneesRecord.AssigneeID] = 1
  1021. } else {
  1022. resultMap[issueAssigneesRecord.AssigneeID] += 1
  1023. }
  1024. }
  1025. indexTotal += PAGE_SIZE
  1026. if indexTotal >= count {
  1027. break
  1028. }
  1029. }
  1030. return resultMap
  1031. }
  1032. func queryPullRequest(start_unix int64, end_unix int64) map[int64]int {
  1033. sess := x.NewSession()
  1034. defer sess.Close()
  1035. resultMap := make(map[int64]int)
  1036. cond := "pull_request.merged_unix>=" + fmt.Sprint(start_unix) + " and pull_request.merged_unix<=" + fmt.Sprint(end_unix)
  1037. count, err := sess.Table("issue").Join("inner", "pull_request", "issue.id=pull_request.issue_id").Where(cond).Count(new(Issue))
  1038. if err != nil {
  1039. log.Info("query issue error. return.")
  1040. return resultMap
  1041. }
  1042. var indexTotal int64
  1043. indexTotal = 0
  1044. for {
  1045. issueList := make([]*Issue, 0)
  1046. 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))
  1047. sess.Find(&issueList)
  1048. log.Info("query issue(PR) size=" + fmt.Sprint(len(issueList)))
  1049. for _, issueRecord := range issueList {
  1050. if _, ok := resultMap[issueRecord.PosterID]; !ok {
  1051. resultMap[issueRecord.PosterID] = 1
  1052. } else {
  1053. resultMap[issueRecord.PosterID] += 1
  1054. }
  1055. }
  1056. indexTotal += PAGE_SIZE
  1057. if indexTotal >= count {
  1058. break
  1059. }
  1060. }
  1061. return resultMap
  1062. }
  1063. func queryCommitAction(start_unix int64, end_unix int64, actionType int64) map[int64]int {
  1064. sess := x.NewSession()
  1065. defer sess.Close()
  1066. resultMap := make(map[int64]int)
  1067. 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)
  1068. count, err := sess.Where(cond).Count(new(Action))
  1069. if err != nil {
  1070. log.Info("query action error. return.")
  1071. return resultMap
  1072. }
  1073. var indexTotal int64
  1074. indexTotal = 0
  1075. for {
  1076. sess.Select("id,user_id,op_type,act_user_id").Table("action").Where(cond).OrderBy("id asc").Limit(PAGE_SIZE, int(indexTotal))
  1077. actionList := make([]*Action, 0)
  1078. sess.Find(&actionList)
  1079. log.Info("query action size=" + fmt.Sprint(len(actionList)))
  1080. for _, actionRecord := range actionList {
  1081. if _, ok := resultMap[actionRecord.UserID]; !ok {
  1082. resultMap[actionRecord.UserID] = 1
  1083. } else {
  1084. resultMap[actionRecord.UserID] += 1
  1085. }
  1086. }
  1087. indexTotal += PAGE_SIZE
  1088. if indexTotal >= count {
  1089. break
  1090. }
  1091. }
  1092. return resultMap
  1093. }
  1094. func queryCreateIssue(start_unix int64, end_unix int64) map[int64]int {
  1095. sess := x.NewSession()
  1096. defer sess.Close()
  1097. resultMap := make(map[int64]int)
  1098. cond := "is_pull=false and created_unix>=" + fmt.Sprint(start_unix) + " and created_unix<=" + fmt.Sprint(end_unix)
  1099. count, err := sess.Where(cond).Count(new(Issue))
  1100. if err != nil {
  1101. log.Info("query Issue error. return.")
  1102. return resultMap
  1103. }
  1104. var indexTotal int64
  1105. indexTotal = 0
  1106. for {
  1107. sess.Select("id,poster_id").Table("issue").Where(cond).OrderBy("id asc").Limit(PAGE_SIZE, int(indexTotal))
  1108. issueList := make([]*Issue, 0)
  1109. sess.Find(&issueList)
  1110. log.Info("query issue size=" + fmt.Sprint(len(issueList)))
  1111. for _, issueRecord := range issueList {
  1112. if _, ok := resultMap[issueRecord.PosterID]; !ok {
  1113. resultMap[issueRecord.PosterID] = 1
  1114. } else {
  1115. resultMap[issueRecord.PosterID] += 1
  1116. }
  1117. }
  1118. indexTotal += PAGE_SIZE
  1119. if indexTotal >= count {
  1120. break
  1121. }
  1122. }
  1123. return resultMap
  1124. }
  1125. func queryComment(start_unix int64, end_unix int64) map[int64]int {
  1126. sess := x.NewSession()
  1127. defer sess.Close()
  1128. cond := "created_unix>=" + fmt.Sprint(start_unix) + " and created_unix<=" + fmt.Sprint(end_unix)
  1129. resultMap := make(map[int64]int)
  1130. count, err := sess.Where(cond).Count(new(Comment))
  1131. if err != nil {
  1132. log.Info("query Comment error. return.")
  1133. return resultMap
  1134. }
  1135. var indexTotal int64
  1136. indexTotal = 0
  1137. for {
  1138. sess.Select("id,type,poster_id").Table("comment").Where(cond).OrderBy("id asc").Limit(PAGE_SIZE, int(indexTotal))
  1139. commentList := make([]*Comment, 0)
  1140. sess.Find(&commentList)
  1141. log.Info("query Comment size=" + fmt.Sprint(len(commentList)))
  1142. for _, commentRecord := range commentList {
  1143. if _, ok := resultMap[commentRecord.PosterID]; !ok {
  1144. resultMap[commentRecord.PosterID] = 1
  1145. } else {
  1146. resultMap[commentRecord.PosterID] += 1
  1147. }
  1148. }
  1149. indexTotal += PAGE_SIZE
  1150. if indexTotal >= count {
  1151. break
  1152. }
  1153. }
  1154. return resultMap
  1155. }
  1156. func queryWatch(start_unix int64, end_unix int64) map[int64]int {
  1157. sess := x.NewSession()
  1158. defer sess.Close()
  1159. cond := " created_unix>=" + fmt.Sprint(start_unix) + " and created_unix<=" + fmt.Sprint(end_unix)
  1160. resultMap := make(map[int64]int)
  1161. count, err := sess.Where(cond).Count(new(Watch))
  1162. if err != nil {
  1163. log.Info("query issue error. return.")
  1164. return resultMap
  1165. }
  1166. var indexTotal int64
  1167. indexTotal = 0
  1168. for {
  1169. watchList := make([]*Watch, 0)
  1170. sess.Select("id,user_id,repo_id").Table("watch").Where(cond).OrderBy("id asc").Limit(PAGE_SIZE, int(indexTotal))
  1171. sess.Find(&watchList)
  1172. log.Info("query Watch size=" + fmt.Sprint(len(watchList)))
  1173. for _, watchRecord := range watchList {
  1174. if _, ok := resultMap[watchRecord.UserID]; !ok {
  1175. resultMap[watchRecord.UserID] = 1
  1176. } else {
  1177. resultMap[watchRecord.UserID] += 1
  1178. }
  1179. }
  1180. indexTotal += PAGE_SIZE
  1181. if indexTotal >= count {
  1182. break
  1183. }
  1184. }
  1185. return resultMap
  1186. }
  1187. func queryStar(start_unix int64, end_unix int64) map[int64]int {
  1188. sess := x.NewSession()
  1189. defer sess.Close()
  1190. cond := " created_unix>=" + fmt.Sprint(start_unix) + " and created_unix<=" + fmt.Sprint(end_unix)
  1191. resultMap := make(map[int64]int)
  1192. count, err := sess.Where(cond).Count(new(Star))
  1193. if err != nil {
  1194. log.Info("query star error. return.")
  1195. return resultMap
  1196. }
  1197. var indexTotal int64
  1198. indexTotal = 0
  1199. for {
  1200. sess.Select("id,uid,repo_id").Table("star").Where(cond).OrderBy("id asc").Limit(PAGE_SIZE, int(indexTotal))
  1201. starList := make([]*Star, 0)
  1202. sess.Find(&starList)
  1203. log.Info("query Star size=" + fmt.Sprint(len(starList)))
  1204. for _, starRecord := range starList {
  1205. if _, ok := resultMap[starRecord.UID]; !ok {
  1206. resultMap[starRecord.UID] = 1
  1207. } else {
  1208. resultMap[starRecord.UID] += 1
  1209. }
  1210. }
  1211. indexTotal += PAGE_SIZE
  1212. if indexTotal >= count {
  1213. break
  1214. }
  1215. }
  1216. return resultMap
  1217. }
  1218. func queryFollow(start_unix int64, end_unix int64) (map[int64]int, map[int64]int) {
  1219. sess := x.NewSession()
  1220. defer sess.Close()
  1221. resultMap := make(map[int64]int)
  1222. resultFocusedByOtherMap := make(map[int64]int)
  1223. cond := " created_unix>=" + fmt.Sprint(start_unix) + " and created_unix<=" + fmt.Sprint(end_unix)
  1224. count, err := sess.Where(cond).Count(new(Follow))
  1225. if err != nil {
  1226. log.Info("query follow error. return.")
  1227. return resultMap, resultFocusedByOtherMap
  1228. }
  1229. var indexTotal int64
  1230. indexTotal = 0
  1231. for {
  1232. sess.Select("id,user_id,follow_id").Table("follow").Where(cond).OrderBy("id asc").Limit(PAGE_SIZE, int(indexTotal))
  1233. followList := make([]*Follow, 0)
  1234. sess.Find(&followList)
  1235. log.Info("query Follow size=" + fmt.Sprint(len(followList)))
  1236. for _, followRecord := range followList {
  1237. if _, ok := resultMap[followRecord.FollowID]; !ok {
  1238. resultMap[followRecord.FollowID] = 1
  1239. } else {
  1240. resultMap[followRecord.FollowID] += 1
  1241. }
  1242. if _, ok := resultFocusedByOtherMap[followRecord.UserID]; !ok {
  1243. resultFocusedByOtherMap[followRecord.UserID] = 1
  1244. } else {
  1245. resultFocusedByOtherMap[followRecord.UserID] += 1
  1246. }
  1247. }
  1248. indexTotal += PAGE_SIZE
  1249. if indexTotal >= count {
  1250. break
  1251. }
  1252. }
  1253. return resultMap, resultFocusedByOtherMap
  1254. }
  1255. func queryRecommedDataSet(start_unix int64, end_unix int64) map[int64]int {
  1256. sess := x.NewSession()
  1257. defer sess.Close()
  1258. userIdDdatasetMap := make(map[int64]int)
  1259. cond := " created_unix>=" + fmt.Sprint(start_unix) + " and created_unix<=" + fmt.Sprint(end_unix) + " and recommend=true"
  1260. count, err := sess.Where(cond).Count(new(Dataset))
  1261. if err != nil {
  1262. log.Info("query recommend dataset error. return.")
  1263. return userIdDdatasetMap
  1264. }
  1265. var indexTotal int64
  1266. indexTotal = 0
  1267. for {
  1268. sess.Select("id,user_id,recommend").Where(cond).Table(new(Dataset)).OrderBy("id asc").Limit(PAGE_SIZE, int(indexTotal))
  1269. datasetList := make([]*Dataset, 0)
  1270. sess.Find(&datasetList)
  1271. log.Info("query datasetList size=" + fmt.Sprint(len(datasetList)))
  1272. for _, datasetRecord := range datasetList {
  1273. if _, ok := userIdDdatasetMap[datasetRecord.UserID]; !ok {
  1274. userIdDdatasetMap[datasetRecord.UserID] = 1
  1275. } else {
  1276. userIdDdatasetMap[datasetRecord.UserID] += 1
  1277. }
  1278. }
  1279. indexTotal += PAGE_SIZE
  1280. if indexTotal >= count {
  1281. break
  1282. }
  1283. }
  1284. return userIdDdatasetMap
  1285. }
  1286. func queryAllDataSet() (map[int64]int64, map[int64]int64) {
  1287. sess := x.NewSession()
  1288. defer sess.Close()
  1289. datasetUserIdMap := make(map[int64]int64)
  1290. userIdDdatasetMap := make(map[int64]int64)
  1291. count, err := sess.Count(new(Dataset))
  1292. if err != nil {
  1293. log.Info("query dataset error. return.")
  1294. return datasetUserIdMap, userIdDdatasetMap
  1295. }
  1296. var indexTotal int64
  1297. indexTotal = 0
  1298. for {
  1299. sess.Select("id,user_id").Table(new(Dataset)).OrderBy("id asc").Limit(PAGE_SIZE, int(indexTotal))
  1300. datasetList := make([]*Dataset, 0)
  1301. sess.Find(&datasetList)
  1302. log.Info("query datasetList size=" + fmt.Sprint(len(datasetList)))
  1303. for _, datasetRecord := range datasetList {
  1304. datasetUserIdMap[datasetRecord.ID] = datasetRecord.UserID
  1305. if _, ok := userIdDdatasetMap[datasetRecord.UserID]; !ok {
  1306. userIdDdatasetMap[datasetRecord.UserID] = 1
  1307. } else {
  1308. userIdDdatasetMap[datasetRecord.UserID] += 1
  1309. }
  1310. }
  1311. indexTotal += PAGE_SIZE
  1312. if indexTotal >= count {
  1313. break
  1314. }
  1315. }
  1316. return datasetUserIdMap, userIdDdatasetMap
  1317. }
  1318. func queryRecommedImage(start_unix int64, end_unix int64) map[int64]int {
  1319. sess := x.NewSession()
  1320. defer sess.Close()
  1321. userIdImageMap := make(map[int64]int)
  1322. cond := " created_unix>=" + fmt.Sprint(start_unix) + " and created_unix<=" + fmt.Sprint(end_unix) + " and type=5"
  1323. count, err := sess.Where(cond).Count(new(Image))
  1324. if err != nil {
  1325. log.Info("query recommend image error. return.")
  1326. return userIdImageMap
  1327. }
  1328. var indexTotal int64
  1329. indexTotal = 0
  1330. for {
  1331. sess.Select("id,uid,type").Where(cond).Table(new(Image)).OrderBy("id asc").Limit(PAGE_SIZE, int(indexTotal))
  1332. imageList := make([]*Image, 0)
  1333. sess.Find(&imageList)
  1334. log.Info("query imageList size=" + fmt.Sprint(len(imageList)))
  1335. for _, imageRecord := range imageList {
  1336. if _, ok := userIdImageMap[imageRecord.UID]; !ok {
  1337. userIdImageMap[imageRecord.UID] = 1
  1338. } else {
  1339. userIdImageMap[imageRecord.UID] += 1
  1340. }
  1341. }
  1342. indexTotal += PAGE_SIZE
  1343. if indexTotal >= count {
  1344. break
  1345. }
  1346. }
  1347. return userIdImageMap
  1348. }
  1349. func queryAllImage() (map[int64]int64, map[int64]int64) {
  1350. sess := x.NewSession()
  1351. defer sess.Close()
  1352. imageUserIdMap := make(map[int64]int64)
  1353. userIdDImageMap := make(map[int64]int64)
  1354. count, err := sess.Count(new(Image))
  1355. if err != nil {
  1356. log.Info("query image error. return.")
  1357. return imageUserIdMap, userIdDImageMap
  1358. }
  1359. var indexTotal int64
  1360. indexTotal = 0
  1361. for {
  1362. sess.Select("id,uid").Table(new(Image)).OrderBy("id asc").Limit(PAGE_SIZE, int(indexTotal))
  1363. imageList := make([]*Image, 0)
  1364. sess.Find(&imageList)
  1365. log.Info("query imageList size=" + fmt.Sprint(len(imageList)))
  1366. for _, imageRecord := range imageList {
  1367. imageUserIdMap[imageRecord.ID] = imageRecord.UID
  1368. if _, ok := userIdDImageMap[imageRecord.UID]; !ok {
  1369. userIdDImageMap[imageRecord.UID] = 1
  1370. } else {
  1371. userIdDImageMap[imageRecord.UID] += 1
  1372. }
  1373. }
  1374. indexTotal += PAGE_SIZE
  1375. if indexTotal >= count {
  1376. break
  1377. }
  1378. }
  1379. return imageUserIdMap, userIdDImageMap
  1380. }
  1381. func queryDatasetStars(start_unix int64, end_unix int64) (map[int64]int, map[int64]int) {
  1382. sess := x.NewSession()
  1383. defer sess.Close()
  1384. datasetCollect := make(map[int64]int)
  1385. datasetCollected := make(map[int64]int)
  1386. datasetUserIdMap, _ := queryAllDataSet()
  1387. cond := " created_unix>=" + fmt.Sprint(start_unix) + " and created_unix<=" + fmt.Sprint(end_unix)
  1388. count, err := sess.Where(cond).Count(new(DatasetStar))
  1389. if err != nil {
  1390. log.Info("query follow error. return.")
  1391. return datasetCollect, datasetCollected
  1392. }
  1393. var indexTotal int64
  1394. indexTotal = 0
  1395. for {
  1396. sess.Select("id,uid,dataset_id").Table(new(DatasetStar)).Where(cond).OrderBy("id asc").Limit(PAGE_SIZE, int(indexTotal))
  1397. datasetStarList := make([]*DatasetStar, 0)
  1398. sess.Find(&datasetStarList)
  1399. log.Info("query datasetStarList size=" + fmt.Sprint(len(datasetStarList)))
  1400. for _, datasetStarRecord := range datasetStarList {
  1401. if _, ok := datasetCollect[datasetStarRecord.UID]; !ok {
  1402. datasetCollect[datasetStarRecord.UID] = 1
  1403. } else {
  1404. datasetCollect[datasetStarRecord.UID] += 1
  1405. }
  1406. if _, ok := datasetCollected[datasetUserIdMap[datasetStarRecord.DatasetID]]; !ok {
  1407. datasetCollected[datasetUserIdMap[datasetStarRecord.DatasetID]] = 1
  1408. } else {
  1409. datasetCollected[datasetUserIdMap[datasetStarRecord.DatasetID]] += 1
  1410. }
  1411. }
  1412. indexTotal += PAGE_SIZE
  1413. if indexTotal >= count {
  1414. break
  1415. }
  1416. }
  1417. return datasetCollect, datasetCollected
  1418. }
  1419. func queryImageStars(start_unix int64, end_unix int64) (map[int64]int, map[int64]int) {
  1420. sess := x.NewSession()
  1421. defer sess.Close()
  1422. imageCollect := make(map[int64]int)
  1423. imageCollected := make(map[int64]int)
  1424. imageUserIdMap, _ := queryAllDataSet()
  1425. cond := " created_unix>=" + fmt.Sprint(start_unix) + " and created_unix<=" + fmt.Sprint(end_unix)
  1426. count, err := sess.Where(cond).Count(new(ImageStar))
  1427. if err != nil {
  1428. log.Info("query follow error. return.")
  1429. return imageCollect, imageCollected
  1430. }
  1431. var indexTotal int64
  1432. indexTotal = 0
  1433. for {
  1434. sess.Select("id,uid,dataset_id").Table(new(ImageStar)).Where(cond).OrderBy("id asc").Limit(PAGE_SIZE, int(indexTotal))
  1435. imageStarList := make([]*ImageStar, 0)
  1436. sess.Find(&imageStarList)
  1437. log.Info("query imageStarList size=" + fmt.Sprint(len(imageStarList)))
  1438. for _, imageStarRecord := range imageStarList {
  1439. if _, ok := imageCollect[imageStarRecord.UID]; !ok {
  1440. imageCollect[imageStarRecord.UID] = 1
  1441. } else {
  1442. imageCollect[imageStarRecord.UID] += 1
  1443. }
  1444. if _, ok := imageCollected[imageUserIdMap[imageStarRecord.ImageID]]; !ok {
  1445. imageCollected[imageUserIdMap[imageStarRecord.ImageID]] = 1
  1446. } else {
  1447. imageCollected[imageUserIdMap[imageStarRecord.ImageID]] += 1
  1448. }
  1449. }
  1450. indexTotal += PAGE_SIZE
  1451. if indexTotal >= count {
  1452. break
  1453. }
  1454. }
  1455. return imageCollect, imageCollected
  1456. }
  1457. func queryDatasetSize(start_unix int64, end_unix int64) (map[int64]int, map[int64]int) {
  1458. sess := x.NewSession()
  1459. defer sess.Close()
  1460. resultSizeMap := make(map[int64]int)
  1461. resultNumMap := make(map[int64]int)
  1462. cond := " created_unix>=" + fmt.Sprint(start_unix) + " and created_unix<=" + fmt.Sprint(end_unix)
  1463. count, err := sess.Where(cond).Count(new(Attachment))
  1464. if err != nil {
  1465. log.Info("query attachment error. return.")
  1466. return resultSizeMap, resultNumMap
  1467. }
  1468. var indexTotal int64
  1469. indexTotal = 0
  1470. for {
  1471. sess.Select("id,uploader_id,size").Table("attachment").Where(cond).OrderBy("id asc").Limit(PAGE_SIZE, int(indexTotal))
  1472. attachmentList := make([]*Attachment, 0)
  1473. sess.Find(&attachmentList)
  1474. log.Info("query Attachment size=" + fmt.Sprint(len(attachmentList)))
  1475. for _, attachRecord := range attachmentList {
  1476. if _, ok := resultSizeMap[attachRecord.UploaderID]; !ok {
  1477. resultSizeMap[attachRecord.UploaderID] = int(attachRecord.Size / (1024 * 1024)) //MB
  1478. resultNumMap[attachRecord.UploaderID] = 1
  1479. } else {
  1480. resultSizeMap[attachRecord.UploaderID] += int(attachRecord.Size / (1024 * 1024)) //MB
  1481. resultNumMap[attachRecord.UploaderID] += 1
  1482. }
  1483. }
  1484. indexTotal += PAGE_SIZE
  1485. if indexTotal >= count {
  1486. break
  1487. }
  1488. }
  1489. return resultSizeMap, resultNumMap
  1490. }
  1491. func queryUserCreateRepo(start_unix int64, end_unix int64) map[int64]int {
  1492. sess := x.NewSession()
  1493. defer sess.Close()
  1494. resultMap := make(map[int64]int)
  1495. cond := "is_fork=false and created_unix>=" + fmt.Sprint(start_unix) + " and created_unix<=" + fmt.Sprint(end_unix)
  1496. count, err := sess.Where(cond).Count(new(Repository))
  1497. if err != nil {
  1498. log.Info("query Repository error. return.")
  1499. return resultMap
  1500. }
  1501. var indexTotal int64
  1502. indexTotal = 0
  1503. for {
  1504. sess.Select("id,owner_id,name").Table("repository").Where(cond).OrderBy("id asc").Limit(PAGE_SIZE, int(indexTotal))
  1505. repoList := make([]*Repository, 0)
  1506. sess.Find(&repoList)
  1507. log.Info("query Repository size=" + fmt.Sprint(len(repoList)))
  1508. for _, repoRecord := range repoList {
  1509. if _, ok := resultMap[repoRecord.OwnerID]; !ok {
  1510. resultMap[repoRecord.OwnerID] = 1
  1511. } else {
  1512. resultMap[repoRecord.OwnerID] += 1
  1513. }
  1514. }
  1515. indexTotal += PAGE_SIZE
  1516. if indexTotal >= count {
  1517. break
  1518. }
  1519. }
  1520. return resultMap
  1521. }
  1522. func queryUserRepoOpenIIndex(start_unix int64, end_unix int64) map[int64]float64 {
  1523. statictisSess := xStatistic.NewSession()
  1524. defer statictisSess.Close()
  1525. 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")
  1526. repoStatisticList := make([]*RepoStatistic, 0)
  1527. statictisSess.Find(&repoStatisticList)
  1528. repoOpenIIndexMap := make(map[int64]float64)
  1529. log.Info("query repo_statistic size=" + fmt.Sprint(len(repoStatisticList)))
  1530. for _, repoRecord := range repoStatisticList {
  1531. if _, ok := repoOpenIIndexMap[repoRecord.RepoID]; !ok {
  1532. repoOpenIIndexMap[repoRecord.RepoID] = repoRecord.RadarTotal
  1533. }
  1534. }
  1535. sess := x.NewSession()
  1536. defer sess.Close()
  1537. sess.Select("id,owner_id,name").Table("repository").Where("is_fork=false")
  1538. repoList := make([]*Repository, 0)
  1539. sess.Find(&repoList)
  1540. userMap := make(map[int64]float64)
  1541. log.Info("query Repository size=" + fmt.Sprint(len(repoList)))
  1542. for _, repoRecord := range repoList {
  1543. if _, ok := userMap[repoRecord.OwnerID]; !ok {
  1544. if _, ok := repoOpenIIndexMap[repoRecord.ID]; ok {
  1545. userMap[repoRecord.OwnerID] = repoOpenIIndexMap[repoRecord.ID]
  1546. }
  1547. }
  1548. }
  1549. //query collaboration
  1550. sess.Select("repo_id,user_id,mode").Table("collaboration")
  1551. collaborationList := make([]*Collaboration, 0)
  1552. sess.Find(&collaborationList)
  1553. log.Info("query collaborationList size=" + fmt.Sprint(len(collaborationList)))
  1554. for _, collaborationRecord := range collaborationList {
  1555. if _, ok := userMap[collaborationRecord.UserID]; !ok {
  1556. if _, ok := repoOpenIIndexMap[collaborationRecord.RepoID]; ok {
  1557. userMap[collaborationRecord.UserID] = repoOpenIIndexMap[collaborationRecord.RepoID]
  1558. }
  1559. } else {
  1560. if _, ok := repoOpenIIndexMap[collaborationRecord.RepoID]; ok {
  1561. userMap[collaborationRecord.UserID] += repoOpenIIndexMap[collaborationRecord.RepoID]
  1562. }
  1563. }
  1564. }
  1565. log.Info("user openi index size=" + fmt.Sprint(len(userMap)))
  1566. return userMap
  1567. }
  1568. func queryLoginCount(start_unix int64, end_unix int64) map[int64]int {
  1569. statictisSess := xStatistic.NewSession()
  1570. defer statictisSess.Close()
  1571. resultMap := make(map[int64]int)
  1572. cond := "created_unix>=" + fmt.Sprint(start_unix) + " and created_unix<=" + fmt.Sprint(end_unix)
  1573. count, err := statictisSess.Where(cond).Count(new(UserLoginLog))
  1574. if err != nil {
  1575. log.Info("query UserLoginLog error. return.")
  1576. return resultMap
  1577. }
  1578. var indexTotal int64
  1579. indexTotal = 0
  1580. for {
  1581. statictisSess.Select("id,u_id").Table("user_login_log").Where(cond).OrderBy("id asc").Limit(PAGE_SIZE, int(indexTotal))
  1582. userLoginLogList := make([]*UserLoginLog, 0)
  1583. statictisSess.Find(&userLoginLogList)
  1584. log.Info("query user login size=" + fmt.Sprint(len(userLoginLogList)))
  1585. for _, loginRecord := range userLoginLogList {
  1586. if _, ok := resultMap[loginRecord.UId]; !ok {
  1587. resultMap[loginRecord.UId] = 1
  1588. } else {
  1589. resultMap[loginRecord.UId] += 1
  1590. }
  1591. }
  1592. indexTotal += PAGE_SIZE
  1593. if indexTotal >= count {
  1594. break
  1595. }
  1596. }
  1597. log.Info("user login size=" + fmt.Sprint(len(resultMap)))
  1598. return resultMap
  1599. }
  1600. func queryCommitCodeSize(start_unix int64, end_unix int64) map[int64]int {
  1601. statictisSess := xStatistic.NewSession()
  1602. defer statictisSess.Close()
  1603. resultMap := make(map[int64]int)
  1604. cond := "count_date>=" + fmt.Sprint(start_unix) + " and count_date<=" + fmt.Sprint(end_unix)
  1605. count, err := statictisSess.Where(cond).Count(new(UserBusinessAnalysis))
  1606. if err != nil {
  1607. log.Info("query commit code size error. return.")
  1608. return resultMap
  1609. }
  1610. var indexTotal int64
  1611. indexTotal = 0
  1612. for {
  1613. statictisSess.Select("id,commit_code_size").Table("user_business_analysis").Where(cond).OrderBy("id asc").Limit(PAGE_SIZE, int(indexTotal))
  1614. userBusinessAnalysisList := make([]*UserBusinessAnalysis, 0)
  1615. statictisSess.Find(&userBusinessAnalysisList)
  1616. log.Info("query user login size=" + fmt.Sprint(len(userBusinessAnalysisList)))
  1617. for _, analysisRecord := range userBusinessAnalysisList {
  1618. if _, ok := resultMap[analysisRecord.ID]; !ok {
  1619. resultMap[analysisRecord.ID] = analysisRecord.CommitCodeSize
  1620. } else {
  1621. resultMap[analysisRecord.ID] += analysisRecord.CommitCodeSize
  1622. }
  1623. }
  1624. indexTotal += PAGE_SIZE
  1625. if indexTotal >= count {
  1626. break
  1627. }
  1628. }
  1629. log.Info("user commit code size=" + fmt.Sprint(len(resultMap)))
  1630. return resultMap
  1631. }
  1632. func queryUserModel(start_unix int64, end_unix int64) map[int64]int {
  1633. sess := x.NewSession()
  1634. defer sess.Close()
  1635. resultMap := make(map[int64]int)
  1636. cond := " created_unix>=" + fmt.Sprint(start_unix) + " and created_unix<=" + fmt.Sprint(end_unix)
  1637. count, err := sess.Where(cond).Count(new(AiModelManage))
  1638. if err != nil {
  1639. log.Info("query AiModelManage error. return.")
  1640. return resultMap
  1641. }
  1642. var indexTotal int64
  1643. indexTotal = 0
  1644. for {
  1645. sess.Select("id,user_id").Table("ai_model_manage").Where(cond).OrderBy("id asc").Limit(PAGE_SIZE, int(indexTotal))
  1646. aiModelList := make([]*AiModelManage, 0)
  1647. sess.Find(&aiModelList)
  1648. log.Info("query AiModelManage size=" + fmt.Sprint(len(aiModelList)))
  1649. for _, aiModelRecord := range aiModelList {
  1650. if _, ok := resultMap[aiModelRecord.UserId]; !ok {
  1651. resultMap[aiModelRecord.UserId] = 1
  1652. } else {
  1653. resultMap[aiModelRecord.UserId] += 1
  1654. }
  1655. }
  1656. indexTotal += PAGE_SIZE
  1657. if indexTotal >= count {
  1658. break
  1659. }
  1660. }
  1661. return resultMap
  1662. }
  1663. func queryCloudBrainTask(start_unix int64, end_unix int64) (map[int64]int, map[string]int) {
  1664. sess := x.NewSession()
  1665. defer sess.Close()
  1666. resultMap := make(map[int64]int)
  1667. resultItemMap := make(map[string]int)
  1668. cond := " created_unix>=" + fmt.Sprint(start_unix) + " and created_unix<=" + fmt.Sprint(end_unix)
  1669. count, err := sess.Where(cond).Count(new(Cloudbrain))
  1670. if err != nil {
  1671. log.Info("query cloudbrain error. return.")
  1672. return resultMap, resultItemMap
  1673. }
  1674. var indexTotal int64
  1675. indexTotal = 0
  1676. for {
  1677. sess.Select("id,job_type,user_id,duration,train_job_duration,type").Table("cloudbrain").Where(cond).OrderBy("id asc").Limit(PAGE_SIZE, int(indexTotal))
  1678. cloudTaskList := make([]*Cloudbrain, 0)
  1679. sess.Find(&cloudTaskList)
  1680. log.Info("query cloudbrain size=" + fmt.Sprint(len(cloudTaskList)))
  1681. for _, cloudTaskRecord := range cloudTaskList {
  1682. if _, ok := resultMap[cloudTaskRecord.UserID]; !ok {
  1683. resultMap[cloudTaskRecord.UserID] = 1
  1684. } else {
  1685. resultMap[cloudTaskRecord.UserID] += 1
  1686. }
  1687. setMapKey("CloudBrainRunTime", cloudTaskRecord.UserID, int(cloudTaskRecord.Duration), resultItemMap)
  1688. if cloudTaskRecord.Type == 1 { //npu
  1689. if cloudTaskRecord.JobType == "TRAIN" {
  1690. setMapKey("NpuTrainJob", cloudTaskRecord.UserID, 1, resultItemMap)
  1691. } else if cloudTaskRecord.JobType == "INFERENCE" {
  1692. setMapKey("NpuInferenceJob", cloudTaskRecord.UserID, 1, resultItemMap)
  1693. } else {
  1694. setMapKey("NpuDebugJob", cloudTaskRecord.UserID, 1, resultItemMap)
  1695. }
  1696. } else { //type=0 gpu
  1697. if cloudTaskRecord.JobType == "TRAIN" {
  1698. setMapKey("GpuTrainJob", cloudTaskRecord.UserID, 1, resultItemMap)
  1699. } else if cloudTaskRecord.JobType == "BENCHMARK" {
  1700. setMapKey("GpuBenchMarkJob", cloudTaskRecord.UserID, 1, resultItemMap)
  1701. } else {
  1702. setMapKey("GpuDebugJob", cloudTaskRecord.UserID, 1, resultItemMap)
  1703. }
  1704. }
  1705. }
  1706. indexTotal += PAGE_SIZE
  1707. if indexTotal >= count {
  1708. break
  1709. }
  1710. }
  1711. return resultMap, resultItemMap
  1712. }
  1713. func setMapKey(key string, userId int64, value int, resultItemMap map[string]int) {
  1714. newKey := fmt.Sprint(userId) + "_" + key
  1715. if _, ok := resultItemMap[newKey]; !ok {
  1716. resultItemMap[newKey] = value
  1717. } else {
  1718. resultItemMap[newKey] += value
  1719. }
  1720. }
  1721. func subMonth(t1, t2 time.Time) (month int) {
  1722. y1 := t1.Year()
  1723. y2 := t2.Year()
  1724. m1 := int(t1.Month())
  1725. m2 := int(t2.Month())
  1726. d1 := t1.Day()
  1727. d2 := t2.Day()
  1728. yearInterval := y1 - y2
  1729. // 如果 d1的 月-日 小于 d2的 月-日 那么 yearInterval-- 这样就得到了相差的年数
  1730. if m1 < m2 || m1 == m2 && d1 < d2 {
  1731. yearInterval--
  1732. }
  1733. // 获取月数差值
  1734. monthInterval := (m1 + 12) - m2
  1735. if d1 < d2 {
  1736. monthInterval--
  1737. }
  1738. monthInterval %= 12
  1739. month = yearInterval*12 + monthInterval
  1740. if month == 0 {
  1741. month = 1
  1742. }
  1743. return month
  1744. }