task.go 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230
  1. package dao
  2. import (
  3. "bytes"
  4. "context"
  5. "encoding/json"
  6. "fmt"
  7. "io/ioutil"
  8. "net/http"
  9. "net/url"
  10. "strings"
  11. "time"
  12. "go-common/app/job/main/dm2/model"
  13. "go-common/library/database/sql"
  14. "go-common/library/log"
  15. "go-common/library/xstr"
  16. )
  17. const (
  18. _taskInfo = "SELECT id,topic,state,qcount,result,sub,last_index,priority,creator,reviewer,title FROM dm_task WHERE state=? order by priority desc,ctime asc"
  19. _oneTask = "SELECT id,topic,state,qcount,result,sub,last_index,priority,creator,reviewer,title FROM dm_task WHERE state in (3,9) order by priority desc,ctime asc limit 1"
  20. _taskByID = "SELECT id,topic,state,qcount,result,sub,last_index,priority,creator,reviewer,title FROM dm_task WHERE id=?"
  21. _uptTask = "UPDATE dm_task SET state=?,last_index=?,qcount=?,result=? WHERE id=?"
  22. _uptSubTask = "UPDATE dm_sub_task SET tcount=tcount+?,end=? WHERE task_id=?"
  23. _selectSubTask = "SELECT id,operation,rate,tcount,start,end FROM dm_sub_task WHERE task_id=?"
  24. _delDMIndex = "UPDATE dm_index_%03d SET state=? WHERE oid=? AND id IN (%s)"
  25. _uptSubCountSQL = "UPDATE dm_subject_%02d SET count=count-? WHERE type=? AND oid=?"
  26. _merakMsgURI = "/"
  27. )
  28. // TaskInfos task infos.
  29. func (d *Dao) TaskInfos(c context.Context, state int32) (tasks []*model.TaskInfo, err error) {
  30. rows, err := d.biliDMWriter.Query(c, _taskInfo, state)
  31. if err != nil {
  32. log.Error("d.biliDMWriter.Query(query:%s,state:%d) error(%v)", _taskInfo, state, err)
  33. return
  34. }
  35. defer rows.Close()
  36. for rows.Next() {
  37. task := &model.TaskInfo{}
  38. if err = rows.Scan(&task.ID, &task.Topic, &task.State, &task.Count, &task.Result, &task.Sub, &task.LastIndex, &task.Priority, &task.Creator, &task.Reviewer, &task.Title); err != nil {
  39. log.Error("d.biliDMWriter.Scan(query:%s,state:%d) error(%v)", _taskInfo, state, err)
  40. return
  41. }
  42. tasks = append(tasks, task)
  43. }
  44. if err = rows.Err(); err != nil {
  45. log.Error("d.biliDMWriter.rows.Err() error(%v)", err)
  46. }
  47. return
  48. }
  49. // OneTask .
  50. func (d *Dao) OneTask(c context.Context) (task *model.TaskInfo, err error) {
  51. task = &model.TaskInfo{}
  52. row := d.biliDMWriter.QueryRow(c, _oneTask)
  53. if err = row.Scan(&task.ID, &task.Topic, &task.State, &task.Count, &task.Result, &task.Sub, &task.LastIndex, &task.Priority, &task.Creator, &task.Reviewer, &task.Title); err != nil {
  54. if err == sql.ErrNoRows {
  55. err = nil
  56. task = nil
  57. } else {
  58. log.Error("d.biliDMWriter.Scan(query:%s) error(%v)", _oneTask, err)
  59. }
  60. }
  61. return
  62. }
  63. // TaskInfoByID .
  64. func (d *Dao) TaskInfoByID(c context.Context, id int64) (task *model.TaskInfo, err error) {
  65. task = &model.TaskInfo{}
  66. row := d.biliDMWriter.QueryRow(c, _taskByID, id)
  67. if err = row.Scan(&task.ID, &task.Topic, &task.State, &task.Count, &task.Result, &task.Sub, &task.LastIndex, &task.Priority, &task.Creator, &task.Reviewer, &task.Title); err != nil {
  68. if err == sql.ErrNoRows {
  69. err = nil
  70. task = nil
  71. } else {
  72. log.Error("d.biliDMWriter.Scan(query:%s,id:%d) error(%v)", _taskByID, id, err)
  73. }
  74. }
  75. return
  76. }
  77. // UpdateTask update dm task.
  78. func (d *Dao) UpdateTask(c context.Context, task *model.TaskInfo) (affected int64, err error) {
  79. row, err := d.biliDMWriter.Exec(c, _uptTask, task.State, task.LastIndex, task.Count, task.Result, task.ID)
  80. if err != nil {
  81. log.Error("d.biliDMWriter.Exec(query:%s,task:%+v) error(%v)", _uptTask, task, err)
  82. return
  83. }
  84. return row.RowsAffected()
  85. }
  86. // UptSubTask uopdate dm sub task.
  87. func (d *Dao) UptSubTask(c context.Context, taskID, delCount int64, end time.Time) (affected int64, err error) {
  88. row, err := d.biliDMWriter.Exec(c, _uptSubTask, delCount, end, taskID)
  89. if err != nil {
  90. log.Error("d.biliDMWriter.Exec(query:%s) error(%v)", _uptSubTask, err)
  91. return
  92. }
  93. return row.RowsAffected()
  94. }
  95. // SubTask .
  96. func (d *Dao) SubTask(c context.Context, id int64) (subTask *model.SubTask, err error) {
  97. // TODO: operation time
  98. subTask = new(model.SubTask)
  99. row := d.biliDMWriter.QueryRow(c, _selectSubTask, id)
  100. if err = row.Scan(&subTask.ID, &subTask.Operation, &subTask.Rate, &subTask.Tcount, &subTask.Start, &subTask.End); err != nil {
  101. if err == sql.ErrNoRows {
  102. err = nil
  103. subTask = nil
  104. }
  105. log.Error("biliDM.Scan(%s, taskID:%d) error*(%v)", _selectSubTask, id, err)
  106. return
  107. }
  108. return
  109. }
  110. // DelDMs dm task del dms.
  111. func (d *Dao) DelDMs(c context.Context, oid int64, dmids []int64, state int32) (affected int64, err error) {
  112. rows, err := d.dmWriter.Exec(c, fmt.Sprintf(_delDMIndex, d.hitIndex(oid), xstr.JoinInts(dmids)), state, oid)
  113. if err != nil {
  114. log.Error("d.dmWriter.Exec(query:%s,oid:%d,dmids:%v) error(%v)", _delDMIndex, oid, dmids, err)
  115. return
  116. }
  117. return rows.RowsAffected()
  118. }
  119. // UptSubjectCount update count.
  120. func (d *Dao) UptSubjectCount(c context.Context, tp int32, oid, count int64) (affected int64, err error) {
  121. res, err := d.dmWriter.Exec(c, fmt.Sprintf(_uptSubCountSQL, d.hitSubject(oid)), count, tp, oid)
  122. if err != nil {
  123. log.Error("dmWriter.Exec(query:%s,oid:%d) error(%v)", _uptSubCountSQL, oid, err)
  124. return
  125. }
  126. return res.RowsAffected()
  127. }
  128. // TaskSearchRes get res from BI url
  129. func (d *Dao) TaskSearchRes(c context.Context, task *model.TaskInfo) (count int64, result string, state int32, err error) {
  130. var (
  131. resp *http.Response
  132. res struct {
  133. Code int64 `json:"code"`
  134. StatusID int32 `json:"statusId"`
  135. Path []string `json:"hdfsPath"`
  136. Count int64 `json:"count"`
  137. }
  138. bs []byte
  139. )
  140. // may costing long time use default transport
  141. if resp, err = http.Get(task.Topic); err != nil {
  142. log.Error("http.Get(%s) error(%v)", task.Topic, err)
  143. return
  144. }
  145. defer resp.Body.Close()
  146. if bs, err = ioutil.ReadAll(resp.Body); err != nil {
  147. log.Error("ioutil.ReadAll url:%v error(%v)", task.Topic, err)
  148. return
  149. }
  150. if err = json.Unmarshal(bs, &res); err != nil {
  151. return
  152. }
  153. if res.Code != 200 {
  154. err = fmt.Errorf("%v", res)
  155. log.Error("d.httpClient.Get(%s) code(%d)", task.Topic, res.Code)
  156. return
  157. }
  158. if res.StatusID == model.TaskSearchSuc && len(res.Path) > 0 {
  159. result = res.Path[0]
  160. count = res.Count
  161. }
  162. return count, result, res.StatusID, err
  163. }
  164. // SendWechatWorkMsg send wechat work msg.
  165. func (d *Dao) SendWechatWorkMsg(c context.Context, content, title string, users []string) (err error) {
  166. userMap := make(map[string]struct{}, len(users))
  167. unames := make([]string, 0, len(users))
  168. for _, user := range users {
  169. if user == "" {
  170. continue
  171. }
  172. if _, ok := userMap[user]; ok {
  173. continue
  174. }
  175. userMap[user] = struct{}{}
  176. unames = append(unames, user)
  177. }
  178. params := url.Values{}
  179. params.Set("Action", "CreateWechatMessage")
  180. params.Set("PublicKey", d.conf.TaskConf.MsgPublicKey)
  181. params.Set("UserName", strings.Join(unames, ","))
  182. params.Set("Title", title)
  183. params.Set("Content", content)
  184. params.Set("Signature", "")
  185. params.Set("TreeId", "")
  186. paramStr := params.Encode()
  187. if strings.IndexByte(paramStr, '+') > -1 {
  188. paramStr = strings.Replace(paramStr, "+", "%20", -1)
  189. }
  190. var (
  191. buffer bytes.Buffer
  192. querry string
  193. )
  194. buffer.WriteString(paramStr)
  195. querry = buffer.String()
  196. res := &struct {
  197. Code int `json:"RetCode"`
  198. }{}
  199. url := d.conf.Host.MerakHost + _merakMsgURI
  200. req, err := http.NewRequest("POST", url, strings.NewReader(querry))
  201. if err != nil {
  202. return
  203. }
  204. req.Header.Add("content-type", "application/x-www-form-urlencoded; charset=UTF-8")
  205. if err = d.httpCli.Do(c, req, res); err != nil {
  206. log.Error("d.SendWechatWorkMsg.client.Do(%v,%v) error(%v)", req, querry, err)
  207. return
  208. }
  209. if res.Code != 0 {
  210. log.Error("d.SendWechatWorkMsg(%s,%s,%v) res.Code != 0, res(%v)", content, title, users, res)
  211. err = fmt.Errorf("uri:%s,code:%d", url+querry, res.Code)
  212. }
  213. return
  214. }