Esempio n. 1
0
    def __init__(self, hostname, protocol="https", port=8443, k_entry="api/v1", o_entry="oapi/v1",
                 debug=False, verify_ssl=False, **kwargs):
        super(Openshift, self).__init__(kwargs)
        self.hostname = hostname
        self.username = kwargs.get('username', '')
        self.password = kwargs.get('password', '')
        self.base_url = kwargs.get('base_url', None)
        self.token = kwargs.get('token', '')
        self.auth = self.token if self.token else (self.username, self.password)
        self.old_k_api = self.k_api = ContainerClient(hostname, self.auth, protocol, port, k_entry)
        self.old_o_api = self.o_api = ContainerClient(hostname, self.auth, protocol, port, o_entry)
        if 'new_client' in kwargs:
            url = '{proto}://{host}:{port}'.format(proto=protocol, host=self.hostname, port=port)
            ociclient.configuration.host = url
            kubeclient.configuration.host = url

            ociclient.configuration.verify_ssl = verify_ssl
            kubeclient.configuration.verify_ssl = verify_ssl

            kubeclient.configuration.debug = debug
            ociclient.configuration.debug = debug

            token = 'Bearer {token}'.format(token=self.token)
            ociclient.configuration.api_key['authorization'] = token
            kubeclient.configuration.api_key['authorization'] = token
            self.ociclient = ociclient
            self.kclient = kubeclient
            self.o_api = ociclient.OapiApi()
            self.k_api = kubeclient.CoreV1Api()

        self.api = self.k_api  # default api is the kubernetes one for Kubernetes-class requests
        self.list_image_openshift = self.list_docker_image  # For backward compatibility
Esempio n. 2
0
 def __init__(self, hostname, protocol="https", port=6443, entry='api/v1', **kwargs):
     self.hostname = hostname
     self.username = kwargs.get('username', '')
     self.password = kwargs.get('password', '')
     self.token = kwargs.get('token', '')
     self.auth = self.token if self.token else (self.username, self.password)
     self.api = ContainerClient(hostname, self.auth, protocol, port, entry)
     super(Kubernetes, self).__init__(kwargs)
Esempio n. 3
0
 def __init__(self,
         hostname, protocol="https", port=8443, k_entry="api/v1", o_entry="oapi/v1", **kwargs):
     self.hostname = hostname
     self.username = kwargs.get('username', '')
     self.password = kwargs.get('password', '')
     self.token = kwargs.get('token', '')
     self.auth = self.token if self.token else (self.username, self.password)
     self.k_api = ContainerClient(hostname, self.auth, protocol, port, k_entry)
     self.o_api = ContainerClient(hostname, self.auth, protocol, port, o_entry)
     self.api = self.k_api  # default api is the kubernetes one for Kubernetes-class requests
     self.list_image_openshift = self.list_docker_image  # For backward compatibility
