|
| 1 | +# -*- coding: utf-8 -*- |
| 2 | + |
| 3 | +import json |
| 4 | +import logging |
| 5 | + |
| 6 | +from ..config import uid |
| 7 | +from ..helpers.cmd import init_cmd |
| 8 | +from ..helpers.exceptions import UserDockerException |
| 9 | +from ..helpers.execute import exec_cmd |
| 10 | +from ..helpers.logger import logger |
| 11 | +from ..helpers.parser import init_subcommand_parser |
| 12 | + |
| 13 | + |
| 14 | +def parser_attach(parser): |
| 15 | + sub_parser = init_subcommand_parser(parser, 'attach') |
| 16 | + |
| 17 | + sub_parser.add_argument( |
| 18 | + "--detach-keys", |
| 19 | + help="Override the key sequence for detaching a container", |
| 20 | + ) |
| 21 | + |
| 22 | + sub_parser.add_argument( |
| 23 | + "container", |
| 24 | + help="container's ID or name to attach to" |
| 25 | + ) |
| 26 | + |
| 27 | + |
| 28 | +def exec_cmd_attach(args): |
| 29 | + cmd = init_cmd(args) |
| 30 | + |
| 31 | + if args.detach_keys: |
| 32 | + cmd += ['--detach-keys', args.detach_keys] |
| 33 | + |
| 34 | + container = args.container |
| 35 | + container_env = exec_cmd( |
| 36 | + [ |
| 37 | + args.executor_path, 'inspect', |
| 38 | + '--format', '{{json .Config.Env}}', |
| 39 | + container |
| 40 | + ], |
| 41 | + return_status=False, |
| 42 | + loglvl=logging.DEBUG, |
| 43 | + ) |
| 44 | + if not container_env: |
| 45 | + raise UserDockerException( |
| 46 | + 'ERROR: could not find container %s' % container |
| 47 | + ) |
| 48 | + userdocker_uid_env = [ |
| 49 | + env for env in json.loads(container_env) |
| 50 | + if env.startswith('USERDOCKER_UID') |
| 51 | + ] |
| 52 | + if not userdocker_uid_env: |
| 53 | + raise UserDockerException( |
| 54 | + 'ERROR: could not find USERDOCKER_UID env var in container %s' |
| 55 | + % container |
| 56 | + ) |
| 57 | + userdocker_uid = int(userdocker_uid_env[0].split('USERDOCKER_UID=')[1]) |
| 58 | + logger.debug( |
| 59 | + "Container %s was started by user id %d", container, userdocker_uid) |
| 60 | + if uid != userdocker_uid: |
| 61 | + raise UserDockerException( |
| 62 | + 'ERROR: container %s was started by %d, but you are %d. Permission ' |
| 63 | + 'denied!' % (container, userdocker_uid, uid) |
| 64 | + ) |
| 65 | + |
| 66 | + exec_cmd(cmd, dry_run=args.dry_run) |
0 commit comments