Exemplo n.º 1
0
def run(w, app, service_name, command, out=None, environment=[]):
    project = compose.cli.command.get_project(w + '/services/' + app['name'])

    service = project.get_service(service_name)

    container = service.create_container(quiet=True,
                                         one_off=True,
                                         **{
                                             'command': command,
                                             'tty': False,
                                             'stdin_open': False,
                                             'detach': False,
                                             'environment': environment
                                         })

    operation = RunOperation(
        project.client,
        container.id,
        interactive=False,
        logs=False,
        stdout=out,
    )
    pty = PseudoTerminal(project.client, operation)
    sockets = pty.sockets()
    service.start_container(container)
    pty.start(sockets)
    exit_code = container.wait()

    project.client.remove_container(container.id, force=True, v=True)

    return exit_code
Exemplo n.º 2
0
def adduser(ctx, username):

    cmd = "pure-pw useradd {0} -f /etc/pure-ftpd/passwd/pureftpd.passwd -m -u ftpuser -d /home/ftpusers/{0}".format(
        username)

    create_exec_options = {
        "privileged": True,
        "tty": True,
        "stdin": True,
    }

    client = docker.APIClient(base_url='unix://var/run/docker.sock')
    exec_id = client.exec_create(CONTAINER_NAME, cmd, **create_exec_options)

    signals.set_signal_handler_to_shutdown()
    try:
        operation = ExecOperation(
            client,
            exec_id,
            interactive=True,
        )
        pty = PseudoTerminal(client, operation)
        pty.start()
    except signals.ShutdownException:
        error(ctx, "received shutdown exception: closing")

    exit_code = client.exec_inspect(exec_id).get("ExitCode")
    sys.exit(exit_code)
Exemplo n.º 3
0
    def exec_command(self, options):
        """
        Execute a command in a running container

        Usage: exec [options] SERVICE COMMAND [ARGS...]

        Options:
            -d                Detached mode: Run command in the background.
            --privileged      Give extended privileges to the process.
            --user USER       Run the command as this user.
            -T                Disable pseudo-tty allocation. By default `docker-compose exec`
                              allocates a TTY.
            --index=index     index of the container if there are multiple
                              instances of a service [default: 1]
        """
        index = int(options.get('--index'))
        service = self.project.get_service(options['SERVICE'])
        detach = options['-d']

        if IS_WINDOWS_PLATFORM and not detach:
            raise UserError(
                "Interactive mode is not yet supported on Windows.\n"
                "Please pass the -d flag when using `docker-compose exec`."
            )
        try:
            container = service.get_container(number=index)
        except ValueError as e:
            raise UserError(str(e))
        command = [options['COMMAND']] + options['ARGS']
        tty = not options["-T"]

        create_exec_options = {
            "privileged": options["--privileged"],
            "user": options["--user"],
            "tty": tty,
            "stdin": tty,
        }

        exec_id = container.create_exec(command, **create_exec_options)

        if detach:
            container.start_exec(exec_id, tty=tty)
            return

        signals.set_signal_handler_to_shutdown()
        try:
            operation = ExecOperation(
                self.project.client,
                exec_id,
                interactive=tty,
            )
            pty = PseudoTerminal(self.project.client, operation)
            pty.start()
        except signals.ShutdownException:
            log.info("received shutdown exception: closing")
        exit_code = self.project.client.exec_inspect(exec_id).get("ExitCode")
        sys.exit(exit_code)
