コード例 #1
0
ファイル: fabfile.py プロジェクト: midonet/senbazuru
def midonet_manager():

    if "OS_MIDOKURA_REPOSITORY_USER" in os.environ:
        puts(green("installing MidoNet Manager on %s" % env.host_string))

        run("""
API_IP="%s"
dpkg --configure -a
apt-get install -y -u midonet-manager

#
# midonet manager 1.9.3
#
cat >/var/www/html/midonet-manager/config/client.js <<EOF
{
  "api_host": "http://${API_IP}:8080",
  "login_host": "http://${API_IP}:8080",
  "api_namespace": "midonet-api",
  "api_version": "1.8",
  "api_token": false,
  "poll_enabled": true,
  "agent_config_api_host": "http://${API_IP}:8459",
  "agent_config_api_namespace": "conf",
  "trace_api_host": "http://${API_IP}:8080",
  "traces_ws_url": "ws://${API_IP}:8460"
}
EOF

service apache2 restart

""" % metadata.servers[metadata.roles['midonet_api'][0]]['ip'])

    else:
        puts(yellow("MidoNet Manager is only available in MEM"))
コード例 #2
0
ファイル: fabfile.py プロジェクト: sap1ens/deploy-scripts
def help():
    puts("""
    Usage: fab command:[arg1],[arg2]

    Description:
        Deployment (and not only...) tool for work in Apache Tomcat + Maven multi-module environment

    Required:
        Apache Tomcat 6+
        Apache Maven 2+

    Commands:
        help                        - this page

        build                       - Maven package build
        war                         - copy current WAR package to Tomcat
        static                      - copy current static files to Tomcat

        tomcat:[start|stop|restart] - Tomcat management
        clean                       - clean deployed Tomcat app
        jpda                        - run Tomcat's JPDA

        test:[test profile],[name]  - run test with specified profile and class name with Maven

        full                        - 'build' + 'tomcat:stop' + 'war' + 'tomcat:start' commands coherently
    """)
コード例 #3
0
ファイル: fabfile.py プロジェクト: Ichag/vagrant_openerp
def openerp_rsyslog():
    require.files.file(
        '/etc/rsyslog.d/20-openerp.conf', 
        source='files/etc/rsyslog.d/20-openerp.conf', 
        owner='root', 
        group='root', 
        mode=644, 
        use_sudo = True
    )
    require.files.file(
        '/etc/init.d/openerp',
        source='files/etc/init.d/openerp',
        owner='root',
        group='root',
        mode='755',
        use_sudo=True
    )
    require.files.directory(
        '/var/log/openerp',
        mode=777, 
        use_sudo=True
    )
    require.service.restarted('rsyslog')
    ## we need a full stop and start as we updated /etc/init.d/openerp file
    puts('Stopping openerp')
    service.stop('openerp')
    puts('Starting openerp')
    service.start('openerp')
コード例 #4
0
ファイル: fabfile.py プロジェクト: benroeder/pi-me-up
def install_motd():
    """ Installs a succulent ascii-art MOTD. In colour!
    The raspberry was by RPi forum user b3n, taken from
    http://www.raspberrypi.org/phpBB3/viewtopic.php?f=2&t=5494
    """

    puts(green("Installing succulent MOTD"))
    motd = text_strip_margin("""
        |
        |{g}      .~~.   .~~.
        |{g}     ". \ " " / ."
        |{r}      .~ .~~~..~.
        |{r}     : .~."~".~. :    {b}                       __                      {o}     _
        |{r}    ~ (   ) (   ) ~   {b}    _______ ____ ___  / /  ___ __________ __  {o}___  (_)
        |{r}   ( : "~".~."~" : )  {b}   / __/ _ `(_-</ _ \/ _ \/ -_) __/ __/ // / {o}/ _ \/ /
        |{r}    ~ .~ (   ) ~. ~   {p}  /_/  \_,_/___/ .__/_.__/\__/_/ /_/  \_, / {o}/ .__/_/
        |{r}     (  : "~" :  )    {p}              /_/                    /___/ {o}/_/
        |{r}      "~ .~~~. ~"
        |{r}          "~"
        |{n}
        |
        |""".format(
            g="",
            r="",
            b="",
            o="",
            p="",
            n="",
        )
    )
    with hide("output", "running"):
        sudo_file_write("/etc/motd", motd)
