Source

beanstalk-stack / beanstalk / tasks / server.py

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
import ConfigParser
import datetime
import json
import os
import socket
from fabric.api import *
from fabric.colors import *
from fabric.contrib.console import confirm
from ground_soil.fabric import eval_kwargs, virtual_env
from ground_soil.filesystem import temporary_directory, render_file, sed
from beanstalk import IDENTIFIER, BEANSTALK_ROOT_PATH
from beanstalk.decorators import beanstalk_role
from beanstalk.paths.server import (project_base_path, project_source_path, project_logs_path, project_venv_path,
                                    project_uwsgi_path, apache_conf_path, app_ports_path)
from beanstalk.tasks.utils import load_role_settings, set_verbose_level, run_hooked_actions
from beanstalk.console.titles import tool_title, section_title, separator


# Tasks
#-----------------------------------------------------------------------------------------------------------------------


@task
@beanstalk_role('server')
def setup(settings_path=None, **settings_patches):
    """Setup remote base of beanstalk-stack in this server
    """
    print tool_title('Beanstalk-stack server setup tool')
    print ''

    # Load beanstalk settings
    settings_patches = eval_kwargs(settings_patches)
    beanstalk_settings = load_role_settings(additional_settings_path=settings_path, **settings_patches)
    beanstalk_stack_base = beanstalk_settings['BEANSTALK_STACK_BASE']
    set_verbose_level()

    # Call pre-setup script
    run_hooked_actions('PRE_SETUP_ACTIONS')

    # Install packages for building uwsgi
    print section_title('Install system packages')
    local('yum install -y python-virtualenv python-devel sqlite-devel libxml2-devel pcre-devel zeromq-devel'
          ' libcap-devel libuuid-devel libev-devel python-greenlet-devel httpd-devel')

    # Install Uwsgi
    with temporary_directory(identifier=IDENTIFIER, prefix='init_remote_base') as tmp_directory:
        with lcd(tmp_directory):
            print section_title('Install uwsgi and mod_uwsgi')
            # Get source code
            local('wget http://projects.unbit.it/downloads/uwsgi-lts.tar.gz')
            local('tar -zxf uwsgi-lts.tar.gz')
            try:
                uwsgi_src_folder = [path for path in os.listdir(tmp_directory)
                                    if path.startswith('uwsgi-') and '-lts' not in path][0]
            except IndexError:
                abort('Failed to extract uwsgi source folder')
                return

            # Check version
            install_uwsgi = True
            with settings(hide('everything'), warn_only=True):
                new_version = tuple(map(lambda x: int(x), uwsgi_src_folder.split('-')[-1].split('.')))
                has_uwsgi = local('which uwsgi', capture=True).return_code == 0
                if has_uwsgi:
                    current_version = tuple(map(lambda x: int(x), local('uwsgi --version', capture=True).split('.')))
                    print 'Current uWSGI version: {0}.{1}.{2}'.format(*current_version)
                    print 'New LTS uWSGI version: {0}.{1}.{2}'.format(*new_version)
                    if new_version == current_version:
                        print 'You have the newest LTS uWSGI.'
                        install_uwsgi = confirm('Re-install Uwsgi?', default=False)

            if install_uwsgi:
                print 'Install uwsgi {0}.{1}.{2}'.format(*new_version)
                # Stop services before install it
                if os.path.exists('/etc/init.d/beanstalk'):
                    with settings(hide('warnings'), warn_only=True):
                        local('/etc/init.d/beanstalk stop')

                with lcd(uwsgi_src_folder):
                    # Create build configuration
                    local('mkdir -p /usr/local/lib/uwsgi')
                    uwsgi_build_ini_path = os.path.join(BEANSTALK_ROOT_PATH, 'static/uwsgi_build.ini')
                    local('cp %s buildconf/beanstalk.ini' % uwsgi_build_ini_path)
                    # Build and install
                    local('python uwsgiconfig.py --build beanstalk')
                    local('cp uwsgi /usr/local/bin/uwsgi')
                    if os.path.exists('/usr/bin/uwsgi'):
                        local('rm -rf /usr/bin/uwsgi')
                    local('ln -s /usr/local/bin/uwsgi /usr/bin/uwsgi')
                    # mod_uwsgi
                    local('apxs -i -c apache2/mod_uwsgi.c')
                    local('echo "LoadModule uwsgi_module modules/mod_uwsgi.so" > /etc/httpd/conf.d/uwsgi.conf')

    # Init script
    local('mkdir -p /var/run/beanstalk')
    local('cp %s /etc/init.d/beanstalk' % os.path.join(BEANSTALK_ROOT_PATH, 'static/beanstalk_init.sh'))
    local('chmod +x /etc/init.d/beanstalk')
    local('chkconfig beanstalk on')

    # Do you have user "beanstalk"?
    with settings(hide('everything'), warn_only=True):
        has_beanstalk_user = local('egrep ^beanstalk: /etc/passwd').return_code == 0
    if not has_beanstalk_user:
        print section_title('Create user "beanstalk"')
        # Create user
        local('useradd beanstalk')
        # Setup user password
        print yellow('Set password for user beanstalk', bold=True)
        local('passwd beanstalk')
        # Setup git
        local('su -c "git config --global user.name \'beanstalk\'" - beanstalk')
        local('su -c "git config --global user.email %s" - beanstalk' % beanstalk_settings['BEANSTALK_EMAIL'])
        # Setup .ssh
        local('mkdir -p ~beanstalk/.ssh')
        local('chmod 700 ~beanstalk/.ssh')
        local('touch ~beanstalk/.ssh/authorized_keys')
        local('chmod 644 ~beanstalk/.ssh/authorized_keys')
        local('chown -R beanstalk:beanstalk ~beanstalk/.ssh')

    # Create homebase
    print section_title('Deploy target is: %s' % beanstalk_stack_base)
    local('mkdir -p %s' % beanstalk_stack_base)
    local('mkdir -p %s' % os.path.join(beanstalk_stack_base, 'apps'))
    local('mkdir -p %s' % os.path.join(beanstalk_stack_base, 'global-logs'))
    local('mkdir -p %s' % os.path.join(beanstalk_stack_base, 'confs'))
    if not os.path.exists(app_ports_path()):
        local('echo "[]" > %s' % app_ports_path())
    local('chmod o+rx %s' % beanstalk_stack_base)

    # Global ini
    local('mkdir -p /etc/beanstalk')
    if not os.path.exists('/etc/beanstalk/uwsgi.ini'):
        print section_title('Create global settings')
        global_uwsgi_ini_template_path = os.path.join(BEANSTALK_ROOT_PATH, 'static/global_uwsgi.ini')
        with hide('everything'):
            uid = local('id -u beanstalk', capture=True)
        global_uwsgi_ini_content = render_file(global_uwsgi_ini_template_path, beanstalk_settings, BEANSTALK_UID=uid)
        with open('/etc/beanstalk/uwsgi.ini', 'w') as f:
            f.write(global_uwsgi_ini_content)

    # Apache command
    httpd_cmd_path = '/usr/sbin/httpd_reload'
    if not os.path.exists(httpd_cmd_path):
        print section_title('Create apache-reload command')
        httpd_cmd_source = os.path.join(BEANSTALK_ROOT_PATH, 'static/httpd_reload.sh')
        local('/bin/cp -f %s %s' % (httpd_cmd_source, httpd_cmd_path))
        local('chmod +x %s' % httpd_cmd_path)

    # Give beanstalk permission
    sudoer_file = '/etc/sudoers.d/beanstalk_reload_httpd'
    if not os.path.exists(sudoer_file):
        print section_title('Give beanstalk permission for apache-reload command')
        local('echo "beanstalk ALL=(root) NOPASSWD: %s" > %s' % (httpd_cmd_path, sudoer_file))
        local('chmod 440 %s' % sudoer_file)

    # Make beanstalk access ssh
    print section_title('Configure SSH server')
    sshd_config = '/etc/ssh/sshd_config'
    #new_lines = [
    #    'Match Group beanstalk',
    #    '       ForceCommand /usr/bin/bs_ssh_entry',
    #]
    #local(sed('$ a\\\n{command}'.format(command='\\n'.join(new_lines)), sshd_config))
    local(sed('/^AllowGroups wheel$/cAllowGroups wheel beanstalk', sshd_config))  # TODO: More general form

    # Apache conf
    print section_title('Configure Apache HTTP server')
    if not os.path.exists('/etc/httpd/conf.d/beanstalk.conf'):
        beanstalk_apache_conf_template = os.path.join(BEANSTALK_ROOT_PATH, 'static/beanstalk_apache.conf')
        beanstalk_apache_conf = render_file(beanstalk_apache_conf_template, beanstalk_settings)
        with open('/etc/httpd/conf.d/beanstalk.conf', 'w') as f:
            f.write(beanstalk_apache_conf)
    if not os.path.exists(apache_conf_path()):
        local('echo "# Beanstalk Apache conf" > %s' % apache_conf_path())
        local('chown beanstalk:beanstalk %s' % apache_conf_path())
    if not os.path.exists('/etc/httpd/conf.d/beanstalk_app.conf'):
        local('ln -s %s /etc/httpd/conf.d/beanstalk_app.conf' % apache_conf_path())

    print section_title('Final setup')
    local('chown -R beanstalk:beanstalk %s' % beanstalk_stack_base)
    with settings(hide('warnings'), warn_only=True):
        local('/etc/init.d/beanstalk restart')
        local('/etc/init.d/sshd restart')
        local('/etc/init.d/httpd restart')

    # Call post-setup script
    run_hooked_actions('POST_SETUP_ACTIONS')


