Send broks to a specific broker

        :param broker_name: broker name to send broks
        :type broker_name: str
        :greturn: dict of brok for this broker
        :rtype: dict[alignak.brok.Brok]
18322
def get_broks(self, broker_name):
        
        logger.debug("Broker %s requests my broks list", broker_name)
        res = []
        if not broker_name:
            return res

        for broker_link in list(self.brokers.values()):
            if broker_name == broker_link.name:
                for brok in sorted(broker_link.broks, key=lambda x: x.creation_time):
                    # Only provide broks that did not yet sent to our external modules
                    if getattr(brok, 'sent_to_externals', False):
                        res.append(brok)
                        brok.got = True
                broker_link.broks = [b for b in broker_link.broks if not getattr(b, 'got', False)]
                logger.debug("Providing %d broks to %s", len(res), broker_name)
                break
        else:
            logger.warning("Got a brok request from an unknown broker: %s", broker_name)

        return res
463163
def push_broks_to_broker(self):  # pragma: no cover - not used!
        
        someone_is_concerned = False
        sent = False
        for broker_link in self.conf.brokers:
            # Send only if the broker is concerned...
            if not broker_link.manage_arbiters:
                continue

            someone_is_concerned = True
            if broker_link.reachable:
                logger.debug("Sending %d broks to the broker %s", len(self.broks), broker_link.name)
                if broker_link.push_broks(self.broks):
                    statsmgr.counter('broks.pushed.count', len(self.broks))
                    sent = True

        if not someone_is_concerned or sent:
            # No one is anymore interested with...
            del self.broks[:]
743626
def send_event(self, name, ev, state=None):
        

        if name in SERVICE_BRICKS:
            if isinstance(ev, EventRequestBase):
                ev.src = self.name
            LOG.debug("EVENT %s->%s %s",
                      self.name, name, ev.__class__.__name__)
            SERVICE_BRICKS[name]._send_event(ev, state)
        else:
            LOG.debug("EVENT LOST %s->%s %s",
                      self.name, name, ev.__class__.__name__)
1003871
def assignment(self):
        """"""
        return {
            partition.name: [
                self.brokers[bid].id for bid in self.replicas[pid]
            ]
            for pid, partition in enumerate(self.partitions)
        }
754497
def get_initial_broks_from_satellites(self):
        
        for satellites in [self.conf.brokers, self.conf.schedulers,
                           self.conf.pollers, self.conf.reactionners, self.conf.receivers]:
            for satellite in satellites:
                # Get only if reachable...
                if not satellite.reachable:
                    continue
                logger.debug("Getting initial brok from: %s", satellite.name)
                brok = satellite.get_initial_status_brok()
                logger.debug("Satellite '%s' initial brok: %s", satellite.name, brok)
                self.add(brok)
811324
def send(self, *sender, **kwargs):
        
        if len(sender) == 0:
            sender = None
        elif len(sender) > 1:
            raise TypeError('send() accepts only one positional argument, '
                            '%s given' % len(sender))
        else:
            sender = sender[0]

        if not self.receivers:
            return []

        rv = list()
        for receiver in self.receivers_for(sender):
            try:
                rv.append((receiver, receiver(sender, **kwargs)))
            except Exception:
                logger.exception('Error while dispatching signal "{}" '
                                 'to receiver'.format(self.name))
        return rv
816639
def get_new_broks(self):
        
        for satellites in [self.schedulers, self.pollers, self.reactionners, self.receivers]:
            for satellite_link in list(satellites.values()):
                logger.debug("Getting broks from %s", satellite_link)

                _t0 = time.time()
                try:
                    tmp_broks = satellite_link.get_broks(self.name)
                except LinkError:
                    logger.warning("Daemon %s connection failed, I could not get the broks!",
                                   satellite_link)
                else:
                    if tmp_broks:
                        logger.debug("Got %d Broks from %s in %s",
                                     len(tmp_broks), satellite_link.name, time.time() - _t0)
                        statsmgr.gauge('get-new-broks-count.%s'
                                       % (satellite_link.name), len(tmp_broks))
                        statsmgr.timer('get-new-broks-time.%s'
                                       % (satellite_link.name), time.time() - _t0)
                        for brok in tmp_broks:
                            brok.instance_id = satellite_link.instance_id

                        # Add the broks to our global list
                        self.external_broks.extend(tmp_broks)
364238
def send(self, message, *args, **kwargs):
        
        routing_keys = kwargs.get('routing_key') or self.routing_key
        routing_keys = [routing_keys] if isinstance(routing_keys, basestring) else routing_keys
        correlation_id = kwargs.get('correlation_id', None)
        reply_to = kwargs.get('reply_to', None)
        declare=[self.exchange] + kwargs.get('declare', [])
        conn = self.get_connection()
        with connections[conn].acquire(block=True) as connection:
            self.exchange.maybe_bind(connection)
            #reply_to.maybe_bind(connection)
            #reply_to.declare(True)
            with producers[connection].acquire(block=True) as producer:
                for routing_key in routing_keys:
                    LOGGER.info('Send message %s to exchange %s with routing_key %s reply_to %s correlation_id %s',
                                message, self.exchange.name, routing_key, reply_to, correlation_id)
                    producer.publish(
                        message,
                        exchange=self.exchange,
                        declare=declare,
                        serializer=self.settings['serializer'],
                        routing_key=routing_key,
                        correlation_id=correlation_id,
                        retry=self.settings['retry'],
                        delivery_mode=self.settings['delivery_mode'],
                        reply_to=reply_to,
                        retry_policy=self.settings['retry_policy'])
