Initializes an agent at runtime and adds it to VM. Returns true if the
initialization was successful, false otherwise.
506954
public static Instrumentation initAgentAtRuntimeAndReportSuccess() {
        try {
            setSystemClassLoaderClassPath();
        } catch (Exception e) {
            Log.e("Could not set classpath. Tool will be off.", e);
            return null;
        }
        try {
            return addClassfileTransformer();
        } catch (Exception e) {
            Log.e("Could not add transformer. Tool will be off.", e);
            return null;
        }
    }
281281
public static void addNewAgent(ShanksSimulation sim, ShanksAgent agent)
            throws ShanksException {
        sim.registerShanksAgent(agent);
        if (sim.schedule.getTime() < 0) {
            sim.schedule.scheduleRepeating(Schedule.EPOCH, 2, agent, 1);
        } else {
            sim.schedule.scheduleRepeating(sim.schedule.getTime(), 2, agent, 1);
        }
        sim.logger
                .info("Added a new agent to the simulation: " + agent.getID());
    }
479915
@Override
	public void addJvmMemberInitializer(Runnable runnable) {
		if (isInitializingJvmMembers) {
			throw new IllegalStateException("Cannot enqueue runnables during JvmMemberInitialization");
		}
		if (this.jvmMemberInitializers == null) {
			this.jvmMemberInitializers = new LinkedHashSet<Runnable>();
			this.hasJvmMemberInitializers = true;
			for (EObject obj : getContents()) {
				if (obj instanceof JvmDeclaredTypeImplCustom) {
					JvmDeclaredTypeImplCustom type = (JvmDeclaredTypeImplCustom) obj;
					markPendingInitialization(type);
				}
			}
		}
		this.jvmMemberInitializers.add(runnable);
	}
625232
public void init() {
    Configuration.Builder configuration = Configuration.newBuilder();
    configuration.setStopAtScript(false);
    configuration.setStopAtAbort(false);
    configuration.setStopAtException(false);
    configuration.setStopAtError(false);
    configuration.setStopAtDebuggerStatement(false);
    configuration.setStopAtGc(false);

    executeMessage(EcmascriptDebuggerMessage.SET_CONFIGURATION, configuration);

    if (!updateRuntime()) {
      throw new ScopeException("Could not find a runtime for script injection");
    }

    // TODO: Workaround for internal dialogue
    // The dialog is finally removed but just keeping this here
    // until every platform upgrades to core 2.7+
    executeJavascript("return 1;", true);
  }
1059551
@Override
    public boolean applyAction(Model i) {
        Mapping c = i.getMapping();
        return c.isRunning(vm)
                && c.getVMLocation(vm).equals(src)
                && !src.equals(dst)
                && c.addRunningVM(vm, dst);
    }
