docstrings, flake8, error handling
Project: http://git-wip-us.apache.org/repos/asf/libcloud/repo Commit: http://git-wip-us.apache.org/repos/asf/libcloud/commit/d96fc83d Tree: http://git-wip-us.apache.org/repos/asf/libcloud/tree/d96fc83d Diff: http://git-wip-us.apache.org/repos/asf/libcloud/diff/d96fc83d Branch: refs/heads/trunk Commit: d96fc83dbfa3b39916b1575a953a31f6f9bf8bea Parents: 8495ea7 Author: Mario Loria <ma...@arroyonetworks.com> Authored: Wed Sep 28 21:57:39 2016 -0400 Committer: Anthony Shaw <anthonys...@apache.org> Committed: Sat Oct 8 13:29:22 2016 +1100 ---------------------------------------------------------------------- libcloud/container/drivers/rancher.py | 871 +++++++++++++++++++++++------ 1 file changed, 707 insertions(+), 164 deletions(-) ---------------------------------------------------------------------- http://git-wip-us.apache.org/repos/asf/libcloud/blob/d96fc83d/libcloud/container/drivers/rancher.py ---------------------------------------------------------------------- diff --git a/libcloud/container/drivers/rancher.py b/libcloud/container/drivers/rancher.py index 5229442..62a88b5 100644 --- a/libcloud/container/drivers/rancher.py +++ b/libcloud/container/drivers/rancher.py @@ -1,7 +1,5 @@ import base64 -import datetime import shlex -import re try: import simplejson as json @@ -83,13 +81,13 @@ class RancherContainerDriver(ContainerDriver): name = 'Rancher' website = 'http://rancher.com' connectionCls = RancherConnection - # Holding off on this for now. Only Environment API interaction enabled. + # Holding off on cluster support for now. + # Only Environment API interaction enabled. supports_clusters = False # As in the /v1/ version = '1' - def __init__(self, key, secret, secure=False, host='localhost', - port=80, key_file=None, cert_file=None): + def __init__(self, key, secret, secure=False, host='localhost', port=80): """ :param key: API key or username to used (required) :type key: ``str`` @@ -107,19 +105,12 @@ class RancherContainerDriver(ContainerDriver): :param port: Override port used for connections. :type port: ``int`` - :param key_file: Path to private key for TLS connection (optional) - :type key_file: ``str`` - - :param cert_file: Path to public key for TLS connection (optional) - :type cert_file: ``str`` :return: ``None`` """ super(RancherContainerDriver, self).__init__(key=key, secret=secret, secure=secure, host=host, - port=port, - key_file=key_file, - cert_file=cert_file) + port=port) if host.startswith('https://'): secure = True @@ -128,26 +119,10 @@ class RancherContainerDriver(ContainerDriver): for prefix in prefixes: if host.startswith(prefix): host = host.strip(prefix) - """ - if key_file or cert_file: - # docker tls authentication- - # https://docs.docker.com/articles/https/ - # We pass two files, a key_file with the - # private key and cert_file with the certificate - # libcloud will handle them through LibcloudHTTPSConnection - if not (key_file and cert_file): - raise Exception( - 'Needs both private key file and ' - 'certificate file for tls authentication') - self.connection.key_file = key_file - self.connection.cert_file = cert_file - self.connection.secure = True - else: - self.connection.secure = secure - """ self.connection.host = host self.connection.port = port + self.connection.secure = secure # We only support environment api keys, meaning none of this: # self.baseuri = "/v%s/projects/%s" % (self.version, project_id) @@ -155,21 +130,60 @@ class RancherContainerDriver(ContainerDriver): def ex_list_environments(self): """ - List the deployed container images - :param image: Filter to containers with a certain image - :type image: :class:`libcloud.container.base.ContainerImage` - :param all: Show all container (including stopped ones) - :type all: ``bool`` - :rtype: ``list`` of :class:`libcloud.container.base.Container` + List all Rancher Environments (called "Stacks" in the UI) + + http://docs.rancher.com/rancher/v1.2/en/api/api-resources/environment/ + + :rtype: ``list`` of ``dict`` """ - result = self.connection.request("%s/environments" % self.baseuri).object + result = self.connection.request( + "%s/environments" % self.baseuri).object return result['data'] def ex_deploy_environment(self, name, description=None, dockercompose=None, environment=None, externalid=None, outputs=None, - previousenvironment=None, previousexternalid=None, - ranchercompose=None, start=True): + previousenvironment=None, + previousexternalid=None, ranchercompose=None, + start=True): + """ + Deploy a new environment ("Stack" in the UI) + + http://docs.rancher.com/rancher/v1.2/en/api/api-resources/environment/#create + + :param name: The desired name of the environment. + :type name: ``str`` + + :param description: A desired description for the environment. + :type description: ``str`` + + :param dockercompose: The Docker Compose configuration to use. + :type dockercompose: ``str`` + + :param environment: Environment K/V specific to this environment. + :type environment: ``dict`` + + :param externalid: The externalId of the environment. + :type externalid: ``str`` + + :param outputs: Any outputs the environment should contain. + :type outputs: ``dict`` + + :param previousenvironment: The previousEnvironment for this env. + :type previousenvironment: ``dict`` + + :param previousexternalid: The previousExternalId for this env. + :type previousexternalid: ``str`` + + :param ranchercompose: The Rancher Compose configuration for this env. + :type ranchercompose: ``str`` + + :param start: Whether to start this environment on creation. + :type start: ``bool`` + + :return: The newly created environment. + :rtype: ``dict`` + """ payload = { "description": description, @@ -192,9 +206,12 @@ class RancherContainerDriver(ContainerDriver): def ex_get_environment(self, env_id): """ - Get a service by ID + Get an environment by ID + :param env_id: The environment to be obtained. - :return: The API dict object returned for the new service. + :type env_id: ``str`` + + :rtype: ``dict`` """ result = self.connection.request("%s/environments/%s" % (self.baseuri, env_id)).object @@ -202,57 +219,230 @@ class RancherContainerDriver(ContainerDriver): return result def ex_destroy_environment(self, env_id): + """ + Destroy an environment by ID + http://docs.rancher.com/rancher/v1.2/en/api/api-resources/environment/#delete + + :param env_id: The environment to be destroyed. + :type env_id: ``str`` + + :return: True if destroy was successful, False otherwise. + :rtype: ``bool`` + """ result = self.connection.request('%s/environments/%s' % ( - self.baseuri, env_id), method='DELETE') - if result.status in VALID_RESPONSE_CODES: - return result.status in VALID_RESPONSE_CODES - else: - raise RancherException(result.status, - 'failed to destroy environment') + self.baseuri, env_id), + method='DELETE') + return result.status in VALID_RESPONSE_CODES def ex_activate_environment(self, env_id): + """ + Activate Services for a environment. - result = self.connection.request('%s/environments/%s?action=activateservices' % - (self.baseuri, env_id), - method='POST') - if result.status in VALID_RESPONSE_CODES: - return result.status in VALID_RESPONSE_CODES - else: - raise RancherException(result.status, - 'failed to activate environment') + http://docs.rancher.com/rancher/v1.2/en/api/api-resources/environment/#activateservices + + :param env_id: The environment to activate services for. + :type env_id: ``str`` + + :return: True if activate was successful, False otherwise. + :rtype: ``bool`` + """ + result = self.connection.request( + '%s/environments/%s?action=activateservices' % ( + self.baseuri, env_id), method='POST' + ) + return result.status in VALID_RESPONSE_CODES def ex_deactivate_environment(self, env_id): + """ + Deactivate Services for a environment. - result = self.connection.request('%s/environments/%s?action=deactivateservices' % - (self.baseuri, env_id), - method='POST') - if result.status in VALID_RESPONSE_CODES: - return result.status in VALID_RESPONSE_CODES - else: - raise RancherException(result.status, - 'failed to deactivate environment') - - def build_payload(self, image, start=True, name=None, image_type="docker", - blkiodeviceoptions=None, build=None, - capadd=None, - capdrop=None, command=None, - count=None, cpuset=None, cpushares=None, - datavolumemounts=None, datavolumes=None, - datavolumesfrom=None, description=None, devices=None, - dns=None, dnssearch=None, domainname=None, - entrypoint=None, environment=None, expose=None, - extrahosts=None, healthcheck=None, hostname=None, - instancelinks=None, labels=None, logconfig=None, - lxcconf=None, memory=None, memoryswap=None, - networkcontainerrid=None, networkids=None, - networkmode=None, pidmode=None, ports=None, - privileged=None, publishallports=None, - readonly=None, registrycredentialid=None, - requestedhostid=None, restartpolicy=None, - securityopt=None, - stdinopen=None, tty=None, user=None, - volumedriver=None, workingdir=None): + http://docs.rancher.com/rancher/v1.2/en/api/api-resources/environment/#deactivateservices + + :param env_id: The environment to deactivate services for. + :type env_id: ``str`` + + :return: True if deactivate was successful, False otherwise. + :rtype: ``bool`` + """ + + result = self.connection.request( + '%s/environments/%s?action=deactivateservices' % ( + self.baseuri, env_id), method='POST' + ) + return result.status in VALID_RESPONSE_CODES + + def _build_payload(self, image, start=True, name=None, image_type="docker", + blkiodeviceoptions=None, build=None, + capadd=None, + capdrop=None, command=None, + count=None, cpuset=None, cpushares=None, + datavolumemounts=None, datavolumes=None, + datavolumesfrom=None, description=None, devices=None, + dns=None, dnssearch=None, domainname=None, + entrypoint=None, environment=None, expose=None, + extrahosts=None, healthcheck=None, hostname=None, + instancelinks=None, labels=None, logconfig=None, + lxcconf=None, memory=None, memoryswap=None, + networkcontainerrid=None, networkids=None, + networkmode=None, pidmode=None, ports=None, + privileged=None, publishallports=None, + readonly=None, registrycredentialid=None, + requestedhostid=None, restartpolicy=None, + securityopt=None, + stdinopen=None, tty=None, user=None, + volumedriver=None, workingdir=None): + """ + + :param image: The Image object to deploy. + :type image: :class:`libcloud.container.base.ContainerImage` + + :param start: Whether to start the container on creation. + :type start: ``bool`` + + :param name: The desired name of the container. + :type name: ``str`` + + :param image_type: The image format of the desired image to deploy. + :type image_type: ``str`` + + :param blkiodeviceoptions: The blkioDeviceOptions for the container. + :type blkiodeviceoptions: ``dict`` + + :param build: Build details for the container. + :type build: ``dict`` + + :param capadd: Linux Capabilities to enable for this container. + :type capadd: ``list`` + + :param capdrop: Linux capabilities to disable for this container. + :type capdrop: ``list`` + + :param command: The command to execute when this container is run. + :type command: ``list`` + + :param count: The number of containers of this nature to launch. + :type count: ``int`` + + :param cpuset: Memory nodes in which to allow execution. + :type cpuset: ``str`` + + :param cpushares: Relative weight cpu shares to allow. + :type cpushares: ``int`` + + :param datavolumemounts: Data volume mountes this container should have + :type datavolumemounts: ``dict`` + + :param datavolumes: Data volumes to associate with this container. + :type datavolumes: ``list`` + + :param datavolumesfrom: Data volumes to inherit. + :type datavolumesfrom: ``list`` + + :param description: Description for this container. + :type description: ``str`` + + :param devices: Devices inside the container without privliged mode. + :type devices: ``list`` + + :param dns: DNS servers the container should utilize. + :type dns: ``list`` + + :param dnssearch: DNS search domains the container should utilize. + :type dnssearch: ``list`` + + :param domainname: The domain name the container should have. + :type domainname: ``str`` + + :param entrypoint: The entrypoint the container should have. + :type entrypoint: ``list`` + + :param environment: Environment variables the container should have. + :type environment: ``dict`` + + :param expose: Ports which should be exposed in the container. + :type expose: ``list`` + + :param extrahosts: Extra hosts file entries this container should have. + :type extrahosts: ``list`` + + :param healthcheck: Health check parameters for this container. + :type healthcheck: ``dict`` + + :param hostname: The hostname this container should have. + :type hostname: ``str`` + + :param instancelinks: Instance links the container should have. + :type instancelinks: ``dict`` + + :param labels: Labels to associate with this container. + :type labels: ``dict`` + + :param logconfig: Log configuration for this container. + :type logconfig: ``dict`` + + :param lxcconf: lxcConf specific to this container. + :type lxcconf: ``dict`` + + :param memory: The memory limit for this container. + :type memory: ``int`` + + :param memoryswap: Total memory limit for this container. + :type memoryswap: ``int`` + + :param networkcontainerrid: A Network container Id for this container. + :type networkcontainerrid: ``dict`` + + :param networkids: NetworkIds this container should contain. + :type networkids: ``list`` + + :param networkmode: The networkMode to enable for this container. + :type networkmode: ``str`` + + :param pidmode: The pidMode for this container. + :type pidmode: ``str`` + + :param ports: The ports to publicize for this container. + :type ports: ``list`` + + :param privileged: Whether to enable privileged mode for this container + :type privileged: ``bool`` + + :param publishallports: Publish all ports in container. + :type publishallports: ``bool`` + + :param readonly: Whether this container should be readOnly. + :type readonly: ``bool`` + + :param registrycredentialid: Registry credentials to use. + :type registrycredentialid: ``dict`` + + :param requestedhostid: Id of the requested host to run this container. + :type requestedhostid: ``dict`` + + :param restartpolicy: The container restart policy. + :type restartpolicy: ``dict`` + + :param securityopt: Security options to provide for this container. + :type securityopt: ``list`` + + :param stdinopen: Whether to keep stdin open. + :type stdinopen: ``bool`` + + :param tty: Enable a tty for this container. + :type tty: ``bool`` + + :param user: User this container should be tied to. + :type user: ``str`` + + :param volumedriver: The volume driver to use for this container. + :type volumedriver: ``str`` + + :param workingdir: The workingDir this container should start in. + :type workingdir: ``str`` + + :return: + """ if command is not None: command = shlex.split(str(command)) @@ -317,35 +507,237 @@ class RancherContainerDriver(ContainerDriver): def ex_list_services(self): """ - List the deployed container images - :param image: Filter to containers with a certain image - :type image: :class:`libcloud.container.base.ContainerImage` - :param all: Show all container (including stopped ones) - :type all: ``bool`` - :rtype: ``list`` of :class:`libcloud.container.base.Container` + List all Rancher Services + + http://docs.rancher.com/rancher/v1.2/en/api/api-resources/service/ + + :rtype: ``list`` of ``dict`` """ result = self.connection.request("%s/services" % self.baseuri).object return result['data'] - def ex_deploy_service(self, name, image, environmentid, start=True, - assignserviceipaddress=None, service_description=None, - externalid=None, metadata=None, retainip=None, - scale=None, scalepolicy=None, - secondarylaunchconfigs=None, selectorcontainer=None, - selectorlink=None, + def ex_deploy_service(self, name, image, environmentid, + start=True, assignserviceipaddress=None, + service_description=None, externalid=None, + metadata=None, retainip=None, scale=None, + scalepolicy=None, secondarylaunchconfigs=None, + selectorcontainer=None, selectorlink=None, vip=None, datavolumesfromlaunchconfigs=None, disks=None, kind=None, memorymb=None, networklaunchconfig=None, requsetedipaddress=None, userdata=None, vcpu=None, **kwargs): """ Deploy a Rancher Service under a stack. - :param name: Name of the service. - :param image: ContainerImage object of image to utilize. + + http://docs.rancher.com/rancher/v1.2/en/api/api-resources/service/#create + + :param name: The desired name of the service. + :type name: ``str`` + + :param image: The Image object to deploy. + :type image: :class:`libcloud.container.base.ContainerImage` + :param environmentid: The environment/stack ID this service is tied to. - :param kwargs: The Launchconfig provided as top-level options, - similar to deploy_container. - :return: The API object returned on proper service creation. + :type environmentid: ``str`` + + :param start: Whether to start the service/container on creation. + :type start: ``bool`` + + :param assignserviceipaddress: The IP address to assign the service. + :type assignserviceipaddress: ``bool`` + + :param service_description: The service description. + :type service_description: ``str`` + + :param externalid: The externalId for this service. + :type externalid: ``str`` + + :param metadata: K/V Metadata for this service. + :type metadata: ``dict`` + + :param retainip: Whether this service should retain its IP. + :type retainip: ``bool`` + + :param scale: The scale of containers in this service. + :type scale: ``int`` + + :param scalepolicy: The scaling policy for this service. + :type scalepolicy: ``dict`` + + :param secondarylaunchconfigs: Secondary container launch configs. + :type secondarylaunchconfigs: ``list`` + + :param selectorcontainer: The selectorContainer for this service. + :type selectorcontainer: ``str`` + + :param selectorlink: The selectorLink for this service. + :type selectorlink: ``type`` + + :param vip: The VIP to assign to this service. + :type vip: ``str`` + + :param datavolumesfromlaunchconfigs: The dataVolumesFromLaunchConfigs. + :type datavolumesfromlaunchconfigs: ``list`` + + :param disks: The disks to associate with this container/service. + :type disks: ``list`` + + :param kind: The kind of object to deploy. + :type kind: ``str`` + + :param memorymb: The memoryMb to allow this container/service. + :type memorymb: ``int`` + + :param networklaunchconfig: The networkLaunchConfig for this container. + :type networklaunchconfig: ``str`` + + :param requsetedipaddress: The requested IP address for this container. + :type requsetedipaddress: ``str`` + + :param userdata: User data to associate with this container. + :type userdata: ``str`` + + :param vcpu: Virtual host cpu's to assign to allow this container. + :type vcpu: ``int`` + + :param blkiodeviceoptions: The blkioDeviceOptions for the container. + :type blkiodeviceoptions: ``dict`` + + :param build: Build details for the container. + :type build: ``dict`` + + :param capadd: Linux Capabilities to enable for this container. + :type capadd: ``list`` + + :param capdrop: Linux capabilities to disable for this container. + :type capdrop: ``list`` + + :param command: The command to execute when this container is run. + :type command: ``list`` + + :param count: The number of containers of this nature to launch. + :type count: ``int`` + + :param cpuset: Memory nodes in which to allow execution. + :type cpuset: ``str`` + + :param cpushares: Relative weight cpu shares to allow. + :type cpushares: ``int`` + + :param datavolumemounts: Data volume mountes this container should have + :type datavolumemounts: ``dict`` + + :param datavolumes: Data volumes to associate with this container. + :type datavolumes: ``list`` + + :param datavolumesfrom: Data volumes to inherit. + :type datavolumesfrom: ``list`` + + :param description: Description for this container. + :type description: ``str`` + + :param devices: Devices inside the container without privliged mode. + :type devices: ``list`` + + :param dns: DNS servers the container should utilize. + :type dns: ``list`` + + :param dnssearch: DNS search domains the container should utilize. + :type dnssearch: ``list`` + + :param domainname: The domain name the container should have. + :type domainname: ``str`` + + :param entrypoint: The entrypoint the container should have. + :type entrypoint: ``list`` + + :param environment: Environment variables the container should have. + :type environment: ``dict`` + + :param expose: Ports which should be exposed in the container. + :type expose: ``list`` + + :param extrahosts: Extra hosts file entries this container should have. + :type extrahosts: ``list`` + + :param healthcheck: Health check parameters for this container. + :type healthcheck: ``dict`` + + :param hostname: The hostname this container should have. + :type hostname: ``str`` + + :param instancelinks: Instance links the container should have. + :type instancelinks: ``dict`` + + :param labels: Labels to associate with this container. + :type labels: ``dict`` + + :param logconfig: Log configuration for this container. + :type logconfig: ``dict`` + + :param lxcconf: lxcConf specific to this container. + :type lxcconf: ``dict`` + + :param memory: The memory limit for this container. + :type memory: ``int`` + + :param memoryswap: Total memory limit for this container. + :type memoryswap: ``int`` + + :param networkcontainerrid: A Network container Id for this container. + :type networkcontainerrid: ``dict`` + + :param networkids: NetworkIds this container should contain. + :type networkids: ``list`` + + :param networkmode: The networkMode to enable for this container. + :type networkmode: ``str`` + + :param pidmode: The pidMode for this container. + :type pidmode: ``str`` + + :param ports: The ports to publicize for this container. + :type ports: ``list`` + + :param privileged: Whether to enable privileged mode for this container + :type privileged: ``bool`` + + :param publishallports: Publish all ports in container. + :type publishallports: ``bool`` + + :param readonly: Whether this container should be readOnly. + :type readonly: ``bool`` + + :param registrycredentialid: Registry credentials to use. + :type registrycredentialid: ``dict`` + + :param requestedhostid: Id of the requested host to run this container. + :type requestedhostid: ``dict`` + + :param restartpolicy: The container restart policy. + :type restartpolicy: ``dict`` + + :param securityopt: Security options to provide for this container. + :type securityopt: ``list`` + + :param stdinopen: Whether to keep stdin open. + :type stdinopen: ``bool`` + + :param tty: Enable a tty for this container. + :type tty: ``bool`` + + :param user: User this container should be tied to. + :type user: ``str`` + + :param volumedriver: The volume driver to use for this container. + :type volumedriver: ``str`` + + :param workingdir: The workingDir this container should start in. + :type workingdir: ``str`` + + :return: The newly created service. + :rtype: ``dict`` """ service_specific_container_config = { @@ -361,7 +753,7 @@ class RancherContainerDriver(ContainerDriver): # Build the de-facto container payload # Note that we don't need to remove "name" since its None by default. - launchconfig = self.build_payload(image, start, **kwargs) + launchconfig = self._build_payload(image, start, **kwargs) # Add in extra service configuration launchconfig.update(service_specific_container_config) launchconfig = json.dumps({k: v for k, v in launchconfig.items() @@ -394,8 +786,11 @@ class RancherContainerDriver(ContainerDriver): def ex_get_service(self, service_id): """ Get a service by ID - :param service_id: The service to be obtained. - :return: The API dict object returned for the new service. + + :param service_id: The service_id to be obtained. + :type service_id: ``str`` + + :rtype: ``dict`` """ result = self.connection.request("%s/services/%s" % (self.baseuri, service_id)).object @@ -404,48 +799,60 @@ class RancherContainerDriver(ContainerDriver): def ex_destroy_service(self, service_id): """ - Delete a service. - :param service_id: The service to be destroyed - :return: True if the destroy was successful, False otherwise. + Destroy a service by ID + + http://docs.rancher.com/rancher/v1.2/en/api/api-resources/service/#delete + + :param service_id: The service to be destroyed. + :type service_id: ``str`` + + :return: True if destroy was successful, False otherwise. :rtype: ``bool`` """ result = self.connection.request('%s/services/%s' % (self.baseuri, service_id), method='DELETE') - if result.status in VALID_RESPONSE_CODES: - return result.status in VALID_RESPONSE_CODES - else: - raise RancherException(result.status, - 'failed to destroy service') + return result.status in VALID_RESPONSE_CODES def ex_activate_service(self, service_id): + """ + Activate a service. + + http://docs.rancher.com/rancher/v1.2/en/api/api-resources/service/#activate + :param service_id: The service to activate services for. + :type service_id: ``str`` + + :return: True if activate was successful, False otherwise. + :rtype: ``bool`` + """ result = self.connection.request('%s/services/%s?action=activate' % (self.baseuri, service_id), method='POST') - if result.status in VALID_RESPONSE_CODES: - return result.status in VALID_RESPONSE_CODES - else: - raise RancherException(result.status, - 'failed to activate service') + return result.status in VALID_RESPONSE_CODES def ex_deactivate_service(self, service_id): + """ + Deactivate a service. + + http://docs.rancher.com/rancher/v1.2/en/api/api-resources/service/#deactivate + + :param service_id: The service to deactivate services for. + :type service_id: ``str`` + :return: True if deactivate was successful, False otherwise. + :rtype: ``bool`` + """ result = self.connection.request('%s/services/%s?action=deactivate' % (self.baseuri, service_id), method='POST') - if result.status in VALID_RESPONSE_CODES: - return result.status in VALID_RESPONSE_CODES - else: - raise RancherException(result.status, - 'failed to deactivate service') + return result.status in VALID_RESPONSE_CODES - def list_containers(self, image=None, all=True): + def list_containers(self): """ - List the deployed container images - :param image: Filter to containers with a certain image - :type image: :class:`libcloud.container.base.ContainerImage` - :param all: Show all container (including stopped ones) - :type all: ``bool`` + List the deployed containers. + + http://docs.rancher.com/rancher/v1.2/en/api/api-resources/container/ + :rtype: ``list`` of :class:`libcloud.container.base.Container` """ @@ -456,19 +863,160 @@ class RancherContainerDriver(ContainerDriver): def deploy_container(self, name, image, parameters=None, start=True, **kwargs): """ - Deploy an installed container image - For details on the additional parameters see : http://bit.ly/1PjMVKV - :param name: The name of the new container - :type name: ``str`` - :param image: The container image to deploy - :type image: :class:`libcloud.container.base.ContainerImage` - :param parameters: Container Image parameters + Deploy a new container. + + http://docs.rancher.com/rancher/v1.2/en/api/api-resources/container/#create + + :param name: The desired name of the container. + :type name: ``str`` + + :param image: The Image object to deploy. + :type image: :class:`libcloud.container.base.ContainerImage` + + :param parameters: Container Image parameters (unused) :type parameters: ``str`` - :param start: Start the container on deployment - :type start: ``bool`` + + :param start: Whether to start the container on creation. + :type start: ``bool`` + + :param blkiodeviceoptions: The blkioDeviceOptions for the container. + :type blkiodeviceoptions: ``dict`` + + :param build: Build details for the container. + :type build: ``dict`` + + :param capadd: Linux Capabilities to enable for this container. + :type capadd: ``list`` + + :param capdrop: Linux capabilities to disable for this container. + :type capdrop: ``list`` + + :param command: The command to execute when this container is run. + :type command: ``list`` + + :param count: The number of containers of this nature to launch. + :type count: ``int`` + + :param cpuset: Memory nodes in which to allow execution. + :type cpuset: ``str`` + + :param cpushares: Relative weight cpu shares to allow. + :type cpushares: ``int`` + + :param datavolumemounts: Data volume mountes this container should have + :type datavolumemounts: ``dict`` + + :param datavolumes: Data volumes to associate with this container. + :type datavolumes: ``list`` + + :param datavolumesfrom: Data volumes to inherit. + :type datavolumesfrom: ``list`` + + :param description: Description for this container. + :type description: ``str`` + + :param devices: Devices inside the container without privliged mode. + :type devices: ``list`` + + :param dns: DNS servers the container should utilize. + :type dns: ``list`` + + :param dnssearch: DNS search domains the container should utilize. + :type dnssearch: ``list`` + + :param domainname: The domain name the container should have. + :type domainname: ``str`` + + :param entrypoint: The entrypoint the container should have. + :type entrypoint: ``list`` + + :param environment: Environment variables the container should have. + :type environment: ``dict`` + + :param expose: Ports which should be exposed in the container. + :type expose: ``list`` + + :param extrahosts: Extra hosts file entries this container should have. + :type extrahosts: ``list`` + + :param healthcheck: Health check parameters for this container. + :type healthcheck: ``dict`` + + :param hostname: The hostname this container should have. + :type hostname: ``str`` + + :param instancelinks: Instance links the container should have. + :type instancelinks: ``dict`` + + :param labels: Labels to associate with this container. + :type labels: ``dict`` + + :param logconfig: Log configuration for this container. + :type logconfig: ``dict`` + + :param lxcconf: lxcConf specific to this container. + :type lxcconf: ``dict`` + + :param memory: The memory limit for this container. + :type memory: ``int`` + + :param memoryswap: Total memory limit for this container. + :type memoryswap: ``int`` + + :param networkcontainerrid: A Network container Id for this container. + :type networkcontainerrid: ``dict`` + + :param networkids: NetworkIds this container should contain. + :type networkids: ``list`` + + :param networkmode: The networkMode to enable for this container. + :type networkmode: ``str`` + + :param pidmode: The pidMode for this container. + :type pidmode: ``str`` + + :param ports: The ports to publicize for this container. + :type ports: ``list`` + + :param privileged: Whether to enable privileged mode for this container + :type privileged: ``bool`` + + :param publishallports: Publish all ports in container. + :type publishallports: ``bool`` + + :param readonly: Whether this container should be readOnly. + :type readonly: ``bool`` + + :param registrycredentialid: Registry credentials to use. + :type registrycredentialid: ``dict`` + + :param requestedhostid: Id of the requested host to run this container. + :type requestedhostid: ``dict`` + + :param restartpolicy: The container restart policy. + :type restartpolicy: ``dict`` + + :param securityopt: Security options to provide for this container. + :type securityopt: ``list`` + + :param stdinopen: Whether to keep stdin open. + :type stdinopen: ``bool`` + + :param tty: Enable a tty for this container. + :type tty: ``bool`` + + :param user: User this container should be tied to. + :type user: ``str`` + + :param volumedriver: The volume driver to use for this container. + :type volumedriver: ``str`` + + :param workingdir: The workingDir this container should start in. + :type workingdir: ``str`` + :rtype: :class:`Container` """ - payload = self.build_payload(name, image, start, **kwargs) + payload = self._build_payload(name, image, start, **kwargs) data = json.dumps({k: v for k, v in payload.items() if v is not None}) result = self.connection.request('%s/containers' % self.baseuri, @@ -479,8 +1027,10 @@ class RancherContainerDriver(ContainerDriver): def get_container(self, id): """ Get a container by ID + :param id: The ID of the container to get :type id: ``str`` + :rtype: :class:`libcloud.container.base.Container` """ result = self.connection.request("%s/containers/%s" % @@ -491,8 +1041,10 @@ class RancherContainerDriver(ContainerDriver): def stop_container(self, container): """ Stop a container + :param container: The container to be stopped :type container: :class:`libcloud.container.base.Container` + :return: The container refreshed with current data :rtype: :class:`libcloud.container.base.Container` """ @@ -502,43 +1054,43 @@ class RancherContainerDriver(ContainerDriver): if result.status in VALID_RESPONSE_CODES: return self.get_container(container.id) else: - raise RancherException(result.status, - 'failed to stop container') + raise RancherException(result.status, 'failed to stop container') def destroy_container(self, container): """ Remove a container + :param container: The container to be destroyed :type container: :class:`libcloud.container.base.Container` + :return: True if the destroy was successful, False otherwise. :rtype: ``bool`` """ result = self.connection.request('%s/containers/%s' % (self.baseuri, container.id), method='DELETE') - if result.status in VALID_RESPONSE_CODES: - return self.get_container(container.id) - else: - raise RancherException(result.status, - 'failed to destroy container') + return result.status in VALID_RESPONSE_CODES def _gen_image(self, imageuuid): """ - This function converts a valid Rancher `imageUuid` string to a valid + This function converts a valid Rancher ``imageUuid`` string to a valid image object. Only supports docker based images hence `docker:` must prefix!! - For a imageuuid: - docker:<hostname>:<port>/<namespace>/<imagename>:<version> + For a ``imageuuid``: + ``docker:<hostname>:<port>/<namespace>/<imagename>:<version>`` The following applies: - id = <imagename> - name = <imagename> - path = <hostname>:<port>/<namespace>/<imagename> - version = <version> + ``id`` = ``<imagename>`` + ``name`` = ``<imagename>`` + ``path`` = ``<hostname>:<port>/<namespace>/<imagename>`` + ``version`` = ``<version>`` + + :param imageuuid: A valid Rancher image string + i.e. ``docker:rlister/hastebin:8.0`` + :type imageuuid: ``str`` - :param imageUuid: A valid Rancher image string - i.e. `docker:rlister/hastebin:8.0` - :return: Proper ContainerImage object. + :return: Converted ContainerImage object. + :rtype: :class:`libcloud.container.base.ContainerImage` """ # Obtain just the name(:version) for parsing if '/' not in imageuuid: @@ -637,12 +1189,3 @@ class RancherContainerDriver(ContainerDriver): state=state, driver=self.connection.driver, extra=extra) - - -def ts_to_str(timestamp): - """ - Return a timestamp as a nicely formated datetime string. - """ - date = datetime.datetime.fromtimestamp(timestamp) - date_string = date.strftime("%d/%m/%Y %H:%M %Z") - return date_string