@task
@beanstalk_role('server')
def create_app(project_name, settings_path=None, **settings_patches):
    """Create an app
    """
    settings_patches = eval_kwargs(settings_patches)
    load_role_settings(additional_settings_path=settings_path, **settings_patches)
    env.project_name = project_name
    set_verbose_level()

    # Folder paths
    project_base = project_base_path(project_name)
    project_source = project_source_path(project_name)
    project_logs = project_logs_path(project_name)
    project_venv = project_venv_path(project_name)

    if os.path.exists(project_base):
        print 'Nothing to do. App existed!'
        return

    # Pre-create actions
    run_hooked_actions('PRE_CREATE_ACTIONS')

    # Create folders
    print section_title('Create folders')
    local('mkdir -p %s' % project_base)
    local('mkdir -p %s' % project_source)
    local('mkdir -p %s' % project_logs)

    # Initialize venv
    if not os.path.exists(project_venv):
        print section_title('Initialize virtual env')
        with lcd(project_base):
            local('virtualenv venv')

    # Initialize git
    if not os.path.exists(os.path.join(project_base, '.git')):
        print section_title('Make git repository')
        with lcd(project_base):
            local('git init')
            local('touch .gitignore')
            local('git add .gitignore')
            local('git commit -m "Init commit"')

    # Get uwsgi port
    with open(app_ports_path(), 'r') as f:
        ports = json.loads(f.read())
    if len(ports) == 0:
        uwsgi_port = 50000
    else:
        uwsgi_port = max(ports) + 1
    # Available ports?
    try_times = 1
    port_available = False
    while try_times <= 10:
        try:
            s = socket.socket()
            s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
            s.bind(('localhost', uwsgi_port))
            s.close()
            port_available = True
            break
        except socket.error:
            uwsgi_port += 1
            try_times += 1
    if not port_available:
        abort('No available port for uwsgi')
    else:
        env.uwsgi_port = uwsgi_port
        ports.append(uwsgi_port)
    # Save it
    with open(app_ports_path(), 'w') as f:
        f.write(json.dumps(ports, separators=(',', ':')))

    print section_title('Add to apache httpd')
    with open(apache_conf_path(), 'r') as f:
        apache_conf = f.read()
    if not '# %s' % project_name in apache_conf:
        commands = [
            '# %s' % project_name,
            '#' + '-' * 20,
            '<Location /%s>' % project_name,
            '    SetHandler uwsgi-handler',
            '    uWSGISocket 127.0.0.1:%s' % uwsgi_port,
            '</Location>',
            '#' + '-' * 20,
            ' ',
        ]
        sed_command = '\\n'.join(commands)
        local(sed('$ a\\{command}'.format(command=sed_command), apache_conf_path()))
        local('sudo /usr/sbin/httpd_reload')

    port_file_path = os.path.join(project_base_path(project_name), '%d.port' % uwsgi_port)
    local('echo "%d" > %s' % (uwsgi_port, port_file_path))

    # Post-create actions
    run_hooked_actions('POST_CREATE_ACTIONS')


