github.com/cloudfoundry-attic/cli-with-i18n@v6.32.1-0.20171002233121-7401370d3b85+incompatible/api/cloudcontroller/ccv3/job.go (about) 1 package ccv3 2 3 import ( 4 "time" 5 6 "code.cloudfoundry.org/cli/api/cloudcontroller" 7 "code.cloudfoundry.org/cli/api/cloudcontroller/ccerror" 8 ) 9 10 // JobState is the current state of a job. 11 type JobState string 12 13 const ( 14 // JobStateFailed is when the job is no longer running due to a failure. 15 JobStateFailed JobState = "FAILED" 16 17 // JobStateFinished is when the job is no longer and it was successful. 18 JobStateComplete JobState = "COMPLETE" 19 20 // JobStateQueued is when the job is waiting to be run. 21 JobStateProcessing JobState = "PROCESSING" 22 ) 23 24 type ErrorDetails struct { 25 Detail string `json:"detail"` 26 Title string `json:"title"` 27 Code int `json:"code"` 28 } 29 30 // Job represents a Cloud Controller Job. 31 type Job struct { 32 Errors []ErrorDetails `json:"errors"` 33 GUID string `json:"guid"` 34 State JobState `json:"state"` 35 } 36 37 // Complete returns true when the job has completed successfully. 38 func (job Job) Complete() bool { 39 return job.State == JobStateComplete 40 } 41 42 // Failed returns true when the job has completed with an error/failure. 43 func (job Job) Failed() bool { 44 return job.State == JobStateFailed 45 } 46 47 // GetJob returns a job for the provided GUID. 48 func (client *Client) GetJob(jobURL string) (Job, Warnings, error) { 49 request, err := client.newHTTPRequest(requestOptions{URL: jobURL}) 50 if err != nil { 51 return Job{}, nil, err 52 } 53 54 var job Job 55 response := cloudcontroller.Response{ 56 Result: &job, 57 } 58 59 err = client.connection.Make(request, &response) 60 return job, response.Warnings, err 61 } 62 63 // PollJob will keep polling the given job until the job has terminated, an 64 // error is encountered, or config.OverallPollingTimeout is reached. In the 65 // last case, a JobTimeoutError is returned. 66 func (client *Client) PollJob(jobURL string) (Warnings, error) { 67 var ( 68 err error 69 warnings Warnings 70 allWarnings Warnings 71 job Job 72 ) 73 74 startTime := time.Now() 75 for time.Now().Sub(startTime) < client.jobPollingTimeout { 76 job, warnings, err = client.GetJob(jobURL) 77 allWarnings = append(allWarnings, warnings...) 78 if err != nil { 79 return allWarnings, err 80 } 81 82 if job.Failed() { 83 return allWarnings, ccerror.JobFailedError{ 84 JobGUID: job.GUID, 85 Message: job.Errors[0].Detail, 86 } 87 } 88 89 if job.Complete() { 90 return allWarnings, nil 91 } 92 93 time.Sleep(client.jobPollingInterval) 94 } 95 96 return allWarnings, ccerror.JobTimeoutError{ 97 JobGUID: job.GUID, 98 Timeout: client.jobPollingTimeout, 99 } 100 }