Refactor code

- Fix pep8 error H903: [1]
- Add method _update_task_state to reduce code lines.
- Change single quotes to double quotes in docstring - PEP8 docstring
convention [2].

[1] http://paste.openstack.org/show/614990/
[2] https://www.python.org/dev/peps/pep-0257/

Partials-Bug: #1702587

Change-Id: Idd125665a2a5f0a73337d36f0259a9f9107946ad
This commit is contained in:
Kien Nguyen 2017-07-11 16:52:36 +07:00
parent 076c921229
commit 56592105f9
17 changed files with 171 additions and 178 deletions

View File

@ -172,13 +172,13 @@ class ContainersController(base.Controller):
return view.format_container(pecan.request.host_url, container) return view.format_container(pecan.request.host_url, container)
def _generate_name_for_container(self): def _generate_name_for_container(self):
'''Generate a random name like: zeta-22-container.''' """Generate a random name like: zeta-22-container."""
name_gen = name_generator.NameGenerator() name_gen = name_generator.NameGenerator()
name = name_gen.generate() name = name_gen.generate()
return name + '-container' return name + '-container'
def _check_for_restart_policy(self, container_dict): def _check_for_restart_policy(self, container_dict):
'''Check for restart policy input''' """Check for restart policy input"""
restart_policy = container_dict.get('restart_policy') restart_policy = container_dict.get('restart_policy')
if not restart_policy: if not restart_policy:
return return

View File

