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

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