Skip to content

Commit 6f616a2

Browse files
epicartsstephenfin
authored andcommitted
Add support '--progress' option for 'image create'
openstack-client doesn’t support the upload progress bar. This patch shows progressbar when create image if you added '--progress' option like a python-glanceclient. like this. [=============================>] 100% +------------------+---------------------------+ | Field | Value | +------------------+---------------------------+ | container_format | bare | | created_at | 2020-09-06T20:44:40Z | ... How to use Add the'--progress' option on the 'openstack image create' command. Code was written by referring to 'python-glanceclient' project on stable/ussuri branch Change-Id: Ic3035b49da10b6555066eee607a14a5b73797c00 task: 40003 story: 2007777
1 parent f083fc6 commit 6f616a2

4 files changed

Lines changed: 161 additions & 0 deletions

File tree

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
# Copyright 2013 OpenStack Foundation
2+
# All Rights Reserved.
3+
#
4+
# Licensed under the Apache License, Version 2.0 (the "License"); you may
5+
# not use this file except in compliance with the License. You may obtain
6+
# a copy of the License at
7+
#
8+
# http://www.apache.org/licenses/LICENSE-2.0
9+
#
10+
# Unless required by applicable law or agreed to in writing, software
11+
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12+
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13+
# License for the specific language governing permissions and limitations
14+
# under the License.
15+
16+
import sys
17+
18+
19+
class _ProgressBarBase(object):
20+
"""A progress bar provider for a wrapped obect.
21+
22+
Base abstract class used by specific class wrapper to show
23+
a progress bar when the wrapped object are consumed.
24+
25+
:param wrapped: Object to wrap that hold data to be consumed.
26+
:param totalsize: The total size of the data in the wrapped object.
27+
28+
:note: The progress will be displayed only if sys.stdout is a tty.
29+
"""
30+
31+
def __init__(self, wrapped, totalsize):
32+
self._wrapped = wrapped
33+
self._totalsize = float(totalsize)
34+
self._show_progress = sys.stdout.isatty() and self._totalsize != 0
35+
self._percent = 0
36+
37+
def _display_progress_bar(self, size_read):
38+
if self._show_progress:
39+
self._percent += size_read / self._totalsize
40+
# Output something like this: [==========> ] 49%
41+
sys.stdout.write('\r[{0:<30}] {1:.0%}'.format(
42+
'=' * int(round(self._percent * 29)) + '>', self._percent
43+
))
44+
sys.stdout.flush()
45+
46+
def __getattr__(self, attr):
47+
# Forward other attribute access to the wrapped object.
48+
return getattr(self._wrapped, attr)
49+
50+
51+
class VerboseFileWrapper(_ProgressBarBase):
52+
"""A file wrapper with a progress bar.
53+
54+
The file wrapper shows and advances a progress bar whenever the
55+
wrapped file's read method is called.
56+
"""
57+
58+
def read(self, *args, **kwargs):
59+
data = self._wrapped.read(*args, **kwargs)
60+
if data:
61+
self._display_progress_bar(len(data))
62+
else:
63+
if self._show_progress:
64+
# Break to a new line from the progress bar for incoming
65+
# output.
66+
sys.stdout.write('\n')
67+
return data

openstackclient/image/v2/image.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@
3030
from osc_lib import exceptions
3131
from osc_lib import utils
3232

33+
from openstackclient.common import progressbar
3334
from openstackclient.common import sdk_utils
3435
from openstackclient.i18n import _
3536
from openstackclient.identity import common
@@ -255,6 +256,12 @@ def get_parser(self, prog_name):
255256
help=_("Force image creation if volume is in use "
256257
"(only meaningful with --volume)"),
257258
)
259+
parser.add_argument(
260+
"--progress",
261+
action="store_true",
262+
default=False,
263+
help=_("Show upload progress bar."),
264+
)
258265
parser.add_argument(
259266
'--sign-key-path',
260267
metavar="<sign-key-path>",
@@ -412,6 +419,11 @@ def take_action(self, parsed_args):
412419
if fp is None and parsed_args.file:
413420
LOG.warning(_("Failed to get an image file."))
414421
return {}, {}
422+
if fp is not None and parsed_args.progress:
423+
filesize = os.path.getsize(fname)
424+
if filesize is not None:
425+
kwargs['validate_checksum'] = False
426+
kwargs['data'] = progressbar.VerboseFileWrapper(fp, filesize)
415427
elif fname:
416428
kwargs['filename'] = fname
417429
elif fp:
Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
# Licensed under the Apache License, Version 2.0 (the "License"); you may
2+
# not use this file except in compliance with the License. You may obtain
3+
# a copy of the License at
4+
#
5+
# http://www.apache.org/licenses/LICENSE-2.0
6+
#
7+
# Unless required by applicable law or agreed to in writing, software
8+
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
9+
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
10+
# License for the specific language governing permissions and limitations
11+
# under the License.
12+
#
13+
14+
import sys
15+
16+
import six
17+
18+
from openstackclient.common import progressbar
19+
from openstackclient.tests.unit import utils
20+
21+
22+
class TestProgressBarWrapper(utils.TestCase):
23+
24+
def test_iter_file_display_progress_bar(self):
25+
size = 98304
26+
file_obj = six.StringIO('X' * size)
27+
saved_stdout = sys.stdout
28+
try:
29+
sys.stdout = output = FakeTTYStdout()
30+
file_obj = progressbar.VerboseFileWrapper(file_obj, size)
31+
chunksize = 1024
32+
chunk = file_obj.read(chunksize)
33+
while chunk:
34+
chunk = file_obj.read(chunksize)
35+
self.assertEqual(
36+
'[%s>] 100%%\n' % ('=' * 29),
37+
output.getvalue()
38+
)
39+
finally:
40+
sys.stdout = saved_stdout
41+
42+
def test_iter_file_no_tty(self):
43+
size = 98304
44+
file_obj = six.StringIO('X' * size)
45+
saved_stdout = sys.stdout
46+
try:
47+
sys.stdout = output = FakeNoTTYStdout()
48+
file_obj = progressbar.VerboseFileWrapper(file_obj, size)
49+
chunksize = 1024
50+
chunk = file_obj.read(chunksize)
51+
while chunk:
52+
chunk = file_obj.read(chunksize)
53+
# If stdout is not a tty progress bar should do nothing.
54+
self.assertEqual('', output.getvalue())
55+
finally:
56+
sys.stdout = saved_stdout
57+
58+
59+
class FakeTTYStdout(six.StringIO):
60+
"""A Fake stdout that try to emulate a TTY device as much as possible."""
61+
62+
def isatty(self):
63+
return True
64+
65+
def write(self, data):
66+
# When a CR (carriage return) is found reset file.
67+
if data.startswith('\r'):
68+
self.seek(0)
69+
data = data[1:]
70+
return six.StringIO.write(self, data)
71+
72+
73+
class FakeNoTTYStdout(FakeTTYStdout):
74+
"""A Fake stdout that is not a TTY device."""
75+
76+
def isatty(self):
77+
return False
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
features:
3+
- |
4+
Add ``--progress`` option to ``image create`` command to enable a progress
5+
bar when creating and uploading an image.

0 commit comments

Comments
 (0)