You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

user_business_analysis.go 75 kB

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