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

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