Example #1
0
def exec_cmd_in_pod(command,
                    pod_name,
                    namespace,
                    container=None,
                    base_command="bash"):

    exec_command = [base_command, "-c", command]
    try:
        if container:
            ret = stream(
                cli.connect_get_namespaced_pod_exec,
                pod_name,
                namespace,
                container=container,
                command=exec_command,
                stderr=True,
                stdin=False,
                stdout=True,
                tty=False,
            )
        else:
            ret = stream(
                cli.connect_get_namespaced_pod_exec,
                pod_name,
                namespace,
                command=exec_command,
                stderr=True,
                stdin=False,
                stdout=True,
                tty=False,
            )
    except Exception:
        return False
    return ret
Example #2
0
def Exec(commandDetails, clients, command):

    try:
        pod = clients.clientCoreV1.read_namespaced_pod(
            name=commandDetails.PodName, namespace=commandDetails.Namespace)
    except Exception as exp:
        return "", ValueError(
            "unable to get {} pod in {} namespace, err: {}".format(
                commandDetails.PodName, commandDetails.Namespace, exp))

    err = checkPodStatus(pod, commandDetails.ContainerName)
    if err != None:
        return "", err

    # Calling exec and waiting for response
    stream(clients.clientCoreV1.connect_get_namespaced_pod_exec,
           commandDetails.PodName,
           commandDetails.Namespace,
           command=command,
           stderr=True,
           stdin=False,
           stdout=True,
           tty=False)

    return None
Example #3
0
    def get_pods_exec(self, pod, namespace, command=None, container=None):
        core_v1_api = self.get_core_v1_api()
        if not command:
            command = [
                "/bin/sh", "-c",
                'TERM=xterm-256color; export TERM; [ -x /bin/bash ] '
                '&& ([ -x /usr/bin/script ] '
                '&& /usr/bin/script -q -c "/bin/bash" /dev/null || exec /bin/bash) '
                '|| exec /bin/sh'
            ]

        if container:
            container_stream = stream(
                core_v1_api.connect_get_namespaced_pod_exec,
                pod,
                namespace,
                command=command,
                container=container,
                stderr=True,
                stdin=True,
                stdout=True,
                tty=True,
                _preload_content=False)
        else:
            container_stream = stream(
                core_v1_api.connect_get_namespaced_pod_exec,
                pod,
                namespace,
                command=command,
                stderr=True,
                stdin=True,
                stdout=True,
                tty=True,
                _preload_content=False)
        return container_stream
Example #4
0
def backup_mysql(pod, namespace, tag):
    dump_directory = project_directory + "/" + directory + "/" + tag
    try:
        os.makedirs(dump_directory)
    except OSError as e:
        if e.errno != errno.EEXIST:
            raise

    exec_command = ['/bin/bash']
    resp = stream(api.connect_get_namespaced_pod_exec,
                  pod,
                  namespace,
                  command=exec_command,
                  stderr=True,
                  stdin=True,
                  stdout=True,
                  tty=False,
                  _preload_content=False)
    while resp.is_open():
        resp.update(timeout=1)
        if resp.peek_stdout():
            print("STDOUT: %s" % resp.read_stdout())
            db_name = resp.read_stdout()
            print(db_name)
        if resp.peek_stderr():
            print("STDERR: %s" % resp.read_stderr())
        if exec_command:
            c = exec_command.pop(0)
            db_name = resp.read_stdout()
            backup_comand = [
                '/bin/bash', '-c',
                'mysqldump -h 127.0.0.1 -u $MYSQL_USER --password=$MYSQL_PASSWORD $MYSQL_DATABASE',
                '>', '$MYSQL_DATABASE.mysql_dump_custom'
            ]

            with open(
                    dump_directory + "/" + pod + "-" + tag + "-" + date +
                    ".dmp", 'w') as file_buffer:

                resp = stream(api.connect_get_namespaced_pod_exec,
                              pod,
                              namespace,
                              command=backup_comand,
                              stderr=True,
                              stdin=True,
                              stdout=True,
                              tty=True,
                              _preload_content=False)
                while resp.is_open():
                    resp.update(timeout=1)
                    if resp.peek_stdout():
                        out = resp.read_stdout()
                        file_buffer.write(out)
                    if resp.peek_stderr():
                        print("STDERR: %s" % resp.read_stderr())
                resp.close()
                file_buffer.close()

        else:
            break