84105
def create(vm_):
    '''
    
    '''
    try:
        # Check for required profile parameters before sending any API calls.
        if vm_['profile'] and config.is_profile_configured(__opts__,
                                                           __active_provider_name__ or 'parallels',
                                                           vm_['profile'],
                                                           vm_=vm_) is False:
            return False
    except AttributeError:
        pass

    __utils__['cloud.fire_event'](
        'event',
        'starting create',
        'salt/cloud/{0}/creating'.format(vm_['name']),
        args=__utils__['cloud.filter_event']('creating', vm_, ['name', 'profile', 'provider', 'driver']),
        sock_dir=__opts__['sock_dir'],
        transport=__opts__['transport']
    )

    log.info('Creating Cloud VM %s', vm_['name'])

    try:
        data = create_node(vm_)
    except Exception as exc:
        log.error(
            'Error creating %s on PARALLELS\n\n'
            'The following exception was thrown when trying to '
            'run the initial deployment: \n%s',
            vm_['name'], exc,
            # Show the traceback if the debug logging level is enabled
            exc_info_on_loglevel=logging.DEBUG
        )
        return False

    name = vm_['name']
    if not wait_until(name, 'CREATED'):
        return {'Error': 'Unable to start {0}, command timed out'.format(name)}
    start(vm_['name'], call='action')

    if not wait_until(name, 'STARTED'):
        return {'Error': 'Unable to start {0}, command timed out'.format(name)}

    def __query_node_data(vm_name):
        data = show_instance(vm_name, call='action')
        if 'public-ip' not in data['network']:
            # Trigger another iteration
            return
        return data

    try:
        data = salt.utils.cloud.wait_for_ip(
            __query_node_data,
            update_args=(vm_['name'],),
            timeout=config.get_cloud_config_value(
                'wait_for_ip_timeout', vm_, __opts__, default=5 * 60),
            interval=config.get_cloud_config_value(
                'wait_for_ip_interval', vm_, __opts__, default=5),
        )
    except (SaltCloudExecutionTimeout, SaltCloudExecutionFailure) as exc:
        try:
            # It might be already up, let's destroy it!
            destroy(vm_['name'])
        except SaltCloudSystemExit:
            pass
        finally:
            raise SaltCloudSystemExit(six.text_type(exc))

    comps = data['network']['public-ip']['address'].split('/')
    public_ip = comps[0]

    vm_['ssh_host'] = public_ip
    ret = __utils__['cloud.bootstrap'](vm_, __opts__)

    log.info('Created Cloud VM \'%s\'', vm_['name'])
    log.debug(
        '\'%s\' VM creation details:\n%s',
        vm_['name'], pprint.pformat(data)
    )

    __utils__['cloud.fire_event'](
        'event',
        'created instance',
        'salt/cloud/{0}/created'.format(vm_['name']),
        args=__utils__['cloud.filter_event']('created', vm_, ['name', 'profile', 'provider', 'driver']),
        sock_dir=__opts__['sock_dir'],
        transport=__opts__['transport']
    )

    return data
1253831
def initiate(self, **kwargs):
        ''''''
        run_startup = kwargs.pop('run_startup', True)

        setter = lambda value, name: setattr(self, name, value)

        d = defer.Deferred()
        d.addCallback(defer.drop_param,
                      self.agency._messaging.get_connection, self)
        d.addCallback(setter, "_messaging")
        d.addCallback(defer.drop_param,
                      self.agency._database.get_connection)
        d.addCallback(setter, '_database')
        d.addCallback(defer.drop_param,
                      self._reload_descriptor)
        d.addCallback(defer.drop_param,
                      self._subscribe_for_descriptor_changes)
        d.addCallback(defer.drop_param, self._store_instance_id)
        d.addCallback(defer.drop_param, self._load_configuration)
        d.addCallback(setter, '_configuration')
        d.addCallback(defer.drop_param,
                      self.join_shard, self._descriptor.shard)
        d.addCallback(defer.drop_param,
                      self.journal_agent_created)
        d.addCallback(defer.drop_param,
                      self._call_initiate, **kwargs)
        d.addCallback(defer.drop_param, self.call_next, self._call_startup,
                      call_startup=run_startup)
        d.addCallback(defer.override_result, self)
        d.addErrback(self._startup_error)

        # Ensure the execution chain is broken
        self.call_next(d.callback, None)

        return d
367474
void initialize() throws ManagerCommunicationException
    {
        ResponseEvents re;

        re = server.sendEventGeneratingAction(new AgentsAction());

        for (ManagerEvent event : re.getEvents())
        {
            if (event instanceof AgentsEvent)
            {
                logger.info( event );
                handleAgentsEvent((AgentsEvent) event);
            }
        }
    }
