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

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