CLI interface for cinder management.
"""
+from __future__ import print_function
+
import os
import sys
def _db_error(caught_exception):
- print caught_exception
- print _("The above error may show that the database has not "
+ print('%s' % caught_exception)
+ print(_("The above error may show that the database has not "
"been created.\nPlease create a database using "
- "'cinder-manage db sync' before running this command.")
+ "'cinder-manage db sync' before running this command."))
exit(1)
"""Show a list of all physical hosts. Filter by zone.
args: [zone]
"""
- print "%-25s\t%-15s" % (_('host'),
- _('zone'))
+ print("%-25s\t%-15s" % (_('host'),
+ _('zone')))
ctxt = context.get_admin_context()
services = db.service_get_all(ctxt)
if zone:
hosts.append(srv)
for h in hosts:
- print "%-25s\t%-15s" % (h['host'], h['availability_zone'])
+ print("%-25s\t%-15s" % (h['host'], h['availability_zone']))
class DbCommands(object):
def version(self):
"""Print the current database version."""
- print migration.db_version()
+ print(migration.db_version())
class VersionCommands(object):
host = volume['host']
if not host:
- print "Volume not yet assigned to host."
- print "Deleting volume from database and skipping rpc."
+ print("Volume not yet assigned to host.")
+ print("Deleting volume from database and skipping rpc.")
db.volume_destroy(ctxt, param2id(volume_id))
return
if volume['status'] == 'in-use':
- print "Volume is in-use."
- print "Detach volume from instance and then try again."
+ print("Volume is in-use.")
+ print("Detach volume from instance and then try again.")
return
rpc.cast(ctxt,
ctxt = context.get_admin_context()
volume = db.volume_get(ctxt, param2id(volume_id))
if not volume['instance_id']:
- print "volume is not attached to an instance"
+ print("volume is not attached to an instance")
return
instance = db.instance_get(ctxt, volume['instance_id'])
host = instance['host']
"""
param = param and param.strip()
if param:
- print '%s = %s' % (param, CONF.get(param))
+ print('%s = %s' % (param, CONF.get(param)))
else:
for key, value in CONF.iteritems():
- print '%s = %s' % (key, value)
+ print('%s = %s' % (key, value))
class GetLogCommands(object):
if line.find(" ERROR ") > 0:
error_found += 1
if print_name == 0:
- print log_file + ":-"
+ print(log_file + ":-")
print_name = 1
- print "Line %d : %s" % (len(lines) - index, line)
+ print("Line %d : %s" % (len(lines) - index, line))
if error_found == 0:
- print "No errors in logfiles!"
+ print("No errors in logfiles!")
@args('num_entries', nargs='?', type=int, default=10,
help='Number of entries to list (default: %(default)d)')
elif os.path.exists('/var/log/messages'):
log_file = '/var/log/messages'
else:
- print "Unable to find system log file!"
+ print("Unable to find system log file!")
sys.exit(1)
lines = [line.strip() for line in open(log_file, "r")]
lines.reverse()
- print "Last %s cinder syslog entries:-" % (entries)
+ print("Last %s cinder syslog entries:-" % (entries))
for line in lines:
if line.find("cinder") > 0:
count += 1
- print "%s" % (line)
+ print("%s" % (line))
if count == entries:
break
if count == 0:
- print "No cinder entries in syslog!"
+ print("No cinder entries in syslog!")
class BackupCommands(object):
backups = db.backup_get_all(ctxt)
hdr = "%-32s\t%-32s\t%-32s\t%-24s\t%-24s\t%-12s\t%-12s\t%-12s\t%-12s"
- print hdr % (_('ID'),
+ print(hdr % (_('ID'),
_('User ID'),
_('Project ID'),
_('Host'),
_('Container'),
_('Status'),
_('Size'),
- _('Object Count'))
+ _('Object Count')))
res = "%-32s\t%-32s\t%-32s\t%-24s\t%-24s\t%-12s\t%-12s\t%-12d\t%-12d"
for backup in backups:
object_count = 0
if backup['object_count'] is not None:
object_count = backup['object_count']
- print res % (backup['id'],
+ print(res % (backup['id'],
backup['user_id'],
backup['project_id'],
backup['host'],
backup['container'],
backup['status'],
backup['size'],
- object_count)
+ object_count))
class ServiceCommands(object):
ctxt = context.get_admin_context()
services = db.service_get_all(ctxt)
print_format = "%-16s %-36s %-16s %-10s %-5s %-10s"
- print print_format % (_('Binary'),
+ print(print_format % (_('Binary'),
_('Host'),
_('Zone'),
_('Status'),
_('State'),
- _('Updated At'))
+ _('Updated At')))
for svc in services:
alive = utils.service_is_up(svc)
art = ":-)" if alive else "XXX"
status = 'enabled'
if svc['disabled']:
status = 'disabled'
- print print_format % (svc['binary'], svc['host'].partition('.')[0],
+ print(print_format % (svc['binary'], svc['host'].partition('.')[0],
svc['availability_zone'], status, art,
- svc['updated_at'])
+ svc['updated_at']))
CATEGORIES = {
if len(sys.argv) < 2:
print(_("\nOpenStack Cinder version: %(version)s\n") %
{'version': version.version_string()})
- print script_name + " category action [<args>]"
- print _("Available categories:")
+ print(script_name + " category action [<args>]")
+ print (_("Available categories:"))
for category in CATEGORIES:
- print "\t%s" % category
+ print("\t%s" % category)
sys.exit(2)
try:
cfgfile = CONF.config_file[-1] if CONF.config_file else None
if cfgfile and not os.access(cfgfile, os.R_OK):
st = os.stat(cfgfile)
- print _("Could not read %s. Re-running with sudo") % cfgfile
+ print(_("Could not read %s. Re-running with sudo") % cfgfile)
try:
os.execvp('sudo', ['sudo', '-u', '#%s' % st.st_uid] + sys.argv)
except Exception:
- print _('sudo failed, continuing as if nothing happened')
+ print(_('sudo failed, continuing as if nothing happened'))
- print _('Please re-run cinder-manage as root.')
+ print(_('Please re-run cinder-manage as root.'))
sys.exit(2)
fn = CONF.category.action_fn
they are needed, to avoid allowing more than is necessary.
"""
+from __future__ import print_function
+
import ConfigParser
import logging
import os
def _exit_error(execname, message, errorcode, log=True):
- print "%s: %s" % (execname, message)
+ print("%s: %s" % (execname, message))
if log:
logging.error(message)
sys.exit(errorcode)
Jan 1 through Dec 31 of the previous year.
"""
+from __future__ import print_function
import os
import sys
version=version.version_string())
logging.setup("cinder")
begin, end = utils.last_completed_audit_period()
- print _("Starting volume usage audit")
+ print(_("Starting volume usage audit"))
msg = _("Creating usages for %(begin_period)s until %(end_period)s")
- print (msg % {"begin_period": str(begin), "end_period": str(end)})
+ print(msg % {"begin_period": str(begin), "end_period": str(end)})
extra_info = {
'audit_period_beginning': str(begin),
volumes = db.volume_get_active_by_window(admin_context,
begin,
end)
- print _("Found %d volumes") % len(volumes)
+ print(_("Found %d volumes") % len(volumes))
for volume_ref in volumes:
try:
cinder.volume.utils.notify_usage_exists(admin_context,
volume_ref)
except Exception as e:
- print traceback.format_exc(e)
+ print(traceback.format_exc(e))
snapshots = db.snapshot_get_active_by_window(admin_context,
begin,
end)
- print _("Found %d snapshots") % len(snapshots)
+ print(_("Found %d snapshots") % len(snapshots))
for snapshot_ref in snapshots:
try:
cinder.volume.utils.notify_about_snapshot_usage(admin_context,
'exists',
extra_info)
except Exception as e:
- print traceback.fromat_exc(e)
+ print(traceback.fromat_exc(e))
- print _("Volume usage audit completed")
+ print(_("Volume usage audit completed"))
extra_specs = stub_volume_type_extra_specs()
text = serializer.serialize(dict(extra_specs=extra_specs))
- print text
tree = etree.fromstring(text)
self.assertEqual('extra_specs', tree.tag)
exemplar = dict(key1='value1')
text = serializer.serialize(exemplar)
- print text
tree = etree.fromstring(text)
self.assertEqual('key1', tree.tag)
volume_id='vol_id', )
text = serializer.serialize(dict(snapshot=raw_snapshot))
- print text
tree = etree.fromstring(text)
self._verify_snapshot(raw_snapshot, tree)
volume_id='vol2_id', )]
text = serializer.serialize(dict(snapshots=raw_snapshots))
- print text
tree = etree.fromstring(text)
self.assertEqual('snapshots', tree.tag)
self.assertEqual(str(vol[attr]), tree.get(attr))
for child in tree:
- print child.tag
self.assertTrue(child.tag in (NS + 'attachments', NS + 'metadata'))
if child.tag == 'attachments':
self.assertEqual(1, len(child))
baz='quux', ), )
text = serializer.serialize(dict(volume=raw_volume))
- print text
tree = etree.fromstring(text)
self._verify_volume(raw_volume, tree)
bar='vol2_bar', ), )]
text = serializer.serialize(dict(volumes=raw_volumes))
- print text
tree = etree.fromstring(text)
self.assertEqual(NS + 'volumes', tree.tag)
)
text = serializer.serialize(dict(snapshot=raw_snapshot))
- print text
tree = etree.fromstring(text)
self._verify_snapshot(raw_snapshot, tree)
]
text = serializer.serialize(dict(snapshots=raw_snapshots))
- print text
tree = etree.fromstring(text)
self.assertEqual('snapshots', tree.tag)
self.assertEqual(str(vol[attr]), tree.get(attr))
for child in tree:
- print child.tag
self.assertTrue(child.tag in (NS + 'attachments', NS + 'metadata'))
if child.tag == 'attachments':
self.assertEqual(1, len(child))
)
text = serializer.serialize(dict(volume=raw_volume))
- print text
tree = etree.fromstring(text)
self._verify_volume(raw_volume, tree)
bar='vol2_bar', ), )]
text = serializer.serialize(dict(volumes=raw_volumes))
- print text
tree = etree.fromstring(text)
self.assertEqual(NS + 'volumes', tree.tag)
self.log_action('clear_volume', volume)
def local_path(self, volume):
- print "local_path not implemented"
+ LOG.error(_("local_path not implemented"))
raise NotImplementedError()
def ensure_export(self, context, volume):
def test_update(self):
fixture = self._make_fixture(name='test image')
image = self.service.create(self.context, fixture)
- print image
image_id = image['id']
fixture['name'] = 'new image name'
self.service.update(self.context, image_id, fixture)
"""
def test_service_isolation(self):
- import os
- print os.path.abspath(".")
self.start_service('volume')
def test_rpc_consumer_isolation(self):
"""Utility methods for working with WSGI servers."""
+from __future__ import print_function
import errno
import os
@webob.dec.wsgify(RequestClass=Request)
def __call__(self, req):
- print ('*' * 40) + ' REQUEST ENVIRON'
+ print(('*' * 40) + ' REQUEST ENVIRON')
for key, value in req.environ.items():
- print key, '=', value
- print
+ print(key, '=', value)
+ print()
resp = req.get_response(self.application)
- print ('*' * 40) + ' RESPONSE HEADERS'
+ print(('*' * 40) + ' RESPONSE HEADERS')
for (key, value) in resp.headers.iteritems():
- print key, '=', value
- print
+ print(key, '=', value)
+ print()
resp.app_iter = self.print_generator(resp.app_iter)
@staticmethod
def print_generator(app_iter):
"""Iterator that prints the contents of a wrapper string."""
- print ('*' * 40) + ' BODY'
+ print(('*' * 40) + ' BODY')
for part in app_iter:
sys.stdout.write(part)
sys.stdout.flush()
yield part
- print
+ print()
class Router(object):
# See the License for the specific language governing permissions and
# limitations under the License.
+# THIS FILE IS MANAGED BY THE GLOBAL REQUIREMENTS REPO - DO NOT EDIT
import setuptools
setuptools.setup(
- setup_requires=['d2to1>=0.2.10,<0.3', 'pbr>=0.5.10,<0.6'],
- d2to1=True)
+ setup_requires=['pbr>=0.5.21,<1.0'],
+ pbr=True)
"""Extracts OpenStack config option info from module(s)."""
+from __future__ import print_function
+
import __builtin__
setattr(__builtin__, '_', lambda x: x)
import os
def main(srcfiles):
- print '\n'.join(['#' * 20, '# cinder.conf sample #', '#' * 20,
- '', '[DEFAULT]', ''])
+ print('\n'.join(['#' * 20, '# cinder.conf sample #', '#' * 20,
+ '', '[DEFAULT]', '']))
_list_opts(cfg.ConfigOpts,
cfg.__name__ + ':' + cfg.ConfigOpts.__name__)
mods_by_pkg = dict()
mods.sort()
for mod_str in mods:
_print_module(mod_str)
- print "# Total option count: %d" % OPTION_COUNT
+ print("# Total option count: %d" % OPTION_COUNT)
def _print_module(mod_str):
return
global OPTION_COUNT
OPTION_COUNT += len(opts)
- print '#'
- print '# Options defined in %s' % name
- print '#'
- print
+ print('#')
+ print('# Options defined in %s' % name)
+ print('#')
+ print()
for opt in opts:
_print_opt(opt)
- print
+ print()
def _get_my_ip():
sys.stderr.write("%s\n" % str(err))
sys.exit(1)
opt_help += ' (' + OPT_TYPES[opt_type] + ')'
- print '#', "\n# ".join(textwrap.wrap(opt_help, WORDWRAP_WIDTH))
+ print('#', "\n# ".join(textwrap.wrap(opt_help, WORDWRAP_WIDTH)))
try:
if opt_default is None:
- print '#%s=<None>' % opt_name
+ print('#%s=<None>' % opt_name)
elif opt_type == STROPT:
assert(isinstance(opt_default, basestring))
- print '#%s=%s' % (opt_name, _sanitize_default(opt_default))
+ print('#%s=%s' % (opt_name, _sanitize_default(opt_default)))
elif opt_type == BOOLOPT:
assert(isinstance(opt_default, bool))
- print '#%s=%s' % (opt_name, str(opt_default).lower())
+ print('#%s=%s' % (opt_name, str(opt_default).lower()))
elif opt_type == INTOPT:
assert(isinstance(opt_default, int) and
not isinstance(opt_default, bool))
- print '#%s=%s' % (opt_name, opt_default)
+ print('#%s=%s' % (opt_name, opt_default))
elif opt_type == FLOATOPT:
assert(isinstance(opt_default, float))
- print '#%s=%s' % (opt_name, opt_default)
+ print('#%s=%s' % (opt_name, opt_default))
elif opt_type == LISTOPT:
assert(isinstance(opt_default, list))
- print '#%s=%s' % (opt_name, ','.join(opt_default))
+ print('#%s=%s' % (opt_name, ','.join(opt_default)))
elif opt_type == MULTISTROPT:
assert(isinstance(opt_default, list))
for default in opt_default:
- print '#%s=%s' % (opt_name, default)
- print
+ print('#%s=%s' % (opt_name, default))
+ print()
except Exception:
sys.stderr.write('Error in option "%s"\n' % opt_name)
sys.exit(1)
if __name__ == '__main__':
if len(sys.argv) < 2:
- print "usage: python %s [srcfile]...\n" % sys.argv[0]
+ print("usage: python %s [srcfile]...\n" % sys.argv[0])
sys.exit(0)
main(sys.argv[1:])
"""Installation script for Cinder's development virtualenv."""
+from __future__ import print_function
+
import optparse
import os
import subprocess
Also, make test will automatically use the virtualenv.
"""
- print help
+ print(help)
def main(argv):
"""pylint error checking."""
+from __future__ import print_function
+
import cStringIO as StringIO
import json
import re
@classmethod
def print_json(cls, errors, output=sys.stdout):
- print >>output, "# automatically generated by tools/lintstack.py"
+ print("# automatically generated by tools/lintstack.py", file=output)
for i in sorted(errors.keys()):
- print >>output, json.dumps(i)
+ print(json.dumps(i), file=output)
@classmethod
def from_file(cls, filename):
def generate_error_keys(msg=None):
- print "Generating", KNOWN_PYLINT_EXCEPTIONS_FILE
+ print("Generating", KNOWN_PYLINT_EXCEPTIONS_FILE)
if msg is None:
msg = run_pylint()
errors = LintOutput.from_msg_to_dict(msg)
def validate(newmsg=None):
- print "Loading", KNOWN_PYLINT_EXCEPTIONS_FILE
+ print("Loading", KNOWN_PYLINT_EXCEPTIONS_FILE)
known = ErrorKeys.from_file(KNOWN_PYLINT_EXCEPTIONS_FILE)
if newmsg is None:
- print "Running pylint. Be patient..."
+ print("Running pylint. Be patient...")
newmsg = run_pylint()
errors = LintOutput.from_msg_to_dict(newmsg)
- print "Unique errors reported by pylint: was %d, now %d." \
- % (len(known), len(errors))
+ print("Unique errors reported by pylint: was %d, now %d."
+ % (len(known), len(errors)))
passed = True
for err_key, err_list in errors.items():
for err in err_list:
if err_key not in known:
- print err.lintoutput
- print
+ print(err.lintoutput)
+ print()
passed = False
if passed:
- print "Congrats! pylint check passed."
+ print("Congrats! pylint check passed.")
redundant = known - set(errors.keys())
if redundant:
- print "Extra credit: some known pylint exceptions disappeared."
+ print("Extra credit: some known pylint exceptions disappeared.")
for i in sorted(redundant):
- print json.dumps(i)
- print "Consider regenerating the exception file if you will."
+ print(json.dumps(i))
+ print("Consider regenerating the exception file if you will.")
else:
- print ("Please fix the errors above. If you believe they are false "
- "positives, run 'tools/lintstack.py generate' to overwrite.")
+ print("Please fix the errors above. If you believe they are false "
+ "positives, run 'tools/lintstack.py generate' to overwrite.")
sys.exit(1)
def usage():
- print """Usage: tools/lintstack.py [generate|validate]
+ print("""Usage: tools/lintstack.py [generate|validate]
To generate pylint_exceptions file: tools/lintstack.py generate
To validate the current commit: tools/lintstack.py
- """
+ """)
def main():
commands = {posargs}
[flake8]
-ignore = E711,E712,F401,F403,F811,F841,H233,H302,H303,H304,H402,H404
+ignore = E711,E712,F401,F403,F811,F841,H302,H303,H304,H402,H404
builtins = _
exclude = .git,.venv,.tox,dist,doc,common,*egg,build