@task
@beanstalk_role('server')
def delete_app(project_name, settings_path=None, **settings_patches):
    """Delete an app
    """
    settings_patches = eval_kwargs(settings_patches)
    load_role_settings(additional_settings_path=settings_path, **settings_patches)
    set_verbose_level()
    env.project_name = project_name

    # Folder paths
    project_base = project_base_path(project_name)

    remove = confirm(red('Remove project: %s ?' % project_name), default=False)

    # delete
    if remove:
        print section_title('Remove app @ %s' % project_base)
        try:
            port_number = int([name for name in os.listdir(project_base) if name.endswith('.port')][0].split('.')[0])
            with open(app_ports_path(), 'r') as f:
                ports = json.loads(f.read())
            if port_number in ports:
                ports.remove(port_number)
            with open(app_ports_path(), 'w') as f:
                f.write(json.dumps(ports))
        except (IndexError, ValueError):
            pass

        local('rm -rf %s' % project_base)

    local(sed('/# {name}/,+7d'.format(name=project_name), apache_conf_path()))
    local('sudo /usr/sbin/httpd_reload')


@task
@beanstalk_role('server')
def install_app(project_name, settings_path=None, **settings_patches):
    """Install an app (call when u updated the code)
    """
    settings_patches = eval_kwargs(settings_patches)
    load_role_settings(additional_settings_path=settings_path, **settings_patches)
    set_verbose_level()
    env.project_name = project_name

    run_hooked_actions('PRE_INSTALL_ACTIONS')

    project_source = project_source_path(project_name)
    project_venv = project_venv_path(project_name)

    print section_title('Install/Update packages in virtualenv')
    with settings(virtual_env(project_venv)):
        local('pip install -r %s' % os.path.join(project_source, 'requirements.txt'))

    print section_title('Compile python code')
    local('find %s -name \'*.pyc\' -exec rm -rf {} \;' % project_source)
    local('find %s -name \'*.pyo\' -exec rm -rf {} \;' % project_source)
    local('python -m compileall -q %s' % project_source)

    print section_title('Setup uwsgi')
    # uwsgi port
    try:
        uwsgi_port = int([name for name in os.listdir(project_base_path(project_name))
                          if name.endswith('.port')][0].split('.')[0])
    except (IndexError, ValueError):
        abort('No port number!?')
        return
    # edit ini
    uwsgi_path = project_uwsgi_path(project_name)
    config = ConfigParser.ConfigParser()
    if os.path.exists(uwsgi_path):
        config.read(uwsgi_path)
    if not config.has_section('uwsgi'):
        config.add_section('uwsgi')
    optional_overrride_options = [
        ('master', True),
        ('enable-threads', True),
        ('threads', 20),
        ('processes', 4),
        ('module', '%s.wsgi:application' % project_name),
    ]
    for key, value in optional_overrride_options:
        if not config.has_option('uwsgi', key):
            config.set('uwsgi', key, value)
    must_override_options = [
        ('socket', '127.0.0.1:%d' % uwsgi_port),
        ('chdir', project_source_path(project_name)),
        ('home', project_venv_path(project_name)),
    ]
    for key, value in must_override_options:
        config.set('uwsgi', key, value)
    with hide('everything'):
        uid = local('id -u beanstalk', capture=True)
    config.set('uwsgi', 'uid', uid)
    config.set('uwsgi', 'logto', os.path.join(project_logs_path(project_name), 'uwsgi.log'))
    config.remove_option('uwsgi', 'http')
    config.remove_option('uwsgi', 'https')
    config.remove_option('uwsgi', 'http-proxy')
    config.remove_option('uwsgi', 'http-to')
    with open(uwsgi_path, 'wb') as f:
        config.write(f)

    run_hooked_actions('POST_INSTALL_ACTIONS')