Example #5
0
    def __k8sExecPod(self, pod, container, namespace, exec_cmd):
        try:
            resp = self.v1.read_namespaced_pod(name=pod, namespace=namespace)
        except ApiException as e:
            if e.status != 404:
                print('Unknown error: %s' % e)
                exit(1)

        if container is not None:
            resp = stream(self.v1.connect_get_namespaced_pod_exec,
                          pod,
                          namespace,
                          command=exec_cmd,
                          container=container,
                          stderr=True,
                          stdin=False,
                          stdout=True,
                          tty=False)
        else:
            resp = stream(self.v1.connect_get_namespaced_pod_exec,
                          pod,
                          namespace,
                          command=exec_cmd,
                          stderr=True,
                          stdin=False,
                          stdout=True,
                          tty=False)

        return filter(lambda str: str != '', resp.split('\n'))
def getIplink(api_instance, name):

    # Calling exec and waiting for response
    exec_command = ['/bin/sh', '-c', 'ip link show']
    resp = stream(api_instance.connect_get_namespaced_pod_exec,
                  name,
                  'default',
                  command=exec_command,
                  stderr=True,
                  stdin=False,
                  stdout=True,
                  tty=False)
    iplink = resp
    # Calling exec interactively
    exec_command = ['/bin/sh']
    resp = stream(api_instance.connect_get_namespaced_pod_exec,
                  name,
                  'default',
                  command=exec_command,
                  stderr=True,
                  stdin=True,
                  stdout=True,
                  tty=False,
                  _preload_content=False)
    resp.write_stdin("hostname\n")
    host = resp.readline_stdout(timeout=1)
    resp.close()

    return split(iplink, host)
Example #7
0
    def test_consist(self):
        """
        # You should create some data before testing
        mkdir -p /home/nas/test
        mkdir -p /nashome/guest/test/tmp1
        # os.makedirs("/home/nas/test/tmp0", exist_ok=True)
        # os.makedirs("/nashome/guest/test/tmp1", exist_ok=True)
        """
        # error creating
        rep = post(self.url + "/create",
                   data=self.getCreateParam(node="123", naspvc=""))
        self.errorCatch(rep)

        # create
        print("Create")
        rep = post(self.url + "/create", data=self.getCreateParam())
        self.checkOk(rep)
        self.wait(lambda rep: rep['status'] == 200 and rep['data'].get(
            "status") == "Running")

        # double create
        rep = post(self.url + "/create", data=self.getCreateParam(naspvc=""))
        self.errorCatch(rep)

        # check running
        rep = post(self.url + "/search", data={'name': name}).json()["data"]
        self.assertIn("id", rep)
        v1.read_namespaced_service(name, ns)
        v1beta.read_namespaced_ingress(name, ns)

        # Check Share Dir
        resp = stream.stream(v1.connect_get_namespaced_pod_exec,
                             name,
                             ns,
                             command=["ls", "/home/nas"],
                             stderr=True,
                             stdin=True,
                             stdout=True,
                             tty=False)
        self.assertIn("test", resp)
        resp = stream.stream(v1.connect_get_namespaced_pod_exec,
                             name,
                             ns,
                             command=["ls", "/home/ubuntu"],
                             stderr=True,
                             stdin=True,
                             stdout=True,
                             tty=False)
        self.assertIn("tmp1", resp)

        # Check if delete it
        print("Delete")
        rep = post(self.url + "/delete", data={'name': name})
        self.checkOk(rep)
        self.wait(lambda rep: rep['status'] == 400)
