Initialize server configuration and given+required services for embedded running.
480477
private void initEmbedded(String[] args, String[] services) {
        if (m_bInitialized) {
            m_logger.warn("initEmbedded: Already initialized -- ignoring");
            return;
        }
        m_logger.info("Initializing embedded mode");
        initConfig(args);
        initEmbeddedServices(services);
        RESTService.instance().registerCommands(CMD_CLASSES);
        m_bInitialized = true;
    }
1327532
def init(name, runtime):
    """"""
    runtime = click.unstyle(runtime)

    stdout.write(
        style.format_command(
            'Initializing',
            '%s %s %s' % (name, style.gray('@'), style.green(runtime))
        )
    )

    config = Config(os.getcwd())
    config.set('runtime', runtime)
    config.save()

    generate.main(['init', name], standalone_mode=False)
    run.main(['python', 'manage.py', 'migrate'])
920946
public function init()
    {
        if ($this->isEnabled()) {
            $this->client = \PHPDaemon\Clients\Valve\Pool::getInstance();
            $this->db = \MongoClient::getInstance();
            $this->servers = $this->db->{$this->config->dbname->value . '.servers'};
        }
    }
681836
def initialize(self, runtime):
        """"""
        from .primitives import Id
        if self._runtime is not None:
            raise IllegalState('Manager has already been initialized')
        self._runtime = runtime
        config = runtime.get_configuration()
        parameter_id = Id('parameter:resourceProviderImpl@dlkit_service')
        provider_impl = config.get_value_by_parameter(parameter_id).get_string_value()
        if self._proxy is None:
            # need to add version argument
            self._provider_manager = runtime.get_manager('RESOURCE', provider_impl)
        else:
            # need to add version argument
            self._provider_manager = runtime.get_proxy_manager('RESOURCE', provider_impl)
1331429
private void init() {
    host = DEFAULT_HOST;
    port = DEFAULT_PORT;
    database = DEFAULT_DATABASE;
    user = DEFAULT_USER;
    password = DEFAULT_PASSWORD;
    cachePreparedStatements = DEFAULT_CACHE_PREPARED_STATEMENTS;
    pipeliningLimit = DEFAULT_PIPELINING_LIMIT;
    sslMode = DEFAULT_SSLMODE;
  }
979656
private void init(Configuration pConfig) {
        // Central objects
        converters = new Converters();
        initLimits(pConfig);

        // Create and remember request dispatchers
        localDispatcher = new LocalRequestDispatcher(converters,
                                                     restrictor,
                                                     pConfig,
                                                     logHandler);
        ServerHandle serverHandle = localDispatcher.getServerHandle();
        requestDispatchers = createRequestDispatchers(pConfig, converters,serverHandle,restrictor);
        requestDispatchers.add(localDispatcher);

        // Backendstore for remembering agent state
        initMBeans(pConfig);

        agentDetails.setServerInfo(serverHandle.getVendor(),serverHandle.getProduct(),serverHandle.getVersion());
    }
63809
private void startDbServer() {
        final String mode = Config.getInstance().getProperty(Config.AlpineKey.DATABASE_MODE);
        final int port = Config.getInstance().getPropertyAsInt(Config.AlpineKey.DATABASE_PORT);

        if (StringUtils.isEmpty(mode) || !("server".equals(mode) || "embedded".equals(mode) || "external".equals(mode))) {
            LOGGER.error("Database mode not specified. Expected values are 'server', 'embedded', or 'external'");
        }

        if (dbServer != null || "embedded".equals(mode) || "external".equals(mode)) {
            return;
        }
        final String[] args = new String[] {
                "-tcp",
                "-tcpPort", String.valueOf(port),
                "-tcpAllowOthers",
        };
        try {
            LOGGER.info("Attempting to start database service");
            dbServer = Server.createTcpServer(args).start();
            LOGGER.info("Database service started");
        } catch (SQLException e) {
            LOGGER.error("Unable to start database service: " + e.getMessage());
            stopDbServer();
        }
    }
1088586
private function initSessionConfig():void
    {
        if (!defined("IUMIO_ENV")) {
            throw new Server500(new \ArrayObject(array("explain" => "Framework Environment is not defined",
                "solution" => "Please initialize the framework environment")));
        }
        if (false === Server::exist(IUMIO_ROOT."/elements/cache/".strtolower(IUMIO_ENV)."/sessions")) {
            Server::create(IUMIO_ROOT."/elements/cache/".
                strtolower(IUMIO_ENV)."/sessions", "directory");
        }

        $this->id = session_id();
        $this->name = session_name();
        if (!$this->isStarted()) {
            session_save_path(IUMIO_ROOT . '/elements/cache/' . strtolower(IUMIO_ENV) . '/sessions');
            ini_set('session.gc_probability', 1);
        }
    }