Esempio n. 4
0
class Openshift(Kubernetes):

    _stats_available = Kubernetes._stats_available.copy()
    _stats_available.update({
        'num_route': lambda self: len(self.list_route()),
        'num_template': lambda self: len(self.list_template())
    })

    def __init__(self,
            hostname, protocol="https", port=8443, k_entry="api/v1", o_entry="oapi/v1", **kwargs):
        self.hostname = hostname
        self.username = kwargs.get('username', '')
        self.password = kwargs.get('password', '')
        self.token = kwargs.get('token', '')
        self.auth = self.token if self.token else (self.username, self.password)
        self.k_api = ContainerClient(hostname, self.auth, protocol, port, k_entry)
        self.o_api = ContainerClient(hostname, self.auth, protocol, port, o_entry)
        self.api = self.k_api  # default api is the kubernetes one for Kubernetes-class requests
        self.list_image_openshift = self.list_docker_image  # For backward compatibility

    def list_route(self):
        """Returns list of routes"""
        entities = []
        entities_j = self.o_api.get('route')[1]['items']
        for entity_j in entities_j:
            meta = entity_j['metadata']
            entity = Route(self, meta['name'], meta['namespace'])
            entities.append(entity)
        return entities

    def list_docker_registry(self):
        """Returns list of docker registries"""
        entities = []
        entities_j = self.o_api.get('imagestream')[1]['items']
        for entity_j in entities_j:
            if 'dockerImageRepository' not in entity_j['status']:
                continue
            meta = entity_j['metadata']
            entity = ImageRegistry(self, meta['name'],
                                   entity_j['status']['dockerImageRepository'],
                                   meta['namespace'])
            if entity not in entities:
                entities.append(entity)
        return entities

    def list_project(self):
        """Returns list of projects"""
        entities = []
        entities_j = self.o_api.get('project')[1]['items']
        for entity_j in entities_j:
            meta = entity_j['metadata']
            entity = Project(self, meta['name'])
            entities.append(entity)
        return entities

    def list_template(self):
        """Returns list of templates"""
        entities = []
        entities_j = self.o_api.get('template')[1]['items']
        for entity_j in entities_j:
            meta = entity_j['metadata']
            entity = Template(self, meta['name'], meta['namespace'])
            entities.append(entity)
        return entities

    def list_docker_image(self):
        """Returns list of images (Docker registry only)"""
        entities = []
        entities_j = self.o_api.get('image')[1]['items']
        for entity_j in entities_j:
            if 'dockerImageReference' not in entity_j:
                continue
            _, name, image_id, _ = Image.parse_docker_image_info(entity_j['dockerImageReference'])
            entities.append(Image(self, name, image_id))
        return entities

    def list_deployment_config(self):
        """Returns list of deployment configs"""
        entities = []
        entities_j = self.o_api.get('deploymentconfig')[1]['items']
        for entity_j in entities_j:
            meta = entity_j['metadata']
            spec = entity_j['spec']
            entity = DeploymentConfig(self, meta['name'], meta['namespace'],
                                      spec['template']['spec']['containers'][-1].get('image'),
                                      spec['replicas'])
            entities.append(entity)
        return entities