Example #8
0
def collect_files(pod_name, files):
    dest_file = log_dir + "/collector-files.tar"
    files = list(map(lambda f: f.split("/")[-1:][0], files))
    command = ['tar', '-C', '/tmp', '-cf', "/tmp/collector-files.tar"]
    command += files
    resp = stream(core_api_instance.connect_get_namespaced_pod_exec,
                  pod_name,
                  NAMESPACE,
                  command=command,
                  stderr=True,
                  stdin=True,
                  stdout=True,
                  tty=False,
                  _preload_content=False)

    while resp.is_open():
        resp.update(timeout=1)
        if resp.peek_stdout():
            out = resp.read_stdout()
        if resp.peek_stderr():
            print("STDERR: %s" % resp.read_stderr())
    resp.close()

    command = ['cat', '/tmp/collector-files.tar']
    resp = stream(core_api_instance.connect_get_namespaced_pod_exec,
                  pod_name,
                  NAMESPACE,
                  command=command,
                  stderr=True,
                  stdin=True,
                  stdout=True,
                  tty=False,
                  _preload_content=False)

    with open(dest_file, "w") as out_file:
        while resp.is_open():
            resp.update(timeout=1)
            if resp.peek_stdout():
                out = resp.read_stdout()
                out_file.write(out)
            if resp.peek_stderr():
                print("STDERR: %s" % resp.read_stderr())
        resp.close()

    TMP_DIR = ".tar_gz_converter_tmp"

    with tarfile.open(dest_file) as f:
        f.extractall(TMP_DIR)

    with tarfile.open(dest_file + ".gz", "w:gz") as f:
        f.add(TMP_DIR, ".")

    shutil.rmtree(TMP_DIR)
    os.remove(dest_file)
 def exec_cmd(self, container, cmd):
     stream(
         self.client.connect_get_namespaced_pod_exec,
         container.metadata.name,
         container.metadata.namespace,
         # command=["/bin/sh", "-c", cmd],
         command=[cmd],
         stderr=True,
         stdin=True,
         stdout=True,
         tty=False,
     )
    def copy_to_container(self, container, path):
        # make sure parent directory is created first
        resp = stream(
            self.client.connect_get_namespaced_pod_exec,
            container.metadata.name,
            container.metadata.namespace,
            # command=["/bin/sh", "-c", "mkdir -p {}".format(os.path.dirname(path))],
            command=["mkdir -p {}".format(os.path.dirname(path))],
            stderr=True,
            stdin=True,
            stdout=True,
            tty=False,
        )

        # copy file implementation
        resp = stream(
            self.client.connect_get_namespaced_pod_exec,
            container.metadata.name,
            container.metadata.namespace,
            command=["tar", "xvf", "-", "-C", "/"],
            stderr=True,
            stdin=True,
            stdout=True,
            tty=False,
            _preload_content=False,
        )

        with TemporaryFile() as tar_buffer:
            with tarfile.open(fileobj=tar_buffer, mode="w") as tar:
                tar.add(path)

            tar_buffer.seek(0)
            commands = []
            commands.append(tar_buffer.read())

            while resp.is_open():
                resp.update(timeout=1)
                if resp.peek_stdout():
                    # logger.info("STDOUT: %s" % resp.read_stdout())
                    pass
                if resp.peek_stderr():
                    # logger.info("STDERR: %s" % resp.read_stderr())
                    pass
                if commands:
                    c = commands.pop(0)
                    resp.write_stdin(c)
                else:
                    break
            resp.close()
Example #11
0
    def write_to_pod(self):
        logging.info(f"Writing {self.genval} to our pvc")

        exec_command = [
            "/bin/bash", "-c",
            f"echo {self.genval} > /usr/share/nginx/html/index.html"
        ]
        stream.stream(self.pod_client.connect_get_namespaced_pod_exec,
                      self.pod,
                      self.namespace,
                      command=exec_command,
                      stderr=True,
                      stdin=False,
                      stdout=True,
                      tty=False)
Example #12
0
    def limit_bw(self, bw):
        veths = self.get_container_veth()
        for node in veths:
            for veth in veths[node]:
                # set download BW in node
                cmd = "ssh %s sudo tc qdisc add dev %s root tbf rate %dmbit latency 50ms burst 10000 mpu 64 mtu 15000" % (
                    node, veth[1], bw)
                subprocess.check_output(cmd, shell=True).decode()

                # set upload BW in container
                cmd = "tc qdisc add dev eth0 root tbf rate %dmbit latency 50ms burst 10000 mpu 64 mtu 15000" % bw
                stream(self.core_v1_api.connect_get_namespaced_pod_exec, name=veth[0], namespace='default',
                       command=cmd,
                       stderr=True, stdin=False,
                       stdout=True, tty=False)
Example #13
0
    def exec_command(self, container, command=None):
        if not command:
            command = []

        stream(
            self.api_client.connect_post_namespaced_pod_exec,
            name=self.pod_name,
            namespace=self.namespace,
            container=container,
            command=command,
            stderr=True,
            stdin=False,
            stdout=True,
            tty=False,
        )
