1
      1
  7   ˆl–äY>”ji?u8 _¸Ðn6ò˜´o‘äÇò 8àC(Ç)üÿÃƒh¹ÂÁÀ      1
  C   ˆl–Ðz¾”Šj"Tâ‚À½q¶”Å£�þ[iÑ¬ãe#qº•à?Ä„\ŸÃ_ŠI|¥�+Wé3ž¯ÃÂ ?÷     # Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements.  See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License.  You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import json
import hashlib
import datetime
from typing import Any, Dict, List, Union, Optional
from collections import OrderedDict

from libcloud.compute.base import Node, NodeSize, NodeImage
from libcloud.compute.types import NodeState
from libcloud.container.base import Container, ContainerImage, ContainerDriver, ContainerCluster
from libcloud.container.types import ContainerState
from libcloud.common.exceptions import BaseHTTPError
from libcloud.common.kubernetes import (
    KubernetesException,
    KubernetesDriverMixin,
    KubernetesBasicAuthConnection,
)
from libcloud.container.providers import Provider

__all__ = [
    "KubernetesContainerDriver",
    "to_n_bytes",
    "to_memory_str",
    "to_cpu_str",
    "to_n_cpus",
]


ROOT_URL = "/api/"


K8S_UNIT_MAP = OrderedDict(
    {
        "K": 1000,
        "Ki": 1024,
        "M": 1000 * 1000,
        "Mi": 1024 * 1024,
        "G": 1000 * 1000 * 1000,
        "Gi": 1024 * 1024 * 1024,
    }
)


def to_n_bytes(memory_str: str) -> int:
    """Convert memory string to number of bytes
    (e.g. '1234Mi'-> 1293942784)
    """

    if memory_str.startswith("0"):
        return 0

    if memory_str.isnumeric():
        return int(memory_str)

    for unit, multiplier in K8S_UNIT_MAP.items():
        if memory_str.endswith(unit):
            return int(memory_str.strip(unit)) * multiplier


def to_memory_str(n_bytes: int, unit: Optional[str] = None) -> str:
    """Convert number of bytes to k8s memory string
    (e.g. 1293942784 -> '1234Mi')
    """

    if n_bytes == 0:
        return "0K"
    n_bytes = int(n_bytes)
    memory_str = None

    if unit is None:
        for unit, multiplier in reversed(K8S_UNIT_MAP.items()):
            converted_n_bytes_float = n_bytes / multiplier
            converted_n_bytes = n_bytes // multiplier
            memory_str = f"{converted_n_bytes}{unit}"

            if converted_n_bytes_float % 1 == 0:
                break
    elif K8S_UNIT_MAP.get(unit):
        memory_str = f"{n_bytes // K8S_UNIT_MAP[unit]}{unit}"

    return memory_str


def to_cpu_str(n_cpus: Union[int, float]) -> str:
    """Convert number of cpus to cpu string
    (e.g. 0.5 -> '500m')
    """

    if n_cpus == 0:
        return "0"
    millicores = n_cpus * 1000

    if millicores % 1 == 0:
        return f"{int(millicores)}m"
    microcores = n_cpus * 1000000

    if microcores % 1 == 0:
        return f"{int(microcores)}u"
    nanocores = n_cpus * 1000000000

    return f"{int(nanocores)}n"


def to_n_cpus(cpu_str: str) -> Union[int, float]:
    """Convert cpu string to number of cpus
    (e.g. '500m' -> 0.5, '2000000000n' -> 2)
    """

    if cpu_str.endswith("n"):
        return int(cpu_str.strip("n")) / 1000000000
    elif cpu_str.endswith("u"):
        return int(cpu_str.strip("u")) / 1000000
    elif cpu_str.endswith("m"):
        return int(cpu_str.strip("m")) / 1000
    elif cpu_str.isnumeric():
        return int(cpu_str)
    else:
        return 0


def sum_resources(*resource_dicts):
    total_cpu = 0
    total_memory = 0

    for rd in resource_dicts:
        total_cpu += to_n_cpus(rd.get("cpu", "0m"))
        tot