コード例 #1
0
    def node_info_in_k8s_api(self, hostname):
        """
        Stubs K8S api call used to retrieve node data from K8S.
        Response is dynamic if node info update stubs were also enabled. It
        uses metadata altered by PATCH requests. Otherwise returns some
        predefined stub
        :param hostname: hostname of a node to enable this stub for
        """
        def request_callback(request):
            metadata = {
                "resourceVersion": 1,
                "annotations": {
                    K8SNode.FREE_PUBLIC_IP_COUNTER_FIELD: "0"
                }
            }

            if hostname in self.nodes:
                body = self.nodes[hostname]
            else:
                body = {
                    "apiVersion": "v1",
                    "kind": "Node",
                    "metadata": metadata,
                    "labels": {
                        "kuberdock-kube-type": "type_0",
                        "kuberdock-node-hostname": hostname
                    },
                    "name": hostname,
                    "status": {},
                }
            return 200, {}, json.dumps(body)

        url = get_api_url('nodes', hostname, namespace=None)
        responses.add_callback(responses.GET, url, callback=request_callback)
コード例 #2
0
    def node_info_update_in_k8s_api(self,
                                    hostname,
                                    always_raise_conflict=False,
                                    always_raise_failure=False):
        def request_callback(request):
            payload = json.loads(request.body)
            version = int(payload['metadata']['resourceVersion'])
            # Node spec is altered. Increase version
            payload['metadata']['resourceVersion'] = str(version + 1)
            payload['code'] = 200
            self.nodes[hostname] = payload
            return 200, {}, json.dumps(payload)

        url = get_api_url('nodes', hostname, namespace=None)
        if always_raise_conflict:
            resp_body_on_conflict = """{
                "apiVersion": "v1",
                "code": 409,
                "details": {},
                "kind": "status"
            }
            """
            responses.add(responses.PUT,
                          url,
                          status=409,
                          body=resp_body_on_conflict)
        elif always_raise_failure:
            responses.add(responses.PUT, url, status=500, body="")
        else:
            responses.add_callback(responses.PUT,
                                   url,
                                   callback=request_callback)
コード例 #3
0
def set_schedulable(node_id, value, upd=None):
    """
    Set node unschedulable property
    :param node_id: node id in kubernetes (now it's node hostname)
    :param value: boolean, true if node schedulable
    :param upd: db update record, if present print logs there too
    :return: boolean true if successful
    """
    url = get_api_url('nodes', node_id, namespace=False)
    try_times = 100
    for i in range(try_times):
        try:
            node = requests.get(url).json()
            node['spec']['unschedulable'] = not value
            res = requests.put(url, data=json.dumps(node))
        except (requests.RequestException, ValueError, KeyError):
            continue
        if res.ok:
            return True
    msg = "Failed to set node schedulable mode in kubernetes after {0} tries"\
          ". You can try later to set mode again manually with {1} on|off"\
          .format(try_times, CLI_COMMANDS.set_node_schedulable)
    if upd:
        upd.print_log(msg)
    else:
        print msg
    return False
コード例 #4
0
    def node_info_patch_in_k8s_api(self, hostname):
        """
        Stubs K8S API call used to update node info using PATCH requests.
        For now it saves metadata part in cache per node, so it can be used
        by node_info stub if one is enabled
        on
        :param hostname: hostname of a node to enable this stub for
        """
        def request_callback(request):
            payload = json.loads(request.body)
            if 'metadata' in payload:
                # TODO: Actually patch metadata, not just replace it
                self.metadata[hostname] = payload['metadata']
            return 200, {}, json.dumps(payload)

        url = get_api_url('nodes', hostname, namespace=None)
        responses.add_callback(responses.PATCH, url, callback=request_callback)
コード例 #5
0
def _get_container_ids():
    """Requests all pods from kubes-API."""

    from kubedock.utils import get_api_url

    url = get_api_url('pods', namespace=False, watch=False)
    req = requests.get(url)
    data = req.json()
    pods = data.get('items', [])
    res = {}
    for item in pods:
        uid = item.get('metadata', {}).get('uid')
        if not uid:
            continue
        status = item.get('status', {})
        if status.get('phase') != 'Running':
            # skip pods&containers wich are not running, because we need
            # will fill docker_id only for running containers
            continue
        cont_statuses = status.get('containerStatuses', [])
        res.update({(uid, cs.get('name')): cs.get('containerID')
                    for cs in cont_statuses})
    return res
コード例 #6
0
 def build_api_url(self, *args, **kwargs):
     return get_api_url(*args, **kwargs)