Deploys a new satellite app over any existing app
556475
def launch_satellite(cli):
    """"""

    cli.info("Launching skypipe satellite:")

    finish = wait_for("    Pushing to dotCloud")

    # destroy any existing satellite
    destroy_satellite(cli)

    # create new satellite app
    url = '/applications'
    try:
        cli.user.post(url, {
            'name': APPNAME,
            'flavor': 'sandbox'
            })
    except RESTAPIError as e:
        if e.code == 409:
            cli.die('Application "{0}" already exists.'.format(APPNAME))
        else:
            cli.die('Creating application "{0}" failed: {1}'.format(APPNAME, e))
    class args: application = APPNAME
    #cli._connect(args)

    # push satellite code
    protocol = 'rsync'
    url = '/applications/{0}/push-endpoints{1}'.format(APPNAME, '')
    endpoint = cli._select_endpoint(cli.user.get(url).items, protocol)
    class args: path = satellite_path
    cli.push_with_rsync(args, endpoint)

    # tell dotcloud to deploy, then wait for it to finish
    revision = None
    clean = False
    url = '/applications/{0}/deployments'.format(APPNAME)
    response = cli.user.post(url, {'revision': revision, 'clean': clean})
    deploy_trace_id = response.trace_id
    deploy_id = response.item['deploy_id']


    original_stdout = sys.stdout

    finish = wait_for("    Waiting for deployment", finish, original_stdout)

    try:
        sys.stdout = StringIO()
        res = cli._stream_deploy_logs(APPNAME, deploy_id,
                deploy_trace_id=deploy_trace_id, follow=True)
        if res != 0:
            return res
    except KeyboardInterrupt:
        cli.error('You\'ve closed your log stream with Ctrl-C, ' \
            'but the deployment is still running in the background.')
        cli.error('If you aborted because of an error ' \
            '(e.g. the deployment got stuck), please e-mail\n' \
            'support@dotcloud.com and mention this trace ID: {0}'
            .format(deploy_trace_id))
        cli.error('If you want to continue following your deployment, ' \
                'try:\n{0}'.format(
                    cli._fmt_deploy_logs_command(deploy_id)))
        cli.die()
    except RuntimeError:
        # workaround for a bug in the current dotcloud client code
        pass
    finally:
        sys.stdout = original_stdout

    finish = wait_for("    Satellite coming online", finish)

    endpoint = lookup_endpoint(cli)
    ok = client.check_skypipe_endpoint(endpoint, 120)
   
    finish.set()
    time.sleep(0.1) # sigh, threads

    if ok:
        return endpoint
    else:
        cli.die("Satellite failed to come online")
1081736
def create_app(app_id, app_name, source_id, region, app_data):
    
    try:
        create_at = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        conn = get_conn()
        c = conn.cursor()

        #check old app
        c.execute("SELECT count(*) FROM app WHERE name='{0}' ".format(app_name))
        old_app = c.fetchone()
        if old_app[0] > 0:
            print 'app name (%s) already existed, clear old app and container info ...' % app_name
            c.execute("DELETE FROM container WHERE app_id='{0}'".format(app_id))
            c.execute("DELETE FROM app WHERE name='{0}'".format(app_name))
            conn.commit()

        #insert new app
        c.execute("INSERT INTO app (id,name,source_id,region,state,create_at,change_at,app_data) VALUES ('{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}')"
            .format(app_id, app_name, source_id, region, constant.STATE_APP_RUNNING, create_at, create_at, app_data))
        conn.commit()
        conn.close()
        print 'create app %s succeed!' % app_id
    except Exception, e:
        raise RuntimeError('create app %s failed! %s' % (app_id,e))
1237689
def deploy(project, version, promote, quiet):
    
    from . import logic

    logic.deploy(project, version, promote, quiet)
392643
function create(appName, callback) {
    commons.post(format('/%s/apps/', deis.version), {
      id: appName
    }, callback);
  }