コード例 #5
0
ファイル: fabfile.py プロジェクト: dariosky/tam
def get_repository():
    if run("test -d %s" % env.REPOSITORY_FOLDER, quiet=True).failed:
        puts("Creating repository folder.")
        run("mkdir -p %s" % env.REPOSITORY_FOLDER)
    if not exists(posixpath.join(env.REPOSITORY_FOLDER, '.git')):
        puts("Cloning from repository.")
        run("git clone %s %s" % (env.GIT_REPOSITORY, env.REPOSITORY_FOLDER))
コード例 #6
0
ファイル: elasticsearch.py プロジェクト: closeio/burlybeetle
def post_stop_callback(node):
    """Wait until the node leaves the cluster"""

    if env.commit:
        wait_for_node(node, leave=True)
    else:
        utils.puts('wait for node {} (noop): to leave'.format(node))
コード例 #7
0
ファイル: s3.py プロジェクト: pauloalem/fabix
def upload_file(bucket, key_name, file_path, remote_prefix=None, policy='public-read', metadata=None):
    if not metadata:
        metadata = {}

    if remote_prefix:
        key_name = '{0}/{1}'.format(remote_prefix, key_name)

    fd = open(file_path)
    md5 = compute_md5(fd)
    fd.close()

    current_md5 = None
    current_key = bucket.lookup(key_name)
    if current_key:
        current_md5 = current_key.get_metadata('fabix-md5')
        if current_md5 == md5[0]:
            for k, v in metadata.iteritems():
                current_key.set_metadata(k, v)
            puts("Skip file {0}".format(file_path))
            return current_key

    key = bucket.new_key(key_name)

    for k, v in metadata.iteritems():
        key.set_metadata(k, v)

    key.set_metadata('fabix-md5', md5[0])

    puts("Upload file {0}".format(file_path))
    key.set_contents_from_filename(file_path, md5=md5, policy=policy)
    return key
コード例 #8
0
ファイル: git.py プロジェクト: arjunktr/docs-tools
def apply(obj,repo=None):
    if repo is None:

        repo = get_conf().git.remote.upstream

    cmd = ['curl',
           'https://github.com/{0}/'.format(repo),
           '|', 'git', 'am',
           '--signoff --3way' if env.sign else '--3way' ]

    if obj.startswith('http'):
        cmd[1] = obj
        if not obj.endswith('.patch'):
            cmd[1] += '.patch'
        local(' '.join(cmd))
    elif re.search('[a-zA-Z]+', obj):
        cmd[1] = cmd[1] + 'commit/' + obj + '.patch'

        local(' '.join(cmd))
        puts('[git]: merged commit {0} for {1} into {2}'.format(obj, repo, get_branch()))
    else:
        cmd[1] = cmd[1] + 'pull/' + obj + '.patch'

        local(' '.join(cmd))
        puts('[git]: merged pull request #{0} for {1} into {2}'.format(obj, repo, get_branch()))
コード例 #9
0
ファイル: manage_content.py プロジェクト: Gastove/foodblag
def clean(output = ABS_OUTPUT_PATH):
    """ Remove old content """
    cmd = "rm -r {0}".format(output)
    with settings(warn_ony = True):
        outcome  = local(cmd)
    if outcome.failed:
        puts("Nothing found; probably already deleted.")
