github.com/minamijoyo/terraform@v0.7.8-0.20161029001309-18b3736ba44b/builtin/providers/google/sqladmin_operation.go (about)

     1  package google
     2  
     3  import (
     4  	"bytes"
     5  	"fmt"
     6  	"log"
     7  	"time"
     8  
     9  	"github.com/hashicorp/terraform/helper/resource"
    10  	"google.golang.org/api/sqladmin/v1beta4"
    11  )
    12  
    13  type SqlAdminOperationWaiter struct {
    14  	Service *sqladmin.Service
    15  	Op      *sqladmin.Operation
    16  	Project string
    17  }
    18  
    19  func (w *SqlAdminOperationWaiter) RefreshFunc() resource.StateRefreshFunc {
    20  	return func() (interface{}, string, error) {
    21  		var op *sqladmin.Operation
    22  		var err error
    23  
    24  		log.Printf("[DEBUG] self_link: %s", w.Op.SelfLink)
    25  		op, err = w.Service.Operations.Get(w.Project, w.Op.Name).Do()
    26  
    27  		if err != nil {
    28  			return nil, "", err
    29  		}
    30  
    31  		log.Printf("[DEBUG] Got %q when asking for operation %q", op.Status, w.Op.Name)
    32  
    33  		return op, op.Status, nil
    34  	}
    35  }
    36  
    37  func (w *SqlAdminOperationWaiter) Conf() *resource.StateChangeConf {
    38  	return &resource.StateChangeConf{
    39  		Pending: []string{"PENDING", "RUNNING"},
    40  		Target:  []string{"DONE"},
    41  		Refresh: w.RefreshFunc(),
    42  	}
    43  }
    44  
    45  // SqlAdminOperationError wraps sqladmin.OperationError and implements the
    46  // error interface so it can be returned.
    47  type SqlAdminOperationError sqladmin.OperationErrors
    48  
    49  func (e SqlAdminOperationError) Error() string {
    50  	var buf bytes.Buffer
    51  
    52  	for _, err := range e.Errors {
    53  		buf.WriteString(err.Message + "\n")
    54  	}
    55  
    56  	return buf.String()
    57  }
    58  
    59  func sqladminOperationWait(config *Config, op *sqladmin.Operation, activity string) error {
    60  	w := &SqlAdminOperationWaiter{
    61  		Service: config.clientSqlAdmin,
    62  		Op:      op,
    63  		Project: config.Project,
    64  	}
    65  
    66  	state := w.Conf()
    67  	state.Timeout = 10 * time.Minute
    68  	state.MinTimeout = 2 * time.Second
    69  	opRaw, err := state.WaitForState()
    70  	if err != nil {
    71  		return fmt.Errorf("Error waiting for %s: %s", activity, err)
    72  	}
    73  
    74  	op = opRaw.(*sqladmin.Operation)
    75  	if op.Error != nil {
    76  		return SqlAdminOperationError(*op.Error)
    77  	}
    78  
    79  	return nil
    80  }