588779
def load_app(target):
    
    global NORUN
    NORUN, nr_old = True, NORUN
    tmp = default_app.push()  # Create a new "default application"
    try:
        rv = load(target)  # Import the target module
        return rv if callable(rv) else tmp
    finally:
        default_app.remove(tmp)  # Remove the temporary added default application
        NORUN = nr_old
1086771
def setup_app(command, conf, vars):
    """"""
    load_environment(conf.global_conf, conf.local_conf)

    # Merge and minify JavaScript code
    input_file = config['js_tmpl']
    public_dir = config['pylons.paths']['static_files']
    output_file = os.path.join(public_dir, 'js', 'Studio', 'studio-all.js')
    _merge_js(input_file, public_dir, output_file)
    log.info('JavaScript successfully merged and minified in ' + output_file)

    # Load the models
    from studio.model import meta
    meta.metadata.bind = meta.engine

    filename = os.path.split(conf.filename)[-1]
    if filename == 'test.ini':
        # Permanently drop any existing tables
        log.info("Dropping existing tables...")
        meta.metadata.drop_all(checkfirst=True)

    # Create the tables if they aren't there already
    meta.metadata.create_all(checkfirst=True)

    # Create permissions
    # datastores permissions
    perm_create_update_datastores = model.Permission()
    perm_create_update_datastores.name = 'create_update_datastores'
    meta.Session.add(perm_create_update_datastores)
    perm_view_datastores = model.Permission()
    perm_view_datastores.name = 'view_datastores'
    meta.Session.add(perm_view_datastores)
    # datasources permissions
    perm_view_datasources = model.Permission()
    perm_view_datasources.name = 'view_datasources'
    meta.Session.add(perm_view_datasources)
    perm_create_datasources = model.Permission()
    perm_create_datasources.name = 'create_datasources'
    meta.Session.add(perm_create_datasources)
    # mapfiles permissions
    perm_create_update_mapfiles = model.Permission()
    perm_create_update_mapfiles.name = 'create_update_mapfiles'
    meta.Session.add(perm_create_update_mapfiles)
    perm_view_mapfiles = model.Permission()
    perm_view_mapfiles.name = 'view_mapfiles'
    meta.Session.add(perm_view_mapfiles)
    # layertemplates permissions
    perm_create_update_layertemplates = model.Permission()
    perm_create_update_layertemplates.name = 'create_update_layertemplates'
    meta.Session.add(perm_create_update_layertemplates)
    perm_view_layertemplates = model.Permission()
    perm_view_layertemplates.name = 'view_layertemplates'
    meta.Session.add(perm_view_layertemplates)

    # Create group admin
    admin_gp = model.Group()
    admin_gp.name = 'admin'
    admin_gp.permissions.append(perm_create_update_datastores)
    admin_gp.permissions.append(perm_view_datastores)
    admin_gp.permissions.append(perm_view_datasources)
    admin_gp.permissions.append(perm_create_datasources)
    admin_gp.permissions.append(perm_create_update_mapfiles)
    admin_gp.permissions.append(perm_view_mapfiles)
    admin_gp.permissions.append(perm_create_update_layertemplates)
    admin_gp.permissions.append(perm_view_layertemplates)
    meta.Session.add(admin_gp)

    # Create group enduser
    enduser_gp = model.Group()
    enduser_gp.name = 'enduser'
    enduser_gp.permissions.append(perm_view_datastores)
    enduser_gp.permissions.append(perm_view_datasources)
    enduser_gp.permissions.append(perm_create_update_mapfiles)
    enduser_gp.permissions.append(perm_view_mapfiles)
    enduser_gp.permissions.append(perm_create_update_layertemplates)
    enduser_gp.permissions.append(perm_view_layertemplates)
    meta.Session.add(enduser_gp)

    # Create user admin
    admin = model.User()
    admin.name = 'Admin'
    admin.login = 'admin'
    admin.password = config['admin_password']
    admin.groups.append(admin_gp)
    meta.Session.add(admin)

    if filename == 'test.ini':
        # create enduser user for test purpose only
        enduser = model.User()
        enduser.name = 'Test User'
        enduser.login = 'enduser'
        enduser.password = 'password'
        enduser.groups.append(enduser_gp)
        meta.Session.add(enduser)

    mfdir = config['mapfiles_dir']
    if not os.path.exists(mfdir):
        os.makedirs(mfdir, 0755)

    if 'default_datastore_postgis' in config:
        # Create default datastore
        datastore = model.DataStore('default (postgis)', 'postgis', config['default_datastore_postgis'])
        meta.Session.add(datastore)
        meta.Session.flush()

    if 'default_datastore_dir' in config:
        # Create default datastore
        datastore = model.DataStore('default (directory)', 'directory', config['default_datastore_dir'])
        meta.Session.add(datastore)
        meta.Session.flush()

        # Create dummy mapfile
        mapfile = create_default_mapfile()
        dict = mapfile.to_dict()
        ds = DataStore(datastore.ogrstring)
        dsources = ds.get_datasources()
        palette = QualitativePalette(len(dsources)).get_palette()
        for dss in dsources:
            if dss.type == 'RASTER':
                print "adding %s datasource"%dss.name
                l = _make_mapfile_layer(datastore.id,dss)
                if 'projection' in l:
                    dict['projection'] = l['projection']
                dict['layers'].append(l)
        for dss in dsources:
            if dss.type == 'POLYGON':
                print "adding %s datasource"%dss.name
                color = palette.pop(0)
                l = _make_mapfile_layer(datastore.id,dss)
                if 'projection' in l:
                    dict['projection'] = l['projection']
                l['classes'][0]['styles'][0]['color']=color
                dict['layers'].append(l)
        for dss in dsources:
            if dss.type == 'LINE':
                print "adding %s datasource"%dss.name
                color = palette.pop(0)
                l = _make_mapfile_layer(datastore.id,dss)
                if 'projection' in l:
                    dict['projection'] = l['projection']
                l['classes'][0]['styles'][0]['color']=color
                dict['layers'].append(l)
        for dss in dsources:
            if dss.type == 'POINT':
                print "adding %s datasource"%dss.name
                color = palette.pop(0)
                l = _make_mapfile_layer(datastore.id,dss)
                if 'projection' in l:
                    dict['projection'] = l['projection']
                l['classes'][0]['styles'][0]['color']=color
                dict['layers'].append(l)
        if 'projection' not in dict:
            dict['projection']="init=epsg:4326"
        mapfile.from_dict(dict)
        mapfile.to_file(os.path.join(config['mapfiles_dir'], 'dummy_mapfile.map'))

        # Create dummy_mapfile in db, owned by user 'admin'
        map = model.Map('dummy_mapfile', 'dummy_mapfile.map', 1)
        model.meta.Session.add(map)

    # Commit the new objects into the database
    meta.Session.commit()

    log.info("Data successfully set up")
