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

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