Example #1
0
def exec_cmd(args, live_output=True):
    """
    Execute a child program (args) in a new process. Displays
    live output by default.
    :param args: list: describes the command to be run
    :param live_output: bool: whether to print live output
    :return str: child program output
    """

    LOG.debug(' '.join(args))

    process = Popen(args, stdout=PIPE, stderr=STDOUT)
    output = []

    for line in iter(process.stdout.readline, b''):
        line = line.decode('utf-8')
        if line != os.linesep:
            if live_output:
                sys.stdout.write(line)
                sys.stdout.flush()
            else:
                LOG.debug(line)

        output.append(line)

    process.stdout.close()
    process.wait()

    returncode = process.returncode
    error_msg = 'Exited with return code {}'.format(returncode)
    output_str = ''.join(output)

    if returncode:
        raise CommandError(error_msg, output_str, returncode)
    return output_str
Example #2
0
def _handle_command_error(e):
    socket_perm_msg = "dial unix /var/run/docker.sock: permission denied."

    if socket_perm_msg in e.output:
        raise CommandError(strings['local.run.socketperms'], e.output, e.code)
    else:
        raise CommandError
Example #3
0
 def is_setup(self):
     if fileoperations.is_git_directory_present():
         if not fileoperations.program_is_installed('git'):
             raise CommandError(strings['sc.gitnotinstalled'])
         else:
             return True
     return False
Example #4
0
 def is_setup(self):
     if fileoperations.is_git_directory_present():
         # We know that the directory has git, but
         # is git on the path?
         if not fileoperations.program_is_installed('git'):
             raise CommandError(strings['sc.gitnotinstalled'])
         else:
             return True
     return False
Example #5
0
 def _handle_exitcode(self, exitcode, stderr):
     if exitcode == 0:
         return
     if exitcode == 127:
         # 127 = git not installed
         raise NoSourceControlError
     if exitcode == 128:
         # 128 = No HEAD
         if "HEAD" in stderr:
             LOG.debug('An error occurred while handling git command.'
                                '\nError code: ' + str(exitcode) + ' Error: ' +
                                stderr)
             raise CommandError('git could not find the HEAD; most likely because there are no commits present')
         
     # Something else happened
     raise CommandError('An error occurred while handling git command.'
                        '\nError code: ' + str(exitcode) + ' Error: ' +
                        stderr)
Example #6
0
def _validate_docker_installed(supported_docker_installed):
    versions = {
        'boot2docker-version': SUPPORTED_BOOT2DOCKER_V,
        'docker-version': SUPPORTED_DOCKER_V
    }
    err = strings['local.dockernotpresent'].format(**versions)

    if not supported_docker_installed:
        raise CommandError(err)
Example #7
0
def _generate_and_upload_keypair(keys):
    io.echo()
    io.echo(prompts['keypair.nameprompt'])
    unique = utils.get_unique_name('aws-eb', keys)
    keyname = io.prompt('Default is ' + unique, default=unique)
    file_name = fileoperations.get_ssh_folder() + keyname

    try:
        exitcode = subprocess.call(
            ['ssh-keygen', '-f', file_name, '-C', keyname])
    except OSError:
        raise CommandError(strings['ssh.notpresent'])

    if exitcode == 0 or exitcode == 1:
        commonops.upload_keypair_if_needed(keyname)
        return keyname
    else:
        LOG.debug('ssh-keygen returned exitcode: ' + str(exitcode) +
                  ' with filename: ' + file_name)
        raise CommandError('An error occurred while running ssh-keygen.')
Example #8
0
def _get_public_ssh_key(keypair_name):
    key_file = fileoperations.get_ssh_folder() + keypair_name
    if os.path.exists(key_file):
        file_name = key_file
    elif os.path.exists(key_file + '.pem'):
        file_name = key_file + '.pem'
    else:
        raise NotSupportedError(strings['ssh.filenotfound'].replace(
            '{key-name}', keypair_name))

    try:
        stdout, stderr, returncode = exec_cmd(
            ['ssh-keygen', '-y', '-f', file_name])
        if returncode != 0:
            raise CommandError('An error occurred while trying '
                               'to get ssh public key')
        key_material = stdout
        return key_material
    except OSError:
        raise CommandError(strings['ssh.notpresent'])
Example #9
0
    def get_current_branch(self):
        try:
            stdout, stderr, exitcode = self._run_cmd(['git', '--version'])
            LOG.debug('Git Version: ' + stdout)
        except:
            raise CommandError('Error getting "git --version".')

        stdout, stderr, exitcode = self._run_cmd(
            ['git', 'symbolic-ref', 'HEAD'], handle_exitcode=False)
        if exitcode != 0:
            io.log_warning('Git is in a detached head state. Using branch "default".')
            return 'default'
        else:
            self._handle_exitcode(exitcode, stderr)

        LOG.debug('git symbolic-ref result: ' + stdout)
        # Need to parse branch from ref manually because "--short" is
        # not supported on git < 1.8
        return stdout.split('/')[-1]
