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

     1  package ultradns
     2  
     3  import (
     4  	"fmt"
     5  	"log"
     6  
     7  	"github.com/Ensighten/udnssdk"
     8  	"github.com/hashicorp/terraform/helper/schema"
     9  )
    10  
    11  func resourceUltradnsProbeHTTP() *schema.Resource {
    12  	return &schema.Resource{
    13  		Create: resourceUltradnsProbeHTTPCreate,
    14  		Read:   resourceUltradnsProbeHTTPRead,
    15  		Update: resourceUltradnsProbeHTTPUpdate,
    16  		Delete: resourceUltradnsProbeHTTPDelete,
    17  
    18  		Schema: map[string]*schema.Schema{
    19  			// Key
    20  			"zone": &schema.Schema{
    21  				Type:     schema.TypeString,
    22  				Required: true,
    23  				ForceNew: true,
    24  			},
    25  			"name": &schema.Schema{
    26  				Type:     schema.TypeString,
    27  				Required: true,
    28  				ForceNew: true,
    29  			},
    30  			"pool_record": &schema.Schema{
    31  				Type:     schema.TypeString,
    32  				Optional: true,
    33  				ForceNew: true,
    34  			},
    35  			// Required
    36  			"agents": &schema.Schema{
    37  				Type:     schema.TypeSet,
    38  				Set:      schema.HashString,
    39  				Required: true,
    40  				Elem:     &schema.Schema{Type: schema.TypeString},
    41  			},
    42  			"threshold": &schema.Schema{
    43  				Type:     schema.TypeInt,
    44  				Required: true,
    45  			},
    46  			// Optional
    47  			"interval": &schema.Schema{
    48  				Type:     schema.TypeString,
    49  				Optional: true,
    50  				Default:  "FIVE_MINUTES",
    51  			},
    52  			"http_probe": &schema.Schema{
    53  				Type:     schema.TypeList,
    54  				Optional: true,
    55  				Elem:     schemaHTTPProbe(),
    56  			},
    57  			// Computed
    58  			"id": &schema.Schema{
    59  				Type:     schema.TypeString,
    60  				Computed: true,
    61  			},
    62  		},
    63  	}
    64  }
    65  
    66  func schemaHTTPProbe() *schema.Resource {
    67  	return &schema.Resource{
    68  		Schema: map[string]*schema.Schema{
    69  			"transaction": &schema.Schema{
    70  				Type:     schema.TypeList,
    71  				Optional: true,
    72  				Elem: &schema.Resource{
    73  					Schema: map[string]*schema.Schema{
    74  						"method": &schema.Schema{
    75  							Type:     schema.TypeString,
    76  							Required: true,
    77  						},
    78  						"url": &schema.Schema{
    79  							Type:     schema.TypeString,
    80  							Required: true,
    81  						},
    82  						"transmitted_data": &schema.Schema{
    83  							Type:     schema.TypeString,
    84  							Optional: true,
    85  						},
    86  						"follow_redirects": &schema.Schema{
    87  							Type:     schema.TypeBool,
    88  							Optional: true,
    89  							Default:  false,
    90  						},
    91  						"limit": &schema.Schema{
    92  							Type:     schema.TypeSet,
    93  							Optional: true,
    94  							Set:      hashLimits,
    95  							Elem:     resourceProbeLimits(),
    96  						},
    97  					},
    98  				},
    99  			},
   100  			"total_limits": &schema.Schema{
   101  				Type:     schema.TypeList,
   102  				Optional: true,
   103  				Elem: &schema.Resource{
   104  					Schema: map[string]*schema.Schema{
   105  						"warning": &schema.Schema{
   106  							Type:     schema.TypeInt,
   107  							Optional: true,
   108  						},
   109  						"critical": &schema.Schema{
   110  							Type:     schema.TypeInt,
   111  							Optional: true,
   112  						},
   113  						"fail": &schema.Schema{
   114  							Type:     schema.TypeInt,
   115  							Optional: true,
   116  						},
   117  					},
   118  				},
   119  			},
   120  		},
   121  	}
   122  }
   123  
   124  func resourceUltradnsProbeHTTPCreate(d *schema.ResourceData, meta interface{}) error {
   125  	client := meta.(*udnssdk.Client)
   126  
   127  	r, err := makeHTTPProbeResource(d)
   128  	if err != nil {
   129  		return fmt.Errorf("Could not load ultradns_probe_http configuration: %v", err)
   130  	}
   131  
   132  	log.Printf("[INFO] ultradns_probe_http create: %#v, detail: %#v", r, r.Details.Detail)
   133  	resp, err := client.Probes.Create(r.Key().RRSetKey(), r.ProbeInfoDTO())
   134  	if err != nil {
   135  		return fmt.Errorf("create failed: %v", err)
   136  	}
   137  
   138  	uri := resp.Header.Get("Location")
   139  	d.Set("uri", uri)
   140  	d.SetId(uri)
   141  	log.Printf("[INFO] ultradns_probe_http.id: %v", d.Id())
   142  
   143  	return resourceUltradnsProbeHTTPRead(d, meta)
   144  }
   145  
   146  func resourceUltradnsProbeHTTPRead(d *schema.ResourceData, meta interface{}) error {
   147  	client := meta.(*udnssdk.Client)
   148  
   149  	r, err := makeHTTPProbeResource(d)
   150  	if err != nil {
   151  		return fmt.Errorf("Could not load ultradns_probe_http configuration: %v", err)
   152  	}
   153  
   154  	log.Printf("[DEBUG] ultradns_probe_http read: %#v", r)
   155  	probe, _, err := client.Probes.Find(r.Key())
   156  	log.Printf("[DEBUG] ultradns_probe_http response: %#v", probe)
   157  
   158  	if err != nil {
   159  		uderr, ok := err.(*udnssdk.ErrorResponseList)
   160  		if ok {
   161  			for _, r := range uderr.Responses {
   162  				// 70002 means Probes Not Found
   163  				if r.ErrorCode == 70002 {
   164  					d.SetId("")
   165  					return nil
   166  				}
   167  				return fmt.Errorf("not found: %s", err)
   168  			}
   169  		}
   170  		return fmt.Errorf("not found: %s", err)
   171  	}
   172  
   173  	return populateResourceDataFromHTTPProbe(probe, d)
   174  }
   175  
   176  func resourceUltradnsProbeHTTPUpdate(d *schema.ResourceData, meta interface{}) error {
   177  	client := meta.(*udnssdk.Client)
   178  
   179  	r, err := makeHTTPProbeResource(d)
   180  	if err != nil {
   181  		return fmt.Errorf("Could not load ultradns_probe_http configuration: %v", err)
   182  	}
   183  
   184  	log.Printf("[INFO] ultradns_probe_http update: %+v", r)
   185  	_, err = client.Probes.Update(r.Key(), r.ProbeInfoDTO())
   186  	if err != nil {
   187  		return fmt.Errorf("update failed: %s", err)
   188  	}
   189  
   190  	return resourceUltradnsProbeHTTPRead(d, meta)
   191  }
   192  
   193  func resourceUltradnsProbeHTTPDelete(d *schema.ResourceData, meta interface{}) error {
   194  	client := meta.(*udnssdk.Client)
   195  
   196  	r, err := makeHTTPProbeResource(d)
   197  	if err != nil {
   198  		return fmt.Errorf("Could not load ultradns_probe_http configuration: %s", err)
   199  	}
   200  
   201  	log.Printf("[INFO] ultradns_probe_http delete: %+v", r)
   202  	_, err = client.Probes.Delete(r.Key())
   203  	if err != nil {
   204  		return fmt.Errorf("delete failed: %s", err)
   205  	}
   206  
   207  	return nil
   208  }
   209  
   210  // Resource Helpers
   211  
   212  func makeHTTPProbeResource(d *schema.ResourceData) (probeResource, error) {
   213  	p := probeResource{}
   214  	p.Zone = d.Get("zone").(string)
   215  	p.Name = d.Get("name").(string)
   216  	p.ID = d.Id()
   217  	p.Interval = d.Get("interval").(string)
   218  	p.PoolRecord = d.Get("pool_record").(string)
   219  	p.Threshold = d.Get("threshold").(int)
   220  	for _, a := range d.Get("agents").(*schema.Set).List() {
   221  		p.Agents = append(p.Agents, a.(string))
   222  	}
   223  
   224  	p.Type = udnssdk.HTTPProbeType
   225  	hps := d.Get("http_probe").([]interface{})
   226  	if len(hps) >= 1 {
   227  		if len(hps) > 1 {
   228  			return p, fmt.Errorf("http_probe: only 0 or 1 blocks alowed, got: %#v", len(hps))
   229  		}
   230  		p.Details = makeHTTPProbeDetails(hps[0])
   231  	}
   232  
   233  	return p, nil
   234  }
   235  
   236  func makeHTTPProbeDetails(configured interface{}) *udnssdk.ProbeDetailsDTO {
   237  	data := configured.(map[string]interface{})
   238  	// Convert limits from flattened set format to mapping.
   239  	d := udnssdk.HTTPProbeDetailsDTO{}
   240  
   241  	ts := []udnssdk.Transaction{}
   242  	for _, rt := range data["transaction"].([]interface{}) {
   243  		mt := rt.(map[string]interface{})
   244  		ls := make(map[string]udnssdk.ProbeDetailsLimitDTO)
   245  		for _, limit := range mt["limit"].(*schema.Set).List() {
   246  			l := limit.(map[string]interface{})
   247  			name := l["name"].(string)
   248  			ls[name] = *makeProbeDetailsLimit(l)
   249  		}
   250  		t := udnssdk.Transaction{
   251  			Method:          mt["method"].(string),
   252  			URL:             mt["url"].(string),
   253  			TransmittedData: mt["transmitted_data"].(string),
   254  			FollowRedirects: mt["follow_redirects"].(bool),
   255  			Limits:          ls,
   256  		}
   257  		ts = append(ts, t)
   258  	}
   259  	d.Transactions = ts
   260  	rawLims := data["total_limits"].([]interface{})
   261  	if len(rawLims) >= 1 {
   262  		// TODO: validate 0 or 1 total_limits
   263  		// if len(rawLims) > 1 {
   264  		// 	return nil, fmt.Errorf("total_limits: only 0 or 1 blocks alowed, got: %#v", len(rawLims))
   265  		// }
   266  		d.TotalLimits = makeProbeDetailsLimit(rawLims[0])
   267  	}
   268  	res := udnssdk.ProbeDetailsDTO{
   269  		Detail: d,
   270  	}
   271  	return &res
   272  }
   273  
   274  func populateResourceDataFromHTTPProbe(p udnssdk.ProbeInfoDTO, d *schema.ResourceData) error {
   275  	d.SetId(p.ID)
   276  	d.Set("pool_record", p.PoolRecord)
   277  	d.Set("interval", p.Interval)
   278  	d.Set("agents", makeSetFromStrings(p.Agents))
   279  	d.Set("threshold", p.Threshold)
   280  
   281  	hp := map[string]interface{}{}
   282  	hd, err := p.Details.HTTPProbeDetails()
   283  	if err != nil {
   284  		return fmt.Errorf("ProbeInfo.details could not be unmarshalled: %v, Details: %#v", err, p.Details)
   285  	}
   286  	ts := make([]map[string]interface{}, 0, len(hd.Transactions))
   287  	for _, rt := range hd.Transactions {
   288  		t := map[string]interface{}{
   289  			"method":           rt.Method,
   290  			"url":              rt.URL,
   291  			"transmitted_data": rt.TransmittedData,
   292  			"follow_redirects": rt.FollowRedirects,
   293  			"limit":            makeSetFromLimits(rt.Limits),
   294  		}
   295  		ts = append(ts, t)
   296  	}
   297  	hp["transaction"] = ts
   298  
   299  	tls := []map[string]interface{}{}
   300  	rawtl := hd.TotalLimits
   301  	if rawtl != nil {
   302  		tl := map[string]interface{}{
   303  			"warning":  rawtl.Warning,
   304  			"critical": rawtl.Critical,
   305  			"fail":     rawtl.Fail,
   306  		}
   307  		tls = append(tls, tl)
   308  	}
   309  	hp["total_limits"] = tls
   310  
   311  	err = d.Set("http_probe", []map[string]interface{}{hp})
   312  	if err != nil {
   313  		return fmt.Errorf("http_probe set failed: %v, from %#v", err, hp)
   314  	}
   315  	return nil
   316  }