github.com/anuaimi/terraform@v0.6.4-0.20150904235404-2bf9aec61da8/builtin/providers/google/operation.go (about)

     1  package google
     2  
     3  import (
     4  	"bytes"
     5  	"fmt"
     6  
     7  	"github.com/hashicorp/terraform/helper/resource"
     8  	"google.golang.org/api/compute/v1"
     9  )
    10  
    11  // OperationWaitType is an enum specifying what type of operation
    12  // we're waiting on.
    13  type OperationWaitType byte
    14  
    15  const (
    16  	OperationWaitInvalid OperationWaitType = iota
    17  	OperationWaitGlobal
    18  	OperationWaitRegion
    19  	OperationWaitZone
    20  )
    21  
    22  type OperationWaiter struct {
    23  	Service *compute.Service
    24  	Op      *compute.Operation
    25  	Project string
    26  	Region  string
    27  	Type    OperationWaitType
    28  	Zone    string
    29  }
    30  
    31  func (w *OperationWaiter) RefreshFunc() resource.StateRefreshFunc {
    32  	return func() (interface{}, string, error) {
    33  		var op *compute.Operation
    34  		var err error
    35  
    36  		switch w.Type {
    37  		case OperationWaitGlobal:
    38  			op, err = w.Service.GlobalOperations.Get(
    39  				w.Project, w.Op.Name).Do()
    40  		case OperationWaitRegion:
    41  			op, err = w.Service.RegionOperations.Get(
    42  				w.Project, w.Region, w.Op.Name).Do()
    43  		case OperationWaitZone:
    44  			op, err = w.Service.ZoneOperations.Get(
    45  				w.Project, w.Zone, w.Op.Name).Do()
    46  		default:
    47  			return nil, "bad-type", fmt.Errorf(
    48  				"Invalid wait type: %#v", w.Type)
    49  		}
    50  
    51  		if err != nil {
    52  			return nil, "", err
    53  		}
    54  
    55  		return op, op.Status, nil
    56  	}
    57  }
    58  
    59  func (w *OperationWaiter) Conf() *resource.StateChangeConf {
    60  	return &resource.StateChangeConf{
    61  		Pending: []string{"PENDING", "RUNNING"},
    62  		Target:  "DONE",
    63  		Refresh: w.RefreshFunc(),
    64  	}
    65  }
    66  
    67  // OperationError wraps compute.OperationError and implements the
    68  // error interface so it can be returned.
    69  type OperationError compute.OperationError
    70  
    71  func (e OperationError) Error() string {
    72  	var buf bytes.Buffer
    73  
    74  	for _, err := range e.Errors {
    75  		buf.WriteString(err.Message + "\n")
    76  	}
    77  
    78  	return buf.String()
    79  }