Exemplo n.º 4
0
    def exec_command(self, options):
        """
        Execute a command in a running container

        Usage: exec [options] SERVICE COMMAND [ARGS...]

        Options:
            -d                Detached mode: Run command in the background.
            --privileged      Give extended privileges to the process.
            --user USER       Run the command as this user.
            -T                Disable pseudo-tty allocation. By default `docker-compose exec`
                              allocates a TTY.
            --index=index     index of the container if there are multiple
                              instances of a service [default: 1]
        """
        index = int(options.get('--index'))
        service = self.project.get_service(options['SERVICE'])
        detach = options['-d']

        if IS_WINDOWS_PLATFORM and not detach:
            raise UserError(
                "Interactive mode is not yet supported on Windows.\n"
                "Please pass the -d flag when using `docker-compose exec`."
            )
        try:
            container = service.get_container(number=index)
        except ValueError as e:
            raise UserError(str(e))
        command = [options['COMMAND']] + options['ARGS']
        tty = not options["-T"]

        create_exec_options = {
            "privileged": options["--privileged"],
            "user": options["--user"],
            "tty": tty,
            "stdin": tty,
        }

        exec_id = container.create_exec(command, **create_exec_options)

        if detach:
            container.start_exec(exec_id, tty=tty)
            return

        signals.set_signal_handler_to_shutdown()
        try:
            operation = ExecOperation(
                self.project.client,
                exec_id,
                interactive=tty,
            )
            pty = PseudoTerminal(self.project.client, operation)
            pty.start()
        except signals.ShutdownException:
            log.info("received shutdown exception: closing")
        exit_code = self.project.client.exec_inspect(exec_id).get("ExitCode")
        sys.exit(exit_code)
Exemplo n.º 5
0
def run_one_off_container(container_options, project, service, options):
    if not options['--no-deps']:
        deps = service.get_dependency_names()
        if deps:
            project.up(
                service_names=deps,
                start_deps=True,
                strategy=ConvergenceStrategy.never,
                rescale=False
            )

    project.initialize()

    container = service.create_container(
        quiet=True,
        one_off=True,
        **container_options)

    if options['-d']:
        service.start_container(container)
        print(container.name)
        return

    def remove_container(force=False):
        if options['--rm']:
            project.client.remove_container(container.id, force=True, v=True)

    signals.set_signal_handler_to_shutdown()
    try:
        try:
            if IS_WINDOWS_PLATFORM:
                service.connect_container_to_networks(container)
                exit_code = call_docker(["start", "--attach", "--interactive", container.id])
            else:
                operation = RunOperation(
                    project.client,
                    container.id,
                    interactive=not options['-T'],
                    logs=False,
                )
                pty = PseudoTerminal(project.client, operation)
                sockets = pty.sockets()
                service.start_container(container)
                pty.start(sockets)
                exit_code = container.wait()
        except signals.ShutdownException:
            project.client.stop(container.id)
            exit_code = 1
    except signals.ShutdownException:
        project.client.kill(container.id)
        remove_container(force=True)
        sys.exit(2)

    remove_container()
    sys.exit(exit_code)
Exemplo n.º 6
0
def run_one_off_container(container_options, project, service, options):
    if not options['--no-deps']:
        deps = service.get_dependency_names()
        if deps:
            project.up(
                service_names=deps,
                start_deps=True,
                strategy=ConvergenceStrategy.never,
                rescale=False
            )

    project.initialize()

    container = service.create_container(
        quiet=True,
        one_off=True,
        **container_options)

    if options['-d']:
        service.start_container(container)
        print(container.name)
        return

    def remove_container(force=False):
        if options['--rm']:
            project.client.remove_container(container.id, force=True, v=True)

    signals.set_signal_handler_to_shutdown()
    try:
        try:
            if IS_WINDOWS_PLATFORM:
                service.connect_container_to_networks(container)
                exit_code = call_docker(["start", "--attach", "--interactive", container.id])
            else:
                operation = RunOperation(
                    project.client,
                    container.id,
                    interactive=not options['-T'],
                    logs=False,
                )
                pty = PseudoTerminal(project.client, operation)
                sockets = pty.sockets()
                service.start_container(container)
                pty.start(sockets)
                exit_code = container.wait()
        except signals.ShutdownException:
            project.client.stop(container.id)
            exit_code = 1
    except signals.ShutdownException:
        project.client.kill(container.id)
        remove_container(force=True)
        sys.exit(2)

    remove_container()
    sys.exit(exit_code)
