This repository has been archived by the owner on Nov 14, 2020. It is now read-only.
/
images_image_v2.go
282 lines (241 loc) · 7.62 KB
/
images_image_v2.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
package openstack
import (
"crypto/md5"
"encoding/hex"
"fmt"
"io"
"log"
"net/http"
"os"
"path/filepath"
"regexp"
"strings"
"github.com/gophercloud/gophercloud"
"github.com/gophercloud/gophercloud/openstack/imageservice/v2/images"
"github.com/gophercloud/gophercloud/openstack/imageservice/v2/members"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceImagesImageV2MemberStatusFromString(v string) images.ImageMemberStatus {
switch v {
case string(images.ImageMemberStatusAccepted):
return images.ImageMemberStatusAccepted
case string(images.ImageMemberStatusPending):
return images.ImageMemberStatusPending
case string(images.ImageMemberStatusRejected):
return images.ImageMemberStatusRejected
case string(images.ImageMemberStatusAll):
return images.ImageMemberStatusAll
}
return ""
}
func resourceImagesImageV2VisibilityFromString(v string) images.ImageVisibility {
switch v {
case string(images.ImageVisibilityPublic):
return images.ImageVisibilityPublic
case string(images.ImageVisibilityPrivate):
return images.ImageVisibilityPrivate
case string(images.ImageVisibilityShared):
return images.ImageVisibilityShared
case string(images.ImageVisibilityCommunity):
return images.ImageVisibilityCommunity
}
return ""
}
func fileMD5Checksum(f *os.File) (string, error) {
hash := md5.New()
if _, err := io.Copy(hash, f); err != nil {
return "", err
}
return hex.EncodeToString(hash.Sum(nil)), nil
}
func resourceImagesImageV2FileProps(filename string) (int64, string, error) {
var filesize int64
var filechecksum string
file, err := os.Open(filename)
if err != nil {
return -1, "", fmt.Errorf("Error opening file for Image: %s", err)
}
defer file.Close()
fstat, err := file.Stat()
if err != nil {
return -1, "", fmt.Errorf("Error reading image file %q: %s", file.Name(), err)
}
filesize = fstat.Size()
filechecksum, err = fileMD5Checksum(file)
if err != nil {
return -1, "", fmt.Errorf("Error computing image file %q checksum: %s", file.Name(), err)
}
return filesize, filechecksum, nil
}
func resourceImagesImageV2File(d *schema.ResourceData) (string, error) {
if filename := d.Get("local_file_path").(string); filename != "" {
return filename, nil
} else if furl := d.Get("image_source_url").(string); furl != "" {
dir := d.Get("image_cache_path").(string)
os.MkdirAll(dir, 0700)
filename := filepath.Join(dir, fmt.Sprintf("%x.img", md5.Sum([]byte(furl))))
if _, err := os.Stat(filename); err != nil {
if !os.IsNotExist(err) {
return "", fmt.Errorf("Error while trying to access file %q: %s", filename, err)
}
log.Printf("[DEBUG] File doens't exists %s. will download from %s", filename, furl)
file, err := os.Create(filename)
if err != nil {
return "", fmt.Errorf("Error creating file %q: %s", filename, err)
}
defer file.Close()
resp, err := http.Get(furl)
if err != nil {
return "", fmt.Errorf("Error downloading image from %q", furl)
}
defer resp.Body.Close()
if _, err = io.Copy(file, resp.Body); err != nil {
return "", fmt.Errorf("Error downloading image %q to file %q: %s", furl, filename, err)
}
return filename, nil
} else {
log.Printf("[DEBUG] File exists %s", filename)
return filename, nil
}
} else {
return "", fmt.Errorf("Error in config. no file specified")
}
}
func resourceImagesImageV2RefreshFunc(client *gophercloud.ServiceClient, id string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
img, err := images.Get(client, id).Extract()
if err != nil {
return nil, "", err
}
log.Printf("[DEBUG] OpenStack image status is: %s", img.Status)
return img, fmt.Sprintf("%s", img.Status), nil
}
}
func resourceImagesImageV2BuildTags(v []interface{}) []string {
tags := make([]string, len(v))
for i, tag := range v {
tags[i] = tag.(string)
}
return tags
}
func resourceImagesImageV2ExpandProperties(v map[string]interface{}) map[string]string {
properties := map[string]string{}
for key, value := range v {
if v, ok := value.(string); ok {
properties[key] = v
}
}
return properties
}
func resourceImagesImageV2UpdateComputedAttributes(diff *schema.ResourceDiff, meta interface{}) error {
if diff.HasChange("properties") {
// Only check if the image has been created.
if diff.Id() != "" {
// Try to reconcile the properties set by the server
// with the properties set by the user.
//
// old = user properties + server properties
// new = user properties only
o, n := diff.GetChange("properties")
newProperties := resourceImagesImageV2ExpandProperties(n.(map[string]interface{}))
for oldKey, oldValue := range o.(map[string]interface{}) {
// os_ keys are provided by the OpenStack Image service.
if strings.HasPrefix(oldKey, "os_") {
if v, ok := oldValue.(string); ok {
newProperties[oldKey] = v
}
}
// direct_url is provided by some storage drivers.
if oldKey == "direct_url" {
if v, ok := oldValue.(string); ok {
newProperties[oldKey] = v
}
}
}
// Set the diff to the newProperties, which includes the server-side
// os_ properties.
//
// If the user has changed properties, they will be caught at this
// point, too.
diff.SetNew("properties", newProperties)
}
}
return nil
}
func resourceImagesImageAccessV2ParseID(id string) (string, string, error) {
idParts := strings.Split(id, "/")
if len(idParts) < 2 {
return "", "", fmt.Errorf("Unable to determine image share access ID")
}
imageID := idParts[0]
memberID := idParts[1]
return imageID, memberID, nil
}
func resourceImagesImageAccessV2DetectMemberID(client *gophercloud.ServiceClient, imageID string) (string, error) {
allPages, err := members.List(client, imageID).AllPages()
if err != nil {
return "", fmt.Errorf("Unable to list image members: %s", err)
}
allMembers, err := members.ExtractMembers(allPages)
if err != nil {
return "", fmt.Errorf("Unable to extract image members: %s", err)
}
if len(allMembers) == 0 {
return "", fmt.Errorf("No members found for the %q image", imageID)
}
if len(allMembers) > 1 {
return "", fmt.Errorf("Too many members found for the %q image, please specify the member_id explicitly", imageID)
}
return allMembers[0].MemberID, nil
}
func imagesFilterByRegex(imageArr []images.Image, name_regex string) []images.Image {
var result []images.Image
r := regexp.MustCompile(name_regex)
for _, image := range imageArr {
// Check for a very rare case where the response would include no
// image name. No name means nothing to attempt a match against,
// therefore we are skipping such image.
if image.Name == "" {
log.Printf("[WARN] Unable to find image name to match against "+
"for image ID %q owned by %q, nothing to do.",
image.ID, image.Owner)
continue
}
if r.MatchString(image.Name) {
result = append(result, image)
}
}
return result
}
// v - slice of images to filter
// p - field "properties" of schema.Resource from dataSourceImagesImageIDsV2
// or dataSourceImagesImageV2. If p is empty no filtering applies and the
// function returns the v.
func imagesFilterByProperties(v []images.Image, p map[string]string) []images.Image {
var result []images.Image
if len(p) > 0 {
for _, image := range v {
if len(image.Properties) > 0 {
match := true
for searchKey, searchValue := range p {
imageValue, ok := image.Properties[searchKey]
if !ok {
match = false
break
}
if searchValue != imageValue {
match = false
break
}
}
if match {
result = append(result, image)
}
}
}
} else {
result = v
}
return result
}