Example #14
0
    def connect(self,
                namespace,
                podname,
                containername,
                socketer,
                pty_width=80,
                pty_height=24):
        config.load_kube_config(settings.K8S_CONFIG)
        self.command = ''
        self.socketer = socketer
        self.new()
        print('K8sclient init end')
        #command = ['/bin/bash']
        #print(podname)
        #print(namespace)
        command = [
            "/bin/sh", "-c",
            'TERM=xterm-256color; export TERM; [ -x /bin/bash ] '
            '&& ([ -x /usr/bin/script ] '
            '&& /usr/bin/script -q -c "/bin/bash" /dev/null || exec /bin/bash) '
            '|| exec /bin/sh'
        ]

        container_stream = stream(self.k8s.connect_get_namespaced_pod_exec,
                                  name=podname,
                                  namespace=namespace,
                                  command=command,
                                  stderr=True,
                                  stdin=True,
                                  stdout=True,
                                  tty=True,
                                  _preload_content=False)
        self.container_stream = container_stream
        return container_stream
Example #15
0
def exec_redis_command(name, namespace, command):
    """Execute a single command on a Redis sentinel container in the cluster

    Args:
        name - Name of the pod to execute the command inside of; string
        namespace - Namespace that the pod lives in; string
        command - Command to run within the pod.  Expects an array of strings

    Returns:
        Output from the command as a string

    Raises:
        If the command passed to the container fails or if the container itself does not exist,
        then the attempt to execute the command will fail and raise an exception
    """
    return stream(
        client.CoreV1Api().connect_get_namespaced_pod_exec,
        name,
        namespace,
        command=command,
        stderr=False,
        stdin=False,
        stdout=True,
        tty=False,
        container="sentinel",
    )
def ps_pod(pod, userid=1000):
    """Get ps output from a single pod"""
    kube = get_kube()
    try:
        client = stream(
            kube.connect_get_namespaced_pod_exec,
            pod["metadata"]["name"],
            namespace=pod["metadata"]["namespace"],
            command=["ps", "aux"],
            stderr=True,
            stdin=False,
            stdout=True,
            _preload_content=False,
        )
        client.run_forever(timeout=60)
        stderr = client.read_stderr()
        if stderr.strip():
            print(f"err! {stderr}", file=sys.stderr)
        stdout = client.read_stdout()

        returncode = client.returncode
        if returncode:
            raise RuntimeError(f"stdout={stdout}\nstderr={stderr}")
        return stdout
    except Exception as e:
        return f"Error reporting on ps in {pod['metadata']['name']}: {e}"
Example #17
0
    def test_pod_connect(self, pod, namespace, command=None, container=None):
        """
        测试链接pod
        :param pod:
        :param namespace:
        :param command:
        :param container:
        :return:
        """
        if not command:
            command = [
                "/bin/sh", "-c",
                'TERM=xterm-256color; export TERM; [ -x /bin/bash ] '
                '&& ([ -x /usr/bin/script ] '
                '&& /usr/bin/script -q -c "/bin/bash" /dev/null || exec /bin/bash) '
                '|| exec /bin/sh'
            ]

        core_v1_api = self.get_core_v1_api()
        if stream(core_v1_api.connect_get_namespaced_pod_exec,
                  pod,
                  namespace,
                  command=command,
                  container=container,
                  stderr=True,
                  stdin=False,
                  stdout=True,
                  tty=False):
            return True
        else:
            return False
 def pxctl(command):
     return stream(k8s_core.connect_get_namespaced_pod_exec,
                   name=pwx_pod_name,
                   namespace="kube-system",
                   command=['/opt/pwx/bin/pxctl'] + command,
                   stdin=False, stdout=True,
                   stderr=False, tty=False).strip().split('\n')[1:]
Example #19
0
def inyect_memory(name, namespace, module, duration):
    api_instance = client.CoreV1Api()
    module.log(msg="pod: " + name)
    try:
        resp = api_instance.read_namespaced_pod(name=name, namespace=namespace)
    except ApiException as e:
        if e.status != 404:
            print("Unknown error: %s" % e)
            exit(1)
        # Calling exec and waiting for response
    exec_command = [
        '/bin/sh',
        '-c',
        'apt update; apt-get install -y stress-ng; stress-ng --version; stress-ng --vm 2 --vm-bytes 2048M --vm-method all -t '
        + str(duration) + 'm',
    ]
    resp = stream(api_instance.connect_get_namespaced_pod_exec,
                  name,
                  namespace,
                  command=exec_command,
                  stderr=True,
                  stdin=False,
                  stdout=True,
                  tty=False)

    print("Response: " + resp)
    module.log(msg="Response: " + resp)
