github.com/danp/terraform@v0.9.5-0.20170426144147-39d740081351/builtin/providers/google/serviceman_operation.go (about)

     1  package google
     2  
     3  import (
     4  	"fmt"
     5  	"log"
     6  	"time"
     7  
     8  	"github.com/hashicorp/terraform/helper/resource"
     9  	"google.golang.org/api/servicemanagement/v1"
    10  )
    11  
    12  type ServiceManagementOperationWaiter struct {
    13  	Service *servicemanagement.APIService
    14  	Op      *servicemanagement.Operation
    15  }
    16  
    17  func (w *ServiceManagementOperationWaiter) RefreshFunc() resource.StateRefreshFunc {
    18  	return func() (interface{}, string, error) {
    19  		var op *servicemanagement.Operation
    20  		var err error
    21  
    22  		op, err = w.Service.Operations.Get(w.Op.Name).Do()
    23  
    24  		if err != nil {
    25  			return nil, "", err
    26  		}
    27  
    28  		log.Printf("[DEBUG] Got %v while polling for operation %s's 'done' status", op.Done, w.Op.Name)
    29  
    30  		return op, fmt.Sprint(op.Done), nil
    31  	}
    32  }
    33  
    34  func (w *ServiceManagementOperationWaiter) Conf() *resource.StateChangeConf {
    35  	return &resource.StateChangeConf{
    36  		Pending: []string{"false"},
    37  		Target:  []string{"true"},
    38  		Refresh: w.RefreshFunc(),
    39  	}
    40  }
    41  
    42  func serviceManagementOperationWait(config *Config, op *servicemanagement.Operation, activity string) error {
    43  	return serviceManagementOperationWaitTime(config, op, activity, 4)
    44  }
    45  
    46  func serviceManagementOperationWaitTime(config *Config, op *servicemanagement.Operation, activity string, timeoutMin int) error {
    47  	w := &ServiceManagementOperationWaiter{
    48  		Service: config.clientServiceMan,
    49  		Op:      op,
    50  	}
    51  
    52  	state := w.Conf()
    53  	state.Delay = 10 * time.Second
    54  	state.Timeout = time.Duration(timeoutMin) * time.Minute
    55  	state.MinTimeout = 2 * time.Second
    56  	opRaw, err := state.WaitForState()
    57  	if err != nil {
    58  		return fmt.Errorf("Error waiting for %s: %s", activity, err)
    59  	}
    60  
    61  	op = opRaw.(*servicemanagement.Operation)
    62  	if op.Error != nil {
    63  		return fmt.Errorf("Error code %v, message: %s", op.Error.Code, op.Error.Message)
    64  	}
    65  
    66  	return nil
    67  }