github.com/huaweicloud/golangsdk@v0.0.0-20210831081626-d823fe11ceba/openstack/ims/v2/cloudimages/results_job.go (about) 1 package cloudimages 2 3 import ( 4 "fmt" 5 "time" 6 7 "github.com/huaweicloud/golangsdk" 8 ) 9 10 type JobResponse struct { 11 JobID string `json:"job_id"` 12 } 13 14 type JobStatus struct { 15 Status string `json:"status"` 16 Entities JobEntity `json:"entities"` 17 JobID string `json:"job_id"` 18 JobType string `json:"job_type"` 19 BeginTime string `json:"begin_time"` 20 EndTime string `json:"end_time"` 21 ErrorCode string `json:"error_code"` 22 FailReason string `json:"fail_reason"` 23 } 24 25 type JobEntity struct { 26 ImageID string `json:"image_id"` 27 DataImageID string `json:"__data_images"` 28 } 29 30 type JobResult struct { 31 golangsdk.Result 32 } 33 34 func (r JobResult) ExtractJobResponse() (*JobResponse, error) { 35 job := new(JobResponse) 36 err := r.ExtractInto(job) 37 return job, err 38 } 39 40 func (r JobResult) ExtractJobStatus() (*JobStatus, error) { 41 job := new(JobStatus) 42 err := r.ExtractInto(job) 43 return job, err 44 } 45 46 func WaitForJobSuccess(client *golangsdk.ServiceClient, secs int, jobID string) error { 47 jobClient := *client 48 // v1/{project_id}/jobs/{job_id} 49 jobClient.ResourceBase = jobClient.Endpoint + "v1/" + jobClient.ProjectID + "/" 50 return golangsdk.WaitFor(secs, func() (bool, error) { 51 job := new(JobStatus) 52 _, err := jobClient.Get(jobClient.ServiceURL("jobs", jobID), &job, nil) 53 if err != nil { 54 return false, err 55 } 56 time.Sleep(10 * time.Second) 57 if job.Status == "SUCCESS" { 58 return true, nil 59 } 60 if job.Status == "FAIL" { 61 err = fmt.Errorf("Job failed with code %s: %s.\n", job.ErrorCode, job.FailReason) 62 return false, err 63 } 64 65 return false, nil 66 }) 67 } 68 69 func GetJobEntity(client *golangsdk.ServiceClient, jobId string, label string) (interface{}, error) { 70 if label != "image_id" && label != "__data_images" { 71 return nil, fmt.Errorf("Unsupported label %s in GetJobEntity.", label) 72 } 73 74 jobClient := *client 75 // v1/{project_id}/jobs/{job_id} 76 jobClient.ResourceBase = jobClient.Endpoint + "v1/" + jobClient.ProjectID + "/" 77 job := new(JobStatus) 78 _, err := jobClient.Get(jobClient.ServiceURL("jobs", jobId), &job, nil) 79 if err != nil { 80 return nil, err 81 } 82 83 if job.Status == "SUCCESS" { 84 if e := job.Entities.ImageID; e != "" { 85 return e, nil 86 } 87 if e := job.Entities.DataImageID; e != "" { 88 return e, nil 89 } 90 } 91 92 return nil, fmt.Errorf("Unexpected conversion error in GetJobEntity.") 93 }