task.go 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. // Copyright 2019 Yunion
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package proxmox
  15. import (
  16. "encoding/json"
  17. "fmt"
  18. "strings"
  19. "time"
  20. "yunion.io/x/log"
  21. "yunion.io/x/pkg/errors"
  22. "yunion.io/x/cloudmux/pkg/cloudprovider"
  23. )
  24. type STask struct {
  25. User string `json:"user"`
  26. Type string `json:"type"`
  27. Saved string `json:"saved"`
  28. Status string `json:"status"`
  29. Starttime int `json:"starttime"`
  30. Node string `json:"node"`
  31. ID string `json:"id"`
  32. Endtime int `json:"endtime"`
  33. Upid string `json:"upid"`
  34. }
  35. func (c *SProxmoxClient) getTaskId(taskResponse map[string]interface{}) string {
  36. if taskResponse["errors"] != nil {
  37. errJSON, _ := json.MarshalIndent(taskResponse["errors"], "", " ")
  38. return string(errJSON)
  39. }
  40. if taskResponse["data"] == nil {
  41. return ""
  42. }
  43. taskUpid := taskResponse["data"].(string)
  44. return taskUpid
  45. }
  46. func (self *SProxmoxClient) waitTask(id string) (string, error) {
  47. resId := ""
  48. return resId, cloudprovider.Wait(time.Second*10, time.Minute*10, func() (bool, error) {
  49. tasks := []STask{}
  50. err := self.get("/cluster/tasks", nil, &tasks)
  51. if err != nil {
  52. return false, errors.Wrapf(err, "get task %s", id)
  53. }
  54. for _, task := range tasks {
  55. if task.Upid == id {
  56. switch strings.ToLower(task.Status) {
  57. case "running":
  58. log.Debugf("task %s state: %s", task.Upid, task.Status)
  59. return false, nil
  60. case "ok":
  61. log.Debugf("task %s state: %s", task.Upid, task.Status)
  62. resId = task.Upid
  63. return true, nil
  64. case "":
  65. log.Debugf("task %s not finish", task.Upid)
  66. return false, nil
  67. default:
  68. log.Debugf("task %s state: %s", task.Upid, task.Status)
  69. return false, fmt.Errorf("task %s state: %s", task.Upid, task.Status)
  70. }
  71. }
  72. }
  73. return false, fmt.Errorf("not find task %s ", id)
  74. })
  75. }