コード例 #10
0
ファイル: fabfile.py プロジェクト: ben181231/skygear-server
def add_plugin(name, image=None, dockerfile='Dockerfile', build_context=None,
               should_restart=True):
    """
    Add a new plugin by modifying skygear server configuration

    If an image is specified, it will be treated as a Docker repository image
    and pulled from the repository. If an image is not specified, a build
    directory is configured where you should upload your plugin via git.

    Skygear Server is restarted automatically by default if an image is
    specified.

    If your Dockerfile is not at the project root, you should specify
    an alternative Dockerfile location and build context.
    """
    config_file = '/home/ubuntu/myapp/development.ini'
    service_name = "plugin_{0}".format(name)
    with cd("myapp"):
        data = read_compose_override()
        if service_name in data.get('services', {}):
            error("Plugin '{0}' already exists.".format(name))
            return
        augtool(r"""
        set /files{0}/plugin\ \"{1}\"/transport http
        set /files{0}/plugin\ \"{1}\"/path http://{1}:8000
        """.format(config_file, service_name))
        data = add_docker_plugin(data, name, image, dockerfile, build_context)
        write_compose_override(data)
    if image is None:
        puts("""Plugin '{0}' is added to Skygear. To upload plugin, add
'[email protected]<ip address>:{0}' as a git remote and push your code.""".format(name))
        return
    if should_restart:
        restart(should_recreate=True)
コード例 #11
0
ファイル: git.py プロジェクト: joeytwiddle/docs
def apply(obj, repo=None):
    if repo is None:
        repo = docs_meta.GIT_REMOTE["upstream"]

    cmd = [
        "curl",
        "https://github.com/{0}/".format(repo),
        "|",
        "git",
        "am",
        "--signoff --3way" if env.sign else "--3way",
    ]

    if obj.startswith("http"):
        cmd[1] = obj
        if not obj.endswith(".patch"):
            cmd[1] += ".patch"

        local(" ".join(cmd))
    elif re.search("[a-zA-Z]+", obj):
        cmd[1] = cmd[1] + "commit/" + obj + ".patch"

        local(" ".join(cmd))
        puts("[git]: merged commit {0} for {1} into {2}".format(obj, repo, docs_meta.get_branch()))
    else:
        cmd[1] = cmd[1] + "pull/" + obj + ".patch"

        local(" ".join(cmd))
        puts("[git]: merged pull request #{0} for {1} into {2}".format(obj, repo, docs_meta.get_branch()))
コード例 #12
0
ファイル: utils.py プロジェクト: 5monkeys/refabric
def info(text, *args, **kwargs):
    args = (yellow(arg) for arg in args)
    kwargs = {key: yellow(value) for key, value in kwargs.items()}
    text = text.format(*args, **kwargs)
    if not text.startswith(' '):
        text = green(text)
    puts(text)
コード例 #13
0
ファイル: fabfile.py プロジェクト: cloudsecninja1975/orizuru
def stage7_midonet_tunnelzone_members():
    metadata = Config(os.environ["CONFIGFILE"])

    if cuisine.file_exists("/tmp/.%s.lck" % sys._getframe().f_code.co_name):
        return

    cuisine.package_ensure("expect")

    for container_role in ['container_midonet_gateway', 'container_openstack_compute', 'container_openstack_neutron']:
        if container_role in metadata.roles:
            for container in metadata.containers:
                if container in metadata.roles[container_role]:
                    puts(green("adding container %s as member to tunnel zones" % container))
                    add_host_to_tunnel_zone(metadata.config["debug"], container, metadata.containers[container]["ip"])

    for physical_role in ['physical_midonet_gateway', 'physical_openstack_compute']:
        if physical_role in metadata.roles:
            for server in metadata.servers:
                if server in metadata.roles[physical_role]:
                    puts(green("adding server %s as member to tunnel zones" % server))

                    #
                    # tinc can only work with MTU 1500
                    # we could use the approach from http://lartc.org/howto/lartc.cookbook.mtu-mss.html
                    # but instead we will disable rp_filter and use the physical interface ip
                    #
                    # server_ip = "%s.%s" % (metadata.config["vpn_base"], metadata.config["idx"][server])
                    #

                    server_ip = metadata.servers[server]["ip"]
                    add_host_to_tunnel_zone(metadata.config["debug"], server, server_ip)

    cuisine.file_write("/tmp/.%s.lck" % sys._getframe().f_code.co_name, "xoxo")
