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

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