Exemplo n.º 7
0
 def open_shell(self, service_name):
     compose_project = self.__get_compose_project()
     service = compose_project.get_service(service_name)
     exec_id = service.get_container().create_exec('sh -l',
                                                   stdin=True,
                                                   tty=True)
     operation = ExecOperation(compose_project.client,
                               exec_id,
                               interactive=True)
     pty = PseudoTerminal(compose_project.client, operation)
     pty.start()
Exemplo n.º 8
0
def run_one_off_container(container_options, project, service, options):
    if not options['--no-deps']:
        deps = service.get_linked_service_names()
        if deps:
            project.up(
                service_names=deps,
                start_deps=True,
                strategy=ConvergenceStrategy.never)

    project.initialize()

    container = service.create_container(
        quiet=True,
        one_off=True,
        **container_options)

    if options['-d']:
        service.start_container(container)
        print(container.name)
        return

    def remove_container(force=False):
        if options['--rm']:
            project.client.remove_container(container.id, force=True)

    signals.set_signal_handler_to_shutdown()
    try:
        try:
            pty = PseudoTerminal(
                project.client,
                container.id,
                interactive=not options['-T'],
                logs=False,
            )
            sockets = pty.sockets()
            service.start_container(container)
            pty.start(sockets)
            exit_code = container.wait()
        except signals.ShutdownException:
            project.client.stop(container.id)
            exit_code = 1
    except signals.ShutdownException:
        project.client.kill(container.id)
        remove_container(force=True)
        sys.exit(2)

    remove_container()
    sys.exit(exit_code)
Exemplo n.º 9
0
def run_one_off_container(container_options, project, service, options):
    if not options['--no-deps']:
        deps = service.get_linked_service_names()
        if deps:
            project.up(
                service_names=deps,
                start_deps=True,
                strategy=ConvergenceStrategy.never)

    project.initialize_networks()

    container = service.create_container(
        quiet=True,
        one_off=True,
        **container_options)

    if options['-d']:
        service.start_container(container)
        print(container.name)
        return

    def remove_container(force=False):
        if options['--rm']:
            project.client.remove_container(container.id, force=True)

    signals.set_signal_handler_to_shutdown()
    try:
        try:
            pty = PseudoTerminal(
                project.client,
                container.id,
                interactive=not options['-T'],
                logs=False,
            )
            sockets = pty.sockets()
            service.start_container(container)
            pty.start(sockets)
            exit_code = container.wait()
        except signals.ShutdownException:
            project.client.stop(container.id)
            exit_code = 1
    except signals.ShutdownException:
        project.client.kill(container.id)
        remove_container(force=True)
        sys.exit(2)

    remove_container()
    sys.exit(exit_code)
Exemplo n.º 10
0
def exec_command(client,
                 container,
                 command,
                 interactive=True,
                 stdout=None,
                 stderr=None,
                 stdin=None,
                 environment=None):
    """
    Run provided command via exec API in provided container.

    This is just a wrapper for PseudoTerminal(client, container).exec_command()
    """
    exec_id = exec_create(client,
                          container,
                          command,
                          interactive=interactive,
                          environment=environment)

    operation = ExecOperation(client,
                              exec_id,
                              interactive=interactive,
                              stdout=stdout,
                              stderr=stderr,
                              stdin=stdin)
    PseudoTerminal(client, operation).start()
Exemplo n.º 11
0
    def exec_run(self, cmd, usermode=None, **kwargs):
        if usermode:
            kwargs.update(user=str(os.getuid()))

        exec_id = self.cli.api.exec_create(
            self.cont.id,
            cmd,
            stdout=True,
            stderr=True,
            stdin=True,
            tty=True,
            environment=dict(SSH_AUTH_SOCK=os.getenv('SSH_AUTH_SOCK')),
            **kwargs)
        operation = ExecOperation(self.cli.api, exec_id, interactive=True)
        pty = PseudoTerminal(self.cli.api, operation)
        pty.start()
Exemplo n.º 12
0
def start(client, container, interactive=True):
    """
    Present the PTY of the container inside the current process.

    This is just a wrapper for PseudoTerminal(client, container).start()
    """

    PseudoTerminal(client, container, interactive=interactive).start()