コード例 #14
0
ファイル: mysql.py プロジェクト: amitsrivastav/serverstuffs
def mysql_install():
    """ Installs mysql. """
    if _mysql_is_installed():
        puts('Mysql is already installed.')
        return

    passwd = _get_root_password()

    # this way mysql won't ask for a password on installation
    # see http://serverfault.com/questions/19367/scripted-install-of-mysql-on-ubuntu
    os = utils.detect_os()
    system.aptitude_install('debconf-utils')

    mysql_versions = {'lenny': '5.0', 'squeeze': '5.1', 'maverick': '5.1'}
    version = mysql_versions[os]

    debconf_defaults = [
        "mysql-server-%s mysql-server/root_password_again password %s" % (version, passwd),
        "mysql-server-%s mysql-server/root_password password %s" % (version, passwd),
    ]

    sudo("echo '%s' | debconf-set-selections" % "\n".join(debconf_defaults))

    warn('\n=========\nThe password for mysql "root" user will be set to "%s"\n=========\n' % passwd)
    system.aptitude_install('mysql-server')
コード例 #15
0
ファイル: elasticsearch.py プロジェクト: closeio/burlybeetle
def wait_for_node(node, leave=False):
    """
    Waits for a node to leave or join the cluster

    Continually poll the elasticsearch cluster status API for the node
    """

    tries = DEFAULT_TRIES
    while tries > 0:
        utils.puts(
            'Waiting for node {} to {}'.format(
                node, 'leave' if leave else 'come back',
            )
        )
        data = curl_and_json(env.apis, '/_nodes/_all/info')
        for node_id, node_conf in data['nodes'].items():
            if 'host' in node_conf:
                if not leave and node_conf['host'] == node:
                    return
        else:
            if leave:
                return
            else:
                tries -= 1
                time.sleep(DEFAULT_INTERVAL)
    console.confirm(
        'Node {} never {}! Press Enter to continue, '
        'CTRL+C to abort (check output of {}/_nodes/_all/info?pretty)'.
        format(
            node,
            'left' if leave else 'came back',
            env.apis[0],
        )
    )
コード例 #16
0
ファイル: fabfile.py プロジェクト: yantarou/orizuru
def stage11():
    puts(yellow("adding ssh connections to local known hosts file"))
    for server in metadata.servers:
        puts(green("connecting to %s now and adding the key" % server))
        local("ssh -o StrictHostKeyChecking=no [email protected]%s uptime" % metadata.servers[server]["ip"])

    execute(stage11)
コード例 #17
0
ファイル: elasticsearch.py プロジェクト: closeio/burlybeetle
def wait_for_health(status):
    """
    Waits for the cluster's health to match what we want

    Continually poll the elasticsearch cluster health API for health
    to match what we want
    """

    # wait (limit * sleep) seconds
    tries = DEFAULT_TRIES
    while tries > 0:
        st = get_cluster_health()
        utils.puts(
            'Waiting for cluster health to be {}, currently {}'.format(
                getattr(colors, status)(status),
                getattr(colors, st)(st),
            )
        )
        if st == status:
            return
        else:
            tries -= 1
            time.sleep(DEFAULT_INTERVAL)
    console.confirm(
        'Cluster status never got {}! Press Enter to continue, '
        'CTRL+C to abort (check output of {}/_cluster/health?pretty)'.
        format(status, env.apis[0])
    )
コード例 #18
0
ファイル: fabfile.py プロジェクト: kazufusa/dotfiles
def setup_packages():
    cuisine.select_package('apt')
    puts(green('Installing Ubuntu packages'))
    with cuisine.mode_sudo():
        cuisine.package_update()
        cuisine.package_upgrade()
        cuisine.package_ensure([
            "aptitude",
            "build-essential",
            "curl",
            "git",
            "guake",
            "haskell-platform",
            "htop",
            "ibux-mozc",
            "libclang-dev",
            'libncursesw5-dev',
            "libssl-dev",
            "paco",
            "python3-dev",
            "tmux",
            "tree",
            "wget",
            "zip",
            "zsh",
            ])
