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

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