Exemplo n.º 13
0
def start(client, container, interactive=True, stdout=None, stderr=None, stdin=None, logs=None):
    """
    Present the PTY of the container inside the current process.

    This is just a wrapper for PseudoTerminal(client, container).start()
    """

    operation = RunOperation(client, container, interactive=interactive, stdout=stdout,
                             stderr=stderr, stdin=stdin, logs=logs)

    PseudoTerminal(client, operation).start()
Exemplo n.º 14
0
def start_exec(client,
               exec_id,
               interactive=True,
               stdout=None,
               stderr=None,
               stdin=None):
    operation = ExecOperation(client,
                              exec_id,
                              interactive=interactive,
                              stdout=stdout,
                              stderr=stderr,
                              stdin=stdin)
    PseudoTerminal(client, operation).start()
Exemplo n.º 15
0
def execute(api, container, params, prefix):
    if not params:
        params = ['/bin/sh']

    if prefix:
        params = [prefix, '&&'] + params
    cmd = [
        '/bin/sh',
        '-c',
        " ".join(params),
    ]
    exec_id = api.exec_create(container=container.id,
                              cmd=cmd,
                              tty=True,
                              stdin=True)
    operation = ExecOperation(
        api,
        exec_id,
        interactive=True,
    )
    pty = PseudoTerminal(api, operation)
    pty.start()
Exemplo n.º 16
0
def exec_command(
        client, container, command, interactive=True, stdout=None, stderr=None, stdin=None):
    """
    Run provided command via exec API in provided container.

    This is just a wrapper for PseudoTerminal(client, container).exec_command().
    Also returns the exit_code of the operation.
    """
    exec_id = exec_create(client, container, command, interactive=interactive)

    operation = ExecOperation(client, exec_id,
                              interactive=interactive, stdout=stdout, stderr=stderr, stdin=stdin)
    PseudoTerminal(client, operation).start()

    return operation.exit_code()
Exemplo n.º 17
0
    def exec_command(self, options):
        """
        Execute a command in a running container

        Usage: exec [options] [-e KEY=VAL...] SERVICE COMMAND [ARGS...]

        Options:
            -d                Detached mode: Run command in the background.
            --privileged      Give extended privileges to the process.
            -u, --user USER   Run the command as this user.
            -T                Disable pseudo-tty allocation. By default `docker-compose exec`
                              allocates a TTY.
            --index=index     index of the container if there are multiple
                              instances of a service [default: 1]
            -e, --env KEY=VAL Set environment variables (can be used multiple times,
                              not supported in API < 1.25)
        """
        index = int(options.get('--index'))
        service = self.project.get_service(options['SERVICE'])
        detach = options['-d']

        if options['--env'] and docker.utils.version_lt(
                self.project.client.api_version, '1.25'):
            raise UserError(
                "Setting environment for exec is not supported in API < 1.25'")

        try:
            container = service.get_container(number=index)
        except ValueError as e:
            raise UserError(str(e))
        command = [options['COMMAND']] + options['ARGS']
        tty = not options["-T"]

        if IS_WINDOWS_PLATFORM and not detach:
            sys.exit(
                call_docker(build_exec_command(options, container.id,
                                               command)))

        create_exec_options = {
            "privileged": options["--privileged"],
            "user": options["--user"],
            "tty": tty,
            "stdin": tty,
        }

        if docker.utils.version_gte(self.project.client.api_version, '1.25'):
            create_exec_options["environment"] = options["--env"]

        exec_id = container.create_exec(command, **create_exec_options)

        if detach:
            container.start_exec(exec_id, tty=tty, stream=True)
            return

        signals.set_signal_handler_to_shutdown()
        try:
            operation = ExecOperation(
                self.project.client,
                exec_id,
                interactive=tty,
            )
            pty = PseudoTerminal(self.project.client, operation)
            pty.start()
        except signals.ShutdownException:
            log.info("received shutdown exception: closing")
        exit_code = self.project.client.exec_inspect(exec_id).get("ExitCode")
        sys.exit(exit_code)