684545
public void initServices() {
    initService(repositoryService);
    initService(runtimeService);
    initService(historyService);
    initService(taskService);
    initService(managementService);
    initService(dynamicBpmnService);
  }
251050
protected function beforeInit()
	{
	    // load default config
	    Config::setDefault(DefaultConfig::common());
	    
	    // load common config: /common/config/config.php
	    Config::load('config');
	    
	    // autoload common class: /common/src/...
	    $ns = Config::getCommon('commonNamespace', 'Common');
	    $ns = trim($ns, '\\') . '\\';
	    Ioc::loader()->setPsr4($ns, Config::getCommonPath() . 'src');
	    
	    // init namespaces: load or init
	    Ioc::initNamespace();
	}
309585
def init(self):
        
        # check for existing environment. Only allow subsequent
        # 'mlaunch init' if they are identical.
        if self._load_parameters():
            if self.loaded_args != self.args:
                raise SystemExit('A different environment already exists '
                                 'at %s.' % self.dir)
            first_init = False
        else:
            first_init = True

        self.ssl_pymongo_options = self._get_ssl_pymongo_options(self.args)

        if (self._get_ssl_server_args() and not
                self.args['sslAllowConnectionsWithoutCertificates'] and not
                self.args['sslClientCertificate'] and not
                self.args['sslClientPEMKeyFile']):
            sys.stderr.write('warning: server requires certificates but no'
                             ' --sslClientCertificate provided\n')

        # number of default config servers
        if self.args['config'] == -1:
            self.args['config'] = 1

        # Check if config replicaset is applicable to this version
        current_version = self.getMongoDVersion()

        # Exit with error if --csrs is set and MongoDB < 3.1.0
        if (self.args['csrs'] and
                LooseVersion(current_version) < LooseVersion("3.1.0") and
                LooseVersion(current_version) != LooseVersion("0.0.0")):
            errmsg = (" \n * The '--csrs' option requires MongoDB version "
                      "3.2.0 or greater, the current version is %s.\n"
                      % current_version)
            raise SystemExit(errmsg)

        # add the 'csrs' parameter as default for MongoDB >= 3.3.0
        if (LooseVersion(current_version) >= LooseVersion("3.3.0") or
                LooseVersion(current_version) == LooseVersion("0.0.0")):
            self.args['csrs'] = True

        # construct startup strings
        self._construct_cmdlines()

        # write out parameters
        if self.args['verbose']:
            print("writing .mlaunch_startup file.")
        self._store_parameters()

        # exit if running in testing mode
        if self.test:
            sys.exit(0)

        # check if authentication is enabled, make key file
        if self.args['auth'] and first_init:
            if not os.path.exists(self.dir):
                os.makedirs(self.dir)
            keyfile = os.path.join(self.dir, "keyfile")
            os.system('openssl rand -base64 753 > %s' % keyfile)
            if os.name != 'nt':
                os.system('chmod 600 %s' % keyfile)

        # if not all ports are free, complain and suggest alternatives.
        all_ports = self.get_tagged(['all'])
        ports_avail = self.wait_for(all_ports, 1, 1, to_start=False)

        if not all(map(itemgetter(1), ports_avail)):
            dir_addon = (' --dir %s' % self.relative_dir
                         if self.relative_dir != './data' else '')
            errmsg = ('\nThe following ports are not available: %s\n\n'
                      % ', '.join([str(p[0])
                                   for p in ports_avail if not p[1]]))
            errmsg += (" * If you want to restart nodes from this "
                       "environment, use 'mlaunch start%s' instead.\n"
                       % dir_addon)
            errmsg += (" * If the ports are used by a different mlaunch "
                       "environment, stop those first with 'mlaunch stop "
                       "--dir <env>'.\n")
            errmsg += (" * You can also specify a different port range with "
                       "an additional '--port <startport>'\n")
            raise SystemExit(errmsg)

        if self.args['sharded']:

            shard_names = self._get_shard_names(self.args)

            # start mongod (shard and config) nodes and wait
            nodes = self.get_tagged(['mongod', 'down'])
            self._start_on_ports(nodes, wait=True, override_auth=True)

            # initiate replica sets if init is called for the first time
            if first_init:
                if self.args['csrs']:
                    # Initiate config servers in a replicaset
                    if self.args['verbose']:
                        print('Initiating config server replica set.')
                    members = sorted(self.get_tagged(["config"]))
                    self._initiate_replset(members[0], "configRepl")
                for shard in shard_names:
                    # initiate replica set on first member
                    if self.args['verbose']:
                        print('Initiating shard replica set %s.' % shard)
                    members = sorted(self.get_tagged([shard]))
                    self._initiate_replset(members[0], shard)

            # add mongos
            mongos = sorted(self.get_tagged(['mongos', 'down']))
            self._start_on_ports(mongos, wait=True, override_auth=True)

            if first_init:
                # add shards
                mongos = sorted(self.get_tagged(['mongos']))
                con = self.client('localhost:%i' % mongos[0])

                shards_to_add = len(self.shard_connection_str)
                nshards = con['config']['shards'].count()
                if nshards < shards_to_add:
                    if self.args['replicaset']:
                        print("adding shards. can take up to 30 seconds...")
                    else:
                        print("adding shards.")

                shard_conns_and_names = list(zip(self.shard_connection_str,
                                                 shard_names))
                while True:
                    try:
                        nshards = con['config']['shards'].count()
                    except Exception:
                        nshards = 0
                    if nshards >= shards_to_add:
                        break

                    for conn_str, name in shard_conns_and_names:
                        try:
                            res = con['admin'].command(SON([('addShard',
                                                             conn_str),
                                                       ('name', name)]))
                        except Exception as e:
                            if self.args['verbose']:
                                print('%s will retry in a moment.' % e)
                            continue

                        if res['ok']:
                            if self.args['verbose']:
                                print("shard %s added successfully" % conn_str)
                                shard_conns_and_names.remove((conn_str, name))
                                break
                        else:
                            if self.args['verbose']:
                                print(res + ' - will retry')

                    time.sleep(1)

        elif self.args['single']:
            # just start node
            nodes = self.get_tagged(['single', 'down'])
            self._start_on_ports(nodes, wait=False)

        elif self.args['replicaset']:
            # start nodes and wait
            nodes = sorted(self.get_tagged(['mongod', 'down']))
            self._start_on_ports(nodes, wait=True)

            # initiate replica set
            if first_init:
                self._initiate_replset(nodes[0], self.args['name'])

        # wait for all nodes to be running
        nodes = self.get_tagged(['all'])
        self.wait_for(nodes)

        # now that nodes are running, add admin user if authentication enabled
        if self.args['auth'] and self.args['initial-user'] and first_init:
            self.discover()
            nodes = []

            if self.args['sharded']:
                nodes = self.get_tagged(['mongos', 'running'])
            elif self.args['single']:
                nodes = self.get_tagged(['single', 'running'])
            elif self.args['replicaset']:
                print("waiting for primary to add a user.")
                if self._wait_for_primary():
                    nodes = self.get_tagged(['primary', 'running'])
                else:
                    raise RuntimeError("failed to find a primary, so adding "
                                       "admin user isn't possible")

            if not nodes:
                raise RuntimeError("can't connect to server, so adding admin "
                                   "user isn't possible")

            roles = []
            found_cluster_admin = False
            if self.args['auth_role_docs']:
                for role_str in self.args['auth_roles']:
                    role_doc = json.loads(role_str)
                    roles.append(role_doc)
                    if role_doc['role'] == "clusterAdmin":
                        found_cluster_admin = True
            else:
                roles = self.args['auth_roles']
                found_cluster_admin = "clusterAdmin" in roles

            if not found_cluster_admin:
                warnings.warn("the stop command will not work with auth "
                              "because the user does not have the "
                              "clusterAdmin role")

            self._add_user(sorted(nodes)[0], name=self.args['username'],
                           password=self.args['password'],
                           database=self.args['auth_db'],
                           roles=roles)

            if self.args['sharded']:
                for shard in shard_names:
                    members = sorted(self.get_tagged([shard]))
                    if self.args['verbose']:
                        print("adding users to %s" % shard)
                    self._add_user(members[0],
                                   name=self.args['username'],
                                   password=self.args['password'],
                                   database=self.args['auth_db'],
                                   roles=roles)

            if self.args['verbose']:
                print("added user %s on %s database" % (self.args['username'],
                                                        self.args['auth_db']))

        # in sharded env, if --mongos 0, kill the dummy mongos
        if self.args['sharded'] and self.args['mongos'] == 0:
            port = self.args['port']
            print("shutting down temporary mongos on localhost:%s" % port)
            username = self.args['username'] if self.args['auth'] else None
            password = self.args['password'] if self.args['auth'] else None
            authdb = self.args['auth_db'] if self.args['auth'] else None
            shutdown_host(port, username, password, authdb)

        # discover again, to get up-to-date info
        self.discover()

        # for sharded authenticated clusters, restart after first_init
        # to enable auth
        if self.args['sharded'] and self.args['auth'] and first_init:
            if self.args['verbose']:
                print("restarting cluster to enable auth...")
            self.restart()

        if self.args['auth'] and self.args['initial-user']:
            print('Username "%s", password "%s"'
                  % (self.args['username'], self.args['password']))

        if self.args['verbose']:
            print("done.")