Example #20
0
def exec_in_pod(deployment_name, namespace, command, selector=False):
    try:
        kubernetes.config.load_incluster_config()
    except:
        kubernetes.config.load_kube_config()

    configuration = kubernetes.client.Configuration()
    api_instance = kubernetes.client.CoreV1Api(
        kubernetes.client.ApiClient(configuration))

    name = get_pod_name(deployment_name, namespace, selector)

    try:
        api_response = stream(api_instance.connect_post_namespaced_pod_exec,
                              name,
                              namespace,
                              command=command,
                              stderr=True,
                              stdin=True,
                              stdout=True,
                              tty=False,
                              _preload_content=True)
        logging.critical(pprint(api_response))
    except ApiException as e:
        logging.critical(
            "Exception when calling CoreV1Api->connect_post_namespaced_pod_exec: %s\n"
            % e)
Example #21
0
 def _do_exec(self,
              command: List[str],
              preload_content=True) -> Union[WSClient, str]:
     for i in range(MAGIC_KONSTANT):
         try:
             s = stream(
                 self.api.connect_get_namespaced_pod_exec,
                 self.pod_name,
                 self.k8s_namespace_name,
                 command=command,
                 stdin=False,
                 stderr=True,
                 stdout=True,
                 tty=False,
                 _preload_content=
                 preload_content,  # <<< we need a client object
                 _request_timeout=WEBSOCKET_CALL_TIMEOUT,
             )
             logger.debug(
                 "we have successfully initiated the kube api client")
             return s
         except ApiException as ex:
             # in packit-service prod, occasionally 'No route to host' happens here
             # let's try to repeat the request
             logger.warning("exception while initiating WS Client: %s", ex)
             time.sleep(2 * i + 1)
             continue
     raise SandcastleException(
         "Unable to connect to the kubernetes API server.")
def exec_commands(api_instance, pod_name, namespace, input_file_name):
    name = pod_name
    exec_namespace = namespace
    input_file_name = input_file_name
    resp = None
    try:
        resp = api_instance.read_namespaced_pod(name=name,
                                                namespace=exec_namespace)
    except ApiException as e:
        if e.status != 404:
            print("Unknown error: %s" % e)
            exit(1)

    if not resp:
        print("Pod %s does not exist. Please creating it..." % name)
        exit(1)

    # Begining to exec cmd in lammps-pod
    cmd = 'cd /test-data; source /etc/profile; mpirun -np 4 /home/test/lmp_mpi -in /test-data/%s' % input_file_name
    exec_command = ['/bin/sh', '-c', cmd]
    resp = stream(api_instance.connect_get_namespaced_pod_exec,
                  name,
                  exec_namespace,
                  command=exec_command,
                  stderr=True,
                  stdin=False,
                  stdout=True,
                  tty=False)
    print("Response: " + resp)
Example #23
0
def write_data(k8s_api_client, pod_name):
    src_dir_path = STRESS_RANDOM_DATA_DIR
    dest_dir_path = '/data/'
    file_name = get_data_filename(pod_name)

    src_file_path = src_dir_path + file_name
    dest_file_path = dest_dir_path + file_name

    src_file = open('%s' % src_file_path, 'wb')
    src_file.write(os.urandom(TEST_DATA_BYTES))
    src_file.close()
    src_file_md5sum = get_md5sum(src_file_path)
    command = 'kubectl cp ' + src_file_path + \
              ' ' + pod_name + ':' + dest_file_path
    subprocess.call(command, shell=True)

    exec_command = exec_command = ['/bin/sh']
    resp = stream(k8s_api_client.connect_get_namespaced_pod_exec,
                  pod_name,
                  'default',
                  command=exec_command,
                  stderr=True,
                  stdin=True,
                  stdout=True,
                  tty=False,
                  _preload_content=False)

    resp.write_stdin("md5sum " + dest_file_path + "\n")
    res = resp.readline_stdout(timeout=READ_MD5SUM_TIMEOUT).split()[0]

    assert res == src_file_md5sum