56327
def setup(cls, app):  # pragma: no cover
        """"""
        if cls.directive_name is None:
            raise NotImplementedError('directive_name must be set by '
                                      'subclasses of BaseDirective')
        if not app.registry.has_domain('http'):
            setup_httpdomain(app)
        app.add_config_value('{}_harness'.format(cls.directive_name),
                             None, 'env')
        app.add_directive(cls.directive_name, cls)
        app.connect('builder-inited', cls.run_setup)
        app.connect('build-finished', cls.run_teardown)
        app.connect('env-get-outdated', cls.get_outdated_docs)
        app.connect('env-purge-doc', cls.purge_docs)
119732
def setup_app(app, throw=True):
    
    success = True
    try:
        for func in SETUP_FUNCS:
            try:
                func(app)
            except Exception:
                success = False
                if throw:
                    raise
                else:
                    msg = "Failed to run setup function %r(app)"
                    logger.exception(msg, func.__name__)
    finally:
        setattr(app, 'is_set_up', success)
993113
def apps_installation_create(self, data, **kwargs):
        ""
        api_path = "/api/v2/apps/installations.json"
        return self.call(api_path, method="POST", data=data, **kwargs)
1175032
private function executeInstaller()
    {
        $oInput  = $this->oInput;
        $oOutput = $this->oOutput;

        // --------------------------------------------------------------------------

        $oOutput->writeln('');
        $oOutput->writeln('<info>---------------</info>');
        $oOutput->writeln('<info>Nails Installer</info>');
        $oOutput->writeln('<info>---------------</info>');
        $oOutput->writeln('');

        // --------------------------------------------------------------------------

        //  Define app & deploy vars
        $appVars    = $this->defineAppVars();
        $deployVars = $this->defineDeployVars();

        // --------------------------------------------------------------------------

        //  Pre-Install tests
        $preTestErrors = $this->preInstallTests();

        // --------------------------------------------------------------------------

        if (empty($preTestErrors)) {

            if ($oInput->isInteractive()) {
                $oOutput->writeln('');
                $oOutput->writeln('<info>App Settings</info>');
                $this->setVars($appVars);

                // --------------------------------------------------------------------------

                $oOutput->writeln('');
                $oOutput->writeln('<info>Deploy Settings</info>');
                $this->setVars($deployVars);
            }

            // --------------------------------------------------------------------------

            //  Tell user what's about to happen
            $oOutput->writeln('');
            $oOutput->writeln('<info>I\'m about to do the following:</info>');

            //  app.php
            $oOutput->writeln('');
            $oOutput->writeln('1) Write <info>config/app.php</info>');

            foreach ($appVars as &$v) {

                if (is_string($v)) {
                    continue;
                }

                $sValue = $v['value'] ?: '<blank>';
                $oOutput->writeln(' - Set <comment>' . $v['label'] . '</comment> to <comment>' . $sValue . '</comment>');
            }

            //  deploy.php
            $oOutput->writeln('');
            $oOutput->writeln('2) Write <info>config/deploy.php</info>');

            foreach ($deployVars as &$v) {

                if (is_string($v)) {
                    continue;
                }

                $sValue = $v['value'] ?: '<blank>';
                $oOutput->writeln(' - Set <comment>' . $v['label'] . '</comment> to <comment>' . $sValue . '</comment>');
            }

            //  Migrate database and rewrite routes
            $oOutput->writeln('');
            $oOutput->writeln('3) Migrate the database');
            $oOutput->writeln('4) Rewrite app routes');

            $oOutput->writeln('');
            $question  = 'Does this look OK?';
            $doInstall = $this->confirm($question, true);

            if ($doInstall) {

                $curStep  = 1;
                $numSteps = 1;  //  app.php
                $numSteps += 1; //  deploy.php
                $numSteps += 1; //  migrate DB
                $numSteps += 1; //  rewrite routes
                $numSteps += !empty($users) ? 1 : 0;

                $oOutput->writeln('');
                $oOutput->writeln('<info>Installing...</info>');

                //  Write app.php
                $oOutput->write('<comment>[' . $curStep . '/' . $numSteps . ']</comment> Writing <info>config/app.php</info>... ');
                if ($this->writeFile($appVars, 'config/app.php')) {
                    $oOutput->writeln('<info>done!</info>');
                } else {
                    $oOutput->writeln('<error>failed!</error>');
                }
                $curStep++;

                //  Write deploy.php
                $oOutput->write('<comment>[' . $curStep . '/' . $numSteps . ']</comment> Writing <info>config/deploy.php</info>... ');
                if ($this->writeFile($deployVars, 'config/deploy.php')) {
                    $oOutput->writeln('<info>done!</info>');
                } else {
                    $oOutput->writeln('<error>failed!</error>');
                }
                $curStep++;

                /**
                 * Get the current database credential values. If an existing deploy.php is already there then
                 * we can't rely on it having the latest details (as it might have just been updated).
                 */

                $dbHost = $this->getVarValue('DEPLOY_DB_HOST', $deployVars);
                $dbUser = $this->getVarValue('DEPLOY_DB_USERNAME', $deployVars);
                $dbPass = $this->getVarValue('DEPLOY_DB_PASSWORD', $deployVars);
                $dbName = $this->getVarValue('DEPLOY_DB_DATABASE', $deployVars);

                Factory::setProperty('DB_HOST', $dbHost);
                Factory::setProperty('DB_USERNAME', $dbUser);
                Factory::setProperty('DB_PASSWORD', $dbPass);
                Factory::setProperty('DB_DATABASE', $dbName);

                //  Migrate DB
                $oOutput->write('<comment>[' . $curStep . '/' . $numSteps . ']</comment> Migrating database... ');
                $this->migrateDb($dbHost, $dbUser, $dbPass, $dbName);
                $curStep++;

                //  Rewrite routes
                $oOutput->write('<comment>[' . $curStep . '/' . $numSteps . ']</comment> Rewriting routes... ');
                $this->rewriteRoutes();

                // --------------------------------------------------------------------------

                //  Cleaning up
                $oOutput->writeln('');
                $oOutput->writeln('<comment>Cleaning up...</comment>');

                //  And we're done!
                $oOutput->writeln('');
                $oOutput->writeln('Complete!');

                return self::EXIT_CODE_SUCCESS;

            } else {
                return $this->abort();
            }

        } else {

            $exitCode = $this->abort();

            foreach ($preTestErrors as $error) {
                $oOutput->writeln(' - ' . $error);
            }

            return $exitCode;
        }
    }
