github.com/loggregator/cli@v6.33.1-0.20180224010324-82334f081791+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  	"code.cloudfoundry.org/cli/api/cloudcontroller/ccv3/constant"
     9  )
    10  
    11  type ErrorDetails struct {
    12  	Detail string `json:"detail"`
    13  	Title  string `json:"title"`
    14  	Code   int    `json:"code"`
    15  }
    16  
    17  // Job represents a Cloud Controller Job.
    18  type Job struct {
    19  	Errors []ErrorDetails    `json:"errors"`
    20  	GUID   string            `json:"guid"`
    21  	State  constant.JobState `json:"state"`
    22  }
    23  
    24  // Complete returns true when the job has completed successfully.
    25  func (job Job) Complete() bool {
    26  	return job.State == constant.JobComplete
    27  }
    28  
    29  // Failed returns true when the job has completed with an error/failure.
    30  func (job Job) Failed() bool {
    31  	return job.State == constant.JobFailed
    32  }
    33  
    34  // GetJob returns a job for the provided GUID.
    35  func (client *Client) GetJob(jobURL string) (Job, Warnings, error) {
    36  	request, err := client.newHTTPRequest(requestOptions{URL: jobURL})
    37  	if err != nil {
    38  		return Job{}, nil, err
    39  	}
    40  
    41  	var job Job
    42  	response := cloudcontroller.Response{
    43  		Result: &job,
    44  	}
    45  
    46  	err = client.connection.Make(request, &response)
    47  	return job, response.Warnings, err
    48  }
    49  
    50  // PollJob will keep polling the given job until the job has terminated, an
    51  // error is encountered, or config.OverallPollingTimeout is reached. In the
    52  // last case, a JobTimeoutError is returned.
    53  func (client *Client) PollJob(jobURL string) (Warnings, error) {
    54  	var (
    55  		err         error
    56  		warnings    Warnings
    57  		allWarnings Warnings
    58  		job         Job
    59  	)
    60  
    61  	startTime := time.Now()
    62  	for time.Now().Sub(startTime) < client.jobPollingTimeout {
    63  		job, warnings, err = client.GetJob(jobURL)
    64  		allWarnings = append(allWarnings, warnings...)
    65  		if err != nil {
    66  			return allWarnings, err
    67  		}
    68  
    69  		if job.Failed() {
    70  			return allWarnings, ccerror.JobFailedError{
    71  				JobGUID: job.GUID,
    72  				Message: job.Errors[0].Detail,
    73  			}
    74  		}
    75  
    76  		if job.Complete() {
    77  			return allWarnings, nil
    78  		}
    79  
    80  		time.Sleep(client.jobPollingInterval)
    81  	}
    82  
    83  	return allWarnings, ccerror.JobTimeoutError{
    84  		JobGUID: job.GUID,
    85  		Timeout: client.jobPollingTimeout,
    86  	}
    87  }