Example #24
0
def check_file_inside_pod(value_pod,
                          pod_name,
                          created_objects,
                          volume_name=None):
    """
    check snaptestfile inside the pod using ls
    """
    api_instance = client.CoreV1Api()
    if volume_name is None:
        exec_command1 = "ls " + value_pod["mount_path"]
    else:
        exec_command1 = "ls " + value_pod[
            "mount_path"] + "/" + volume_name + "-data"
    exec_command = ['/bin/sh', '-c', exec_command1]
    resp = stream(api_instance.connect_get_namespaced_pod_exec,
                  pod_name,
                  namespace_value,
                  command=exec_command,
                  stderr=True,
                  stdin=False,
                  stdout=True,
                  tty=False)
    if resp[0:12] == "snaptestfile":
        LOGGER.info(
            "POD Check : snaptestfile is succesfully restored from snapshot")
        return
    LOGGER.error("snaptestfile is not restored from snapshot")
    cleanup.clean_with_created_objects(created_objects)
    assert False
Example #25
0
    def get_node_endpoint_data(self, node: str):
        exec_command = ['cilium', 'endpoint', 'list', '-o', 'json']
        resp = stream(self.api.connect_get_namespaced_pod_exec,
                      node,
                      self.namespace,
                      command=exec_command,
                      stderr=False,
                      stdin=False,
                      stdout=True,
                      tty=False,
                      _preload_content=False,
                      _return_http_data_only=True)
        output = ""

        # _preload_content causes json to be malformed,
        # so we need to load raw data from websocket
        while resp.is_open():
            resp.update(timeout=1)
            if resp.peek_stdout():
                output += resp.read_stdout()
            try:
                data = json.loads(output)
                resp.close()
            except ValueError:
                continue

        self.data_queue.put(data)
Example #26
0
def create_file_inside_pod(value_pod, pod_name, created_objects):
    """
    create snaptestfile inside the pod using touch
    """
    api_instance = client.CoreV1Api()
    LOGGER.info(
        "POD Check : Trying to create snaptestfile on SpectrumScale mount point inside the pod"
    )
    exec_command1 = "touch " + value_pod["mount_path"] + "/snaptestfile"
    exec_command = ['/bin/sh', '-c', exec_command1]
    resp = stream(api_instance.connect_get_namespaced_pod_exec,
                  pod_name,
                  namespace_value,
                  command=exec_command,
                  stderr=True,
                  stdin=False,
                  stdout=True,
                  tty=False)

    if resp == "":
        LOGGER.info(
            "file snaptestfile created successfully on SpectrumScale mount point inside the pod"
        )
        return
    LOGGER.error("file snaptestfile not created")
    cleanup.clean_with_created_objects(created_objects)
    assert False
def main():
    module = KubernetesExecCommand()
    # Load kubernetes.client.Configuration
    module.get_api_client()
    api = core_v1_api.CoreV1Api()

    # hack because passing the container as None breaks things
    optional_kwargs = {}
    if module.params.get('container'):
        optional_kwargs['container'] = module.params['container']
    resp = stream(api.connect_get_namespaced_pod_exec,
                  module.params["pod"],
                  module.params["namespace"],
                  command=shlex.split(module.params["command"]),
                  stdout=True,
                  stderr=True,
                  stdin=False,
                  tty=False,
                  _preload_content=False,
                  **optional_kwargs)
    stdout, stderr = [], []
    while resp.is_open():
        resp.update(timeout=1)
        if resp.peek_stdout():
            stdout.append(resp.read_stdout())
        if resp.peek_stderr():
            stderr.append(resp.read_stderr())
    module.exit_json(changed=True,
                     stdout="".join(stdout),
                     stderr="".join(stderr))
Example #28
0
    def pod_exec(self, pod_name, exec_command, timeout=60):
        """work as the command (with timeout): kubectl exec 'pod_name' 'exec_command'"""
        try:
            logging.info("Exec on pod {}: {}".format(pod_name, exec_command))
            client = stream(
                self.v1.connect_get_namespaced_pod_exec,
                name=pod_name,
                namespace=self.namespace,
                command=exec_command,
                stderr=True,
                stdin=False,
                stdout=True,
                tty=False,
                _preload_content=False,
            )
            client.run_forever(timeout=timeout)

            err = yaml.full_load(client.read_channel(ERROR_CHANNEL))
            if err is None:
                return [-1, "Timeout"]

            if err["status"] == "Success":
                status_code = 0
            else:
                logging.debug("Exec on pod {} failed. cmd: {}, err: {}.".format(pod_name, exec_command, err))
                status_code = int(err["details"]["causes"][0]["message"])
            output = client.read_all()
            logging.info("Exec on pod {}, status: {}, cmd: {}, output: {}".format(pod_name, status_code, exec_command, output))
            return [status_code, output]
        except ApiException as err:
            logging.error("Exec on pod {} error. cmd: {}, err: {}.".format(pod_name, exec_command, err), exc_info=True)
            return [-1, err.message]