def generate_self_signed_cert(cert_name):
    home = fileoperations.get_home()
    cert_dir = os.path.join(home, '.ssl')
    privatekey_filename = cert_name + '-privatekey.pem'
    privatekey_dir = os.path.join(cert_dir, privatekey_filename)
    sign_request_filename = cert_name + '-csr.pem'
    sign_request_dir = os.path.join(cert_dir, sign_request_filename)
    server_cert_filename = cert_name + '.crt'
    server_cert_dir = os.path.join(cert_dir, server_cert_filename)

    if not os.path.isdir(cert_dir):
        os.mkdir(cert_dir)

    io.log_warning('Generating a self-signed certificate. '
                   'To provide an already created certificate, '
                   'use the command options.'
                   '\nSee "eb labs setup-ssl --help" for more info.')

    if not fileoperations.program_is_installed('openssl'):
        raise CommandError('This command requires openssl to be '
                           'installed on the PATH')

    if not os.path.isfile(privatekey_dir):
        utils.exec_cmd_quiet(['openssl', 'genrsa', '-out', privatekey_dir])

    if not os.path.isfile(sign_request_dir):
        io.echo()
        subprocess.check_call([
            'openssl', 'req', '-new', '-key', privatekey_dir, '-out',
            sign_request_dir
        ])
        io.echo()

    if not os.path.isfile(server_cert_dir):
        utils.exec_cmd_quiet([
            'openssl', 'x509', '-req', '-days', '365', '-in', sign_request_dir,
            '-signkey', privatekey_dir, '-out', server_cert_dir
        ])

    return privatekey_dir, server_cert_dir
Example #11
0
def ssh_into_instance(instance_id,
                      keep_open=False,
                      force_open=False,
                      custom_ssh=None,
                      command=None):
    instance = ec2.describe_instance(instance_id)
    try:
        keypair_name = instance['KeyName']
    except KeyError:
        raise NoKeypairError()
    try:
        ip = instance['PrivateIpAddress']
    except KeyError:
        if 'PrivateIpAddress' in instance:
            ip = instance['PrivateIpAddress']
        else:
            raise NotFoundError(strings['ssh.noip'])
    security_groups = instance['SecurityGroups']

    user = '******'

    ssh_group = None
    has_restriction = False
    rule_existed_before = False
    group_id = None
    for group in security_groups:
        group_id = group['GroupId']
        group = ec2.describe_security_group(group_id)
        for permission in group.get('IpPermissions', []):
            if permission.get('ToPort', None) == 22:
                ssh_group = group_id
                for rng in permission.get('IpRanges', []):
                    ip_restriction = rng.get('CidrIp', None)
                    if ip_restriction is not None:
                        if ip_restriction != '0.0.0.0/0':
                            has_restriction = True
                        elif ip_restriction == '0.0.0.0/0':
                            rule_existed_before = True

    if has_restriction and not force_open:
        io.log_warning(strings['ssh.notopening'])
    elif group_id:
        io.echo(strings['ssh.openingport'])
        ec2.authorize_ssh(ssh_group or group_id)
        io.echo(strings['ssh.portopen'])

    try:
        if custom_ssh:
            custom_ssh = custom_ssh.split()
        else:
            ident_file = _get_ssh_file(keypair_name)
            custom_ssh = ['ssh', '-i', ident_file]

        custom_ssh.extend([user + '@' + ip])

        if command:
            custom_ssh.extend(command.split())

        io.echo('INFO: Running ' + ' '.join(custom_ssh))
        returncode = subprocess.call(custom_ssh)
        if returncode != 0:
            LOG.debug(custom_ssh[0] + ' returned exitcode: ' + str(returncode))
            raise CommandError('An error occurred while running: ' +
                               custom_ssh[0] + '.')
    except OSError:
        CommandError(strings['ssh.notpresent'])
    finally:
        if keep_open:
            pass
        elif (not has_restriction
              or force_open) and group_id and not rule_existed_before:
            ec2.revoke_ssh(ssh_group or group_id)
            io.echo(strings['ssh.closeport'])
    def test_get_container_lowlvl_info_command_error(self, loads,
                                                     exec_cmd_quiet):
        exec_cmd_quiet.side_effect = CommandError(message='', output='', code=1)

        self.assertRaises(CommandError, commands.get_container_lowlvl_info,
                          MOCK_CONTAINER_NAME)