PageRenderTime 136ms CodeModel.GetById 53ms app.highlight 12ms RepoModel.GetById 69ms app.codeStats 0ms

/silverlining/commands/setup_node.py

https://bitbucket.org/ianb/silverlining/
Python | 133 lines | 126 code | 5 blank | 2 comment | 7 complexity | 0745c5c85c363c82a0463bd987b54866 MD5 | raw file
  1"""Setup a new server/node"""
  2import os
  3from cmdutils import CommandError
  4from silversupport.shell import ssh, run
  5
  6
  7def setup_rsync(config, source, dest, delete=False):
  8    cwd = os.path.abspath(os.path.join(__file__, '../..'))
  9    options = ['--quiet', '--executability', '-rvC']
 10    if delete:
 11        options.append('--delete')
 12    stdout, stderr, returncode = run(
 13        ['rsync'] + options +
 14        [source, 'root@%s:%s' % (config.args.node, dest)],
 15        cwd=cwd)
 16    config.logger.notify(
 17        "rsyncing %s to %s" % (source, dest))
 18    if returncode:
 19        config.logger.fatal(
 20            "An error occurred in rsync (code=%s)" % returncode)
 21        response = config.ask(
 22            "Continue?")
 23        if not response:
 24            raise CommandError(
 25                "Aborting due to failure")
 26
 27
 28def command_setup_node(config):
 29    os.environ['LANG'] = 'C'
 30    node = config.args.node
 31    config.logger.notify(
 32        'Setting up authentication on server...')
 33
 34    for path in ['id_rsa.pub', 'id_dsa.pub']:
 35        pubkey_path = os.path.join(os.environ['HOME'], '.ssh', path)
 36        if os.path.exists(pubkey_path):
 37            key = open(pubkey_path, 'rb').read()
 38            config.logger.notify("Using key file:  %s", pubkey_path)
 39            break
 40    else:
 41        config.logger.fatal("Can't locate any key file")
 42        #not sure what error code are used for here but 8 was unused
 43        return 8
 44    ssh('root', node, '''
 45if [ -e /root/.silverlining-server-setup ] ; then
 46    exit 50
 47fi
 48mkdir -p /usr/local/share/silverlining/lib
 49mkdir -p /root/.ssh
 50cat >> /root/.ssh/authorized_keys
 51''',
 52        stdin=key)
 53    config.logger.notify(
 54        "Updating indexes and setting up rsync")
 55    stdout, stderr, returncode = ssh(
 56        'root', node, '''
 57dpkg --configure -a
 58apt-get update -qq
 59apt-get -y -q=2 install rsync
 60''')
 61    config.logger.notify(
 62        "Updating postfix configuration")
 63    stdout, stderr, returncode = ssh(
 64    'root', node, '''
 65echo "
 66Name: postfix/mailname
 67Template: postfix/mailname
 68Value: %s
 69Owners: postfix
 70Flags: seen
 71
 72Name: postfix/main_mailer_type
 73Template: postfix/main_mailer_type
 74Value: Internet site
 75Owners: postfix
 76Flags: seen
 77" >> /root/config.dat
 78''' % node)
 79    if returncode:
 80        config.logger.fatal(
 81            "An error occurred (code=%r)"
 82            % returncode)
 83        response = config.ask(
 84            "Continue?")
 85        if not response:
 86            return 3
 87    config.logger.notify(
 88        "Running apt-get install on server")
 89    lines = list(open(os.path.abspath(
 90        os.path.join(__file__, '../../server-sync-scripts/dpkg-query.txt'))))
 91    packages = ' '.join(line.strip().split()[0]
 92                        for line in lines
 93                        if line.strip() and not line.strip().startswith('#'))
 94    stdout, stderr, returncode = ssh(
 95        'root', node, """DEBCONF_DB_OVERRIDE='File{/root/config.dat}' """ + \
 96                      """apt-get -y -q=2 install --no-install-recommends $(cat)""",
 97        stdin=packages)
 98    if returncode:
 99        config.logger.fatal(
100            "An error occurred (code=%r)"
101            % returncode)
102        response = config.ask(
103            "Continue?")
104        if not response:
105            return 5
106
107    setup_rsync(config, 'server-root/', '/')
108    setup_rsync(config,
109                os.path.abspath(os.path.join(__file__, '../../../silversupport/'))+'/',
110                '/usr/local/share/silverlining/lib/silversupport/')
111    setup_rsync(config,
112                os.path.abspath(os.path.join(__file__, '../../mgr-scripts/'))+'/',
113                '/usr/local/share/silverlining/mgr-scripts/')
114    ssh('root', node, 'mv /var/root/* /root/')
115
116    # Move over the root files, we do *not* rsync a /root dir because
117    # that would copy the wrong permissions for the /root directorty
118    # which results in ssh key auth no longer working
119
120    setup_script = open(os.path.abspath(os.path.join(
121        __file__, '../../server-sync-scripts/update-server-script.sh'))).read()
122    import getpass
123    username = getpass.getuser()
124    setup_script = setup_script.replace('__REMOTE_USER__', username)
125
126    stdout, stderr, returncode = ssh(
127        'root', node, setup_script)
128    if returncode:
129        config.logger.fatal(
130            "An error occurred (code=%r)"
131            % returncode)
132        # No need to ask because it's the last task anyway
133        return 6