Example #29
0
def copy_file_to_pod(client, file_path, pod_name, pod_path, container):
    exec_command = ['tar', 'xmvf', '-', '-C', pod_path]
    resp = stream(client.connect_get_namespaced_pod_exec,
                  pod_name,
                  NAMESPACE,
                  command=exec_command,
                  stderr=True,
                  stdin=True,
                  stdout=True,
                  tty=False,
                  _preload_content=False,
                  container=container)

    filename = file_path.split('/')[-1]
    with TemporaryFile() as tar_buffer:
        with tarfile.open(fileobj=tar_buffer, mode='w') as tar:
            tar.add(file_path, arcname=filename)

        tar_buffer.seek(0)
        commands = [str(tar_buffer.read(), 'utf-8')]

        while resp.is_open():
            resp.update(timeout=1)
            if resp.peek_stdout():
                pass
            if resp.peek_stderr():
                print("Unexpected error while copying files: %s" %
                      (resp.read_stderr()))
                sys.exit(1)
            if commands:
                c = commands.pop(0)
                resp.write_stdin(c)
            else:
                break
        resp.close()
Example #30
0
def run_interactive_command(name, namespace, container, command):
    api = core_v1_api.CoreV1Api()

    # Calling exec interactively.
    resp = stream(api.connect_get_namespaced_pod_exec,
                  name=name,
                  namespace=namespace,
                  container=container,
                  command=command,
                  stderr=True,
                  stdin=True,
                  stdout=True,
                  tty=False,
                  _preload_content=False)

    error = False
    while resp.is_open():
        resp.update(timeout=1)

        if resp.peek_stdout():
            print("%s" % resp.read_stdout())
        if resp.peek_stderr():
            log.error("%s" % resp.read_stderr())
            error = True

    return (resp, error)
Example #31
0
    def _pod_exec_command(self, pod_name, namespace, command):
        try:
            bash_command = ['/bin/bash', '-c', command]
            resp = stream(self.corev1client.connect_get_namespaced_pod_exec,
                          pod_name, namespace, command=bash_command,
                          stdout=True)

            logger.debug(resp)
        except client.rest.ApiException as e:
            logger.error(e)
        except Exception as e:
            logger.error(e)
Example #32
0
    def exec_cmd_on_pod(self, name, cmd, namespace='default', stderr=True,
                        stdin=True, stdout=True, tty=True,
                        shell='/bin/bash -l -c'):

        cmd_prefix = shell.split()
        cmd_prefix.append(cmd)
        output = stream(self.v1_h.connect_get_namespaced_pod_exec, name, namespace,
                                                           command=cmd_prefix,
                                                           stderr=stderr,
                                                           stdin=stdin,
                                                           stdout=stdout,
                                                           tty=tty)
        return output
Example #33
0
 def exec_cmd_on_pod(self, name, cmd, namespace='default', stderr=True,
                     stdin=True, stdout=True, tty=True,
                     shell='/bin/bash -l -c', container=None):
     cmd_prefix = shell.split()
     cmd_prefix.append(cmd)
     kwargs = dict ()
     if container:
         kwargs['container'] = container
     output = stream(self.v1_h.connect_get_namespaced_pod_exec, name, namespace,
                                                        command=cmd_prefix,
                                                        stderr=stderr,
                                                        stdin=stdin,
                                                        stdout=stdout,
                                                        tty=tty, **kwargs)
     return output
def get_file_contents(v1: CoreV1Api, file_path, pod_name, pod_namespace) -> str:
    """
    Execute 'cat file_path' command in a pod.

    :param v1: CoreV1Api
    :param pod_name: pod name
    :param pod_namespace: pod namespace
    :param file_path: an absolute path to a file in the pod
    :return: str
    """
    command = ["cat", file_path]
    resp = stream(
        v1.connect_get_namespaced_pod_exec,
        pod_name,
        pod_namespace,
        command=command,
        stderr=True, stdin=False, stdout=True, tty=False)
    result_conf = str(resp)
    print("\nFile contents:\n" + result_conf)
    return result_conf