712441
protected function _init() {
		if (!$this->_config['host']) {
			throw new ConfigException('No host configured.');
		}

		if (HostString::isSocket($this->_config['host'])) {
			$this->_config['dsn'] = sprintf(
				'mysql:unix_socket=%s;dbname=%s',
				$this->_config['host'],
				$this->_config['database']
			);
		} else {
			$host = HostString::parse($this->_config['host']) + [
				'host' => static::DEFAULT_HOST,
				'port' => static::DEFAULT_PORT
			];
			$this->_config['dsn'] = sprintf(
				'mysql:host=%s;port=%s;dbname=%s',
				$host['host'],
				$host['port'],
				$this->_config['database']
			);
		}
		parent::_init();

		$this->_operators += [
			'REGEXP' => [],
			'NOT REGEXP' => [],
			'SOUNDS LIKE' => []
		];
	}
912614
private void initServices(Set<String> serviceSet) {
        for (String serviceName : serviceSet) {
            Service service = initService(serviceName);
            m_initializedServices.add(service);
            if (service instanceof StorageService) {
                m_storageServices.add((StorageService) service);
            }
        }
        if (m_storageServices.size() == 0) {
            throw new RuntimeException("No storage services were configured");
        }
    }
664542
protected function initializeBaseServices()
    {
        foreach ($this->serviceClass as $serviceClass) {
            $this->container->register($serviceClass::getServiceName(), $serviceClass);
        }
    }
