You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

91 lines
2.5 KiB

  1. // Copyright 2011 Xing Xing <mikespook@gmail.com>
  2. // All rights reserved.
  3. // Use of this source code is governed by a MIT
  4. // license that can be found in the LICENSE file.
  5. package worker
  6. import (
  7. "strconv"
  8. "bitbucket.org/mikespook/gearman-go/common"
  9. )
  10. // Worker side job
  11. type Job struct {
  12. Data []byte
  13. Handle, UniqueId string
  14. agent *agent
  15. magicCode, DataType uint32
  16. }
  17. // Create a new job
  18. func newJob(magiccode, datatype uint32, data []byte) (job *Job) {
  19. return &Job{magicCode: magiccode,
  20. DataType: datatype,
  21. Data: data}
  22. }
  23. // Decode job from byte slice
  24. func decodeJob(data []byte) (job *Job, err error) {
  25. if len(data) < 12 {
  26. return nil, common.Errorf("Invalid data: %V", data)
  27. }
  28. datatype := common.BytesToUint32([4]byte{data[4], data[5], data[6], data[7]})
  29. l := common.BytesToUint32([4]byte{data[8], data[9], data[10], data[11]})
  30. if len(data[12:]) != int(l) {
  31. return nil, common.Errorf("Invalid data: %V", data)
  32. }
  33. data = data[12:]
  34. job = newJob(common.RES, datatype, data)
  35. return
  36. }
  37. // Encode a job to byte slice
  38. func (job *Job) Encode() (data []byte) {
  39. l := len(job.Data)
  40. tl := l
  41. if job.Handle != "" {
  42. tl += len(job.Handle) + 1
  43. }
  44. data = make([]byte, 0, tl + 12)
  45. magiccode := common.Uint32ToBytes(job.magicCode)
  46. datatype := common.Uint32ToBytes(job.DataType)
  47. datalength := common.Uint32ToBytes(uint32(tl))
  48. data = append(data, magiccode[:]...)
  49. data = append(data, datatype[:]...)
  50. data = append(data, datalength[:]...)
  51. if job.Handle != "" {
  52. data = append(data, []byte(job.Handle)...)
  53. data = append(data, 0)
  54. }
  55. data = append(data, job.Data...)
  56. return
  57. }
  58. // Send some datas to client.
  59. // Using this in a job's executing.
  60. func (job *Job) UpdateData(data []byte, iswaring bool) {
  61. result := append([]byte(job.Handle), 0)
  62. result = append(result, data...)
  63. var datatype uint32
  64. if iswaring {
  65. datatype = common.WORK_WARNING
  66. } else {
  67. datatype = common.WORK_DATA
  68. }
  69. job.agent.WriteJob(newJob(common.REQ, datatype, result))
  70. }
  71. // Update status.
  72. // Tall client how many percent job has been executed.
  73. func (job *Job) UpdateStatus(numerator, denominator int) {
  74. n := []byte(strconv.Itoa(numerator))
  75. d := []byte(strconv.Itoa(denominator))
  76. result := append([]byte(job.Handle), 0)
  77. result = append(result, n...)
  78. result = append(result, d...)
  79. job.agent.WriteJob(newJob(common.REQ, common.WORK_STATUS, result))
  80. }