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 72 kB

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