250414
protected void initConfiguration() {
        getTomcat().setBaseDir(baseDir.getAbsolutePath());

        // Setup HTTP port listening
        getTomcat().setPort(getConfig().getPort());

        // Setup vaadin production mode
        getContext().addParameter(PRODUCTION_MODE_PARAM, String.valueOf(getConfig().isProductionMode()));
    }
145785
protected static function initConfiguration()
    {
        $caching   = self::$registry->getParameter('doozr.kernel.caching');
        $namespace = self::$registry->getParameter('doozr.namespace.flat').'.cache.configuration';

        $cache = Doozr_Loader_Serviceloader::load(
            'cache',
            self::$registry->getParameter('doozr.kernel.caching.container'),
            $namespace,
            [],
            self::$registry->getParameter('doozr.unix'),
            $caching
        );

        // Wire the required instances ...
        self::$registry->getContainer()->getMap()->wire(
            [
                'doozr.configuration.reader.json' => new Doozr_Configuration_Reader_Json(
                    Doozr_Loader_Serviceloader::load('filesystem'),
                    $cache,
                    $caching
                ),
                'doozr.cache.service' => $cache,
            ]
        );

        $configuration = self::$registry->getContainer()->build(
            'doozr.configuration',
            [
                $caching,
            ]
        );

        // Read Kernel configuration
        $configuration->read(
            self::$registry->getPath()->get('configuration').'.config.json'
        );

        // Retrieve list of service configuration files and read them ...
        $serviceConfigurationFiles = self::retrieveServiceConfigurationFiles();

        foreach ($serviceConfigurationFiles as $serviceConfigurationFile) {
            $configuration->read($serviceConfigurationFile);
        }

        // Retrieve list of userland configuration files and read them ...
        $userlandConfigurationFiles = self::retrieveUserlandConfigurationFiles();

        foreach ($userlandConfigurationFiles as $userlandConfigurationFile) {
            $configuration->read($userlandConfigurationFile);
        }

        // Store configuration
        self::$registry->setConfiguration($configuration);

        // Check if debugging is enabled ...
        if (true === self::$registry->getParameter('doozr.kernel.debugging')) {

            // Now add a collector for configuration
            self::$registry->getDebugbar()->addCollector(
                new DebugBar\DataCollector\ConfigCollector(
                    json_decode(json_encode(self::$registry->getConfiguration()->get()), true)
                )
            );
        }

        // Important for bootstrap result
        return true;
    }
741798
def initialize(template, service_name, environment='dev'):
    
    template.SERVICE_NAME = os.getenv('SERVICE_NAME', service_name)
    template.SERVICE_ENVIRONMENT = os.getenv('ENV', environment).lower()
    template.DEFAULT_TAGS = troposphere.Tags(**{
        'service-name': template.SERVICE_NAME,
        'environment': template.SERVICE_ENVIRONMENT
    })
    template.add_version("2010-09-09")
    template.add_description("Stack for %s microservice" % service_name)