-
Notifications
You must be signed in to change notification settings - Fork 50
/
upload.go
206 lines (189 loc) · 7.02 KB
/
upload.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
package oci
import (
"context"
"fmt"
"log"
"net/http"
"os"
"time"
"github.com/oracle/oci-go-sdk/v54/common"
"github.com/oracle/oci-go-sdk/v54/core"
"github.com/oracle/oci-go-sdk/v54/identity"
"github.com/oracle/oci-go-sdk/v54/objectstorage"
"github.com/oracle/oci-go-sdk/v54/objectstorage/transfer"
"github.com/oracle/oci-go-sdk/v54/workrequests"
)
type Uploader interface {
Upload(name string, bucketName string, namespace string, file *os.File, user, compartment string) (string, error)
}
type ImageCreator interface {
create(imageName, bucketName, namespace, compartmentID string) (string, error)
}
type Client struct {
Uploader
ImageCreator
ociClient
}
// Upload uploads a file into an objectName under the bucketName in the namespace.
func (c Client) Upload(objectName string, bucketName string, namespace string, file *os.File, compartmentID, imageName string) (string, error) {
err := c.uploadToBucket(objectName, bucketName, namespace, file)
// clean up the object even if we fail
defer func() {
if err := c.deleteObjectFromBucket(objectName, bucketName, namespace); err != nil {
log.Printf("failed to clean up the object '%s' from bucket '%s'", objectName, bucketName)
}
}()
if err != nil {
return "", err
}
imageID, err := c.createImage(objectName, bucketName, namespace, compartmentID, imageName)
if err != nil {
return "", fmt.Errorf("failed to create a custom image using object '%s' bucket '%s' in namespace '%s': %w",
objectName,
bucketName,
namespace,
err)
}
return imageID, nil
}
func (c Client) uploadToBucket(objectName string, bucketName string, namespace string, file *os.File) error {
req := transfer.UploadFileRequest{
UploadRequest: transfer.UploadRequest{
NamespaceName: common.String(namespace),
BucketName: common.String(bucketName),
ObjectName: common.String(objectName),
CallBack: func(multiPartUploadPart transfer.MultiPartUploadPart) {
if multiPartUploadPart.Err != nil {
log.Printf("upload failure: %s\n", multiPartUploadPart.Err)
}
log.Printf("multipart upload stats: parts %d, total-parts %d\n",
multiPartUploadPart.PartNum,
multiPartUploadPart.TotalParts)
},
ObjectStorageClient: &c.storageClient,
},
FilePath: file.Name(),
}
uploadManager := transfer.NewUploadManager()
ctx := context.Background()
resp, err := uploadManager.UploadFile(ctx, req)
if err != nil {
if resp.IsResumable() {
resp, err = uploadManager.ResumeUploadFile(ctx, *resp.MultipartUploadResponse.UploadID)
if err != nil {
return err
}
} else {
return fmt.Errorf("failed to upload the file to object %s: %w", objectName, err)
}
}
return nil
}
// Create creates an image from the storageObjectName stored in the bucketName.
// The result is an image ID or an error if the operation failed.
func (c Client) createImage(objectName, bucketName, namespace, compartmentID, imageName string) (string, error) {
request := core.CreateImageRequest{
CreateImageDetails: core.CreateImageDetails{
DisplayName: common.String(imageName),
CompartmentId: common.String(compartmentID),
FreeformTags: map[string]string{
"Uploaded-By": "osbuild-composer",
"Name": imageName,
},
ImageSourceDetails: core.ImageSourceViaObjectStorageTupleDetails{
BucketName: common.String(bucketName),
NamespaceName: common.String(namespace),
ObjectName: common.String(objectName),
SourceImageType: core.ImageSourceDetailsSourceImageTypeQcow2,
},
},
}
createImageResponse, err := c.computeClient.CreateImage(context.Background(), request)
if err != nil {
return "", fmt.Errorf("failed to create an image from storage object: %w", err)
}
log.Printf("waiting for the work request to complete, this may take a while. Work request ID: %s\n", *createImageResponse.OpcWorkRequestId)
for {
r, err := c.workRequestsClient.GetWorkRequest(context.Background(), workrequests.GetWorkRequestRequest{
WorkRequestId: createImageResponse.OpcWorkRequestId,
OpcRequestId: createImageResponse.OpcRequestId,
})
if err != nil {
return "", fmt.Errorf("failed to fetch the work request for creating the image: %w", err)
}
switch r.Status {
case workrequests.WorkRequestStatusSucceeded:
return *createImageResponse.Id, nil
case workrequests.WorkRequestStatusCanceled, workrequests.WorkRequestStatusFailed:
return "", fmt.Errorf("the work request for creating an image is in status %s", r.Status)
}
time.Sleep(1 * time.Second)
}
}
type ClientParams struct {
User string
Region string
Tenancy string
PrivateKey string
Fingerprint string
}
type ociClient struct {
storageClient objectstorage.ObjectStorageClient
identityClient identity.IdentityClient
computeClient core.ComputeClient
workRequestsClient workrequests.WorkRequestClient
}
// deleteObjectFromBucket deletes the object by name from the bucket.
func (c Client) deleteObjectFromBucket(name string, bucket string, namespace string) error {
_, err := c.storageClient.DeleteObject(context.Background(), objectstorage.DeleteObjectRequest{
NamespaceName: common.String(namespace),
BucketName: common.String(bucket),
ObjectName: common.String(name),
})
return err
}
// NewClient creates a new oci client from the passed in params.
// Pass nil clientParams if you want the client to automatically detect
// the configuration from the official disk location or and env file
// From the docs its: $HOME/.oci/config, $HOME/.obmcs/config and variable
// names starting with TF_VAR.
// Last is the environment variable OCI_CONFIG_FILE
func NewClient(clientParams *ClientParams) (Client, error) {
var configProvider common.ConfigurationProvider
if clientParams != nil {
configProvider = common.NewRawConfigurationProvider(
clientParams.Tenancy,
clientParams.User,
clientParams.Region,
clientParams.Fingerprint,
clientParams.PrivateKey,
nil,
)
} else {
configProvider = common.DefaultConfigProvider()
}
storageClient, err := objectstorage.NewObjectStorageClientWithConfigurationProvider(configProvider)
// this disables the default 60 seconds timeout, to support big files upload (the common scenario)
storageClient.HTTPClient = &http.Client{}
if err != nil {
return Client{}, fmt.Errorf("failed to create an Oracle objectstorage client: %w", err)
}
identityClient, err := identity.NewIdentityClientWithConfigurationProvider(configProvider)
if err != nil {
return Client{}, fmt.Errorf("failed to create an Oracle identity client: %w", err)
}
computeClient, err := core.NewComputeClientWithConfigurationProvider(configProvider)
if err != nil {
return Client{}, fmt.Errorf("failed to create an Oracle compute client: %w", err)
}
workRequestsClient, err := workrequests.NewWorkRequestClientWithConfigurationProvider(configProvider)
if err != nil {
return Client{}, fmt.Errorf("failed to create an Oracle workrequests client: %w", err)
}
return Client{ociClient: ociClient{
storageClient: storageClient,
identityClient: identityClient,
computeClient: computeClient,
workRequestsClient: workRequestsClient,
}}, nil
}