@ -52,7 +52,7 @@ class ImageCollection(collection.Collection):
class ImagesController(base.Controller): class ImagesController(base.Controller):
'''Controller for Images''' """Controller for Images"""
_custom_actions = { _custom_actions = {
'search': ['GET'] 'search': ['GET']
@ -61,7 +61,7 @@ class ImagesController(base.Controller):
@pecan.expose('json') @pecan.expose('json')
@exception.wrap_pecan_controller_exception @exception.wrap_pecan_controller_exception
def get_all(self, **kwargs): def get_all(self, **kwargs):
'''Retrieve a list of images.''' """Retrieve a list of images."""
context = pecan.request.context context = pecan.request.context
policy.enforce(context, "image:get_all", policy.enforce(context, "image:get_all",
action="image:get_all") action="image:get_all")

View File

@ -23,10 +23,10 @@ class NameGenerator(object):
self.random = Random() self.random = Random()
def generate(self): def generate(self):
'''Generate a random name compose of a Greek leter and """Generate a random name compose of a Greek leter and
a number, like: beta_2. a number, like: beta_2.
''' """
letter = self.random.choice(self.letters) letter = self.random.choice(self.letters)
number = self.random.randint(1, 24) number = self.random.randint(1, 24)

View File

@ -170,7 +170,7 @@ def translate_exception(function):
def check_container_id(function): def check_container_id(function):
'''Check container_id property of given container instance.''' """Check container_id property of given container instance."""
@functools.wraps(function) @functools.wraps(function)
def decorated_function(*args, **kwargs): def decorated_function(*args, **kwargs):

View File

@ -33,7 +33,7 @@ LOG = logging.getLogger(__name__)
class Manager(object): class Manager(object):
'''Manages the running containers.''' """Manages the running containers."""
def __init__(self, container_driver=None): def __init__(self, container_driver=None):
super(Manager, self).__init__() super(Manager, self).__init__()
@ -73,6 +73,10 @@ class Manager(object):
LOG.error("Error occurred while deleting sandbox: %s", LOG.error("Error occurred while deleting sandbox: %s",
six.text_type(e)) six.text_type(e))
def _update_task_state(self, context, container, task_state):
container.task_state = task_state
container.save(context)
def _do_container_create(self, context, container, requested_networks, def _do_container_create(self, context, container, requested_networks,
limits=None, reraise=False): limits=None, reraise=False):
LOG.debug('Creating container: %s', container.uuid) LOG.debug('Creating container: %s', container.uuid)
@ -86,9 +90,7 @@ class Manager(object):
self._fail_container(self, context, container, msg) self._fail_container(self, context, container, msg)
return return
container.task_state = consts.SANDBOX_CREATING self._update_task_state(context, container, consts.SANDBOX_CREATING)
container.save(context)
sandbox_id = None
sandbox_image = CONF.sandbox_image sandbox_image = CONF.sandbox_image
sandbox_image_driver = CONF.sandbox_image_driver sandbox_image_driver = CONF.sandbox_image_driver
sandbox_image_pull_policy = CONF.sandbox_image_pull_policy sandbox_image_pull_policy = CONF.sandbox_image_pull_policy
@ -109,8 +111,7 @@ class Manager(object):
self._fail_container(context, container, six.text_type(e)) self._fail_container(context, container, six.text_type(e))
return return
container.task_state = consts.IMAGE_PULLING self._update_task_state(context, container, consts.IMAGE_PULLING)
container.save(context)
repo, tag = utils.parse_image_name(container.image) repo, tag = utils.parse_image_name(container.image)
image_pull_policy = utils.get_image_pull_policy( image_pull_policy = utils.get_image_pull_policy(
container.image_pull_policy, tag) container.image_pull_policy, tag)
@ -151,8 +152,7 @@ class Manager(object):
limits): limits):
container = self.driver.create(context, container, container = self.driver.create(context, container,
sandbox_id, image) sandbox_id, image)
container.task_state = None self._update_task_state(context, container, None)
container.save(context)
return container return container
except exception.DockerError as e: except exception.DockerError as e:
with excutils.save_and_reraise_exception(reraise=reraise): with excutils.save_and_reraise_exception(reraise=reraise):
@ -173,12 +173,10 @@ class Manager(object):
def _do_container_start(self, context, container, reraise=False): def _do_container_start(self, context, container, reraise=False):
LOG.debug('Starting container: %s', container.uuid) LOG.debug('Starting container: %s', container.uuid)
container.task_state = consts.CONTAINER_STARTING self._update_task_state(context, container, consts.CONTAINER_STARTING)
container.save(context)
try: try:
container = self.driver.start(context, container) container = self.driver.start(context, container)
container.task_state = None self._update_task_state(context, container, None)
container.save(context)
return container return container
except exception.DockerError as e: except exception.DockerError as e:
with excutils.save_and_reraise_exception(reraise=reraise): with excutils.save_and_reraise_exception(reraise=reraise):
@ -194,8 +192,7 @@ class Manager(object):
@translate_exception @translate_exception
def container_delete(self, context, container, force): def container_delete(self, context, container, force):
LOG.debug('Deleting container: %s', container.uuid) LOG.debug('Deleting container: %s', container.uuid)
container.task_state = consts.CONTAINER_DELETING self._update_task_state(context, container, consts.CONTAINER_DELETING)
container.save(context)
reraise = not force reraise = not force
try: try:
self.driver.delete(container, force) self.driver.delete(container, force)
@ -211,8 +208,8 @@ class Manager(object):
sandbox_id = self.driver.get_sandbox_id(container) sandbox_id = self.driver.get_sandbox_id(container)
if sandbox_id: if sandbox_id:
container.task_state = consts.SANDBOX_DELETING self._update_task_state(context, container,
container.save(context) consts.SANDBOX_DELETING)
try: try:
self.driver.delete_sandbox(context, container, sandbox_id) self.driver.delete_sandbox(context, container, sandbox_id)
except Exception as e: except Exception as e:
@ -220,8 +217,7 @@ class Manager(object):
LOG.exception("Unexpected exception: %s", LOG.exception("Unexpected exception: %s",
six.text_type(e)) six.text_type(e))
self._fail_container(context, container, six.text_type(e)) self._fail_container(context, container, six.text_type(e))
container.task_state = None self._update_task_state(context, container, None)
container.save(context)
container.destroy(context) container.destroy(context)
self._get_resource_tracker() self._get_resource_tracker()
@ -250,7 +246,7 @@ class Manager(object):
def container_list(self, context): def container_list(self, context):
LOG.debug('Listing container...') LOG.debug('Listing container...')
try: try:
return self.driver.list() return self.driver.list(context)
except exception.DockerError as e: except exception.DockerError as e:
LOG.error("Error occurred while calling Docker list API: %s", LOG.error("Error occurred while calling Docker list API: %s",
six.text_type(e)) six.text_type(e))
@ -277,12 +273,10 @@ class Manager(object):
def _do_container_reboot(self, context, container, timeout, reraise=False): def _do_container_reboot(self, context, container, timeout, reraise=False):
LOG.debug('Rebooting container: %s', container.uuid) LOG.debug('Rebooting container: %s', container.uuid)
container.task_state = consts.CONTAINER_REBOOTING self._update_task_state(context, container, consts.CONTAINER_REBOOTING)
container.save(context)
try: try:
container = self.driver.reboot(context, container, timeout) container = self.driver.reboot(context, container, timeout)
container.task_state = None self._update_task_state(context, container, None)
container.save(context)
return container return container
except exception.DockerError as e: except exception.DockerError as e:
with excutils.save_and_reraise_exception(reraise=reraise): with excutils.save_and_reraise_exception(reraise=reraise):
@ -300,12 +294,10 @@ class Manager(object):
def _do_container_stop(self, context, container, timeout, reraise=False): def _do_container_stop(self, context, container, timeout, reraise=False):
LOG.debug('Stopping container: %s', container.uuid) LOG.debug('Stopping container: %s', container.uuid)
container.task_state = consts.CONTAINER_STOPPING self._update_task_state(context, container, consts.CONTAINER_STOPPING)
container.save(context)
try: try:
container = self.driver.stop(context, container, timeout) container = self.driver.stop(context, container, timeout)
container.task_state = None self._update_task_state(context, container, None)
container.save(context)
return container return container
except exception.DockerError as e: except exception.DockerError as e:
with excutils.save_and_reraise_exception(reraise=reraise): with excutils.save_and_reraise_exception(reraise=reraise):
@ -561,8 +553,6 @@ class Manager(object):
def _do_container_commit(self, context, snapshot_image, container, def _do_container_commit(self, context, snapshot_image, container,
repository, tag=None): repository, tag=None):
LOG.debug('Creating image...') LOG.debug('Creating image...')
container_image = None
container_image_id = None
if tag is None: if tag is None:
tag = 'latest' tag = 'latest'

View File

@ -39,13 +39,13 @@ def check_container_host(func):
@profiler.trace_cls("rpc") @profiler.trace_cls("rpc")
class API(rpc_service.API): class API(rpc_service.API):
'''Client side of the container compute rpc API. """Client side of the container compute rpc API.
API version history: API version history:
* 1.0 - Initial version. * 1.0 - Initial version.
* 1.1 - Add image endpoints. * 1.1 - Add image endpoints.
''' """
def __init__(self, transport=None, context=None, topic=None): def __init__(self, transport=None, context=None, topic=None):
if topic is None: if topic is None:

View File

@ -71,7 +71,7 @@ def wrap_docker_error(function):
class DockerDriver(driver.ContainerDriver): class DockerDriver(driver.ContainerDriver):
'''Implementation of container drivers for Docker.''' """Implementation of container drivers for Docker."""
def __init__(self): def __init__(self):
super(DockerDriver, self).__init__() super(DockerDriver, self).__init__()
@ -758,7 +758,7 @@ class NovaDockerDriver(DockerDriver):
return sandbox_id return sandbox_id
def _ensure_active(self, novaclient, server, timeout=300): def _ensure_active(self, novaclient, server, timeout=300):
'''Wait until the Nova instance to become active.''' """Wait until the Nova instance to become active."""
def _check_active(): def _check_active():
return novaclient.check_active(server) return novaclient.check_active(server)
@ -791,7 +791,7 @@ class NovaDockerDriver(DockerDriver):
novaclient.stop_server(server_name) novaclient.stop_server(server_name)
def _ensure_deleted(self, novaclient, server_id, timeout=300): def _ensure_deleted(self, novaclient, server_id, timeout=300):
'''Wait until the Nova instance to be deleted.''' """Wait until the Nova instance to be deleted."""
def _check_delete_complete(): def _check_delete_complete():
return novaclient.check_delete_server_complete(server_id) return novaclient.check_delete_server_complete(server_id)

View File

@ -58,7 +58,7 @@ def load_container_driver(container_driver=None):
class ContainerDriver(object): class ContainerDriver(object):
'''Base class for container drivers.''' """Base class for container drivers."""
def create(self, context, container, sandbox_name=None): def create(self, context, container, sandbox_name=None):
"""Create a container.""" """Create a container."""
@ -203,6 +203,9 @@ class ContainerDriver(object):
def add_security_group(self, context, container, security_group, **kwargs): def add_security_group(self, context, container, security_group, **kwargs):
raise NotImplementedError() raise NotImplementedError()
def get_available_nodes(self):
pass
def get_available_resources(self, node): def get_available_resources(self, node):
numa_topo_obj = self.get_host_numa_topology() numa_topo_obj = self.get_host_numa_topology()
node.numa_topology = numa_topo_obj node.numa_topology = numa_topo_obj

View File

@ -136,7 +136,7 @@ def upload_image_data(context, image, image_tag, image_data,
class ContainerImageDriver(object): class ContainerImageDriver(object):
'''Base class for container image driver.''' """Base class for container image driver."""
def pull_image(self, context, repo, tag): def pull_image(self, context, repo, tag):
"""Pull an image.""" """Pull an image."""

View File

@ -23,10 +23,10 @@ LOG = log.getLogger(__name__)
class ZunServicePeriodicTasks(periodic_task.PeriodicTasks): class ZunServicePeriodicTasks(periodic_task.PeriodicTasks):
'''Zun periodic Task class """Zun periodic Task class
Any periodic task job need to be added into this class Any periodic task job need to be added into this class
''' """
def __init__(self, conf, binary): def __init__(self, conf, binary):
self.zun_service_ref = None self.zun_service_ref = None

View File

@ -291,7 +291,7 @@ class TestManager(base.TestCase):
@mock.patch.object(fake_driver, 'list') @mock.patch.object(fake_driver, 'list')
def test_container_list(self, mock_list): def test_container_list(self, mock_list):
self.compute_manager.container_list(self.context) self.compute_manager.container_list(self.context)
mock_list.assert_called_once_with() mock_list.assert_called_once_with(self.context)
@mock.patch.object(fake_driver, 'list') @mock.patch.object(fake_driver, 'list')
def test_container_list_failed(self, mock_list): def test_container_list_failed(self, mock_list):

View File

@ -17,7 +17,7 @@ from zun.container import driver
class FakeDriver(driver.ContainerDriver): class FakeDriver(driver.ContainerDriver):
'''Fake driver for testing.''' """Fake driver for testing."""
def __init__(self): def __init__(self):
super(FakeDriver, self).__init__() super(FakeDriver, self).__init__()

View File

@ -117,7 +117,7 @@ def create_test_image(**kwargs):
def _generate_repo_for_image(): def _generate_repo_for_image():
'''Generate a random name like: zeta-22-image.''' """Generate a random name like: zeta-22-image."""
name_gen = name_generator.NameGenerator() name_gen = name_generator.NameGenerator()
name = name_gen.generate() name = name_gen.generate()
return name + '-image' return name + '-image'

View File

@ -12,10 +12,10 @@
# License for the specific language governing permissions and limitations # License for the specific language governing permissions and limitations
# under the License. # under the License.
''' """
Websocket proxy that is compatible with OpenStack Zun. Websocket proxy that is compatible with OpenStack Zun.
Leverages websockify.py by Joel Martin Leverages websockify.py by Joel Martin
''' """
import errno import errno
import select import select
@ -82,10 +82,10 @@ class ZunProxyRequestHandlerBase(object):
return None return None
def _handle_ins_outs(self, target, ins, outs): def _handle_ins_outs(self, target, ins, outs):
'''Handle the select file ins and outs """Handle the select file ins and outs
handle the operation ins and outs from select Handle the operation ins and outs from select
''' """
if self.request in outs: if self.request in outs:
# Send queued target data to the client # Send queued target data to the client
self.c_pend = self.send_frames(self.cqueue) self.c_pend = self.send_frames(self.cqueue)
@ -122,10 +122,10 @@ class ZunProxyRequestHandlerBase(object):
self.cqueue.append(buf) self.cqueue.append(buf)
def do_proxy(self, target): def do_proxy(self, target):
'''Proxy websocket link """Proxy websocket link
Proxy client WebSocket to normal target socket. Proxy client WebSocket to normal target socket.
''' """
self.cqueue = [] self.cqueue = []
self.tqueue = [] self.tqueue = []
self.c_pend = 0 self.c_pend = 0