Esempio n. 5
0
class Kubernetes(WrapanapiAPIBase):

    _stats_available = {
        'num_container':
        lambda self: len(self.list_container()),
        'num_pod':
        lambda self: len(self.list_container_group()),
        'num_service':
        lambda self: len(self.list_service()),
        'num_replication_controller':
        lambda self: len(self.list_replication_controller()),
        'num_replication_controller_labels':
        lambda self: len(self.list_replication_controller_labels()),
        'num_image':
        lambda self: len(self.list_image()),
        'num_node':
        lambda self: len(self.list_node()),
        'num_image_registry':
        lambda self: len(self.list_image_registry()),
        'num_project':
        lambda self: len(self.list_project()),
    }

    def __init__(self,
                 hostname,
                 protocol="https",
                 port=6443,
                 entry='api/v1',
                 **kwargs):
        self.hostname = hostname
        self.username = kwargs.get('username', '')
        self.password = kwargs.get('password', '')
        self.token = kwargs.get('token', '')
        self.auth = self.token if self.token else (self.username,
                                                   self.password)
        self.api = ContainerClient(hostname, self.auth, protocol, port, entry)
        super(Kubernetes, self).__init__(kwargs)

    def disconnect(self):
        pass

    def _parse_image_info(self, image_str):
        """Splits full image name into registry, name and tag

        Both registry and tag are optional, name is always present.

        Example:
            localhost:5000/nginx:latest => localhost:5000, nginx, latest
        """
        registry, image_str = image_str.split(
            '/', 1) if '/' in image_str else ('', image_str)
        name, tag = image_str.split(':',
                                    1) if ':' in image_str else (image_str, '')
        return registry, name, tag

    def info(self):
        """Returns information about the cluster - number of CPUs and memory in GB"""
        aggregate_cpu, aggregate_mem = 0, 0
        for node in self.list_node():
            aggregate_cpu += node.cpu
            aggregate_mem += node.memory
        return {'cpu': aggregate_cpu, 'memory': aggregate_mem}

    def list_container(self, project_name=None):
        """Returns list of containers (derived from pods)
        If project_name is passed, only the containers under the selected project will be returned
        """
        entities = []
        entities_j = self.api.get('pod')[1]['items']
        for entity_j in entities_j:
            if project_name and project_name != entity_j['metadata'][
                    'namespace']:
                continue
            pod = Pod(self, entity_j['metadata']['name'],
                      entity_j['metadata']['namespace'])
            conts_j = entity_j['spec']['containers']
            for cont_j in conts_j:
                cont = Container(self, cont_j['name'], pod, cont_j['image'])
                if cont not in entities:
                    entities.append(cont)
        return entities

    def list_container_group(self, project_name=None):
        """Returns list of container groups (pods).
        If project_name is passed, only the pods under the selected project will be returned"""
        entities = []
        entities_j = self.api.get('pod')[1]['items']
        for entity_j in entities_j:
            meta = entity_j['metadata']
            entity = Pod(self, meta['name'], meta['namespace'])
            if project_name and project_name != meta['namespace']:
                continue
            entities.append(Pod(self, meta['name'], meta['namespace']))
        return entities

    def list_service(self, project_name=None):
        """Returns list of services.
        If project name is passed, only the services under the selected project will be returned"""
        entities = []
        entities_j = self.api.get('service')[1]['items']
        for entity_j in entities_j:
            meta = entity_j['metadata']
            entity = Service(self, meta['name'], meta['namespace'])
            if project_name and project_name != meta['namespace']:
                continue
            entities.append(Service(self, meta['name'], meta['namespace']))
        return entities

    def list_replication_controller(self):
        """Returns list of replication controllers"""
        entities = []
        entities_j = self.api.get('replicationcontroller')[1]['items']
        for entity_j in entities_j:
            meta = entity_j['metadata']
            entity = Replicator(self, meta['name'], meta['namespace'])
            entities.append(entity)
        return entities

    def list_image(self):
        """Returns list of images (derived from pods)"""
        entities = []
        entities_j = self.api.get('pod')[1]['items']
        for entity_j in entities_j:
            imgs_j = entity_j['status'].get('containerStatuses', [])
            img_project_name = entity_j['metadata'].get('namespace', [])
            for img_j in imgs_j:
                _, name, _ = self._parse_image_info(img_j['image'])
                img = Image(self, name, img_j['imageID'], img_project_name)
                if img not in entities:
                    entities.append(img)
        return entities

    def list_node(self):
        """Returns list of nodes"""
        entities = []
        entities_j = self.api.get('node')[1]['items']
        for entity_j in entities_j:
            meta = entity_j['metadata']
            entity = Node(self, meta['name'])
            entities.append(entity)
        return entities

    def list_image_registry(self):
        """Returns list of image registries (derived from pods)"""
        entities = []
        entities_j = self.api.get('pod')[1]['items']
        for entity_j in entities_j:
            imgs_j = entity_j['status'].get('containerStatuses', [])
            for img_j in imgs_j:
                registry, _, _ = self._parse_image_info(img_j['image'])
                if not registry:
                    continue
                host, _ = registry.split(':') if ':' in registry else (
                    registry, '')
                entity = ImageRegistry(self, host, registry, None)
                if entity not in entities:
                    entities.append(entity)
        return entities

    def list_project(self):
        """Returns list of projects (namespaces in k8s)"""
        entities = []
        entities_j = self.api.get('namespace')[1]['items']
        for entity_j in entities_j:
            meta = entity_j['metadata']
            entity = Project(self, meta['name'])
            entities.append(entity)
        return entities

    def list_volume(self):
        entities = []
        entities_j = self.api.get('persistentvolume')[1]['items']
        for entity_j in entities_j:
            meta = entity_j['metadata']
            entity = Volume(self, meta['name'])
            entities.append(entity)
        return entities