1009118
def create(vm_):
    '''
    
    '''
    try:
        if vm_['profile'] and config.is_profile_configured(
            __opts__,
            __active_provider_name__ or 'azurearm',
            vm_['profile'],
            vm_=vm_
        ) is False:
            return False
    except AttributeError:
        pass

    if vm_.get('bootstrap_interface') is None:
        vm_['bootstrap_interface'] = 'public'

    __utils__['cloud.fire_event'](
        'event',
        'starting create',
        'salt/cloud/{0}/creating'.format(vm_['name']),
        args=__utils__['cloud.filter_event'](
            'creating', vm_, ['name', 'profile', 'provider', 'driver']
        ),
        sock_dir=__opts__['sock_dir'],
        transport=__opts__['transport']
    )
    __utils__['cloud.cachedir_index_add'](
        vm_['name'], vm_['profile'], 'azurearm', vm_['driver']
    )
    if not vm_.get('location'):
        vm_['location'] = get_location(kwargs=vm_)

    log.info('Creating Cloud VM %s in %s', vm_['name'], vm_['location'])

    vm_request = request_instance(vm_=vm_)

    if not vm_request or 'error' in vm_request:
        err_message = 'Error creating VM {0}! ({1})'.format(vm_['name'], six.text_type(vm_request))
        log.error(err_message)
        raise SaltCloudSystemExit(err_message)

    def _query_node_data(name, bootstrap_interface):
        '''
        Query node data.
        '''
        data = show_instance(name, call='action')
        if not data:
            return False
        ip_address = None
        if bootstrap_interface == 'public':
            ip_address = data['public_ips'][0]
        if bootstrap_interface == 'private':
            ip_address = data['private_ips'][0]
        if ip_address is None:
            return False
        return ip_address

    try:
        data = salt.utils.cloud.wait_for_ip(
            _query_node_data,
            update_args=(vm_['name'], vm_['bootstrap_interface'],),
            timeout=config.get_cloud_config_value(
                'wait_for_ip_timeout', vm_, __opts__, default=10 * 60),
            interval=config.get_cloud_config_value(
                'wait_for_ip_interval', vm_, __opts__, default=10),
            interval_multiplier=config.get_cloud_config_value(
                'wait_for_ip_interval_multiplier', vm_, __opts__, default=1),
        )
    except (
        SaltCloudExecutionTimeout,
        SaltCloudExecutionFailure,
        SaltCloudSystemExit
    ) as exc:
        try:
            log.warning(exc)
        finally:
            raise SaltCloudSystemExit(six.text_type(exc))

    vm_['ssh_host'] = data
    if not vm_.get('ssh_username'):
        vm_['ssh_username'] = config.get_cloud_config_value(
            'ssh_username', vm_, __opts__
        )
    vm_['password'] = config.get_cloud_config_value(
        'ssh_password', vm_, __opts__
    )
    ret = __utils__['cloud.bootstrap'](vm_, __opts__)

    data = show_instance(vm_['name'], call='action')
    log.info('Created Cloud VM \'%s\'', vm_['name'])
    log.debug(
        '\'%s\' VM creation details:\n%s',
        vm_['name'],
        pprint.pformat(data)
    )

    ret.update(data)

    __utils__['cloud.fire_event'](
        'event',
        'created instance',
        'salt/cloud/{0}/created'.format(vm_['name']),
        args=__utils__['cloud.filter_event'](
            'created',
            vm_, ['name', 'profile', 'provider', 'driver']
        ),
        sock_dir=__opts__['sock_dir'],
        transport=__opts__['transport']
    )

    return ret