コード例 #19
0
ファイル: fabfile.py プロジェクト: aderugin/fabric
def create_project():
    """
    Создает новый проект
    """
    # спрашиваем у пользователя название папки с проектом
    prompt('project root name: ', 'project_root',
           validate='^([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\-]*[A-Za-z0-9])$')

    # спрашиваем у пользователя название проекта
    prompt('project name: ', 'project',
           validate='^([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\-]*[A-Za-z0-9])$')
    puts('create project: {0}'.format(env.project))

    with lcd(PROJECTS_ROOT):
        # Создаем директорию с root проектом
        local('mkdir %s' % env.project_root)

        with lcd(env.project_root):
            # Создаем директорию с django проектом и переходим в нее
            local('mkdir {0}-django'.format(env.project))

            with lcd('{0}-django'.format(env.project)):
                # Создаем виртуальное окружение
                local('virtualenv -p {0} .venv'.format(PYTHON))

                with prefix('.venv/bin/activate'):
                    # Устанавливаем django
                    if DJANGO_VERSION:
                        local('pip install django=={0}'.format(DJANGO_VERSION))
                    else:
                        local('pip install django')

                # Создаем проект из шаблона
                local('django-admin --template={0} {1}'.format(PROJECT_TEMPLATE_PATH,
                                                               env.project))
コード例 #20
0
ファイル: fabfile.py プロジェクト: nuttycom/staticsite
def rollback():
    """
        Rolls back currently deployed version to its predecessor
    """
    with cd(env.basepath):
        run('mv current/rollback rollback')
        run('mv current undeployed')
        run('mv rollback current')
        version = run('readlink current')
        previous = run('readlink undeployed')
        puts(green('>>> Rolled back from %(previous)s to %(version)s' % { 'previous': previous, 'version': version }))
        run('rm -fr %s' % previous)
        run('rm undeployed')
        sudo('service nginx reload')
    with cd(env.nodejs):
        for n in [1, 2]:
            with settings(warn_only=True):
                sudo('stop nodejs N=%s' % n)
            run('mv instance%s/rollback rollback%s' % (n, n))
            run('mv instance%s undeployed' % n)
            run('mv rollback%s instance%s' % (n, n))
            version = run('readlink instance%s' % n)
            previous = run('readlink undeployed')
            puts(green('>>> Rolled back nodejs %(n)s from %(previous)s to %(version)s' % { 'n': n, 'previous': previous, 'version': version }))
            run('rm -fr %s' % previous)
            run('rm undeployed')
            sudo('start nodejs N=%s' % n)
コード例 #21
0
ファイル: __init__.py プロジェクト: local-projects/cubric
    def reboot(self):
        self.before_reboot()

        puts(green('Rebooting server'))
        sudo('reboot')

        self.after_reboot()
コード例 #22
0
ファイル: fabfile.py プロジェクト: nuttycom/staticsite
def production():
    """
        Execute the other actions on production environment
    """
    puts(green('>>> Running on Production!'))
    env.hosts = ['web1.precog.com']
    puts(green('Servers: %s' % ", ".join(env.hosts)))
コード例 #23
0
ファイル: fabfile.py プロジェクト: dariosky/tam
def local_create_run_command():
    gunicorn_command = get_gunicorn_command(daemon=False)
    puts("Creating run_server command to be run " + (
        "with" if env.USE_SUPERVISOR else "without") + " supervisor.")
    with lcd(env.localfolder):
        with open('run_server', 'w') as runner:
            runner.write(run_command_content())
コード例 #24
0
ファイル: __init__.py プロジェクト: Web5design/soundcite
 def _do(f_out, path, imported):
     s = ''
     dirpath = dirname(path)      
     with _open_file(path, 'r') as f_in:
         s = f_in.read()
  
     # Write out prepends
     for m in _re_prepend.finditer(s):
         file_path = _find_file(m.group('file'), dirpath)
         if not file_path in imported:
             puts('  prepend: %s' % file_path)
             imported.append(file_path)
             _do(f_out, file_path, imported)
     
     # Write out file
     _mark(f_out, os.path.basename(path))  
     f_out.write(s+'\n')
     
     # Write out appends    
     for m in _re_append.finditer(s):
         file_path = _find_file(m.group('file'), dirpath)
         if not file_path in imported:
             puts('  append: %s' % file_path)
             imported.append(file_path)
             _do(f_out, file_path, imported)