@task
@beanstalk_role('server')
def reload_app(project_name, settings_path=None, **settings_patches):
    """Update an app (call when u updated the code)
    """
    settings_patches = eval_kwargs(settings_patches)
    load_role_settings(additional_settings_path=settings_path, **settings_patches)
    set_verbose_level()
    env.project_name = project_name

    run_hooked_actions('PRE_RELOAD_ACTIONS')

    print section_title('Reload app: %s' % project_name)
    local('touch %s' % project_uwsgi_path(project_name))

    run_hooked_actions('POST_RELOAD_ACTIONS')


@task
@beanstalk_role('server')
def build_venv(project_name, settings_path=None, **settings_patches):
    """Build virtual env of target app.
    """
    settings_patches = eval_kwargs(settings_patches)
    load_role_settings(additional_settings_path=settings_path, **settings_patches)
    set_verbose_level()

    # path
    project_venv = project_venv_path(project_name)
    requirments_path = os.path.join(project_source_path(project_name), 'requirments.txt')

    print section_title('Build virtualenv for %s' % project_name)

    # Clean it
    local('rm -rf %s' % project_venv)

    venv_base, venv_name = os.path.split(project_venv)
    with lcd(venv_base):
        local('virtualenv %s' % venv_name)
        with settings(virtual_env(project_venv)):
            local('pip intall -r %s' % requirments_path)