464511
def get_arbiter_broks(self):
        
        with self.arbiter_broks_lock:
            statsmgr.gauge('get-new-broks-count.arbiter', len(self.arbiter_broks))
            # Add the broks to our global list
            self.external_broks.extend(self.arbiter_broks)
            self.arbiter_broks = []
1192369
def _send(self, subname, value):
        '''
        '''
        name = self._get_name(self.name, subname)
        self.logger.info('%s: %s', name, value)
        return statsd.Client._send(self, {name: '%s|g' % value})
1084569
def get_broker() -> "Broker":
    
    global global_broker
    if global_broker is None:
        from .brokers.rabbitmq import RabbitmqBroker

        set_broker(RabbitmqBroker(
            host="127.0.0.1",
            port=5672,
            heartbeat=5,
            connection_attempts=5,
            blocked_connection_timeout=30,
        ))
    return global_broker
461928
def _set_logger(logger_name, level=logging.INFO):
        
        log = logging.getLogger(logger_name)
        log.setLevel(level)

        ch = logging.StreamHandler(None)
        ch.setLevel(level)

        formatter = logging.Formatter(DebugFmtString)

        # add formatter to ch
        ch.setFormatter(formatter)

        # add ch to logger
        log.addHandler(ch)
745344
def setup_exchange(self, exchange_name):
        
        self._logger.debug('Declaring exchange %s' % exchange_name)
        try:
            self._channel.exchange_declare(self.on_exchange_declareok,
                                           exchange_name,
                                           self._exchange_type)
        except Exception as e:
            self._logger.exception(e)
1199008
protected String prepareBrokerPoller(String brokerName, String address) throws Exception {
        MBeanAccessConnectionFactory mBeanAccessConnectionFactory =
                this.jmxActiveMQUtil.getLocationConnectionFactory(address);

        if ( brokerName.equals("*") ) {
            String[] brokersAtLocation = this.jmxActiveMQUtil.queryBrokerNames(address);
            if ( brokersAtLocation == null ) {
                throw new Exception("unable to locate broker at " + address);
            } else if ( brokersAtLocation.length != 1 ) {
                throw new Exception("found more than one broker at " + address + "; count=" + brokersAtLocation.length);
            } else {
                brokerName = brokersAtLocation[0];
            }
        }

        this.brokerRegistry.put(address, new BrokerInfo("unknown-broker-id", brokerName, "unknown-broker-url"));

        ActiveMQBrokerPoller brokerPoller =
                this.brokerPollerFactory.createPoller(brokerName, mBeanAccessConnectionFactory,
                        this.websocketBrokerStatsFeed);

        brokerPoller.setQueueRegistry(this.queueRegistry);
        brokerPoller.setTopicRegistry(this.topicRegistry);

        // TBD: one automic update for brokerPollerMap and locations (is there an echo in here?)
        synchronized ( this.brokerPollerMap ) {
            if ( ! this.brokerPollerMap.containsKey(address) ) {
                this.brokerPollerMap.put(address, brokerPoller);
            } else {
                log.info("ignoring duplicate add of broker address {}", address);
                return "already exists";
            }
        }

        // No need to synchronize to avoid races here; the poller will not start if either already started, or already
        //  stopped.
        if ( this.started.get() ) {
            brokerPoller.start();
        }

        // Add auto-discovery of Queues for this broker, if enabled
        if ( this.autoDiscoverQueues ) {
            this.prepareBrokerQueueDiscoverer(brokerName, address, mBeanAccessConnectionFactory);
        }

        return address + " = " + brokerName;
    }
1103089
def create_client(self, name):
        ''''''
        client = {'client':{
            'name': name,
        }}
        response = self.post_request('clients/', client, follow = True)
        if response:
            return Client(self, response['client'])
634662
def _example_broker_queue(quote_ctx):
    
    stock_code_list = ["HK.00700"]

    for stk_code in stock_code_list:
        ret_status, ret_data = quote_ctx.subscribe(stk_code, ft.SubType.BROKER)
        if ret_status != ft.RET_OK:
            print(ret_data)
            exit()

    for stk_code in stock_code_list:
        ret_status, bid_data, ask_data = quote_ctx.get_broker_queue(stk_code)
        if ret_status != ft.RET_OK:
            print(bid_data)
            exit()
        print("%s BROKER" % stk_code)
        print(ask_data)
        print("\n\n")
        print(bid_data)
        print("\n\n")
1341543
def provide(name)
      return nil unless name.respond_to?(:to_sym)
      name = name.to_sym
      fields[name] || fields[aliases[name]]
    end