Example #35
0
    def terminal_start(self, namespace, pod_name, container):
        command = [
            "/bin/sh",
            "-c",
            'TERM=xterm-256color; export TERM; [ -x /bin/bash ] '
            '&& ([ -x /usr/bin/script ] '
            '&& /usr/bin/script -q -c "/bin/bash" /dev/null || exec /bin/bash) '
            '|| exec /bin/sh']

        container_stream = stream(
            self.client_core_v1.connect_get_namespaced_pod_exec,
            name=pod_name,
            namespace=namespace,
            container=container,
            command=command,
            stderr=True, stdin=True,
            stdout=True, tty=True,
            _preload_content=False
        )

        return container_stream
Example #36
0
    def test_pod_apis(self):
        client = api_client.ApiClient(configuration=self.config)
        api = core_v1_api.CoreV1Api(client)

        name = 'busybox-test-' + short_uuid()
        pod_manifest = {
            'apiVersion': 'v1',
            'kind': 'Pod',
            'metadata': {
                'name': name
            },
            'spec': {
                'containers': [{
                    'image': 'busybox',
                    'name': 'sleep',
                    "args": [
                        "/bin/sh",
                        "-c",
                        "while true;do date;sleep 5; done"
                    ]
                }]
            }
        }

        resp = api.create_namespaced_pod(body=pod_manifest,
                                         namespace='default')
        self.assertEqual(name, resp.metadata.name)
        self.assertTrue(resp.status.phase)

        while True:
            resp = api.read_namespaced_pod(name=name,
                                           namespace='default')
            self.assertEqual(name, resp.metadata.name)
            self.assertTrue(resp.status.phase)
            if resp.status.phase != 'Pending':
                break
            time.sleep(1)

        exec_command = ['/bin/sh',
                        '-c',
                        'for i in $(seq 1 3); do date; done']
        resp = stream(api.connect_get_namespaced_pod_exec, name, 'default',
                                                   command=exec_command,
                                                   stderr=False, stdin=False,
                                                   stdout=True, tty=False)
        print('EXEC response : %s' % resp)
        self.assertEqual(3, len(resp.splitlines()))

        exec_command = 'uptime'
        resp = stream(api.connect_post_namespaced_pod_exec, name, 'default',
                                                    command=exec_command,
                                                    stderr=False, stdin=False,
                                                    stdout=True, tty=False)
        print('EXEC response : %s' % resp)
        self.assertEqual(1, len(resp.splitlines()))

        resp = stream(api.connect_post_namespaced_pod_exec, name, 'default',
                                                    command='/bin/sh',
                                                    stderr=True, stdin=True,
                                                    stdout=True, tty=False,
                                                    _preload_content=False)
        resp.write_stdin("echo test string 1\n")
        line = resp.readline_stdout(timeout=5)
        self.assertFalse(resp.peek_stderr())
        self.assertEqual("test string 1", line)
        resp.write_stdin("echo test string 2 >&2\n")
        line = resp.readline_stderr(timeout=5)
        self.assertFalse(resp.peek_stdout())
        self.assertEqual("test string 2", line)
        resp.write_stdin("exit\n")
        resp.update(timeout=5)
        line = resp.read_channel(ERROR_CHANNEL)
        status = json.loads(line)
        self.assertEqual(status['status'], 'Success')
        resp.update(timeout=5)
        self.assertFalse(resp.is_open())

        number_of_pods = len(api.list_pod_for_all_namespaces().items)
        self.assertTrue(number_of_pods > 0)

        resp = api.delete_namespaced_pod(name=name, body={},
                                         namespace='default')
Example #37
0
    while True:
        resp = api.read_namespaced_pod(name=name,
                                       namespace='default')
        if resp.status.phase != 'Pending':
            break
        time.sleep(1)
    print("Done.")


# calling exec and wait for response.
exec_command = [
    '/bin/sh',
    '-c',
    'echo This message goes to stderr >&2; echo This message goes to stdout']
resp = stream(api.connect_get_namespaced_pod_exec, name, 'default',
              command=exec_command,
              stderr=True, stdin=False,
              stdout=True, tty=False)
print("Response: " + resp)

# Calling exec interactively.
exec_command = ['/bin/sh']
resp = stream(api.connect_get_namespaced_pod_exec, name, 'default',
              command=exec_command,
              stderr=True, stdin=True,
              stdout=True, tty=False,
              _preload_content=False)
commands = [
    "echo test1",
    "echo \"This message goes to stderr\" >&2",
]
while resp.is_open():