blob: 16787d053e346b836c8d14bb8e5de1ccd17a8b47 [file] [log] [blame]
Jon Perritte7b86d12015-01-16 20:37:11 -07001package services
2
3import (
Jon Perrittb0ab0d12015-01-27 12:12:51 -07004 "fmt"
Jon Perrittb8713ad2015-01-21 15:02:58 -07005 "strings"
6
Jon Perritte7b86d12015-01-16 20:37:11 -07007 "github.com/racker/perigee"
8 "github.com/rackspace/gophercloud"
9 "github.com/rackspace/gophercloud/pagination"
10)
11
12// ListOptsBuilder allows extensions to add additional parameters to the
13// List request.
14type ListOptsBuilder interface {
15 ToCDNServiceListQuery() (string, error)
16}
17
18// ListOpts allows the filtering and sorting of paginated collections through
19// the API. Marker and Limit are used for pagination.
20type ListOpts struct {
21 Marker string `q:"marker"`
22 Limit int `q:"limit"`
23}
24
25// ToCDNServiceListQuery formats a ListOpts into a query string.
26func (opts ListOpts) ToCDNServiceListQuery() (string, error) {
27 q, err := gophercloud.BuildQueryString(opts)
28 if err != nil {
29 return "", err
30 }
31 return q.String(), nil
32}
33
34// List returns a Pager which allows you to iterate over a collection of
35// CDN services. It accepts a ListOpts struct, which allows for pagination via
36// marker and limit.
37func List(c *gophercloud.ServiceClient, opts ListOptsBuilder) pagination.Pager {
38 url := listURL(c)
39 if opts != nil {
40 query, err := opts.ToCDNServiceListQuery()
41 if err != nil {
42 return pagination.Pager{Err: err}
43 }
44 url += query
45 }
46
47 createPage := func(r pagination.PageResult) pagination.Page {
48 p := ServicePage{pagination.MarkerPageBase{PageResult: r}}
49 p.MarkerPageBase.Owner = p
50 return p
51 }
52
53 pager := pagination.NewPager(c, url, createPage)
54 return pager
55}
56
57// CreateOptsBuilder is the interface options structs have to satisfy in order
58// to be used in the main Create operation in this package. Since many
59// extensions decorate or modify the common logic, it is useful for them to
60// satisfy a basic interface in order for them to be used.
61type CreateOptsBuilder interface {
62 ToCDNServiceCreateMap() (map[string]interface{}, error)
63}
64
65// CreateOpts is the common options struct used in this package's Create
66// operation.
67type CreateOpts struct {
68 // REQUIRED. Specifies the name of the service. The minimum length for name is
69 // 3. The maximum length is 256.
70 Name string
71 // REQUIRED. Specifies a list of domains used by users to access their website.
72 Domains []Domain
73 // REQUIRED. Specifies a list of origin domains or IP addresses where the
74 // original assets are stored.
75 Origins []Origin
76 // REQUIRED. Specifies the CDN provider flavor ID to use. For a list of
77 // flavors, see the operation to list the available flavors. The minimum
78 // length for flavor_id is 1. The maximum length is 256.
79 FlavorID string
80 // OPTIONAL. Specifies the TTL rules for the assets under this service. Supports wildcards for fine-grained control.
Jon Perritt0bd23732015-01-19 20:58:57 -070081 Caching []CacheRule
Jon Perritte7b86d12015-01-16 20:37:11 -070082 // OPTIONAL. Specifies the restrictions that define who can access assets (content from the CDN cache).
83 Restrictions []Restriction
84}
85
86// ToCDNServiceCreateMap casts a CreateOpts struct to a map.
87func (opts CreateOpts) ToCDNServiceCreateMap() (map[string]interface{}, error) {
88 s := make(map[string]interface{})
89
90 if opts.Name == "" {
91 return nil, no("Name")
92 }
93 s["name"] = opts.Name
94
95 if opts.Domains == nil {
96 return nil, no("Domains")
97 }
98 for _, domain := range opts.Domains {
99 if domain.Domain == "" {
100 return nil, no("Domains[].Domain")
101 }
102 }
103 s["domains"] = opts.Domains
104
105 if opts.Origins == nil {
106 return nil, no("Origins")
107 }
108 for _, origin := range opts.Origins {
109 if origin.Origin == "" {
110 return nil, no("Origins[].Origin")
111 }
Jon Perrittb8713ad2015-01-21 15:02:58 -0700112 if origin.Rules == nil && len(opts.Origins) > 1 {
Jon Perritte7b86d12015-01-16 20:37:11 -0700113 return nil, no("Origins[].Rules")
114 }
115 for _, rule := range origin.Rules {
116 if rule.Name == "" {
117 return nil, no("Origins[].Rules[].Name")
118 }
119 if rule.RequestURL == "" {
120 return nil, no("Origins[].Rules[].RequestURL")
121 }
122 }
123 }
124 s["origins"] = opts.Origins
125
126 if opts.FlavorID == "" {
127 return nil, no("FlavorID")
128 }
129 s["flavor_id"] = opts.FlavorID
130
131 if opts.Caching != nil {
132 for _, cache := range opts.Caching {
133 if cache.Name == "" {
134 return nil, no("Caching[].Name")
135 }
136 if cache.Rules != nil {
137 for _, rule := range cache.Rules {
138 if rule.Name == "" {
139 return nil, no("Caching[].Rules[].Name")
140 }
141 if rule.RequestURL == "" {
142 return nil, no("Caching[].Rules[].RequestURL")
143 }
144 }
145 }
146 }
147 s["caching"] = opts.Caching
148 }
149
150 if opts.Restrictions != nil {
151 for _, restriction := range opts.Restrictions {
152 if restriction.Name == "" {
153 return nil, no("Restrictions[].Name")
154 }
155 if restriction.Rules != nil {
156 for _, rule := range restriction.Rules {
157 if rule.Name == "" {
158 return nil, no("Restrictions[].Rules[].Name")
159 }
160 }
161 }
162 }
163 s["restrictions"] = opts.Restrictions
164 }
165
166 return s, nil
167}
168
169// Create accepts a CreateOpts struct and creates a new CDN service using the
170// values provided.
171func Create(c *gophercloud.ServiceClient, opts CreateOptsBuilder) CreateResult {
172 var res CreateResult
173
174 reqBody, err := opts.ToCDNServiceCreateMap()
175 if err != nil {
176 res.Err = err
177 return res
178 }
179
180 // Send request to API
Jon Perrittd21966f2015-01-20 19:22:45 -0700181 resp, err := perigee.Request("POST", createURL(c), perigee.Options{
Jon Perritte7b86d12015-01-16 20:37:11 -0700182 MoreHeaders: c.AuthenticatedHeaders(),
183 ReqBody: &reqBody,
184 OkCodes: []int{202},
185 })
Jon Perrittd21966f2015-01-20 19:22:45 -0700186 res.Header = resp.HttpResponse.Header
187 res.Err = err
Jon Perritte7b86d12015-01-16 20:37:11 -0700188 return res
189}
190
Jon Perrittb8713ad2015-01-21 15:02:58 -0700191// Get retrieves a specific service based on its URL or its unique ID. For
192// example, both "96737ae3-cfc1-4c72-be88-5d0e7cc9a3f0" and
193// "https://global.cdn.api.rackspacecloud.com/v1.0/services/96737ae3-cfc1-4c72-be88-5d0e7cc9a3f0"
194// are valid options for idOrURL.
195func Get(c *gophercloud.ServiceClient, idOrURL string) GetResult {
196 var url string
197 if strings.Contains(idOrURL, "/") {
198 url = idOrURL
199 } else {
200 url = getURL(c, idOrURL)
201 }
202
Jon Perritte7b86d12015-01-16 20:37:11 -0700203 var res GetResult
Jon Perrittb8713ad2015-01-21 15:02:58 -0700204 _, res.Err = perigee.Request("GET", url, perigee.Options{
Jon Perritte7b86d12015-01-16 20:37:11 -0700205 MoreHeaders: c.AuthenticatedHeaders(),
206 Results: &res.Body,
207 OkCodes: []int{200},
208 })
209 return res
210}
211
212// UpdateOptsBuilder is the interface options structs have to satisfy in order
213// to be used in the main Update operation in this package. Since many
214// extensions decorate or modify the common logic, it is useful for them to
215// satisfy a basic interface in order for them to be used.
216type UpdateOptsBuilder interface {
Jon Perritt608d3a52015-01-19 10:38:30 -0700217 ToCDNServiceUpdateMap() ([]map[string]interface{}, error)
Jon Perritte7b86d12015-01-16 20:37:11 -0700218}
219
220// Op represents an update operation.
221type Op string
222
223var (
224 // Add is a constant used for performing a "add" operation when updating.
225 Add Op = "add"
226 // Remove is a constant used for performing a "remove" operation when updating.
227 Remove Op = "remove"
228 // Replace is a constant used for performing a "replace" operation when updating.
229 Replace Op = "replace"
230)
231
Ash Wilsona623ff72015-01-28 15:50:37 -0500232// Path is a JSON pointer location that indicates which service parameter is being added, replaced,
233// or removed.
234type Path struct {
235 baseElement string
236}
237
238func (p Path) renderDash() string {
239 return fmt.Sprintf("/%s/-", p.baseElement)
240}
241
242func (p Path) renderIndex(index int64) string {
243 return fmt.Sprintf("/%s/%d", p.baseElement, index)
244}
245
246var (
247 // PathDomains indicates that an update operation is to be performed on a Domain.
248 PathDomains = Path{baseElement: "domains"}
249
250 // PathOrigins indicates that an update operation is to be performed on an Origin.
251 PathOrigins = Path{baseElement: "origins"}
252
253 // PathCaching indicates that an update operation is to be performed on a CacheRule.
254 PathCaching = Path{baseElement: "caching"}
255)
256
Jon Perritte7b86d12015-01-16 20:37:11 -0700257// UpdateOpts represents the attributes used when updating an existing CDN service.
258type UpdateOpts []UpdateOpt
259
260// UpdateOpt represents a single update to an existing service. Multiple updates
261// to a service can be submitted at the same time. See UpdateOpts.
262type UpdateOpt struct {
263 // Specifies the update operation to perform.
Jon Perrittd21966f2015-01-20 19:22:45 -0700264 Op Op `json:"op"`
Jon Perritte7b86d12015-01-16 20:37:11 -0700265 // Specifies the JSON Pointer location within the service's JSON representation
266 // of the service parameter being added, replaced or removed.
Jon Perrittd21966f2015-01-20 19:22:45 -0700267 Path string `json:"path"`
Jon Perritte7b86d12015-01-16 20:37:11 -0700268 // Specifies the actual value to be added or replaced. It is not required for
269 // the remove operation.
Jon Perrittd21966f2015-01-20 19:22:45 -0700270 Value map[string]interface{} `json:"value,omitempty"`
Jon Perritte7b86d12015-01-16 20:37:11 -0700271}
272
Ash Wilson4ee05012015-01-28 16:13:43 -0500273type value interface {
274 toPatchValue() map[string]interface{}
275 appropriatePath() Path
276}
277
Ash Wilson7b729532015-01-28 16:15:23 -0500278// Patch represents a single update to an existing Service. Multiple updates to a service can be
279// submitted at the same time.
280type Patch interface {
281 ToCDNServiceUpdateMap() map[string]interface{}
282}
283
Ash Wilson334277c2015-01-29 09:08:52 -0500284// Addition is a Patch that requests the addition of one or more values (Domains, Origins, or
285// CacheRules) to a Service. Pass it to the Update function as part of the Patch slice.
286type Addition struct {
287 Value value
288}
289
290// ToCDNServiceUpdateMap converts an Addition into a request body fragment suitable for the
291// Update call.
292func (a Addition) ToCDNServiceUpdateMap() map[string]interface{} {
293 return map[string]interface{}{
294 "op": "add",
295 "path": a.Value.appropriatePath().renderDash(),
296 "value": a.Value.toPatchValue(),
297 }
298}
299
300// Replacement is a Patch that alters a specific service parameter (Domain, Origin, or CacheRule)
301// in-place by index. Pass it to the Update function as part of the Patch slice.
302type Replacement struct {
303 Value value
304 Index int64
305}
306
307// ToCDNServiceUpdateMap converts a Replacement into a request body fragment suitable for the
308// Update call.
309func (r Replacement) ToCDNServiceUpdateMap() map[string]interface{} {
310 return map[string]interface{}{
311 "op": "replace",
312 "path": r.Value.appropriatePath().renderIndex(r.Index),
313 "value": r.Value.toPatchValue(),
314 }
315}
316
317// Removal is a Patch that requests the removal of a service parameter (Domain, Origin, or
318// CacheRule) by index. Pass it to the Update function as part of the Patch slice.
319type Removal struct {
320 Path Path
321 Index int64
322}
323
324// ToCDNServiceUpdateMap converts a Removal into a request body fragment suitable for the
325// Update call.
326func (r Removal) ToCDNServiceUpdateMap() map[string]interface{} {
327 return map[string]interface{}{
328 "op": "remove",
329 "path": r.Path.renderIndex(r.Index),
330 }
331}
332
Jon Perritte7b86d12015-01-16 20:37:11 -0700333// ToCDNServiceUpdateMap casts an UpdateOpts struct to a map.
Jon Perritt608d3a52015-01-19 10:38:30 -0700334func (opts UpdateOpts) ToCDNServiceUpdateMap() ([]map[string]interface{}, error) {
335 s := make([]map[string]interface{}, len(opts))
Jon Perritte7b86d12015-01-16 20:37:11 -0700336
337 for i, opt := range opts {
Jon Perrittb0ab0d12015-01-27 12:12:51 -0700338 if opt.Op != Add && opt.Op != Remove && opt.Op != Replace {
339 return nil, fmt.Errorf("Invalid Op: %v", opt.Op)
340 }
Jon Perritte7b86d12015-01-16 20:37:11 -0700341 if opt.Op == "" {
342 return nil, no("Op")
343 }
344 if opt.Path == "" {
345 return nil, no("Path")
346 }
347 if opt.Op != Remove && opt.Value == nil {
348 return nil, no("Value")
349 }
Jon Perrittd21966f2015-01-20 19:22:45 -0700350 s[i] = map[string]interface{}{
Jon Perrittb8713ad2015-01-21 15:02:58 -0700351 "op": opt.Op,
352 "path": opt.Path,
Jon Perrittd21966f2015-01-20 19:22:45 -0700353 "value": opt.Value,
354 }
Jon Perritte7b86d12015-01-16 20:37:11 -0700355 }
356
357 return s, nil
358}
359
360// Update accepts a UpdateOpts struct and updates an existing CDN service using
Jon Perrittb8713ad2015-01-21 15:02:58 -0700361// the values provided. idOrURL can be either the service's URL or its ID. For
362// example, both "96737ae3-cfc1-4c72-be88-5d0e7cc9a3f0" and
363// "https://global.cdn.api.rackspacecloud.com/v1.0/services/96737ae3-cfc1-4c72-be88-5d0e7cc9a3f0"
364// are valid options for idOrURL.
365func Update(c *gophercloud.ServiceClient, idOrURL string, opts UpdateOptsBuilder) UpdateResult {
366 var url string
367 if strings.Contains(idOrURL, "/") {
368 url = idOrURL
369 } else {
370 url = updateURL(c, idOrURL)
371 }
Jon Perritte7b86d12015-01-16 20:37:11 -0700372
Jon Perrittb8713ad2015-01-21 15:02:58 -0700373 var res UpdateResult
Jon Perritte7b86d12015-01-16 20:37:11 -0700374 reqBody, err := opts.ToCDNServiceUpdateMap()
375 if err != nil {
376 res.Err = err
377 return res
378 }
379
Jon Perrittb8713ad2015-01-21 15:02:58 -0700380 resp, err := perigee.Request("PATCH", url, perigee.Options{
Jon Perritte7b86d12015-01-16 20:37:11 -0700381 MoreHeaders: c.AuthenticatedHeaders(),
382 ReqBody: &reqBody,
383 OkCodes: []int{202},
384 })
Jon Perrittd21966f2015-01-20 19:22:45 -0700385 res.Header = resp.HttpResponse.Header
386 res.Err = err
Jon Perritte7b86d12015-01-16 20:37:11 -0700387 return res
388}
389
Jon Perrittb8713ad2015-01-21 15:02:58 -0700390// Delete accepts a service's ID or its URL and deletes the CDN service
391// associated with it. For example, both "96737ae3-cfc1-4c72-be88-5d0e7cc9a3f0" and
392// "https://global.cdn.api.rackspacecloud.com/v1.0/services/96737ae3-cfc1-4c72-be88-5d0e7cc9a3f0"
393// are valid options for idOrURL.
394func Delete(c *gophercloud.ServiceClient, idOrURL string) DeleteResult {
395 var url string
396 if strings.Contains(idOrURL, "/") {
397 url = idOrURL
398 } else {
399 url = deleteURL(c, idOrURL)
400 }
401
Jon Perritte7b86d12015-01-16 20:37:11 -0700402 var res DeleteResult
Jon Perrittb8713ad2015-01-21 15:02:58 -0700403 _, res.Err = perigee.Request("DELETE", url, perigee.Options{
Jon Perritte7b86d12015-01-16 20:37:11 -0700404 MoreHeaders: c.AuthenticatedHeaders(),
405 OkCodes: []int{202},
406 })
407 return res
408}