Пример #1
0
 def _to_container(self, data, container_status, pod_data):
     """
     Convert container in Container instances
     """
     state = container_status.get("state")
     created_at = None
     if state:
         started_at = list(state.values())[0].get("startedAt")
         if started_at:
             created_at = datetime.datetime.strptime(
                 started_at, "%Y-%m-%dT%H:%M:%SZ")
     extra = {
         "pod": pod_data["metadata"]["name"],
         "namespace": pod_data["metadata"]["namespace"],
     }
     resources = data.get("resources")
     if resources:
         extra["resources"] = resources
     return Container(
         id=container_status.get("containerID") or data["name"],
         name=data["name"],
         image=ContainerImage(
             id=container_status.get("imageID") or data["image"],
             name=data["image"],
             path=None,
             version=None,
             driver=self.connection.driver,
         ),
         ip_addresses=None,
         state=(ContainerState.RUNNING
                if container_status else ContainerState.UNKNOWN),
         driver=self.connection.driver,
         created_at=created_at,
         extra=extra,
     )
Пример #2
0
 def _to_container(self, data):
     """
     Convert container in Container instances
     """
     try:
         name = data.get('Name').strip('/')
     except:
         try:
             name = data.get('Names')[0].strip('/')
         except:
             name = data.get('Id')
     state = data.get('State')
     if isinstance(state, dict):
         status = data.get(
             'Status',
             state.get('Status') if state is not None else None)
     else:
         status = data.get('Status')
     if 'Exited' in status:
         state = ContainerState.STOPPED
     elif status.startswith('Up '):
         state = ContainerState.RUNNING
     elif 'running' in status:
         state = ContainerState.RUNNING
     else:
         state = ContainerState.STOPPED
     image = data.get('Image')
     ports = data.get('Ports', [])
     created = data.get('Created')
     if isinstance(created, float):
         created = ts_to_str(created)
     extra = {
         'id': data.get('Id'),
         'status': data.get('Status'),
         'created': created,
         'image': image,
         'ports': ports,
         'command': data.get('Command'),
         'sizerw': data.get('SizeRw'),
         'sizerootfs': data.get('SizeRootFs'),
     }
     ips = []
     if ports is not None:
         for port in ports:
             if port.get('IP') is not None:
                 ips.append(port.get('IP'))
     return Container(id=data['Id'],
                      name=name,
                      image=ContainerImage(id=data.get('ImageID', None),
                                           path=image,
                                           name=image,
                                           version=None,
                                           driver=self.connection.driver),
                      ip_addresses=ips,
                      state=state,
                      driver=self.connection.driver,
                      extra=extra)
Пример #3
0
 def test_start_container(self):
     container = self.driver.start_container(
         Container(id=None,
                   name=None,
                   image=None,
                   state=None,
                   ip_addresses=None,
                   driver=self.driver,
                   extra={'taskDefinitionArn': ''}))
     self.assertFalse(container is None)
Пример #4
0
 def test_restart_container(self):
     container = self.driver.restart_container(
         Container(
             id=None,
             name=None,
             image=None,
             state=None,
             ip_addresses=None,
             driver=self.driver,
             extra={
                 "taskArn": "12345",
                 "taskDefinitionArn": "123556"
             },
         ))
     self.assertFalse(container is None)
Пример #5
0
 def _to_container(self, data, task_definition_arn):
     return Container(id=data['containerArn'],
                      name=data['name'],
                      image=ContainerImage(id=None,
                                           name=data['name'],
                                           path=None,
                                           version=None,
                                           driver=self.connection.driver),
                      ip_addresses=None,
                      state=self.status_map.get(data['lastStatus'], None),
                      extra={
                          'taskArn': data['taskArn'],
                          'taskDefinitionArn': task_definition_arn
                      },
                      driver=self.connection.driver)
Пример #6
0
 def _to_container(self, data, container_status, pod_data):
     """
     Convert container in Container instances
     """
     return Container(id=container_status['containerID'],
                      name=data['name'],
                      image=ContainerImage(id=container_status['imageID'],
                                           name=data['image'],
                                           path=None,
                                           version=None,
                                           driver=self.connection.driver),
                      ip_addresses=None,
                      state=ContainerState.RUNNING,
                      driver=self.connection.driver,
                      extra={
                          'pod': pod_data['metadata']['name'],
                          'namespace': pod_data['metadata']['namespace']
                      })
Пример #7
0
    def _to_container(self, data):
        """
        Convert container in proper Container instance object
        ** Updating is NOT supported!!

        :param data: API data about container i.e. result.object
        :return: Proper Container object:
         see http://libcloud.readthedocs.io/en/latest/container/api.html

        """
        rancher_state = data["state"]

        # A Removed container is purged after x amt of time.
        # Both of these render the container dead (can't be started later)
        terminate_condition = ["removed", "purged"]

        if "running" in rancher_state:
            state = ContainerState.RUNNING
        elif "stopped" in rancher_state:
            state = ContainerState.STOPPED
        elif "restarting" in rancher_state:
            state = ContainerState.REBOOTING
        elif "error" in rancher_state:
            state = ContainerState.ERROR
        elif any(x in rancher_state for x in terminate_condition):
            state = ContainerState.TERMINATED
        elif data["transitioning"] == "yes":
            # Best we can do for current actions
            state = ContainerState.PENDING
        else:
            state = ContainerState.UNKNOWN

        # Everything contained in the json response is dumped in extra
        extra = data

        return Container(
            id=data["id"],
            name=data["name"],
            image=self._gen_image(data["imageUuid"]),
            ip_addresses=[data["primaryIpAddress"]],
            state=state,
            driver=self.connection.driver,
            extra=extra,
        )