1030898
def create(vm_):
    '''
    
    '''
    try:
        # Check for required profile parameters before sending any API calls.
        if vm_['profile'] and config.is_profile_configured(
                __opts__,
                __active_provider_name__ or 'dimensiondata',
                vm_['profile']) is False:
            return False
    except AttributeError:
        pass

    __utils__['cloud.fire_event'](
        'event',
        'starting create',
        'salt/cloud/{0}/creating'.format(vm_['name']),
        args=__utils__['cloud.filter_event']('creating', vm_, ['name', 'profile', 'provider', 'driver']),
        sock_dir=__opts__['sock_dir'],
        transport=__opts__['transport']
    )

    log.info('Creating Cloud VM %s', vm_['name'])
    conn = get_conn()

    location = conn.ex_get_location_by_id(vm_['location'])
    images = conn.list_images(location=location)
    image = [x for x in images if x.id == vm_['image']][0]
    network_domains = conn.ex_list_network_domains(location=location)
    try:
        network_domain = [y for y in network_domains
                          if y.name == vm_['network_domain']][0]
    except IndexError:
        network_domain = conn.ex_create_network_domain(
            location=location,
            name=vm_['network_domain'],
            plan='ADVANCED',
            description=''
        )

    try:
        vlan = [y for y in conn.ex_list_vlans(
            location=location,
            network_domain=network_domain)
                if y.name == vm_['vlan']][0]
    except (IndexError, KeyError):
        # Use the first VLAN in the network domain
        vlan = conn.ex_list_vlans(
            location=location,
            network_domain=network_domain)[0]

    kwargs = {
        'name': vm_['name'],
        'image': image,
        'ex_description': vm_['description'],
        'ex_network_domain': network_domain,
        'ex_vlan': vlan,
        'ex_is_started': vm_['is_started']
    }

    event_data = _to_event_data(kwargs)

    __utils__['cloud.fire_event'](
        'event',
        'requesting instance',
        'salt/cloud/{0}/requesting'.format(vm_['name']),
        args=__utils__['cloud.filter_event']('requesting', event_data, list(event_data)),
        sock_dir=__opts__['sock_dir'],
        transport=__opts__['transport']
    )

    # Initial password (excluded from event payload)
    initial_password = NodeAuthPassword(vm_['auth'])
    kwargs['auth'] = initial_password

    try:
        data = conn.create_node(**kwargs)
    except Exception as exc:
        log.error(
            'Error creating %s on DIMENSIONDATA\n\n'
            'The following exception was thrown by libcloud when trying to '
            'run the initial deployment: \n%s',
            vm_['name'], exc,
            exc_info_on_loglevel=logging.DEBUG
        )
        return False

    try:
        data = __utils__['cloud.wait_for_ip'](
            _query_node_data,
            update_args=(vm_, data),
            timeout=config.get_cloud_config_value(
                'wait_for_ip_timeout', vm_, __opts__, default=25 * 60),
            interval=config.get_cloud_config_value(
                'wait_for_ip_interval', vm_, __opts__, default=30),
            max_failures=config.get_cloud_config_value(
                'wait_for_ip_max_failures', vm_, __opts__, default=60),
        )
    except (SaltCloudExecutionTimeout, SaltCloudExecutionFailure) as exc:
        try:
            # It might be already up, let's destroy it!
            destroy(vm_['name'])  # pylint: disable=not-callable
        except SaltCloudSystemExit:
            pass
        finally:
            raise SaltCloudSystemExit(six.text_type(exc))

    log.debug('VM is now running')
    if ssh_interface(vm_) == 'private_ips':
        ip_address = preferred_ip(vm_, data.private_ips)
    else:
        ip_address = preferred_ip(vm_, data.public_ips)
    log.debug('Using IP address %s', ip_address)

    if __utils__['cloud.get_salt_interface'](vm_, __opts__) == 'private_ips':
        salt_ip_address = preferred_ip(vm_, data.private_ips)
        log.info('Salt interface set to: %s', salt_ip_address)
    else:
        salt_ip_address = preferred_ip(vm_, data.public_ips)
        log.debug('Salt interface set to: %s', salt_ip_address)

    if not ip_address:
        raise SaltCloudSystemExit(
            'No IP addresses could be found.'
        )

    vm_['salt_host'] = salt_ip_address
    vm_['ssh_host'] = ip_address
    vm_['password'] = vm_['auth']

    ret = __utils__['cloud.bootstrap'](vm_, __opts__)

    ret.update(data.__dict__)

    if 'password' in data.extra:
        del data.extra['password']

    log.info('Created Cloud VM \'%s\'', vm_['name'])
    log.debug(
        '\'%s\' VM creation details:\n%s',
        vm_['name'], pprint.pformat(data.__dict__)
    )

    __utils__['cloud.fire_event'](
        'event',
        'created instance',
        'salt/cloud/{0}/created'.format(vm_['name']),
        args=__utils__['cloud.filter_event']('created', vm_, ['name', 'profile', 'provider', 'driver']),
        sock_dir=__opts__['sock_dir'],
        transport=__opts__['transport']
    )

    return ret
254714
public static void addTransitionInSpecificAutomaton(Agent agent,
            String automatonName, Automaton newTransition) {
        Automaton aut = agent.getAutomaton();
        while (!aut.name.equals(automatonName)) {
            if (aut.currentState == null) {
                throw new RuntimeException("Automaton " + automatonName
                        + " is not been executed in " + agent);

            }
            aut = aut.currentState;
        }
        aut.addTransition(newTransition, true);

    }
