/*
Use this to spawn a broker (DEPRICATED)
764695
function broker(){
    // Like run the test before we start a broker or service bla
    console.log('DEPRICATION WARNING -> Old broker function in uSpawn.js called, this function will be removed in next version');
    // Forward the promise, this is a bit hacky but the function will be removed
    return new unicorn.promise(function(resolve, reject){
        spawnService('uBroker', 'coreService', true).then(function(msg){
            resolve(msg);
        });
    });
}
411411
@Override
	public void started(ServiceBroker broker) throws Exception {
		super.started(broker);

		// Set components
		ServiceBrokerConfig cfg = broker.getConfig();
		this.transporter = cfg.getTransporter();
		this.monitor = cfg.getMonitor();
		
		// Set local nodeID
		this.localNodeID = broker.getNodeID();
	}
256688
def getbroker():
        '''
        
        '''
        if not Configuration.broker_initialized:
            Configuration._initconf()
            Configuration.broker_settings = Configuration.settings['broker']
            Configuration.broker_initialized = True
        return Configuration.broker_settings
125017
def stop_broker(host, connection, stop_command, verbose):
    """"""
    _, stdout, stderr = connection.sudo_command(stop_command)
    if verbose:
        report_stdout(host, stdout)
        report_stderr(host, stderr)
124007
function run(brokerOptions) {
    const defaultPort = 1883;
    const options = {
        port: defaultPort,
        logVerbose: false,
        startBonjour: true,
        bonjourHost: undefined,
    };
    Object.assign(options, brokerOptions);

    const port = options.port;
    const wsPort = options.wsPort || options.port + 8000;

    const node = require("../runtime-node");

    const aedes = require("aedes")();
    const tcpServer = require('net').createServer(aedes.handle);
    const wsServer = require('http').createServer();
    const ws = require('websocket-stream');

    ws.createServer({ server: wsServer }, aedes.handle);

    tcpServer.listen(port, () => {
        wsServer.listen(wsPort, () => {
            utils.logInfo(`Coaty MQTT Broker running on TCP port ${port} and websocket port ${wsPort}...`);
            if (options.startBonjour && port === defaultPort) {
                node.MulticastDnsDiscovery.publishMqttBrokerService(
                    port,
                    wsPort,
                    undefined,
                    undefined,
                    options.bonjourHost)
                    .then(srv => utils.logInfo(`Published multicast DNS for host ${srv.host} on FQDN "${srv.fqdn}:${srv.port}"`))
                    .catch(error => utils.logError(`Error while publishing multicast DNS: ${error}`));

                node.NodeUtils.handleProcessTermination(undefined, () => {
                    return node.MulticastDnsDiscovery.unpublishMulticastDnsServices()
                        .then(() => {
                            utils.logInfo(`Unpublished multicast DNS service. Exiting...`);
                        });
                });
            }
            if (options.onReady) {
                options.onReady();
            }
        })
    });

    if (!options.logVerbose) {
        return;
    }

    aedes.on("publish", (packet, client) => {
        utils.logMessage(`PUBLISH by ${client ? client.id : "broker"} on topic ${packet.topic} with payload ${packet.payload.toString()}`);
    });

    aedes.on("subscribe", (subscriptions, client) => {
        utils.logMessage(`SUBSCRIBE by ${client ? client.id : "broker"}: on topic ${subscriptions.map(s => s.topic).join(", ")}`);
    });

    aedes.on("unsubscribe", (unsubscriptions, client) => {
        utils.logMessage(`UNSUBSCRIBE by ${client ? client.id : "broker"} on topic ${unsubscriptions.join(", ")}`);
    });

    aedes.on("client", (client) => {
        utils.logMessage(`CLIENT CONNECT ${client.id}`);
    });

    aedes.on("clientDisconnect", (client) => {
        utils.logMessage(`CLIENT DISCONNECT ${client.id}`);
    });

    aedes.on("clientError", (client, err) => {
        utils.logError(`CLIENT ERROR ${client.id} ${err.message}`);
    });

    aedes.on("connectionError", (client, err) => {
        utils.logError(`CONNECTION ERROR ${client} ${err.message}`);
    });
}
1219136
function PoolResource(pool) {
    EventEmitter.call(this);
    this.pool = pool;
    this.options = pool.options;

    this.logger = this.options.logger;

    this._connection = false;
    this._connected = false;

    this.messages = 0;
    this.available = true;
}
822906
def spawn(self, actor, aid=None, **params):
        '''
        '''
        aid = aid or create_aid()
        future = actor.send('arbiter', 'spawn', aid=aid, **params)
        return actor_proxy_future(aid, future)
1097780
def process(self, broker):
        
        if any(i in broker for i in IGNORE.get(self.component, [])):
            raise SkipComponent()
        missing = self.get_missing_dependencies(broker)
        if missing:
            raise MissingRequirements(missing)
        return self.invoke(broker)
793764
@Override
	public <T extends Endpoint> Strategy<T> create() {
		return new XorShiftRandomStrategy<T>(broker, preferLocal);
	}
1083428
function(options) {
    if (options && options.baseUrl) {
      throw new Error('baseUrl has been deprecated!');
    }
    if (options && options.exchangePrefix) {
      throw new Error('exchangePrefix has been deprecated!');
    }
    let serviceName = reference.serviceName;

    // allow for older schemas; this should be deleted once it is no longer used.
    if (!serviceName) {
      if (reference.name) {
        // it was called this for a while; https://bugzilla.mozilla.org/show_bug.cgi?id=1463207
        serviceName = reference.name;
      } else if (reference.baseUrl) {
        serviceName = reference.baseUrl.split('//')[1].split('.')[0];
      } else if (reference.exchangePrefix) {
        serviceName = reference.exchangePrefix.split('/')[1].replace('taskcluster-', '');
      }
    }
    this._options = _.defaults({}, options || {}, {
      exchangePrefix:   reference.exchangePrefix,
      serviceName,
      serviceVersion: 'v1',
    }, _defaultOptions);

    assert(this._options.rootUrl, 'Must provide a rootUrl');

    this._options.rootUrl = this._options.rootUrl.replace(/\/$/, '');

    if (this._options.stats) {
      throw new Error('options.stats is now deprecated! Use options.monitor instead.');
    }

    if (this._options.randomizationFactor < 0 ||
        this._options.randomizationFactor >= 1) {
      throw new Error('options.randomizationFactor must be between 0 and 1!');
    }

    // Shortcut for which default agent to use...
    var isHttps = this._options.rootUrl.indexOf('https') === 0;

    if (this._options.agent) {
      // We have explicit options for new agent create one...
      this._httpAgent = isHttps ?
        new https.Agent(this._options.agent) :
        new http.Agent(this._options.agent);
    } else {
      // Use default global agent(s)...
      this._httpAgent = isHttps ?
        DEFAULT_AGENTS.https :
        DEFAULT_AGENTS.http;
    }

    // Timeout for each _individual_ http request.
    this._timeout = this._options.timeout;

    // Build ext for hawk requests
    this._extData = undefined;
    if (this._options.credentials &&
        this._options.credentials.clientId &&
        this._options.credentials.accessToken) {
      var ext = {};

      // If there is a certificate we have temporary credentials, and we
      // must provide the certificate
      if (this._options.credentials.certificate) {
        ext.certificate = this._options.credentials.certificate;
        // Parse as JSON if it's a string
        if (typeof ext.certificate === 'string') {
          try {
            ext.certificate = JSON.parse(ext.certificate);
          } catch (err) {
            debug('Failed to parse credentials.certificate, err: %s, JSON: %j',
              err, err);
            throw new Error('JSON.parse(): Failed for configured certificate');
          }
        }
      }

      // If set of authorized scopes is provided, we'll restrict the request
      // to only use these scopes
      if (this._options.authorizedScopes instanceof Array) {
        ext.authorizedScopes = this._options.authorizedScopes;
      }

      // ext has any keys we better base64 encode it, and set ext on extra
      if (_.keys(ext).length > 0) {
        this._extData = new Buffer(JSON.stringify(ext)).toString('base64');
      }
    }

    // If fake, we create an array this.fakeCalls[method] = [] for each method
    if (this._options.fake) {
      debug('Creating taskcluster-client object in "fake" mode');
      this.fakeCalls = {};
      reference.entries.filter(e => e.type === 'function').forEach(e => this.fakeCalls[e.name] = []);
      // Throw an error if creating fakes in production
      if (process.env.NODE_ENV === 'production') {
        new Error('taskcluster-client object created in "fake" mode, when NODE_ENV == "production"');
      }
    }
  }
104039
public static br_broker start(nitro_service client, br_broker resource) throws Exception
	{
		return ((br_broker[]) resource.perform_operation(client, "start"))[0];
	}
155031
@Override
	public void started(ServiceBroker broker) throws Exception {
		super.started(broker);

		// Store the current nodeID
		nodeID = broker.getNodeID();

		// Set components
		ServiceBrokerConfig cfg = broker.getConfig();
		scheduler = cfg.getScheduler();
		transporter = broker.getConfig().getTransporter();
		if (transporter == null) {
			logger.warn(
					CommonUtils.nameOf(this, true) + " can't work without transporter. Switched to Round-Robin mode.");
		}

		// Start loop
		pingTimer = scheduler.scheduleWithFixedDelay(this::sendNextPing, pingPeriod, pingPeriod, TimeUnit.SECONDS);
	}
448768
function MQTTMsgBusDebugInNode(config) {
        RED.nodes.createNode(this, config)

        this.qos = 0
        this.source = config.source
        
        if (typeof this.source === 'undefined'){
            this.source = "+"
        } else if (this.source == "") {
            this.source = "+"
        }

        this.client     = config.client
        this.clientConn = RED.nodes.getNode(this.client)

        this.broker     = this.clientConn.broker
        this.brokerConn = RED.nodes.getNode(this.broker)

        var node = this

        if (this.brokerConn) {
            this.status({fill:"red", shape:"ring", text:"node-red:common.status.disconnected"})

            this.topic = topicDebugSubscribe(this.clientConn, this.source)

            node.brokerConn.register(this)

            this.brokerConn.subscribe(this.topic, this.qos, function(topic, payload, packet) {
                onDebugHandler(node, node.brokerConn, topic, payload)
            }, this.id)

            if (this.brokerConn.connected) {
                node.status({fill:"green", shape:"dot", text:"node-red:common.status.connected"})
            }

            this.on('close', function(done) {
                if (node.brokerConn) {
                    node.brokerConn.unsubscribe(node.topic, node.id)
                    node.brokerConn.deregister(node, done)
                }
            })
        } else {
            this.error(RED._("msgbus.errors.missing-config"))
        }

    }
152616
def spawn_process(self, target, *args):
        
        p = Process(target=target, args=args)
        p.daemon = True
        if target == worker:
            p.daemon = Conf.DAEMONIZE_WORKERS
            p.timer = args[2]
            self.pool.append(p)
        p.start()
        return p
630234
def fill_initial_broks(self, broker_name):
        # pylint: disable=too-many-branches
        
        broker_uuid = None
        logger.debug("My brokers: %s", self.my_daemon.brokers)
        for broker_link in list(self.my_daemon.brokers.values()):
            logger.debug("Searching broker: %s", broker_link)
            if broker_name == broker_link.name:
                broker_uuid = broker_link.uuid
                logger.info("Filling initial broks for: %s (%s)", broker_name, broker_uuid)
                break
        else:
            if self.pushed_conf:
                # I am yet configured but I do not know this broker ! Something went wrong!!!
                logger.error("Requested initial broks for an unknown broker: %s", broker_name)
            else:
                logger.info("Requested initial broks for an unknown broker: %s", broker_name)
            return 0

        if self.my_daemon.brokers[broker_uuid].initialized:
            logger.warning("The broker %s still got its initial broks...", broker_name)
            return 0

        initial_broks_count = len(self.my_daemon.brokers[broker_uuid].broks)

        # First the program status
        brok = self.get_program_status_brok()
        self.add_brok(brok, broker_uuid)

        #  We can't call initial_status from all this types
        #  The order is important, service need host...
        initial_status_types = (self.timeperiods, self.commands,
                                self.contacts, self.contactgroups,
                                self.hosts, self.hostgroups,
                                self.services, self.servicegroups)

        self.pushed_conf.skip_initial_broks = getattr(self.pushed_conf, 'skip_initial_broks', False)
        logger.debug("Skipping initial broks? %s", str(self.pushed_conf.skip_initial_broks))
        if not self.pushed_conf.skip_initial_broks:
            #  We call initial_status from all this types
            #  The order is important, service need host...
            initial_status_types = (self.realms, self.timeperiods, self.commands,
                                    self.notificationways, self.contacts, self.contactgroups,
                                    self.hosts, self.hostgroups, self.hostdependencies,
                                    self.services, self.servicegroups, self.servicedependencies,
                                    self.escalations)

            for tab in initial_status_types:
                for item in tab:
                    # Awful! simply to get the group members property name... :(
                    # todo: replace this!
                    member_items = None
                    if hasattr(item, 'members'):
                        member_items = getattr(self, item.my_type.replace("group", "s"))
                    brok = item.get_initial_status_brok(member_items)
                    self.add_brok(brok, broker_uuid)

        # Add a brok to say that we finished all initial_pass
        brok = Brok({'type': 'initial_broks_done', 'data': {'instance_id': self.instance_id}})
        self.add_brok(brok, broker_uuid)

        final_broks_count = len(self.my_daemon.brokers[broker_uuid].broks)
        self.my_daemon.brokers[broker_uuid].initialized = True

        # Send the initial broks to our modules
        self.send_broks_to_modules()

        # We now have raised all the initial broks
        self.raised_initial_broks = True

        logger.info("Created %d initial broks for %s",
                    final_broks_count - initial_broks_count, broker_name)
        return final_broks_count - initial_broks_count
933468
function spawnBuild(argv, skyPagesConfig, webpack) {

  if (argv.build === false) {
    logger.info('Skipping build step');

    const file = 'dist/metadata.json';
    if (!fs.existsSync(file)) {
      logger.info(`Unable to skip build step.  "${file}" not found.`);
    } else {
      return Promise.resolve({
        metadata: fs.readJsonSync(file)
      });
    }
  }

  return build(argv, skyPagesConfig, webpack)
    .then(stats => stats.toJson().chunks);
}
892449
def makeService(self, options):
        
        return BrokerService(
            port=options['port'],
            debug=options['debug'],
            activate_ssh_server=options['activate-ssh-server'],
            ssh_user=options['ssh-user'],
            ssh_password=options['ssh-password'],
            ssh_port=options['ssh-port']
        )