Пример #8
0
 def _to_container(self, data, task_definition_arn):
     return Container(
         id=data["containerArn"],
         name=data["name"],
         image=ContainerImage(
             id=None,
             name=data["name"],
             path=None,
             version=None,
             driver=self.connection.driver,
         ),
         ip_addresses=None,
         state=self.status_map.get(data["lastStatus"], None),
         extra={
             "taskArn": data["taskArn"],
             "taskDefinitionArn": task_definition_arn,
         },
         driver=self.connection.driver,
     )
Пример #9
0
 def _to_container(self, data, container_status, pod_data):
     """
     Convert container in Container instances
     """
     return Container(
         id=container_status["containerID"],
         name=data["name"],
         image=ContainerImage(
             id=container_status["imageID"],
             name=data["image"],
             path=None,
             version=None,
             driver=self.connection.driver,
         ),
         ip_addresses=None,
         state=ContainerState.RUNNING,
         driver=self.connection.driver,
         extra={
             "pod": pod_data["metadata"]["name"],
             "namespace": pod_data["metadata"]["namespace"],
         },
     )
Пример #10
0
    def _to_container(self, data):
        """
        Convert container in proper Container instance object
        ** Updating is NOT supported!!

        :param data: API data about container i.e. result.object
        :return: Proper Container object:
         see http://libcloud.readthedocs.io/en/latest/container/api.html

        """
        rancher_state = data['state']
        if 'running' in rancher_state:
            state = ContainerState.RUNNING
        elif 'stopped' in rancher_state:
            state = ContainerState.STOPPED
        elif 'restarting' in rancher_state:
            state = ContainerState.REBOOTING
        elif 'error' in rancher_state:
            state = ContainerState.ERROR
        elif 'removed' or 'purged' in rancher_state:
            # A Removed container is purged after x amt of time.
            # Both of these render the container dead (can't be started later)
            state = ContainerState.TERMINATED
        elif data['transitioning'] == 'yes':
            # Best we can do for current actions
            state = ContainerState.PENDING
        else:
            state = ContainerState.UNKNOWN

        # Everything contained in the json response is dumped in extra
        extra = data

        return Container(id=data['id'],
                         name=data['name'],
                         image=self._gen_image(data['imageUuid']),
                         ip_addresses=[data['primaryIpAddress']],
                         state=state,
                         driver=self.connection.driver,
                         extra=extra)
Пример #11
0
    def deploy_container(
        self,
        name,
        image,
        cluster=None,
        parameters=None,
        start=True,
        ex_cpu=10,
        ex_memory=500,
        ex_container_port=None,
        ex_host_port=None,
    ):
        """
        Creates a task definition from a container image that can be run
        in a cluster.

        :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 cluster: The cluster to deploy to, None is default
        :type  cluster: :class:`libcloud.container.base.ContainerCluster`

        :param parameters: Container Image parameters
        :type  parameters: ``str``

        :param start: Start the container on deployment
        :type  start: ``bool``

        :rtype: :class:`libcloud.container.base.Container`
        """
        data = {}
        if ex_container_port is None and ex_host_port is None:
            port_maps = []
        else:
            port_maps = [{
                "containerPort": ex_container_port,
                "hostPort": ex_host_port
            }]
        data["containerDefinitions"] = [{
            "mountPoints": [],
            "name": name,
            "image": image.name,
            "cpu": ex_cpu,
            "environment": [],
            "memory": ex_memory,
            "portMappings": port_maps,
            "essential": True,
            "volumesFrom": [],
        }]
        data["family"] = name
        response = self.connection.request(
            ROOT,
            method="POST",
            data=json.dumps(data),
            headers=self._get_headers("RegisterTaskDefinition"),
        ).object
        if start:
            return self.ex_start_task(
                response["taskDefinition"]["taskDefinitionArn"])[0]
        else:
            return Container(
                id=None,
                name=name,
                image=image,
                state=ContainerState.RUNNING,
                ip_addresses=[],
                extra={
                    "taskDefinitionArn":
                    response["taskDefinition"]["taskDefinitionArn"]
                },
                driver=self.connection.driver,
            )
Пример #12
0
 def _to_container(self, data):
     """
     Convert container in Container instances
     """
     try:
         name = data.get("Name").strip("/")
     except Exception:
         try:
             name = data.get("Names")[0].strip("/")
         except Exception:
             name = data.get("Id")
     state = data.get("State")
     if isinstance(state, dict):
         status = data.get(
             "Status", state.get("Status") if state is not None else None
         )
     else:
         status = data.get("Status")
     if "Exited" in status:
         state = ContainerState.STOPPED
     elif status.startswith("Up "):
         state = ContainerState.RUNNING
     elif "running" in status:
         state = ContainerState.RUNNING
     else:
         state = ContainerState.STOPPED
     image = data.get("Image")
     ports = data.get("Ports", [])
     created = data.get("Created")
     if isinstance(created, float):
         created = ts_to_str(created)
     extra = {
         "id": data.get("Id"),
         "status": data.get("Status"),
         "created": created,
         "image": image,
         "ports": ports,
         "command": data.get("Command"),
         "sizerw": data.get("SizeRw"),
         "sizerootfs": data.get("SizeRootFs"),
     }
     ips = []
     if ports is not None:
         for port in ports:
             if port.get("IP") is not None:
                 ips.append(port.get("IP"))
     return Container(
         id=data["Id"],
         name=name,
         image=ContainerImage(
             id=data.get("ImageID", None),
             path=image,
             name=image,
             version=None,
             driver=self.connection.driver,
         ),
         ip_addresses=ips,
         state=state,
         driver=self.connection.driver,
         extra=extra,
     )