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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488
  1. package models
  2. import (
  3. "fmt"
  4. "sort"
  5. "strconv"
  6. "time"
  7. "code.gitea.io/gitea/modules/log"
  8. "code.gitea.io/gitea/modules/timeutil"
  9. "xorm.io/builder"
  10. "xorm.io/xorm"
  11. )
  12. const (
  13. PAGE_SIZE = 2000
  14. BATCH_INSERT_SIZE = 50
  15. )
  16. type UserBusinessAnalysisAll struct {
  17. ID int64 `xorm:"pk"`
  18. CountDate int64 `xorm:"pk"`
  19. //action :ActionMergePullRequest // 11
  20. CodeMergeCount int `xorm:"NOT NULL DEFAULT 0"`
  21. //action :ActionCommitRepo // 5
  22. CommitCount int `xorm:"NOT NULL DEFAULT 0"`
  23. //action :ActionCreateIssue // 10
  24. IssueCount int `xorm:"NOT NULL DEFAULT 0"`
  25. //comment table current date
  26. CommentCount int `xorm:"NOT NULL DEFAULT 0"`
  27. //watch table current date
  28. FocusRepoCount int `xorm:"NOT NULL DEFAULT 0"`
  29. //star table current date
  30. StarRepoCount int `xorm:"NOT NULL DEFAULT 0"`
  31. //follow table
  32. WatchedCount int `xorm:"NOT NULL DEFAULT 0"`
  33. // user table
  34. GiteaAgeMonth int `xorm:"NOT NULL DEFAULT 0"`
  35. //
  36. CommitCodeSize int `xorm:"NOT NULL DEFAULT 0"`
  37. //attachement table
  38. CommitDatasetSize int `xorm:"NOT NULL DEFAULT 0"`
  39. //0
  40. CommitModelCount int `xorm:"NOT NULL DEFAULT 0"`
  41. //issue, issueassignees
  42. SolveIssueCount int `xorm:"NOT NULL DEFAULT 0"`
  43. //baike
  44. EncyclopediasCount int `xorm:"NOT NULL DEFAULT 0"`
  45. //user
  46. RegistDate timeutil.TimeStamp `xorm:"NOT NULL"`
  47. //repo
  48. CreateRepoCount int `xorm:"NOT NULL DEFAULT 0"`
  49. //login count, from elk
  50. LoginCount int `xorm:"NOT NULL DEFAULT 0"`
  51. //openi index
  52. OpenIIndex float64 `xorm:"NOT NULL DEFAULT 0"`
  53. //user
  54. Email string `xorm:"NOT NULL"`
  55. //user
  56. Name string `xorm:"NOT NULL"`
  57. DataDate string `xorm:"NULL"`
  58. //cloudbraintask
  59. CloudBrainTaskNum int `xorm:"NOT NULL DEFAULT 0"`
  60. GpuDebugJob int `xorm:"NOT NULL DEFAULT 0"`
  61. NpuDebugJob int `xorm:"NOT NULL DEFAULT 0"`
  62. GpuTrainJob int `xorm:"NOT NULL DEFAULT 0"`
  63. NpuTrainJob int `xorm:"NOT NULL DEFAULT 0"`
  64. NpuInferenceJob int `xorm:"NOT NULL DEFAULT 0"`
  65. GpuBenchMarkJob int `xorm:"NOT NULL DEFAULT 0"`
  66. CloudBrainRunTime int `xorm:"NOT NULL DEFAULT 0"`
  67. CommitDatasetNum int `xorm:"NOT NULL DEFAULT 0"`
  68. UserIndex float64 `xorm:"NOT NULL DEFAULT 0"`
  69. UserLocation string `xorm:"NULL"`
  70. }
  71. type UserBusinessAnalysis struct {
  72. ID int64 `xorm:"pk"`
  73. CountDate int64 `xorm:"pk"`
  74. //action :ActionMergePullRequest // 11
  75. CodeMergeCount int `xorm:"NOT NULL DEFAULT 0"`
  76. //action :ActionCommitRepo // 5
  77. CommitCount int `xorm:"NOT NULL DEFAULT 0"`
  78. //action :ActionCreateIssue // 6
  79. IssueCount int `xorm:"NOT NULL DEFAULT 0"`
  80. //comment table current date
  81. CommentCount int `xorm:"NOT NULL DEFAULT 0"`
  82. //watch table current date
  83. FocusRepoCount int `xorm:"NOT NULL DEFAULT 0"`
  84. //star table current date
  85. StarRepoCount int `xorm:"NOT NULL DEFAULT 0"`
  86. //follow table
  87. WatchedCount int `xorm:"NOT NULL DEFAULT 0"`
  88. // user table
  89. GiteaAgeMonth int `xorm:"NOT NULL DEFAULT 0"`
  90. //
  91. CommitCodeSize int `xorm:"NOT NULL DEFAULT 0"`
  92. //attachement table
  93. CommitDatasetSize int `xorm:"NOT NULL DEFAULT 0"`
  94. //0
  95. CommitModelCount int `xorm:"NOT NULL DEFAULT 0"`
  96. //issue, issueassignees
  97. SolveIssueCount int `xorm:"NOT NULL DEFAULT 0"`
  98. //baike
  99. EncyclopediasCount int `xorm:"NOT NULL DEFAULT 0"`
  100. //user
  101. RegistDate timeutil.TimeStamp `xorm:"NOT NULL"`
  102. //repo
  103. CreateRepoCount int `xorm:"NOT NULL DEFAULT 0"`
  104. //login count, from elk
  105. LoginCount int `xorm:"NOT NULL DEFAULT 0"`
  106. //openi index
  107. OpenIIndex float64 `xorm:"NOT NULL DEFAULT 0"`
  108. //user
  109. Email string `xorm:"NOT NULL"`
  110. //user
  111. Name string `xorm:"NOT NULL"`
  112. DataDate string `xorm:"NULL"`
  113. CloudBrainTaskNum int `xorm:"NOT NULL DEFAULT 0"`
  114. GpuDebugJob int `xorm:"NOT NULL DEFAULT 0"`
  115. NpuDebugJob int `xorm:"NOT NULL DEFAULT 0"`
  116. GpuTrainJob int `xorm:"NOT NULL DEFAULT 0"`
  117. NpuTrainJob int `xorm:"NOT NULL DEFAULT 0"`
  118. NpuInferenceJob int `xorm:"NOT NULL DEFAULT 0"`
  119. GpuBenchMarkJob int `xorm:"NOT NULL DEFAULT 0"`
  120. CloudBrainRunTime int `xorm:"NOT NULL DEFAULT 0"`
  121. CommitDatasetNum int `xorm:"NOT NULL DEFAULT 0"`
  122. UserIndex float64 `xorm:"NOT NULL DEFAULT 0"`
  123. UserLocation string `xorm:"NULL"`
  124. }
  125. type UserBusinessAnalysisQueryOptions struct {
  126. ListOptions
  127. UserName string
  128. SortType string
  129. StartTime int64
  130. EndTime int64
  131. IsAll bool
  132. }
  133. type UserBusinessAnalysisList []*UserBusinessAnalysis
  134. func (ulist UserBusinessAnalysisList) Swap(i, j int) { ulist[i], ulist[j] = ulist[j], ulist[i] }
  135. func (ulist UserBusinessAnalysisList) Len() int { return len(ulist) }
  136. func (ulist UserBusinessAnalysisList) Less(i, j int) bool {
  137. return ulist[i].ID > ulist[j].ID
  138. }
  139. func getLastCountDate() int64 {
  140. statictisSess := xStatistic.NewSession()
  141. defer statictisSess.Close()
  142. statictisSess.Limit(1, 0)
  143. userBusinessAnalysisList := make([]*UserBusinessAnalysis, 0)
  144. if err := statictisSess.Table("user_business_analysis").OrderBy("count_date desc").Limit(1, 0).
  145. Find(&userBusinessAnalysisList); err == nil {
  146. for _, userRecord := range userBusinessAnalysisList {
  147. return userRecord.CountDate - 10000
  148. }
  149. } else {
  150. log.Info("query error." + err.Error())
  151. }
  152. currentTimeNow := time.Now()
  153. pageStartTime := time.Date(currentTimeNow.Year(), currentTimeNow.Month(), currentTimeNow.Day(), 0, 0, 0, 0, currentTimeNow.Location())
  154. return pageStartTime.Unix()
  155. }
  156. func QueryMetrics(start int64, end int64) ([]*UserMetrics, int64) {
  157. statictisSess := xStatistic.NewSession()
  158. defer statictisSess.Close()
  159. userMetricsList := make([]*UserMetrics, 0)
  160. if err := statictisSess.Table(new(UserMetrics)).Where("count_date >" + fmt.Sprint(start) + " and count_date<" + fmt.Sprint(end)).OrderBy("count_date desc").
  161. Find(&userMetricsList); err != nil {
  162. return nil, 0
  163. }
  164. return userMetricsList, int64(len(userMetricsList))
  165. }
  166. func QueryRankList(key string, tableName string, limit int) ([]*UserBusinessAnalysisAll, int64) {
  167. statictisSess := xStatistic.NewSession()
  168. defer statictisSess.Close()
  169. userBusinessAnalysisAllList := make([]*UserBusinessAnalysisAll, 0)
  170. if err := statictisSess.Table(tableName).OrderBy(key+" desc,id desc").Limit(limit, 0).
  171. Find(&userBusinessAnalysisAllList); err != nil {
  172. return nil, 0
  173. }
  174. return userBusinessAnalysisAllList, int64(len(userBusinessAnalysisAllList))
  175. }
  176. func QueryUserStaticDataByTableName(start int, pageSize int, tableName string, queryObj interface{}, userName string) ([]*UserBusinessAnalysisAll, int64) {
  177. statictisSess := xStatistic.NewSession()
  178. defer statictisSess.Close()
  179. var cond = builder.NewCond()
  180. if len(userName) > 0 {
  181. cond = cond.And(
  182. builder.Like{"name", userName},
  183. )
  184. }
  185. allCount, err := statictisSess.Where(cond).Count(queryObj)
  186. if err != nil {
  187. log.Info("query error." + err.Error())
  188. return nil, 0
  189. }
  190. log.Info("query return total:" + fmt.Sprint(allCount))
  191. userBusinessAnalysisAllList := make([]*UserBusinessAnalysisAll, 0)
  192. if err := statictisSess.Table(tableName).Where(cond).OrderBy("user_index desc,id desc").Limit(pageSize, start).
  193. Find(&userBusinessAnalysisAllList); err != nil {
  194. return nil, 0
  195. }
  196. return userBusinessAnalysisAllList, allCount
  197. }
  198. func QueryUserStaticDataAll(opts *UserBusinessAnalysisQueryOptions) ([]*UserBusinessAnalysisAll, int64) {
  199. log.Info("query startTime =" + fmt.Sprint(opts.StartTime) + " endTime=" + fmt.Sprint(opts.EndTime) + " isAll=" + fmt.Sprint(opts.IsAll))
  200. statictisSess := xStatistic.NewSession()
  201. defer statictisSess.Close()
  202. allCount, err := statictisSess.Count(new(UserBusinessAnalysisAll))
  203. if err != nil {
  204. log.Info("query error." + err.Error())
  205. return nil, 0
  206. }
  207. log.Info("query return total:" + fmt.Sprint(allCount))
  208. pageSize := PAGE_SIZE
  209. totalPage := int(allCount) / pageSize
  210. userBusinessAnalysisReturnList := make([]*UserBusinessAnalysisAll, 0)
  211. for i := 0; i <= int(totalPage); i++ {
  212. userBusinessAnalysisAllList := make([]*UserBusinessAnalysisAll, 0)
  213. if err := statictisSess.Table("user_business_analysis_all").OrderBy("id desc").Limit(pageSize, i*pageSize).
  214. Find(&userBusinessAnalysisAllList); err != nil {
  215. return nil, 0
  216. }
  217. log.Info("query " + fmt.Sprint(i+1) + " result size=" + fmt.Sprint(len(userBusinessAnalysisAllList)))
  218. for _, userRecord := range userBusinessAnalysisAllList {
  219. userBusinessAnalysisReturnList = append(userBusinessAnalysisReturnList, userRecord)
  220. }
  221. }
  222. log.Info("return size=" + fmt.Sprint(len(userBusinessAnalysisReturnList)))
  223. return userBusinessAnalysisReturnList, allCount
  224. }
  225. func QueryUserStaticDataPage(opts *UserBusinessAnalysisQueryOptions) ([]*UserBusinessAnalysis, int64) {
  226. log.Info("query startTime =" + fmt.Sprint(opts.StartTime) + " endTime=" + fmt.Sprint(opts.EndTime) + " isAll=" + fmt.Sprint(opts.IsAll))
  227. statictisSess := xStatistic.NewSession()
  228. defer statictisSess.Close()
  229. currentTimeNow := time.Now()
  230. pageStartTime := getLastCountDate()
  231. pageEndTime := time.Date(currentTimeNow.Year(), currentTimeNow.Month(), currentTimeNow.Day(), 23, 59, 59, 0, currentTimeNow.Location()).Unix()
  232. var cond = builder.NewCond()
  233. if len(opts.UserName) > 0 {
  234. cond = cond.And(
  235. builder.Like{"name", opts.UserName},
  236. )
  237. }
  238. cond = cond.And(
  239. builder.Gte{"count_date": pageStartTime},
  240. )
  241. cond = cond.And(
  242. builder.Lte{"count_date": pageEndTime},
  243. )
  244. count, err := statictisSess.Where(cond).Count(new(UserBusinessAnalysis))
  245. if err != nil {
  246. log.Info("query error." + err.Error())
  247. return nil, 0
  248. }
  249. if opts.Page >= 0 && opts.PageSize > 0 {
  250. var start int
  251. if opts.Page == 0 {
  252. start = 0
  253. } else {
  254. start = (opts.Page - 1) * opts.PageSize
  255. }
  256. statictisSess.Limit(opts.PageSize, start)
  257. }
  258. userBusinessAnalysisList := make([]*UserBusinessAnalysis, 0)
  259. if err := statictisSess.Table("user_business_analysis").Where(cond).OrderBy("id desc").
  260. Find(&userBusinessAnalysisList); err != nil {
  261. return nil, 0
  262. }
  263. resultMap := make(map[int64]*UserBusinessAnalysis)
  264. if len(userBusinessAnalysisList) > 0 {
  265. var newAndCond = builder.NewCond()
  266. var newOrCond = builder.NewCond()
  267. for _, userRecord := range userBusinessAnalysisList {
  268. newOrCond = newOrCond.Or(
  269. builder.Eq{"id": userRecord.ID},
  270. )
  271. }
  272. newAndCond = newAndCond.And(
  273. newOrCond,
  274. )
  275. if !opts.IsAll {
  276. newAndCond = newAndCond.And(
  277. builder.Gte{"count_date": opts.StartTime},
  278. )
  279. newAndCond = newAndCond.And(
  280. builder.Lte{"count_date": opts.EndTime},
  281. )
  282. }
  283. allCount, err := statictisSess.Where(newAndCond).Count(new(UserBusinessAnalysis))
  284. if err != nil {
  285. log.Info("query error." + err.Error())
  286. return nil, 0
  287. }
  288. pageSize := 1000
  289. totalPage := int(allCount) / pageSize
  290. for i := 0; i <= int(totalPage); i++ {
  291. userBusinessAnalysisList = make([]*UserBusinessAnalysis, 0)
  292. if err := statictisSess.Table("user_business_analysis").Where(newAndCond).OrderBy("count_date desc").Limit(pageSize, i*pageSize).
  293. Find(&userBusinessAnalysisList); err != nil {
  294. return nil, 0
  295. }
  296. log.Info("query result size=" + fmt.Sprint(len(userBusinessAnalysisList)))
  297. for _, userRecord := range userBusinessAnalysisList {
  298. if _, ok := resultMap[userRecord.ID]; !ok {
  299. resultMap[userRecord.ID] = userRecord
  300. } else {
  301. resultMap[userRecord.ID].CodeMergeCount += userRecord.CodeMergeCount
  302. resultMap[userRecord.ID].CommitCount += userRecord.CommitCount
  303. resultMap[userRecord.ID].IssueCount += userRecord.IssueCount
  304. resultMap[userRecord.ID].CommentCount += userRecord.CommentCount
  305. resultMap[userRecord.ID].FocusRepoCount += userRecord.FocusRepoCount
  306. resultMap[userRecord.ID].StarRepoCount += userRecord.StarRepoCount
  307. resultMap[userRecord.ID].WatchedCount += userRecord.WatchedCount
  308. resultMap[userRecord.ID].CommitCodeSize += userRecord.CommitCodeSize
  309. resultMap[userRecord.ID].CommitDatasetSize += userRecord.CommitDatasetSize
  310. resultMap[userRecord.ID].CommitDatasetNum += userRecord.CommitDatasetNum
  311. resultMap[userRecord.ID].CommitModelCount += userRecord.CommitModelCount
  312. resultMap[userRecord.ID].SolveIssueCount += userRecord.SolveIssueCount
  313. resultMap[userRecord.ID].EncyclopediasCount += userRecord.EncyclopediasCount
  314. resultMap[userRecord.ID].CreateRepoCount += userRecord.CreateRepoCount
  315. resultMap[userRecord.ID].LoginCount += userRecord.LoginCount
  316. }
  317. }
  318. }
  319. }
  320. userBusinessAnalysisReturnList := UserBusinessAnalysisList{}
  321. for _, v := range resultMap {
  322. userBusinessAnalysisReturnList = append(userBusinessAnalysisReturnList, v)
  323. }
  324. sort.Sort(userBusinessAnalysisReturnList)
  325. log.Info("return size=" + fmt.Sprint(len(userBusinessAnalysisReturnList)))
  326. return userBusinessAnalysisReturnList, count
  327. }
  328. func refreshUserStaticTable(wikiCountMap map[string]int, tableName string, pageStartTime time.Time, pageEndTime time.Time, userMetrics map[string]int) {
  329. sess := x.NewSession()
  330. defer sess.Close()
  331. statictisSess := xStatistic.NewSession()
  332. defer statictisSess.Close()
  333. log.Info("truncate all data from table: " + tableName)
  334. statictisSess.Exec("TRUNCATE TABLE " + tableName)
  335. log.Info("pageStartTime:" + pageStartTime.Format("2006-01-02 15:04:05"))
  336. log.Info("pageEndTime time:" + pageEndTime.Format("2006-01-02 15:04:05"))
  337. start_unix := pageStartTime.Unix()
  338. end_unix := pageEndTime.Unix()
  339. currentTimeNow := time.Now()
  340. startTime := currentTimeNow.AddDate(0, 0, -1)
  341. CodeMergeCountMap := queryPullRequest(start_unix, end_unix)
  342. CommitCountMap := queryCommitAction(start_unix, end_unix, 5)
  343. IssueCountMap := queryCreateIssue(start_unix, end_unix)
  344. CommentCountMap := queryComment(start_unix, end_unix)
  345. FocusRepoCountMap := queryWatch(start_unix, end_unix)
  346. StarRepoCountMap := queryStar(start_unix, end_unix)
  347. WatchedCountMap := queryFollow(start_unix, end_unix)
  348. CommitCodeSizeMap := queryCommitCodeSize(start_unix, end_unix)
  349. CommitDatasetSizeMap, CommitDatasetNumMap := queryDatasetSize(start_unix, end_unix)
  350. SolveIssueCountMap := querySolveIssue(start_unix, end_unix)
  351. CreateRepoCountMap := queryUserCreateRepo(start_unix, end_unix)
  352. LoginCountMap := queryLoginCount(start_unix, end_unix)
  353. OpenIIndexMap := queryUserRepoOpenIIndex(startTime.Unix(), end_unix)
  354. CloudBrainTaskMap, CloudBrainTaskItemMap := queryCloudBrainTask(start_unix, end_unix)
  355. AiModelManageMap := queryUserModel(start_unix, end_unix)
  356. DataDate := currentTimeNow.Format("2006-01-02") + " 00:01"
  357. cond := "type != 1 and is_active=true"
  358. count, err := sess.Where(cond).Count(new(User))
  359. if err != nil {
  360. log.Info("query user error. return.")
  361. return
  362. }
  363. ParaWeight := getParaWeight()
  364. var indexTotal int64
  365. indexTotal = 0
  366. insertCount := 0
  367. userIndexMap := make(map[int64]float64, 0)
  368. maxUserIndex := 0.0
  369. minUserIndex := 100000000.0
  370. dateRecordBatch := make([]UserBusinessAnalysisAll, 0)
  371. for {
  372. sess.Select("`user`.*").Table("user").Where(cond).OrderBy("id asc").Limit(PAGE_SIZE, int(indexTotal))
  373. userList := make([]*User, 0)
  374. sess.Find(&userList)
  375. for _, userRecord := range userList {
  376. var dateRecordAll UserBusinessAnalysisAll
  377. dateRecordAll.ID = userRecord.ID
  378. dateRecordAll.Email = userRecord.Email
  379. dateRecordAll.RegistDate = userRecord.CreatedUnix
  380. dateRecordAll.Name = userRecord.Name
  381. dateRecordAll.GiteaAgeMonth = subMonth(currentTimeNow, userRecord.CreatedUnix.AsTime())
  382. dateRecordAll.DataDate = DataDate
  383. dateRecordAll.UserLocation = userRecord.Location
  384. dateRecordAll.CodeMergeCount = getMapValue(dateRecordAll.ID, CodeMergeCountMap)
  385. dateRecordAll.CommitCount = getMapValue(dateRecordAll.ID, CommitCountMap)
  386. dateRecordAll.IssueCount = getMapValue(dateRecordAll.ID, IssueCountMap)
  387. dateRecordAll.CommentCount = getMapValue(dateRecordAll.ID, CommentCountMap)
  388. dateRecordAll.FocusRepoCount = getMapValue(dateRecordAll.ID, FocusRepoCountMap)
  389. dateRecordAll.StarRepoCount = getMapValue(dateRecordAll.ID, StarRepoCountMap)
  390. dateRecordAll.WatchedCount = getMapValue(dateRecordAll.ID, WatchedCountMap)
  391. dateRecordAll.CommitCodeSize = getMapValue(dateRecordAll.ID, CommitCodeSizeMap)
  392. dateRecordAll.CommitDatasetSize = getMapValue(dateRecordAll.ID, CommitDatasetSizeMap)
  393. dateRecordAll.CommitDatasetNum = getMapValue(dateRecordAll.ID, CommitDatasetNumMap)
  394. dateRecordAll.SolveIssueCount = getMapValue(dateRecordAll.ID, SolveIssueCountMap)
  395. dateRecordAll.EncyclopediasCount = getMapKeyStringValue(dateRecordAll.Name, wikiCountMap)
  396. dateRecordAll.CreateRepoCount = getMapValue(dateRecordAll.ID, CreateRepoCountMap)
  397. dateRecordAll.LoginCount = getMapValue(dateRecordAll.ID, LoginCountMap)
  398. if _, ok := OpenIIndexMap[dateRecordAll.ID]; !ok {
  399. dateRecordAll.OpenIIndex = 0
  400. } else {
  401. dateRecordAll.OpenIIndex = OpenIIndexMap[dateRecordAll.ID]
  402. }
  403. dateRecordAll.CloudBrainTaskNum = getMapValue(dateRecordAll.ID, CloudBrainTaskMap)
  404. dateRecordAll.GpuDebugJob = getMapKeyStringValue(fmt.Sprint(dateRecordAll.ID)+"_GpuDebugJob", CloudBrainTaskItemMap)
  405. dateRecordAll.NpuDebugJob = getMapKeyStringValue(fmt.Sprint(dateRecordAll.ID)+"_NpuDebugJob", CloudBrainTaskItemMap)
  406. dateRecordAll.GpuTrainJob = getMapKeyStringValue(fmt.Sprint(dateRecordAll.ID)+"_GpuTrainJob", CloudBrainTaskItemMap)
  407. dateRecordAll.NpuTrainJob = getMapKeyStringValue(fmt.Sprint(dateRecordAll.ID)+"_NpuTrainJob", CloudBrainTaskItemMap)
  408. dateRecordAll.NpuInferenceJob = getMapKeyStringValue(fmt.Sprint(dateRecordAll.ID)+"_NpuInferenceJob", CloudBrainTaskItemMap)
  409. dateRecordAll.GpuBenchMarkJob = getMapKeyStringValue(fmt.Sprint(dateRecordAll.ID)+"_GpuBenchMarkJob", CloudBrainTaskItemMap)
  410. dateRecordAll.CommitModelCount = getMapValue(dateRecordAll.ID, AiModelManageMap)
  411. dateRecordAll.UserIndex = getUserIndexFromAnalysisAll(dateRecordAll, ParaWeight)
  412. userIndexMap[dateRecordAll.ID] = dateRecordAll.UserIndex
  413. if maxUserIndex < dateRecordAll.UserIndex {
  414. maxUserIndex = dateRecordAll.UserIndex
  415. }
  416. if minUserIndex > dateRecordAll.UserIndex {
  417. minUserIndex = dateRecordAll.UserIndex
  418. }
  419. dateRecordBatch = append(dateRecordBatch, dateRecordAll)
  420. if len(dateRecordBatch) >= BATCH_INSERT_SIZE {
  421. insertTable(dateRecordBatch, tableName, statictisSess)
  422. insertCount += BATCH_INSERT_SIZE
  423. if err != nil {
  424. log.Info("insert all data failed." + err.Error())
  425. }
  426. dateRecordBatch = make([]UserBusinessAnalysisAll, 0)
  427. }
  428. if tableName == "user_business_analysis_all" {
  429. if dateRecordAll.UserIndex > 0 || dateRecordAll.LoginCount > 0 {
  430. userMetrics["TotalHasActivityUser"] = getMapKeyStringValue("TotalHasActivityUser", userMetrics) + 1
  431. }
  432. }
  433. }
  434. indexTotal += PAGE_SIZE
  435. if indexTotal >= count {
  436. break
  437. }
  438. }
  439. if len(dateRecordBatch) > 0 {
  440. insertTable(dateRecordBatch, tableName, statictisSess)
  441. insertCount += len(dateRecordBatch)
  442. if err != nil {
  443. log.Info("insert all data failed." + err.Error())
  444. }
  445. }
  446. //normalization
  447. for k, v := range userIndexMap {
  448. tmpResult := (v - minUserIndex) / (maxUserIndex - minUserIndex)
  449. if tmpResult > 0.99 {
  450. tmpResult = 0.99
  451. }
  452. updateUserIndex(tableName, statictisSess, k, tmpResult)
  453. }
  454. log.Info("refresh data finished.tableName=" + tableName + " total record:" + fmt.Sprint(insertCount))
  455. }
  456. func updateUserIndex(tableName string, statictisSess *xorm.Session, userId int64, userIndex float64) {
  457. updateSql := "UPDATE public." + tableName + " set user_index=" + fmt.Sprint(userIndex*100) + " where id=" + fmt.Sprint(userId)
  458. statictisSess.Exec(updateSql)
  459. }
  460. func insertTable(dateRecords []UserBusinessAnalysisAll, tableName string, statictisSess *xorm.Session) {
  461. insertBatchSql := "INSERT INTO public." + tableName +
  462. "(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, " +
  463. "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) " +
  464. "VALUES"
  465. for i, record := range dateRecords {
  466. insertBatchSql += "(" + fmt.Sprint(record.ID) + ", " + fmt.Sprint(record.CountDate) + ", " + fmt.Sprint(record.CodeMergeCount) + ", " + fmt.Sprint(record.CommitCount) +
  467. ", " + fmt.Sprint(record.IssueCount) + ", " + fmt.Sprint(record.CommentCount) + ", " + fmt.Sprint(record.FocusRepoCount) + ", " + fmt.Sprint(record.StarRepoCount) +
  468. ", " + fmt.Sprint(record.WatchedCount) + ", " + fmt.Sprint(record.GiteaAgeMonth) + ", " + fmt.Sprint(record.CommitCodeSize) + ", " + fmt.Sprint(record.CommitDatasetSize) +
  469. ", " + fmt.Sprint(record.CommitModelCount) + ", " + fmt.Sprint(record.SolveIssueCount) + ", " + fmt.Sprint(record.EncyclopediasCount) + ", " + fmt.Sprint(record.RegistDate) +
  470. ", " + 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 + "')"
  471. if i < (len(dateRecords) - 1) {
  472. insertBatchSql += ","
  473. }
  474. }
  475. statictisSess.Exec(insertBatchSql)
  476. }
  477. func RefreshUserStaticAllTabel(wikiCountMap map[string]int, userMetrics map[string]int) {
  478. currentTimeNow := time.Now()
  479. pageStartTime := time.Date(2021, 11, 5, 0, 0, 0, 0, currentTimeNow.Location())
  480. pageEndTime := time.Date(currentTimeNow.Year(), currentTimeNow.Month(), currentTimeNow.Day(), 23, 59, 59, 0, currentTimeNow.Location())
  481. refreshUserStaticTable(wikiCountMap, "user_business_analysis_all", pageStartTime, pageEndTime, userMetrics)
  482. log.Info("refresh all data finished.")
  483. pageStartTime = time.Date(currentTimeNow.Year(), 1, 1, 0, 0, 0, 0, currentTimeNow.Location())
  484. refreshUserStaticTable(wikiCountMap, "user_business_analysis_current_year", pageStartTime, pageEndTime, userMetrics)
  485. thisMonth := time.Date(currentTimeNow.Year(), currentTimeNow.Month(), 1, 0, 0, 0, 0, currentTimeNow.Location())
  486. refreshUserStaticTable(wikiCountMap, "user_business_analysis_current_month", thisMonth, pageEndTime, userMetrics)
  487. offset := int(time.Monday - currentTimeNow.Weekday())
  488. if offset > 0 {
  489. offset = -6
  490. }
  491. pageStartTime = time.Date(currentTimeNow.Year(), currentTimeNow.Month(), currentTimeNow.Day(), 0, 0, 0, 0, time.Local).AddDate(0, 0, offset)
  492. refreshUserStaticTable(wikiCountMap, "user_business_analysis_current_week", pageStartTime, pageEndTime, userMetrics)
  493. pageStartTime = time.Date(currentTimeNow.Year(), currentTimeNow.Month(), currentTimeNow.Day(), 0, 0, 0, 0, time.Local).AddDate(0, 0, -30)
  494. refreshUserStaticTable(wikiCountMap, "user_business_analysis_last30_day", pageStartTime, pageEndTime, userMetrics)
  495. pageStartTime = time.Date(currentTimeNow.Year(), currentTimeNow.Month(), currentTimeNow.Day(), 0, 0, 0, 0, time.Local).AddDate(0, 0, -1)
  496. pageEndTime = time.Date(currentTimeNow.Year(), currentTimeNow.Month(), currentTimeNow.Day(), 23, 59, 59, 0, currentTimeNow.Location()).AddDate(0, 0, -1)
  497. refreshUserStaticTable(wikiCountMap, "user_business_analysis_yesterday", pageStartTime, pageEndTime, userMetrics)
  498. pageStartTime = thisMonth.AddDate(0, -1, 0)
  499. pageEndTime = time.Date(currentTimeNow.Year(), currentTimeNow.Month(), 1, 23, 59, 59, 0, currentTimeNow.Location()).AddDate(0, 0, -1)
  500. refreshUserStaticTable(wikiCountMap, "user_business_analysis_last_month", pageStartTime, pageEndTime, userMetrics)
  501. }
  502. func CounDataByDateAndReCount(wikiCountMap map[string]int, startTime time.Time, endTime time.Time, isReCount bool) error {
  503. log.Info("start to count other user info data")
  504. sess := x.NewSession()
  505. defer sess.Close()
  506. currentTimeNow := time.Now()
  507. log.Info("current time:" + currentTimeNow.Format("2006-01-02 15:04:05"))
  508. start_unix := startTime.Unix()
  509. log.Info("DB query time:" + startTime.Format("2006-01-02 15:04:05"))
  510. end_unix := endTime.Unix()
  511. CountDate := time.Date(currentTimeNow.Year(), currentTimeNow.Month(), currentTimeNow.Day(), 0, 1, 0, 0, currentTimeNow.Location())
  512. if isReCount {
  513. CountDate = time.Date(startTime.Year(), startTime.Month(), startTime.Day(), 0, 1, 0, 0, currentTimeNow.Location())
  514. }
  515. DataDate := startTime.Format("2006-01-02")
  516. CodeMergeCountMap := queryPullRequest(start_unix, end_unix)
  517. CommitCountMap := queryCommitAction(start_unix, end_unix, 5)
  518. IssueCountMap := queryCreateIssue(start_unix, end_unix)
  519. CommentCountMap := queryComment(start_unix, end_unix)
  520. FocusRepoCountMap := queryWatch(start_unix, end_unix)
  521. StarRepoCountMap := queryStar(start_unix, end_unix)
  522. WatchedCountMap := queryFollow(start_unix, end_unix)
  523. CommitCodeSizeMap, err := GetAllUserKPIStats()
  524. if err != nil {
  525. log.Info("query commit code errr.")
  526. } else {
  527. log.Info("query commit code size, len=" + fmt.Sprint(len(CommitCodeSizeMap)))
  528. }
  529. CommitDatasetSizeMap, CommitDatasetNumMap := queryDatasetSize(start_unix, end_unix)
  530. SolveIssueCountMap := querySolveIssue(start_unix, end_unix)
  531. CreateRepoCountMap := queryUserCreateRepo(start_unix, end_unix)
  532. LoginCountMap := queryLoginCount(start_unix, end_unix)
  533. OpenIIndexMap := queryUserRepoOpenIIndex(start_unix, end_unix)
  534. CloudBrainTaskMap, CloudBrainTaskItemMap := queryCloudBrainTask(start_unix, end_unix)
  535. AiModelManageMap := queryUserModel(start_unix, end_unix)
  536. statictisSess := xStatistic.NewSession()
  537. defer statictisSess.Close()
  538. cond := "type != 1 and is_active=true"
  539. count, err := sess.Where(cond).Count(new(User))
  540. if err != nil {
  541. log.Info("query user error. return.")
  542. return err
  543. }
  544. ParaWeight := getParaWeight()
  545. userMetrics := make(map[string]int)
  546. var indexTotal int64
  547. indexTotal = 0
  548. for {
  549. sess.Select("`user`.*").Table("user").Where(cond).OrderBy("id asc").Limit(PAGE_SIZE, int(indexTotal))
  550. userList := make([]*User, 0)
  551. sess.Find(&userList)
  552. for i, userRecord := range userList {
  553. var dateRecord UserBusinessAnalysis
  554. dateRecord.ID = userRecord.ID
  555. log.Info("i=" + fmt.Sprint(i) + " userName=" + userRecord.Name)
  556. dateRecord.CountDate = CountDate.Unix()
  557. statictisSess.Delete(&dateRecord)
  558. dateRecord.Email = userRecord.Email
  559. dateRecord.RegistDate = userRecord.CreatedUnix
  560. dateRecord.Name = userRecord.Name
  561. dateRecord.GiteaAgeMonth = subMonth(currentTimeNow, userRecord.CreatedUnix.AsTime())
  562. dateRecord.DataDate = DataDate
  563. dateRecord.CodeMergeCount = getMapValue(dateRecord.ID, CodeMergeCountMap)
  564. dateRecord.CommitCount = getMapValue(dateRecord.ID, CommitCountMap)
  565. dateRecord.IssueCount = getMapValue(dateRecord.ID, IssueCountMap)
  566. dateRecord.CommentCount = getMapValue(dateRecord.ID, CommentCountMap)
  567. dateRecord.FocusRepoCount = getMapValue(dateRecord.ID, FocusRepoCountMap)
  568. dateRecord.StarRepoCount = getMapValue(dateRecord.ID, StarRepoCountMap)
  569. dateRecord.WatchedCount = getMapValue(dateRecord.ID, WatchedCountMap)
  570. if _, ok := CommitCodeSizeMap[dateRecord.Email]; !ok {
  571. dateRecord.CommitCodeSize = 0
  572. } else {
  573. dateRecord.CommitCodeSize = int(CommitCodeSizeMap[dateRecord.Email].CommitLines)
  574. }
  575. dateRecord.CommitDatasetSize = getMapValue(dateRecord.ID, CommitDatasetSizeMap)
  576. dateRecord.CommitDatasetNum = getMapValue(dateRecord.ID, CommitDatasetNumMap)
  577. dateRecord.SolveIssueCount = getMapValue(dateRecord.ID, SolveIssueCountMap)
  578. dateRecord.EncyclopediasCount = getMapKeyStringValue(dateRecord.Name, wikiCountMap)
  579. dateRecord.CreateRepoCount = getMapValue(dateRecord.ID, CreateRepoCountMap)
  580. dateRecord.LoginCount = getMapValue(dateRecord.ID, LoginCountMap)
  581. if _, ok := OpenIIndexMap[dateRecord.ID]; !ok {
  582. dateRecord.OpenIIndex = 0
  583. } else {
  584. dateRecord.OpenIIndex = OpenIIndexMap[dateRecord.ID]
  585. }
  586. dateRecord.CloudBrainTaskNum = getMapValue(dateRecord.ID, CloudBrainTaskMap)
  587. dateRecord.GpuDebugJob = getMapKeyStringValue(fmt.Sprint(dateRecord.ID)+"_GpuDebugJob", CloudBrainTaskItemMap)
  588. dateRecord.NpuDebugJob = getMapKeyStringValue(fmt.Sprint(dateRecord.ID)+"_NpuDebugJob", CloudBrainTaskItemMap)
  589. dateRecord.GpuTrainJob = getMapKeyStringValue(fmt.Sprint(dateRecord.ID)+"_GpuTrainJob", CloudBrainTaskItemMap)
  590. dateRecord.NpuTrainJob = getMapKeyStringValue(fmt.Sprint(dateRecord.ID)+"_NpuTrainJob", CloudBrainTaskItemMap)
  591. dateRecord.NpuInferenceJob = getMapKeyStringValue(fmt.Sprint(dateRecord.ID)+"_NpuInferenceJob", CloudBrainTaskItemMap)
  592. dateRecord.GpuBenchMarkJob = getMapKeyStringValue(fmt.Sprint(dateRecord.ID)+"_GpuBenchMarkJob", CloudBrainTaskItemMap)
  593. dateRecord.CloudBrainRunTime = getMapKeyStringValue(fmt.Sprint(dateRecord.ID)+"_CloudBrainRunTime", CloudBrainTaskItemMap)
  594. dateRecord.CommitModelCount = getMapValue(dateRecord.ID, AiModelManageMap)
  595. dateRecord.UserIndex = getUserIndex(dateRecord, ParaWeight)
  596. setUserMetrics(userMetrics, userRecord, start_unix, end_unix, dateRecord)
  597. _, err = statictisSess.Insert(&dateRecord)
  598. if err != nil {
  599. log.Info("insert daterecord failed." + err.Error())
  600. return err
  601. }
  602. }
  603. indexTotal += PAGE_SIZE
  604. if indexTotal >= count {
  605. break
  606. }
  607. }
  608. RefreshUserStaticAllTabel(wikiCountMap, userMetrics)
  609. //insert userMetrics table
  610. var useMetrics UserMetrics
  611. useMetrics.CountDate = CountDate.Unix()
  612. statictisSess.Delete(&useMetrics)
  613. useMetrics.ActivateRegistUser = getMapKeyStringValue("ActivateRegistUser", userMetrics)
  614. useMetrics.HasActivityUser = getMapKeyStringValue("HasActivityUser", userMetrics)
  615. useMetrics.NotActivateRegistUser = getMapKeyStringValue("NotActivateRegistUser", userMetrics)
  616. useMetrics.TotalActivateRegistUser = getMapKeyStringValue("TotalActivateRegistUser", userMetrics)
  617. useMetrics.TotalHasActivityUser = getMapKeyStringValue("TotalHasActivityUser", userMetrics)
  618. statictisSess.Insert(&useMetrics)
  619. return nil
  620. }
  621. func setUserMetrics(userMetrics map[string]int, user *User, start_time int64, end_time int64, dateRecord UserBusinessAnalysis) {
  622. //ActivateRegistUser int `xorm:"NOT NULL DEFAULT 0"`
  623. //NotActivateRegistUser int `xorm:"NOT NULL DEFAULT 0"`
  624. //HasActivityUser int `xorm:"NOT NULL DEFAULT 0"`
  625. //TotalActivateRegistUser int `xorm:"NOT NULL DEFAULT 0"`
  626. //TotalHasActivityUser
  627. regist_time := user.CreatedUnix.AsTime().Unix()
  628. if regist_time >= start_time && regist_time <= end_time {
  629. if user.IsActive {
  630. userMetrics["ActivateRegistUser"] = getMapKeyStringValue("ActivateRegistUser", userMetrics) + 1
  631. } else {
  632. userMetrics["NotActivateRegistUser"] = getMapKeyStringValue("NotActivateRegistUser", userMetrics) + 1
  633. }
  634. }
  635. if user.IsActive {
  636. userMetrics["TotalActivateRegistUser"] = getMapKeyStringValue("TotalActivateRegistUser", userMetrics) + 1
  637. }
  638. if dateRecord.UserIndex > 0 || dateRecord.LoginCount > 0 {
  639. userMetrics["HasActivityUser"] = getMapKeyStringValue("HasActivityUser", userMetrics) + 1
  640. }
  641. }
  642. func getParaWeight() map[string]float64 {
  643. result := make(map[string]float64)
  644. statictisSess := xStatistic.NewSession()
  645. defer statictisSess.Close()
  646. statictisSess.Select("*").Table(new(UserAnalysisPara))
  647. paraList := make([]*UserAnalysisPara, 0)
  648. statictisSess.Find(&paraList)
  649. for _, paraRecord := range paraList {
  650. result[paraRecord.Key] = paraRecord.Value
  651. }
  652. return result
  653. }
  654. func getUserIndexFromAnalysisAll(dateRecord UserBusinessAnalysisAll, ParaWeight map[string]float64) float64 {
  655. var result float64
  656. // PR数 0.20
  657. // commit数 0.20
  658. // 提出任务数 0.20
  659. // 评论数 0.20
  660. // 关注项目数 0.10
  661. // 点赞项目数 0.10
  662. // 登录次数 0.10
  663. result = float64(dateRecord.CodeMergeCount) * getParaWeightValue("CodeMergeCount", ParaWeight, 0.2)
  664. result += float64(dateRecord.CommitCount) * getParaWeightValue("CommitCount", ParaWeight, 0.2)
  665. log.Info("1 result=" + fmt.Sprint(result))
  666. result += float64(dateRecord.IssueCount) * getParaWeightValue("IssueCount", ParaWeight, 0.2)
  667. result += float64(dateRecord.CommentCount) * getParaWeightValue("CommentCount", ParaWeight, 0.2)
  668. result += float64(dateRecord.FocusRepoCount) * getParaWeightValue("FocusRepoCount", ParaWeight, 0.1)
  669. result += float64(dateRecord.StarRepoCount) * getParaWeightValue("StarRepoCount", ParaWeight, 0.1)
  670. result += float64(dateRecord.LoginCount) * getParaWeightValue("LoginCount", ParaWeight, 0.1)
  671. result += float64(dateRecord.WatchedCount) * getParaWeightValue("WatchedCount", ParaWeight, 0.3)
  672. result += float64(dateRecord.CommitCodeSize) * getParaWeightValue("CommitCodeSize", ParaWeight, 0.1)
  673. result += float64(dateRecord.SolveIssueCount) * getParaWeightValue("SolveIssueCount", ParaWeight, 0.2)
  674. result += float64(dateRecord.EncyclopediasCount) * getParaWeightValue("EncyclopediasCount", ParaWeight, 0.1)
  675. result += float64(dateRecord.CreateRepoCount) * getParaWeightValue("CreateRepoCount", ParaWeight, 0.05)
  676. result += float64(dateRecord.CloudBrainTaskNum) * getParaWeightValue("CloudBrainTaskNum", ParaWeight, 0.3)
  677. result += float64(dateRecord.CommitModelCount) * getParaWeightValue("CommitModelCount", ParaWeight, 0.2)
  678. result += dateRecord.OpenIIndex * getParaWeightValue("OpenIIndex", ParaWeight, 0.1)
  679. return result
  680. }
  681. func getUserIndex(dateRecord UserBusinessAnalysis, ParaWeight map[string]float64) float64 {
  682. var result float64
  683. // PR数 0.20
  684. // commit数 0.20
  685. // 提出任务数 0.20
  686. // 评论数 0.20
  687. // 关注项目数 0.10
  688. // 点赞项目数 0.10
  689. // 登录次数 0.10
  690. result = float64(dateRecord.CodeMergeCount) * getParaWeightValue("CodeMergeCount", ParaWeight, 0.2)
  691. result += float64(dateRecord.CommitCount) * getParaWeightValue("CommitCount", ParaWeight, 0.2)
  692. log.Info("2 result=" + fmt.Sprint(result))
  693. result += float64(dateRecord.IssueCount) * getParaWeightValue("IssueCount", ParaWeight, 0.2)
  694. result += float64(dateRecord.CommentCount) * getParaWeightValue("CommentCount", ParaWeight, 0.2)
  695. result += float64(dateRecord.FocusRepoCount) * getParaWeightValue("FocusRepoCount", ParaWeight, 0.1)
  696. result += float64(dateRecord.StarRepoCount) * getParaWeightValue("StarRepoCount", ParaWeight, 0.1)
  697. result += float64(dateRecord.LoginCount) * getParaWeightValue("LoginCount", ParaWeight, 0.1)
  698. result += float64(dateRecord.WatchedCount) * getParaWeightValue("WatchedCount", ParaWeight, 0.3)
  699. codeLine := float64(dateRecord.CommitCodeSize) / 1000
  700. limitCodeLine := getParaWeightValue("LimitCommitCodeSize", ParaWeight, 100)
  701. if codeLine >= limitCodeLine {
  702. codeLine = limitCodeLine
  703. }
  704. result += codeLine * getParaWeightValue("CommitCodeSize", ParaWeight, 0.1)
  705. result += float64(dateRecord.SolveIssueCount) * getParaWeightValue("SolveIssueCount", ParaWeight, 0.2)
  706. result += float64(dateRecord.EncyclopediasCount) * getParaWeightValue("EncyclopediasCount", ParaWeight, 0.1)
  707. result += float64(dateRecord.CreateRepoCount) * getParaWeightValue("CreateRepoCount", ParaWeight, 0.05)
  708. result += float64(dateRecord.CloudBrainTaskNum) * getParaWeightValue("CloudBrainTaskNum", ParaWeight, 0.3)
  709. result += float64(dateRecord.CommitModelCount) * getParaWeightValue("CommitModelCount", ParaWeight, 0.2)
  710. result += dateRecord.OpenIIndex * getParaWeightValue("OpenIIndex", ParaWeight, 0.1)
  711. return result
  712. }
  713. func getParaWeightValue(key string, valueMap map[string]float64, defaultValue float64) float64 {
  714. if _, ok := valueMap[key]; !ok {
  715. return defaultValue
  716. } else {
  717. return valueMap[key]
  718. }
  719. }
  720. func getMapKeyStringValue(key string, valueMap map[string]int) int {
  721. if _, ok := valueMap[key]; !ok {
  722. return 0
  723. } else {
  724. return valueMap[key]
  725. }
  726. }
  727. func getMapValue(userId int64, valueMap map[int64]int) int {
  728. if _, ok := valueMap[userId]; !ok {
  729. return 0
  730. } else {
  731. return valueMap[userId]
  732. }
  733. }
  734. func getInt(str string) int {
  735. re, err := strconv.ParseInt(str, 10, 32)
  736. if err != nil {
  737. return 0
  738. }
  739. return int(re)
  740. }
  741. func CounDataByDate(wikiCountMap map[string]int, startTime time.Time, endTime time.Time) {
  742. CounDataByDateAndReCount(wikiCountMap, startTime, endTime, false)
  743. }
  744. func querySolveIssue(start_unix int64, end_unix int64) map[int64]int {
  745. sess := x.NewSession()
  746. defer sess.Close()
  747. resultMap := make(map[int64]int)
  748. cond := "issue.is_closed=true and issue.closed_unix>=" + fmt.Sprint(start_unix) + " and issue.closed_unix<=" + fmt.Sprint(end_unix)
  749. count, err := sess.Table("issue_assignees").Join("inner", "issue", "issue.id=issue_assignees.issue_id").Where(cond).Count(new(IssueAssignees))
  750. if err != nil {
  751. log.Info("query issue error. return.")
  752. return resultMap
  753. }
  754. var indexTotal int64
  755. indexTotal = 0
  756. for {
  757. issueAssigneesList := make([]*IssueAssignees, 0)
  758. sess.Select("issue_assignees.*").Table("issue_assignees").
  759. Join("inner", "issue", "issue.id=issue_assignees.issue_id").
  760. Where(cond).OrderBy("issue_assignees.id asc").Limit(PAGE_SIZE, int(indexTotal))
  761. sess.Find(&issueAssigneesList)
  762. log.Info("query IssueAssignees size=" + fmt.Sprint(len(issueAssigneesList)))
  763. for _, issueAssigneesRecord := range issueAssigneesList {
  764. if _, ok := resultMap[issueAssigneesRecord.AssigneeID]; !ok {
  765. resultMap[issueAssigneesRecord.AssigneeID] = 1
  766. } else {
  767. resultMap[issueAssigneesRecord.AssigneeID] += 1
  768. }
  769. }
  770. indexTotal += PAGE_SIZE
  771. if indexTotal >= count {
  772. break
  773. }
  774. }
  775. return resultMap
  776. }
  777. func queryPullRequest(start_unix int64, end_unix int64) map[int64]int {
  778. sess := x.NewSession()
  779. defer sess.Close()
  780. resultMap := make(map[int64]int)
  781. cond := "pull_request.merged_unix>=" + fmt.Sprint(start_unix) + " and pull_request.merged_unix<=" + fmt.Sprint(end_unix)
  782. count, err := sess.Table("issue").Join("inner", "pull_request", "issue.id=pull_request.issue_id").Where(cond).Count(new(Issue))
  783. if err != nil {
  784. log.Info("query issue error. return.")
  785. return resultMap
  786. }
  787. var indexTotal int64
  788. indexTotal = 0
  789. for {
  790. issueList := make([]*Issue, 0)
  791. 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))
  792. sess.Find(&issueList)
  793. log.Info("query issue(PR) size=" + fmt.Sprint(len(issueList)))
  794. for _, issueRecord := range issueList {
  795. if _, ok := resultMap[issueRecord.PosterID]; !ok {
  796. resultMap[issueRecord.PosterID] = 1
  797. } else {
  798. resultMap[issueRecord.PosterID] += 1
  799. }
  800. }
  801. indexTotal += PAGE_SIZE
  802. if indexTotal >= count {
  803. break
  804. }
  805. }
  806. return resultMap
  807. }
  808. func queryCommitAction(start_unix int64, end_unix int64, actionType int64) map[int64]int {
  809. sess := x.NewSession()
  810. defer sess.Close()
  811. resultMap := make(map[int64]int)
  812. 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)
  813. count, err := sess.Where(cond).Count(new(Action))
  814. if err != nil {
  815. log.Info("query action error. return.")
  816. return resultMap
  817. }
  818. var indexTotal int64
  819. indexTotal = 0
  820. for {
  821. sess.Select("id,user_id,op_type,act_user_id").Table("action").Where(cond).OrderBy("id asc").Limit(PAGE_SIZE, int(indexTotal))
  822. actionList := make([]*Action, 0)
  823. sess.Find(&actionList)
  824. log.Info("query action size=" + fmt.Sprint(len(actionList)))
  825. for _, actionRecord := range actionList {
  826. if _, ok := resultMap[actionRecord.UserID]; !ok {
  827. resultMap[actionRecord.UserID] = 1
  828. } else {
  829. resultMap[actionRecord.UserID] += 1
  830. }
  831. }
  832. indexTotal += PAGE_SIZE
  833. if indexTotal >= count {
  834. break
  835. }
  836. }
  837. return resultMap
  838. }
  839. func queryCreateIssue(start_unix int64, end_unix int64) map[int64]int {
  840. sess := x.NewSession()
  841. defer sess.Close()
  842. resultMap := make(map[int64]int)
  843. cond := "is_pull=false and created_unix>=" + fmt.Sprint(start_unix) + " and created_unix<=" + fmt.Sprint(end_unix)
  844. count, err := sess.Where(cond).Count(new(Issue))
  845. if err != nil {
  846. log.Info("query Issue error. return.")
  847. return resultMap
  848. }
  849. var indexTotal int64
  850. indexTotal = 0
  851. for {
  852. sess.Select("id,poster_id").Table("issue").Where(cond).OrderBy("id asc").Limit(PAGE_SIZE, int(indexTotal))
  853. issueList := make([]*Issue, 0)
  854. sess.Find(&issueList)
  855. log.Info("query issue size=" + fmt.Sprint(len(issueList)))
  856. for _, issueRecord := range issueList {
  857. if _, ok := resultMap[issueRecord.PosterID]; !ok {
  858. resultMap[issueRecord.PosterID] = 1
  859. } else {
  860. resultMap[issueRecord.PosterID] += 1
  861. }
  862. }
  863. indexTotal += PAGE_SIZE
  864. if indexTotal >= count {
  865. break
  866. }
  867. }
  868. return resultMap
  869. }
  870. func queryComment(start_unix int64, end_unix int64) map[int64]int {
  871. sess := x.NewSession()
  872. defer sess.Close()
  873. cond := "created_unix>=" + fmt.Sprint(start_unix) + " and created_unix<=" + fmt.Sprint(end_unix)
  874. resultMap := make(map[int64]int)
  875. count, err := sess.Where(cond).Count(new(Comment))
  876. if err != nil {
  877. log.Info("query Comment error. return.")
  878. return resultMap
  879. }
  880. var indexTotal int64
  881. indexTotal = 0
  882. for {
  883. sess.Select("id,type,poster_id").Table("comment").Where(cond).OrderBy("id asc").Limit(PAGE_SIZE, int(indexTotal))
  884. commentList := make([]*Comment, 0)
  885. sess.Find(&commentList)
  886. log.Info("query Comment size=" + fmt.Sprint(len(commentList)))
  887. for _, commentRecord := range commentList {
  888. if _, ok := resultMap[commentRecord.PosterID]; !ok {
  889. resultMap[commentRecord.PosterID] = 1
  890. } else {
  891. resultMap[commentRecord.PosterID] += 1
  892. }
  893. }
  894. indexTotal += PAGE_SIZE
  895. if indexTotal >= count {
  896. break
  897. }
  898. }
  899. return resultMap
  900. }
  901. func queryWatch(start_unix int64, end_unix int64) map[int64]int {
  902. sess := x.NewSession()
  903. defer sess.Close()
  904. cond := " created_unix>=" + fmt.Sprint(start_unix) + " and created_unix<=" + fmt.Sprint(end_unix)
  905. resultMap := make(map[int64]int)
  906. count, err := sess.Where(cond).Count(new(Watch))
  907. if err != nil {
  908. log.Info("query issue error. return.")
  909. return resultMap
  910. }
  911. var indexTotal int64
  912. indexTotal = 0
  913. for {
  914. watchList := make([]*Watch, 0)
  915. sess.Select("id,user_id,repo_id").Table("watch").Where(cond).OrderBy("id asc").Limit(PAGE_SIZE, int(indexTotal))
  916. sess.Find(&watchList)
  917. log.Info("query Watch size=" + fmt.Sprint(len(watchList)))
  918. for _, watchRecord := range watchList {
  919. if _, ok := resultMap[watchRecord.UserID]; !ok {
  920. resultMap[watchRecord.UserID] = 1
  921. } else {
  922. resultMap[watchRecord.UserID] += 1
  923. }
  924. }
  925. indexTotal += PAGE_SIZE
  926. if indexTotal >= count {
  927. break
  928. }
  929. }
  930. return resultMap
  931. }
  932. func queryStar(start_unix int64, end_unix int64) map[int64]int {
  933. sess := x.NewSession()
  934. defer sess.Close()
  935. cond := " created_unix>=" + fmt.Sprint(start_unix) + " and created_unix<=" + fmt.Sprint(end_unix)
  936. resultMap := make(map[int64]int)
  937. count, err := sess.Where(cond).Count(new(Star))
  938. if err != nil {
  939. log.Info("query star error. return.")
  940. return resultMap
  941. }
  942. var indexTotal int64
  943. indexTotal = 0
  944. for {
  945. sess.Select("id,uid,repo_id").Table("star").Where(cond).OrderBy("id asc").Limit(PAGE_SIZE, int(indexTotal))
  946. starList := make([]*Star, 0)
  947. sess.Find(&starList)
  948. log.Info("query Star size=" + fmt.Sprint(len(starList)))
  949. for _, starRecord := range starList {
  950. if _, ok := resultMap[starRecord.UID]; !ok {
  951. resultMap[starRecord.UID] = 1
  952. } else {
  953. resultMap[starRecord.UID] += 1
  954. }
  955. }
  956. indexTotal += PAGE_SIZE
  957. if indexTotal >= count {
  958. break
  959. }
  960. }
  961. return resultMap
  962. }
  963. func queryFollow(start_unix int64, end_unix int64) map[int64]int {
  964. sess := x.NewSession()
  965. defer sess.Close()
  966. resultMap := make(map[int64]int)
  967. cond := " created_unix>=" + fmt.Sprint(start_unix) + " and created_unix<=" + fmt.Sprint(end_unix)
  968. count, err := sess.Where(cond).Count(new(Follow))
  969. if err != nil {
  970. log.Info("query follow error. return.")
  971. return resultMap
  972. }
  973. var indexTotal int64
  974. indexTotal = 0
  975. for {
  976. sess.Select("id,user_id,follow_id").Table("follow").Where(cond).OrderBy("id asc").Limit(PAGE_SIZE, int(indexTotal))
  977. followList := make([]*Follow, 0)
  978. sess.Find(&followList)
  979. log.Info("query Follow size=" + fmt.Sprint(len(followList)))
  980. for _, followRecord := range followList {
  981. if _, ok := resultMap[followRecord.FollowID]; !ok {
  982. resultMap[followRecord.FollowID] = 1
  983. } else {
  984. resultMap[followRecord.FollowID] += 1
  985. }
  986. }
  987. indexTotal += PAGE_SIZE
  988. if indexTotal >= count {
  989. break
  990. }
  991. }
  992. return resultMap
  993. }
  994. func queryDatasetSize(start_unix int64, end_unix int64) (map[int64]int, map[int64]int) {
  995. sess := x.NewSession()
  996. defer sess.Close()
  997. resultSizeMap := make(map[int64]int)
  998. resultNumMap := make(map[int64]int)
  999. cond := " created_unix>=" + fmt.Sprint(start_unix) + " and created_unix<=" + fmt.Sprint(end_unix)
  1000. count, err := sess.Where(cond).Count(new(Attachment))
  1001. if err != nil {
  1002. log.Info("query attachment error. return.")
  1003. return resultSizeMap, resultNumMap
  1004. }
  1005. var indexTotal int64
  1006. indexTotal = 0
  1007. for {
  1008. sess.Select("id,uploader_id,size").Table("attachment").Where(cond).OrderBy("id asc").Limit(PAGE_SIZE, int(indexTotal))
  1009. attachmentList := make([]*Attachment, 0)
  1010. sess.Find(&attachmentList)
  1011. log.Info("query Attachment size=" + fmt.Sprint(len(attachmentList)))
  1012. for _, attachRecord := range attachmentList {
  1013. if _, ok := resultSizeMap[attachRecord.UploaderID]; !ok {
  1014. resultSizeMap[attachRecord.UploaderID] = int(attachRecord.Size / (1024 * 1024)) //MB
  1015. resultNumMap[attachRecord.UploaderID] = 1
  1016. } else {
  1017. resultSizeMap[attachRecord.UploaderID] += int(attachRecord.Size / (1024 * 1024)) //MB
  1018. resultNumMap[attachRecord.UploaderID] += 1
  1019. }
  1020. }
  1021. indexTotal += PAGE_SIZE
  1022. if indexTotal >= count {
  1023. break
  1024. }
  1025. }
  1026. return resultSizeMap, resultNumMap
  1027. }
  1028. func queryUserCreateRepo(start_unix int64, end_unix int64) map[int64]int {
  1029. sess := x.NewSession()
  1030. defer sess.Close()
  1031. resultMap := make(map[int64]int)
  1032. cond := "is_fork=false and created_unix>=" + fmt.Sprint(start_unix) + " and created_unix<=" + fmt.Sprint(end_unix)
  1033. count, err := sess.Where(cond).Count(new(Repository))
  1034. if err != nil {
  1035. log.Info("query Repository error. return.")
  1036. return resultMap
  1037. }
  1038. var indexTotal int64
  1039. indexTotal = 0
  1040. for {
  1041. sess.Select("id,owner_id,name").Table("repository").Where(cond).OrderBy("id asc").Limit(PAGE_SIZE, int(indexTotal))
  1042. repoList := make([]*Repository, 0)
  1043. sess.Find(&repoList)
  1044. log.Info("query Repository size=" + fmt.Sprint(len(repoList)))
  1045. for _, repoRecord := range repoList {
  1046. if _, ok := resultMap[repoRecord.OwnerID]; !ok {
  1047. resultMap[repoRecord.OwnerID] = 1
  1048. } else {
  1049. resultMap[repoRecord.OwnerID] += 1
  1050. }
  1051. }
  1052. indexTotal += PAGE_SIZE
  1053. if indexTotal >= count {
  1054. break
  1055. }
  1056. }
  1057. return resultMap
  1058. }
  1059. func queryUserRepoOpenIIndex(start_unix int64, end_unix int64) map[int64]float64 {
  1060. statictisSess := xStatistic.NewSession()
  1061. defer statictisSess.Close()
  1062. 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")
  1063. repoStatisticList := make([]*RepoStatistic, 0)
  1064. statictisSess.Find(&repoStatisticList)
  1065. repoOpenIIndexMap := make(map[int64]float64)
  1066. log.Info("query repo_statistic size=" + fmt.Sprint(len(repoStatisticList)))
  1067. for _, repoRecord := range repoStatisticList {
  1068. if _, ok := repoOpenIIndexMap[repoRecord.RepoID]; !ok {
  1069. repoOpenIIndexMap[repoRecord.RepoID] = repoRecord.RadarTotal
  1070. }
  1071. }
  1072. sess := x.NewSession()
  1073. defer sess.Close()
  1074. sess.Select("id,owner_id,name").Table("repository").Where("is_fork=false")
  1075. repoList := make([]*Repository, 0)
  1076. sess.Find(&repoList)
  1077. userMap := make(map[int64]float64)
  1078. log.Info("query Repository size=" + fmt.Sprint(len(repoList)))
  1079. for _, repoRecord := range repoList {
  1080. if _, ok := userMap[repoRecord.OwnerID]; !ok {
  1081. if _, ok := repoOpenIIndexMap[repoRecord.ID]; ok {
  1082. userMap[repoRecord.OwnerID] = repoOpenIIndexMap[repoRecord.ID]
  1083. }
  1084. }
  1085. }
  1086. //query collaboration
  1087. sess.Select("repo_id,user_id,mode").Table("collaboration")
  1088. collaborationList := make([]*Collaboration, 0)
  1089. sess.Find(&collaborationList)
  1090. log.Info("query collaborationList size=" + fmt.Sprint(len(collaborationList)))
  1091. for _, collaborationRecord := range collaborationList {
  1092. if _, ok := userMap[collaborationRecord.UserID]; !ok {
  1093. if _, ok := repoOpenIIndexMap[collaborationRecord.RepoID]; ok {
  1094. userMap[collaborationRecord.UserID] = repoOpenIIndexMap[collaborationRecord.RepoID]
  1095. }
  1096. } else {
  1097. if _, ok := repoOpenIIndexMap[collaborationRecord.RepoID]; ok {
  1098. userMap[collaborationRecord.UserID] += repoOpenIIndexMap[collaborationRecord.RepoID]
  1099. }
  1100. }
  1101. }
  1102. log.Info("user openi index size=" + fmt.Sprint(len(userMap)))
  1103. return userMap
  1104. }
  1105. func queryLoginCount(start_unix int64, end_unix int64) map[int64]int {
  1106. statictisSess := xStatistic.NewSession()
  1107. defer statictisSess.Close()
  1108. resultMap := make(map[int64]int)
  1109. cond := "created_unix>=" + fmt.Sprint(start_unix) + " and created_unix<=" + fmt.Sprint(end_unix)
  1110. count, err := statictisSess.Where(cond).Count(new(UserLoginLog))
  1111. if err != nil {
  1112. log.Info("query UserLoginLog error. return.")
  1113. return resultMap
  1114. }
  1115. var indexTotal int64
  1116. indexTotal = 0
  1117. for {
  1118. statictisSess.Select("id,u_id").Table("user_login_log").Where(cond).OrderBy("id asc").Limit(PAGE_SIZE, int(indexTotal))
  1119. userLoginLogList := make([]*UserLoginLog, 0)
  1120. statictisSess.Find(&userLoginLogList)
  1121. log.Info("query user login size=" + fmt.Sprint(len(userLoginLogList)))
  1122. for _, loginRecord := range userLoginLogList {
  1123. if _, ok := resultMap[loginRecord.UId]; !ok {
  1124. resultMap[loginRecord.UId] = 1
  1125. } else {
  1126. resultMap[loginRecord.UId] += 1
  1127. }
  1128. }
  1129. indexTotal += PAGE_SIZE
  1130. if indexTotal >= count {
  1131. break
  1132. }
  1133. }
  1134. log.Info("user login size=" + fmt.Sprint(len(resultMap)))
  1135. return resultMap
  1136. }
  1137. func queryCommitCodeSize(start_unix int64, end_unix int64) map[int64]int {
  1138. statictisSess := xStatistic.NewSession()
  1139. defer statictisSess.Close()
  1140. resultMap := make(map[int64]int)
  1141. cond := "count_date>=" + fmt.Sprint(start_unix) + " and count_date<=" + fmt.Sprint(end_unix)
  1142. count, err := statictisSess.Where(cond).Count(new(UserBusinessAnalysis))
  1143. if err != nil {
  1144. log.Info("query commit code size error. return.")
  1145. return resultMap
  1146. }
  1147. var indexTotal int64
  1148. indexTotal = 0
  1149. for {
  1150. statictisSess.Select("id,commit_code_size").Table("user_business_analysis").Where(cond).OrderBy("id asc").Limit(PAGE_SIZE, int(indexTotal))
  1151. userBusinessAnalysisList := make([]*UserBusinessAnalysis, 0)
  1152. statictisSess.Find(&userBusinessAnalysisList)
  1153. log.Info("query user login size=" + fmt.Sprint(len(userBusinessAnalysisList)))
  1154. for _, analysisRecord := range userBusinessAnalysisList {
  1155. if _, ok := resultMap[analysisRecord.ID]; !ok {
  1156. resultMap[analysisRecord.ID] = analysisRecord.CommitCodeSize
  1157. } else {
  1158. resultMap[analysisRecord.ID] += analysisRecord.CommitCodeSize
  1159. }
  1160. }
  1161. indexTotal += PAGE_SIZE
  1162. if indexTotal >= count {
  1163. break
  1164. }
  1165. }
  1166. log.Info("user commit code size=" + fmt.Sprint(len(resultMap)))
  1167. return resultMap
  1168. }
  1169. func queryUserModel(start_unix int64, end_unix int64) map[int64]int {
  1170. sess := x.NewSession()
  1171. defer sess.Close()
  1172. resultMap := 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(AiModelManage))
  1175. if err != nil {
  1176. log.Info("query AiModelManage error. return.")
  1177. return resultMap
  1178. }
  1179. var indexTotal int64
  1180. indexTotal = 0
  1181. for {
  1182. sess.Select("id,user_id").Table("ai_model_manage").Where(cond).OrderBy("id asc").Limit(PAGE_SIZE, int(indexTotal))
  1183. aiModelList := make([]*AiModelManage, 0)
  1184. sess.Find(&aiModelList)
  1185. log.Info("query AiModelManage size=" + fmt.Sprint(len(aiModelList)))
  1186. for _, aiModelRecord := range aiModelList {
  1187. if _, ok := resultMap[aiModelRecord.UserId]; !ok {
  1188. resultMap[aiModelRecord.UserId] = 1
  1189. } else {
  1190. resultMap[aiModelRecord.UserId] += 1
  1191. }
  1192. }
  1193. indexTotal += PAGE_SIZE
  1194. if indexTotal >= count {
  1195. break
  1196. }
  1197. }
  1198. return resultMap
  1199. }
  1200. func queryCloudBrainTask(start_unix int64, end_unix int64) (map[int64]int, map[string]int) {
  1201. sess := x.NewSession()
  1202. defer sess.Close()
  1203. resultMap := make(map[int64]int)
  1204. resultItemMap := make(map[string]int)
  1205. cond := " created_unix>=" + fmt.Sprint(start_unix) + " and created_unix<=" + fmt.Sprint(end_unix)
  1206. count, err := sess.Where(cond).Count(new(Cloudbrain))
  1207. if err != nil {
  1208. log.Info("query cloudbrain error. return.")
  1209. return resultMap, resultItemMap
  1210. }
  1211. var indexTotal int64
  1212. indexTotal = 0
  1213. for {
  1214. sess.Select("id,job_type,user_id,duration,train_job_duration,type").Table("cloudbrain").Where(cond).OrderBy("id asc").Limit(PAGE_SIZE, int(indexTotal))
  1215. cloudTaskList := make([]*Cloudbrain, 0)
  1216. sess.Find(&cloudTaskList)
  1217. log.Info("query cloudbrain size=" + fmt.Sprint(len(cloudTaskList)))
  1218. for _, cloudTaskRecord := range cloudTaskList {
  1219. if _, ok := resultMap[cloudTaskRecord.UserID]; !ok {
  1220. resultMap[cloudTaskRecord.UserID] = 1
  1221. } else {
  1222. resultMap[cloudTaskRecord.UserID] += 1
  1223. }
  1224. setMapKey("CloudBrainRunTime", cloudTaskRecord.UserID, int(cloudTaskRecord.Duration), resultItemMap)
  1225. if cloudTaskRecord.Type == 1 { //npu
  1226. if cloudTaskRecord.JobType == "TRAIN" {
  1227. setMapKey("NpuTrainJob", cloudTaskRecord.UserID, 1, resultItemMap)
  1228. } else if cloudTaskRecord.JobType == "INFERENCE" {
  1229. setMapKey("NpuInferenceJob", cloudTaskRecord.UserID, 1, resultItemMap)
  1230. } else {
  1231. setMapKey("NpuDebugJob", cloudTaskRecord.UserID, 1, resultItemMap)
  1232. }
  1233. } else { //type=0 gpu
  1234. if cloudTaskRecord.JobType == "TRAIN" {
  1235. setMapKey("GpuTrainJob", cloudTaskRecord.UserID, 1, resultItemMap)
  1236. } else if cloudTaskRecord.JobType == "BENCHMARK" {
  1237. setMapKey("GpuBenchMarkJob", cloudTaskRecord.UserID, 1, resultItemMap)
  1238. } else {
  1239. setMapKey("GpuDebugJob", cloudTaskRecord.UserID, 1, resultItemMap)
  1240. }
  1241. }
  1242. }
  1243. indexTotal += PAGE_SIZE
  1244. if indexTotal >= count {
  1245. break
  1246. }
  1247. }
  1248. return resultMap, resultItemMap
  1249. }
  1250. func setMapKey(key string, userId int64, value int, resultItemMap map[string]int) {
  1251. newKey := fmt.Sprint(userId) + "_" + key
  1252. if _, ok := resultItemMap[newKey]; !ok {
  1253. resultItemMap[newKey] = value
  1254. } else {
  1255. resultItemMap[newKey] += value
  1256. }
  1257. }
  1258. func subMonth(t1, t2 time.Time) (month int) {
  1259. y1 := t1.Year()
  1260. y2 := t2.Year()
  1261. m1 := int(t1.Month())
  1262. m2 := int(t2.Month())
  1263. d1 := t1.Day()
  1264. d2 := t2.Day()
  1265. yearInterval := y1 - y2
  1266. // 如果 d1的 月-日 小于 d2的 月-日 那么 yearInterval-- 这样就得到了相差的年数
  1267. if m1 < m2 || m1 == m2 && d1 < d2 {
  1268. yearInterval--
  1269. }
  1270. // 获取月数差值
  1271. monthInterval := (m1 + 12) - m2
  1272. if d1 < d2 {
  1273. monthInterval--
  1274. }
  1275. monthInterval %= 12
  1276. month = yearInterval*12 + monthInterval
  1277. if month == 0 {
  1278. month = 1
  1279. }
  1280. return month
  1281. }