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

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