/
upload_disk.py
executable file
·320 lines (255 loc) · 10.2 KB
/
upload_disk.py
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
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Copyright (c) 2016-2017 Red Hat, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
"""
Upload disk example code.
Requires the ovirt-imageio-client package.
"""
import inspect
import json
import os
import subprocess
import time
import uuid
from contextlib import closing
from ovirt_imageio import client
from ovirtsdk4 import types
from helpers import common
from helpers import imagetransfer
from helpers import units
from helpers.common import progress
def parse_args():
parser = common.ArgumentParser(description="Upload images")
parser.add_argument(
"filename",
help="Path to image (e.g. /path/to/image.raw). "
"Supported formats: raw, qcow2, iso.")
parser.add_argument(
"--disk-format",
choices=("raw", "qcow2"),
help="Format of the created disk (default image format).")
parser.add_argument(
"--disk-sparse",
action="store_true",
help="Create sparse disk. Cannot be used with raw format on "
"block storage.")
parser.add_argument(
"--disk-id",
type=validate_uuid,
help="A UUID for the new disk. If not specified oVirt will "
"create a new UUID.")
parser.add_argument(
"--enable-backup",
action="store_true",
help="Creates a disk that can be used for incremental backup. "
"Allowed for disk with qcow2 format only.")
parser.add_argument(
"--sd-name",
required=True,
help="Name of the storage domain.")
parser.add_argument(
"--use-proxy",
dest="use_proxy",
default=False,
action="store_true",
help="Upload via proxy on the engine host (less efficient).")
parser.add_argument(
"--max-workers",
type=int,
default=4,
help="Maximum number of workers to use for upload. The default "
"(4) improves performance when uploading a single disk. "
"You may want to use lower number if you upload many disks "
"in the same time.")
parser.add_argument(
"--buffer-size",
type=units.humansize,
default=client.BUFFER_SIZE,
help="Buffer size per worker. The default ({}) gives good "
"performance with the default number of workers. If you use "
"smaller number of workers you may want use larger value."
.format(client.BUFFER_SIZE))
parser.add_argument(
"--inactivity-timeout",
type=int,
help="Number of seconds to wait before aborting an inactive "
"transfer. May be needed when uploading an image from "
"a very slow remote file system.")
parser.add_argument(
"--timeout-policy",
choices=('legacy', 'pause', 'cancel'),
default='cancel',
help="The action to be made for a timed out transfer")
return parser.parse_args()
def validate_uuid(s):
"""
Validate that the argument is a valid uuid and return a normalized UUID
string.
"""
return str(uuid.UUID(s))
def get_image_info(filename):
progress("Checking image...")
out = subprocess.check_output(
["qemu-img", "info", "--output", "json", filename])
image_info = json.loads(out)
if image_info["format"] not in ("qcow2", "raw"):
raise RuntimeError("Unsupported image format %(format)s" % image_info)
return image_info
def get_disk_info(args, image_info):
disk_info = {}
disk_format = args.disk_format or image_info["format"]
# Convert qemu format names to oVirt constants ("raw", "cow").
if disk_format == "raw":
disk_info["format"] = types.DiskFormat.RAW
elif disk_format == "qcow2":
disk_info["format"] = types.DiskFormat.COW
disk_info["provisioned_size"] = image_info["virtual-size"]
# The initial size is needed only for block storage (iSCSI, FC). We cannot
# use the actual image size because the image may be compressed.
out = subprocess.check_output([
"qemu-img",
"measure",
"-f", image_info["format"],
"-O", disk_format,
"--output", "json",
image_info["filename"]
])
measure = json.loads(out)
disk_info["initial_size"] = measure["required"]
# Detect disk content type
#
# ISO format structure
# ---------------------------------------------------------------------------
# offset type value comment
# ---------------------------------------------------------------------------
# 0x0000 system area (e.g. DOS/MBR boot sector)
# 0x8000 int8 0x01 primary volume descriptor type code
# 0x8001 strA "CD001" primary volume descriptor indentifier
# 0x8006 int8 0x01 primary volume desctptor version
# 0x8007 0x00 unused field
#
# See https://wiki.osdev.org/ISO_9660#Overview_and_caveats for more info.
content_type = types.DiskContentType.DATA
if image_info["format"] == "raw":
with open(image_info["filename"], "rb") as f:
f.seek(0x8000)
primary_volume_descriptor = f.read(8)
if primary_volume_descriptor == b"\x01CD001\x01\x00":
content_type = types.DiskContentType.ISO
# Name the disk based on image file name, format and content type.
basename = os.path.splitext(os.path.basename(image_info["filename"]))[0]
ext = "iso" if content_type == types.DiskContentType.ISO else disk_format
disk_info["name"] = "{}.{}".format(basename, ext)
disk_info["content_type"] = content_type
return disk_info
args = parse_args()
common.configure_logging(args)
# Get image and disk info using qemu-img
image_info = get_image_info(args.filename)
disk_info = get_disk_info(args, image_info)
progress("Image format: %s" % image_info["format"])
progress("Disk format: %s" % disk_info["format"])
progress("Disk content type: %s" % disk_info["content_type"])
progress("Disk provisioned size: %s" % disk_info["provisioned_size"])
progress("Disk initial size: %s" % disk_info["initial_size"])
progress("Disk name: %s" % disk_info["name"])
progress("Disk backup: %s" % args.enable_backup)
# This example will connect to the server and create a new `floating`
# disk, one that isn't attached to any virtual machine.
# Then using transfer service it will transfer disk data from local
# image to the newly created disk in server.
progress("Connecting...")
connection = common.create_connection(args)
with closing(connection):
progress("Creating disk...")
disks_service = connection.system_service().disks_service()
disk = disks_service.add(
disk=types.Disk(
id=args.disk_id,
name=disk_info["name"],
content_type=disk_info["content_type"],
description='Uploaded disk',
format=disk_info["format"],
initial_size=disk_info["initial_size"],
provisioned_size=disk_info["provisioned_size"],
sparse=args.disk_sparse,
backup=types.DiskBackup.INCREMENTAL if args.enable_backup else None,
storage_domains=[
types.StorageDomain(
name=args.sd_name
)
]
)
)
# Wait till the disk is up, as the transfer can't start if the disk is
# locked:
disk_service = disks_service.disk_service(disk.id)
while True:
time.sleep(1)
disk = disk_service.get()
if disk.status == types.DiskStatus.OK:
break
progress("Disk ID: %s" % disk.id)
progress("Creating image transfer...")
# Find a host for this transfer. This is an optional step allowing
# optimizing the transfer using unix socket when running this code on a
# oVirt hypervisor in the same data center.
host = imagetransfer.find_host(connection, args.sd_name)
transfer = imagetransfer.create_transfer(
connection,
disk,
types.ImageTransferDirection.UPLOAD,
host=host,
inactivity_timeout=args.inactivity_timeout,
timeout_policy=types.ImageTransferTimeoutPolicy(args.timeout_policy))
try:
# oVirt started an image transfer for uploading the image data into the
# disk. Any error after this point must cancel the transfer, which will
# delete the disk with the partial data. If the data was uploaded
# successfuly, the transfer must be finalized.
progress("Transfer ID: %s" % transfer.id)
progress("Transfer host name: %s" % transfer.host.name)
extra_args = {}
parameters = inspect.signature(client.download).parameters
# Use multiple workers to speed up the upload.
if "max_workers" in parameters:
extra_args["max_workers"] = args.max_workers
if args.use_proxy:
upload_url = transfer.proxy_url
else:
upload_url = transfer.transfer_url
# Use fallback to proxy_url if feature is available. Upload will
# use the proxy_url if transfer_url is not accessible.
if "proxy_url" in parameters:
extra_args["proxy_url"] = transfer.proxy_url
progress("Uploading image...")
with client.ProgressBar() as pb:
client.upload(
args.filename,
upload_url,
args.cafile,
secure=args.secure,
buffer_size=args.buffer_size,
progress=pb,
**extra_args)
except:
progress("Canceling image transfer...")
imagetransfer.cancel_transfer(connection, transfer)
raise
progress("Finalizing image transfer...")
imagetransfer.finalize_transfer(connection, transfer, disk)
progress("Upload completed successfully")