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

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