コード例 #25
0
def syntax_check():
    """Runs flake8 against the codebase."""
    with fab_settings(warn_only=True):
        for file_type in settings.SYNTAX_CHECK:
            needs_to_abort = False
            # because egrep fails with exit code 1, we need to allow this as
            # a successful exit code in our env
            if 1 not in env.ok_ret_codes:
                env.ok_ret_codes.append(1)
            output = local(
                'find -name "{}" -print'.format(file_type),
                capture=True,
            )
            files = output.split()
            for file in files:
                if any(s in file for s in settings.SYNTAX_CHECK_EXCLUDES):
                    continue
                result = local('egrep -i -n "{0}" {1}'.format(
                    settings.SYNTAX_CHECK[file_type], file), capture=True)
                if result:
                    warn(red("Syntax check found in '{0}': {1}".format(
                        file, result)))
                    needs_to_abort = True
            if needs_to_abort:
                abort(red('There have been errors. Please fix them and run'
                          ' the check again.'))
            else:
                puts(green('Syntax check found no errors. Very good!'))
コード例 #26
0
ファイル: __init__.py プロジェクト: Web5design/soundcite
def stage_latest():
    """
    Copy version to latest within local cdn repository
    """
    if 'version' in CONFIG:
        version = CONFIG['version']
    else:
        tags = _get_tags()
        puts('This project has the following tags:')
        puts(tags)
    
        while True:
            version = prompt("Which version to stage as 'latest'? ").strip()        
            if not version in tags:
                warn('You must enter an existing version')
            else:
                break
    
    print 'stage_latest: %s' % version
    
    # Make sure version has been staged
    version_cdn_path = join(env.cdn_path, version)
    if not os.path.exists(version_cdn_path): 
        abort("Version '%s' has not been staged" % version)
      
    # Stage version as latest           
    latest_cdn_path = join(env.cdn_path, 'latest')
    _clean(latest_cdn_path)
    copy([{"src": version_cdn_path, "dst": latest_cdn_path}])
コード例 #27
0
ファイル: test_utils.py プロジェクト: atassumer/fabric
def test_puts_without_prefix():
    """
    puts() shouldn't prefix output with env.host_string if show_prefix is False
    """
    s = "my output"
    puts(s, show_prefix=False)
    eq_(sys.stdout.getvalue(), "%s" % (s + "\n"))
コード例 #28
0
ファイル: common.py プロジェクト: yantarou/orizuru
    def pingcheck(self):
        domain = self._metadata.config["domain"]
        for server in sorted(self._metadata.servers):
            ip = self._metadata.servers[server]["ip"]
            puts(yellow("pinging %s.%s (%s)" % (server,domain,ip)))

            local("ping -c1 -W20 %s" % ip)
コード例 #29
0
ファイル: test_utils.py プロジェクト: 4hr1m4n/fabric
def test_puts_with_user_output_off():
    """
    puts() shouldn't print input to sys.stdout if "user" output level is off
    """
    output.user = False
    puts("You aren't reading this.")
    eq_(sys.stdout.getvalue(), "")
コード例 #30
0
ファイル: __init__.py プロジェクト: closeio/burlybeetle
def script(path):
    """
    Copy and run the given script *while the service is down*

    Useful for when you need to make adjustments to the service between stop
    and start. This script gets copied to all the target nodes, turned on the
    execution bit, then called without any parameters.

    Arguments:

    * ``path``: Path to the local file to be uploaded. This file has to exist
      and will be uploaded to a temporary location (which will be cleaned up
      upon exit)

    """

    fp = os.path.abspath(os.path.expanduser(path))
    if not os.path.isfile(fp):
        raise IOError('Local script {} is not a file'.format(fp))

    remote_dir = os.path.join(
        tempfile.gettempdir(), 'burlybeetle',
        env.service_name, env.timestamp,
    )
    env.script_file = os.path.join(remote_dir, os.path.basename(fp))
    if env.commit:
        run('mkdir -pv {}'.format(remote_dir))
        put(fp, env.script_file)
        run('chmod -v +x {}'.format(env.script_file))
    else:
        utils.puts('put (noop): {} -> {}'.format(fp, env.script_file))