975171
public static boolean loadEkstaziAgent() {
        // TODO: need to synchronize globally, as we may end up running
        // initialization multiple times, which would lead to:
        // "libattach.so already loaded in another classloader".
        try {
            // Note that this class can be loaded by different classloaders, so
            // we cannot simply use static field to check if the class has been
            // initialized.
            if (System.getProperty(AGENT_LOADER_INIT) != null) {
                return true;
            }
            System.setProperty(AGENT_LOADER_INIT, "");

            URL agentJarURL = Types.extractJarURL(EkstaziAgent.class);
            return loadAgent(agentJarURL);
        } catch (Exception ex) {
            if (System.getProperty("java.version").startsWith("9")) {
                throw new RuntimeException("Running with Java 9 requires -Djdk.attach.allowAttachSelf=true");
            }
            return false;
        }
    }
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'])
919873
def execute_on_vm(vm, options)
      check_runable_on(vm)

      options     = options.clone
      _method     = options.delete(:_method)
      _rebootable = options.delete(:_rebootable)

      options = vm.config.vbguest.to_hash.merge(options)
      machine = VagrantVbguest::Machine.new(vm, options)
      status  = machine.state
      vm.env.ui.send((:ok == status ? :success : :warn), I18n.t("vagrant_vbguest.status.#{status}", machine.info))

      if _method != :status
        machine.send(_method)
      end

      reboot!(vm, options) if _rebootable && machine.reboot?
    rescue VagrantVbguest::Installer::NoInstallerFoundError => e
      vm.env.ui.error e.message
    end
625499
private void initMode(Map<String, String> agentConfig) {
        String mode = agentConfig.get("mode");
        if (mode != null && !mode.equals("start") && !mode.equals("stop")) {
            throw new IllegalArgumentException("Invalid running mode '" + mode + "'. Must be either 'start' or 'stop'");
        }
        isStopMode = "stop".equals(mode);
    }
73282
def create(vm_):
    '''
    
    '''
    try:
        # Check for required profile parameters before sending any API calls.
        if vm_['profile'] and config.is_profile_configured(__opts__,
                                                           __active_provider_name__ or 'joyent',
                                                           vm_['profile'],
                                                           vm_=vm_) is False:
            return False
    except AttributeError:
        pass

    key_filename = config.get_cloud_config_value(
        'private_key', vm_, __opts__, search_global=False, default=None
    )

    __utils__['cloud.fire_event'](
        'event',
        'starting create',
        'salt/cloud/{0}/creating'.format(vm_['name']),
        args=__utils__['cloud.filter_event']('creating', vm_, ['name', 'profile', 'provider', 'driver']),
        sock_dir=__opts__['sock_dir'],
        transport=__opts__['transport']
    )

    log.info(
        'Creating Cloud VM %s in %s',
        vm_['name'], vm_.get('location', DEFAULT_LOCATION)
    )

    # added . for fqdn hostnames
    salt.utils.cloud.check_name(vm_['name'], 'a-zA-Z0-9-.')
    kwargs = {
        'name': vm_['name'],
        'image': get_image(vm_),
        'size': get_size(vm_),
        'location': vm_.get('location', DEFAULT_LOCATION)
    }
    # Let's not assign a default here; only assign a network value if
    # one is explicitly configured
    if 'networks' in vm_:
        kwargs['networks'] = vm_.get('networks')

    __utils__['cloud.fire_event'](
        'event',
        'requesting instance',
        'salt/cloud/{0}/requesting'.format(vm_['name']),
        args={
            'kwargs': __utils__['cloud.filter_event']('requesting', kwargs, list(kwargs)),
        },
        sock_dir=__opts__['sock_dir'],
        transport=__opts__['transport']
    )

    data = create_node(**kwargs)
    if data == {}:
        log.error('Error creating %s on JOYENT', vm_['name'])
        return False

    query_instance(vm_)
    data = show_instance(vm_['name'], call='action')

    vm_['key_filename'] = key_filename
    vm_['ssh_host'] = data[1]['primaryIp']

    __utils__['cloud.bootstrap'](vm_, __opts__)

    __utils__['cloud.fire_event'](
        'event',
        'created instance',
        'salt/cloud/{0}/created'.format(vm_['name']),
        args=__utils__['cloud.filter_event']('created', vm_, ['name', 'profile', 'provider', 'driver']),
        sock_dir=__opts__['sock_dir'],
        transport=__opts__['transport']
    )

    return data[1]
572631
private void addAgent(AsteriskAgentImpl agent)
    {
        synchronized (agents)
        {
            agents.put(agent.getAgentId(), agent);
        }
        server.fireNewAgent(agent);
    }