@task
@beanstalk_role('server')
def app_info(project_name, settings_path=None, **settings_patches):
    """Get info of an app
    """
    settings_patches = eval_kwargs(settings_patches)
    beanstalk_settings = load_role_settings(additional_settings_path=settings_path, **settings_patches)
    set_verbose_level()

    # Gather information
    apps = os.listdir(os.path.join(beanstalk_settings['BEANSTALK_STACK_BASE'], 'apps'))

    if project_name not in apps:
        if beanstalk_settings.get('USE_JSON', False):
            print json.dumps({'error': 'No such app'})
        else:
            print red('No such app')
        return

    try:
        uwsgi_port = int([name for name in os.listdir(project_base_path(project_name))
                          if name.endswith('.port')][0].split('.')[0])
    except (IndexError, ValueError):
        abort('No port number!?')
        return

    if beanstalk_settings.get('USE_JSON', False):
        result = {
            'path': {
                'base': project_base_path(project_name),
                'source': project_source_path(project_name),
                'logs': project_logs_path(project_name),
                'venv': project_venv_path(project_name),
            },
            'uwsgi': {
                'port': uwsgi_port,
            },
        }
        json_string = json.dumps(result, separators=(',', ':'))

        if beanstalk_settings.get('PRINT_JSON', True):
            print json_string
        return json_string
    else:
        print section_title('Beanstalk-stack app: %s' % project_name)
        print separator('-=')
        print 'Base   : %s' % project_base_path(project_name)
        print 'Source : %s' % project_source_path(project_name)
        print 'Logs   : %s' % project_logs_path(project_name)
        print 'venv   : %s' % project_venv_path(project_name)
        print separator('-', 40)
        print 'uwsgi port : %s' % uwsgi_port


@task
@beanstalk_role('server')
def list_apps(settings_path=None, **settings_patches):
    """Get list of apps
    """
    settings_patches = eval_kwargs(settings_patches)
    beanstalk_settings = load_role_settings(additional_settings_path=settings_path, **settings_patches)
    set_verbose_level()

    apps = os.listdir(os.path.join(beanstalk_settings['BEANSTALK_STACK_BASE'], 'apps/'))

    print section_title('Beanstalk-stack apps')
    print separator('-=')
    for app in apps:
        print app


@task
@beanstalk_role('server')
def commit_app(project_name, settings_path=None, **settings_patches):
    """Commit app
    """
    settings_patches = eval_kwargs(settings_patches)
    load_role_settings(additional_settings_path=settings_path, **settings_patches)
    env.project_name = project_name
    set_verbose_level()

    run_hooked_actions('PRE_COMMIT_ACTION')

    project_base = project_base_path(project_name)
    with settings(lcd(project_base), hide('warnings'), warning=True):
        local('git add -A && git commit -m "state at %s"' % datetime.datetime.now().strftime('%s'))

    run_hooked_actions('POST_COMMIT_ACTION')


@task
@beanstalk_role('server')
def add_user(tmp_key_path, clean_tmp_key=False):
    """Add a user's SSH public key to beanstalk
    """
    tmp_key_path = os.path.expanduser(tmp_key_path)

    with open(tmp_key_path, 'r') as f:
        raw_key = f.read().strip()

    new_key = 'no-port-forwarding,no-X11-forwarding,no-agent-forwarding {key}'.format(key=raw_key)

    has_this_key = False
    authorized_keys_path = os.path.expanduser('~/.ssh/authorized_keys')
    with open(authorized_keys_path, 'r') as authorized_keys:
        for authorized_key in authorized_keys:
            if authorized_key.strip() == new_key:
                has_this_key = True
                break

    if not has_this_key:
        # NOTE: Be careful that new_key may contains " (double quote)
        local('cp {0} {0}.bak && echo "{1}" >> {0} && rm -rf {0}.bak'.format(authorized_keys_path, new_key))

    if clean_tmp_key:
        local('rm -rf {path}'.format(path=tmp_key_path))

    print green('User added.')