1040858
function(app, opts) {
  this.app = app;
  this.opts = opts;
  this.client = genRpcClient(this.app, opts);
  this.app.event.on(events.ADD_SERVERS, this.addServers.bind(this));
  this.app.event.on(events.REMOVE_SERVERS, this.removeServers.bind(this));
  this.app.event.on(events.REPLACE_SERVERS, this.replaceServers.bind(this));
}
249303
def install(self):
        """"""
        super(Upstart, self).install()

        self.deploy_service_file(self.svc_file_path, self.svc_file_dest)
764298
function createApplication() {
  var app = connect();
  utils.merge(app, proto);
  app.request = { __proto__: req };
  app.response = { __proto__: res };
  app.init();
  return app;
}
1336532
def deploy(self, package=None):
        
        if package is None:
            package = deployment_package.default()
        package.deploy()
        if self.proper_name in installed_functions():
            self.update(package)
        else:
            self.install(package)
601438
def install_app(cls, id, raw, api=None, raw_format=None):
        
        api = api if api else cls._API
        raw_format = raw_format.lower() if raw_format else AppRawFormat.JSON
        extra = {
            'resource': cls.__name__,
            'query': {
                'id': id,
                'data': raw
            }
        }
        logger.info('Installing app', extra=extra)

        # Set content type for raw app data
        if raw_format not in cls._CONTENT_TYPE.keys():
            raise SbgError(
                'Unsupported raw data format: "{}".'
                .format(raw_format))
        headers = {'Content-Type': cls._CONTENT_TYPE[raw_format]}

        app = api.post(
            url=cls._URL['raw'].format(id=id),
            data=raw,
            headers=headers,
        ).json()
        app_wrapper = api.get(
            url=cls._URL['get'].format(id=app['sbg:id'])).json()
        return App(api=api, **app_wrapper)
1200488
protected function deploy()
    {
        // create deploy outputfile
        $this->createOutputFile($this->outputFile, false);

        // create undo deploy outputfile
        $this->createOutputFile($this->undoOutputFile, true);
    }
742967
def runserver(app=None, reloader=None, debug=None, host=None, port=None):
    """"""
    debug = debug or app.config.get('DEBUG', False)
    reloader = reloader or app.config.get('RELOADER', False)
    host = host or app.config.get('HOST', '127.0.0.1')
    port = port or app.config.get('PORT', 5000)
    app.run(
        use_reloader=reloader,
        debug=debug,
        host=host,
        port=port
    )