예제 #1
0
    def __init__(self, mq_server = None, virtual_host = cfg.CB_CLUSTER_TAG):

        if mq_server == None:
            mq_server = cfg.RABBITMQ_IP

        self.connection = Connection(host= mq_server, userid="guest", password="******", virtual_host = virtual_host)
        self.manager = Client(mq_server+":55672", "guest", "guest")
예제 #2
0
def Main():

    cgiEnv = lib_common.ScriptEnvironment()

    configNam = cgiEnv.GetId()

    nodeManager = survol_rabbitmq_manager.MakeUri(configNam)

    creds = lib_credentials.GetCredentials("RabbitMQ", configNam)

    # cl = Client('localhost:12345', 'guest', 'guest')
    cl = Client(configNam, creds[0], creds[1])

    grph = cgiEnv.GetGraph()

    try:
        lstOverview = cl.get_overview()
    except Exception as exc:
        lib_common.ErrorMessageHtml("Caught:" + str(exc))

    for keyOverview in lstOverview:
        valOverview = lstOverview[keyOverview]

        valClean = valOverview
        # Otherwise it does not work as these chars should be espaced.
        # TODO: Nice display for Python lists and dicts.
        valClean = str(valClean).replace("{", "").replace("}", "")
        grph.add((nodeManager, lib_common.MakeProp(keyOverview),
                  lib_util.NodeLiteral(valClean)))

    cgiEnv.OutCgiRdf()
예제 #3
0
def Main():
    cgiEnv = lib_common.ScriptEnvironment()

    config_nam = cgiEnv.m_entity_id_dict["Url"]
    nam_v_host = cgiEnv.m_entity_id_dict["VHost"]

    node_manager = survol_rabbitmq_manager.MakeUri(config_nam)

    creds = lib_credentials.GetCredentials("RabbitMQ", config_nam)

    # cl = Client('localhost:12345', 'guest', '*****')
    cl = Client(config_nam, creds[0], creds[1])

    grph = cgiEnv.GetGraph()

    nod_v_host = survol_rabbitmq_vhost.MakeUri(config_nam, nam_v_host)
    grph.add(
        (node_manager, lib_common.MakeProp("virtual host node"), nod_v_host))

    for obj_exchange in cl.get_exchanges(nam_v_host):
        nam_exchange = obj_exchange["name"]
        logging.debug("nam_exchange=%s", nam_exchange)

        node_exchange = survol_rabbitmq_exchange.MakeUri(
            config_nam, nam_v_host, nam_exchange)

        management_url = rabbitmq.ManagementUrlPrefix(config_nam, "exchanges",
                                                      nam_v_host, nam_exchange)

        grph.add((node_exchange, lib_common.MakeProp("Management"),
                  lib_common.NodeUrl(management_url)))

        grph.add((nod_v_host, lib_common.MakeProp("Exchange"), node_exchange))

    cgiEnv.OutCgiRdf()
예제 #4
0
def health_iogt(request):
    status_code = status.HTTP_200_OK

    if settings.RABBITMQ_MANAGEMENT_INTERFACE:
        rx = re.compile(r"amqp://(?P<username>[^:]+).*?:(?P<password>[^@]+)."
                        "*/(?P<vhost>[^&]+)")
        match = rx.search(settings.BROKER_URL)

        username = match.groupdict()['username']
        password = match.groupdict()['password']
        vhost = match.groupdict()['vhost']
        base_url = settings.RABBITMQ_MANAGEMENT_INTERFACE

        mq_client = Client(base_url, username, password)
        queue_data = mq_client.get_queue(vhost, 'celery')

        messages = queue_data['messages']
        rate = queue_data['messages_details']['rate']

        if (messages > 0 and rate == 0):
            status_code = status.HTTP_500_INTERNAL_SERVER_ERROR

    app_id = environ.get('MARATHON_APP_ID', None)
    ver = environ.get('MARATHON_APP_VERSION', None)
    return JsonResponse({'id': app_id, 'version': ver}, status=status_code)
예제 #5
0
def main():

    global rabbitClient
    # load config file
    configFilePath = args.config
    if os.path.isfile(configFilePath):
        logging.debug('Processing config file {0}'.format(configFilePath))
        with open(configFilePath) as configFile:
            conf = json.load(configFile)
            logging.debug('Graphite configuration: {0}'.format(
                conf["graphite_servers"]))
            logging.debug('RabbitMQ configuration: {0}'.format(
                conf["rabbitmq_clusters"]))
            for rabbitmq in conf["rabbitmq_clusters"]:
                logging.debug('Working on Rabbitmq cluster: {0}'.format(
                    rabbitmq['cluster_name']))
                rabbitClient = Client(
                    '{0}:{1}'.format(rabbitmq['host'], rabbitmq['port']),
                    rabbitmq['username'], rabbitmq['password'])
                for graphite in conf["graphite_servers"]:
                    process(rabbitmq, graphite)
    else:
        logging.error(
            'You must pass existing configFilePath, actual is {0}'.format(
                configFilePath))
        sys.exit(1)
예제 #6
0
def Main():

    cgiEnv = lib_common.CgiEnv()

    configNam = cgiEnv.m_entity_id_dict["Url"]
    namVHost = cgiEnv.m_entity_id_dict["VHost"]

    nodeManager = survol_rabbitmq_manager.MakeUri(configNam)

    creds = lib_credentials.GetCredentials("RabbitMQ", configNam)

    # cl = Client('localhost:12345', 'guest', 'guest')
    cl = Client(configNam, creds[0], creds[1])

    grph = cgiEnv.GetGraph()

    nodVHost = survol_rabbitmq_vhost.MakeUri(configNam, namVHost)
    grph.add((nodeManager, lib_common.MakeProp("virtual host node"), nodVHost))

    for quList in cl.get_queues(namVHost):
        namQueue = quList["name"]
        DEBUG("q=%s", namQueue)

        nodeQueue = survol_rabbitmq_queue.MakeUri(configNam, namVHost,
                                                  namQueue)

        managementUrl = rabbitmq.ManagementUrlPrefix(configNam, "queues",
                                                     namVHost, namQueue)

        grph.add((nodeQueue, lib_common.MakeProp("Management"),
                  lib_common.NodeUrl(managementUrl)))

        grph.add((nodVHost, lib_common.MakeProp("Queue"), nodeQueue))

    cgiEnv.OutCgiRdf()
예제 #7
0
def connect(options):
    server = environ.get("server", "localhost:15672")
    client = Client(server, environ.get("username", "guest"),
                    environ.get("password", "guest"))

    client.is_admin = True
    return client
예제 #8
0
def configure(configobj):
    global INTERVAL
    global cl
    global queues_to_count
    global vhost

    config = {c.key: c.values for c in configobj.children}
    INTERVAL = config['interval'][0]
    host = config['host'][0]
    port = int(config['port'][0])
    username = config['username'][0]
    password = config['password'][0]
    if 'vhost' in config:
        vhost = config['vhost'][0]
    else:
        vhost = '/'
    queues_to_count = []
    if 'message_count' in config:
        queues_to_count = config['message_count']
    collectd.info('rabbitmq_monitoring: Interval: {}'.format(INTERVAL))
    cl = Client('{}:{}'.format(host, port), username, password)
    collectd.info(
        'rabbitmq_monitoring: Connecting to: {}:{} as user:{} password:{}'.
        format(host, port, username, password))
    collectd.info('rabbitmq_monitoring: Counting messages on: {}'.format(
        queues_to_count))
    collectd.register_read(read, INTERVAL)
예제 #9
0
 def queues(self, ):
     cl = Client('{}:15672'.format(self.config["rabbitmq"]["server"]),
                 self.config["rabbitmq"]["user"],
                 self.config["rabbitmq"]["password"])
     queues = [q['name'] for q in cl.get_queues()]
     queues.remove("scan-result")
     return queues
예제 #10
0
def Main():

    cgiEnv = lib_common.CgiEnv()

    configNam = cgiEnv.m_entity_id_dict["Url"]
    namVHost = cgiEnv.m_entity_id_dict["VHost"]

    nodeManager = survol_rabbitmq_manager.MakeUri(configNam)

    creds = lib_credentials.GetCredentials("RabbitMQ", configNam)

    # cl = Client('localhost:12345', 'guest', 'guest')
    cl = Client(configNam, creds[0], creds[1])

    grph = cgiEnv.GetGraph()

    nodVHost = survol_rabbitmq_vhost.MakeUri(configNam, namVHost)
    grph.add((nodeManager, lib_common.MakeProp("virtual host node"), nodVHost))

    for objExchange in cl.get_exchanges(namVHost):
        namExchange = objExchange["name"]
        sys.stderr.write("namExchange=%s\n" % (namExchange))

        nodeExchange = survol_rabbitmq_exchange.MakeUri(
            configNam, namVHost, namExchange)

        managementUrl = rabbitmq.ManagementUrlPrefix(configNam, "exchanges",
                                                     namVHost, namExchange)

        grph.add((nodeExchange, lib_common.MakeProp("Management"),
                  lib_common.NodeUrl(managementUrl)))

        grph.add((nodVHost, lib_common.MakeProp("Exchange"), nodeExchange))

    cgiEnv.OutCgiRdf()
def get_queue_depths(host, username, password, vhost):
    cl = Client(host, username, password)
    depths = {}
    queues = [q['name'] for q in cl.get_queues(vhost=vhost)]
    for queue in queues:
        depths[queue] = cl.get_queue_depth(vhost, queue)
    return depths
예제 #12
0
def Main():
    cgiEnv = lib_common.ScriptEnvironment()

    config_nam = cgiEnv.m_entity_id_dict["Url"]
    nam_connection = cgiEnv.m_entity_id_dict["Connection"]

    node_manager = survol_rabbitmq_manager.MakeUri(config_nam)

    creds = lib_credentials.GetCredentials("RabbitMQ", config_nam)

    cl = Client(config_nam, creds[0], creds[1])

    grph = cgiEnv.GetGraph()

    logging.debug("nam_connection=%s", nam_connection)

    nod_connection = survol_rabbitmq_connection.MakeUri(config_nam, nam_connection)

    grph.add((node_manager, lib_common.MakeProp("Connection"), nod_connection))

    try:
        connect_list = cl.get_connection(nam_connection)
    except Exception as exc:
        lib_common.ErrorMessageHtml("Caught:" + str(exc))

    for connect_key in connect_list:
        connect_val = connect_list[connect_key]

        if connect_key == "vhost":
            nod_v_host = survol_rabbitmq_vhost.MakeUri(config_nam, connect_val)
            grph.add((nod_connection, lib_common.MakeProp("Virtual host"), nod_v_host))
        elif connect_key == "user":
            nod_user = survol_rabbitmq_user.MakeUri(config_nam, connect_val)
            grph.add((nod_connection, lib_common.MakeProp("User"), nod_user))
        elif connect_key == "host":
            nod_host = lib_uris.gUriGen.HostnameUri(connect_val)
            grph.add((nod_connection, lib_common.MakeProp("Host"), nod_host))
        elif connect_key in ["name", "peer_host", "peer_port"]:
            pass
        else:
            if isinstance(connect_val, six.string_types):
                connect_val = connect_val.replace(">", "@")

                logging.debug("connect_key=%s connect_val=%s", connect_key, connect_val)
            elif isinstance(connect_val, dict):
                pass
            elif isinstance(connect_val, tuple):
                pass
            elif isinstance(connect_val, list):
                pass
            else:
                pass

            logging.debug("Literal=%s", lib_util.NodeLiteral(connect_val))

            grph.add((nod_connection, lib_common.MakeProp(connect_key), lib_util.NodeLiteral(connect_val)))

    survol_rabbitmq_connection.AddSockets(grph, nod_connection, nam_connection)

    cgiEnv.OutCgiRdf()
예제 #13
0
def Main():

    cgiEnv = lib_common.ScriptEnvironment()

    configNam = cgiEnv.GetId()

    nodeManager = survol_rabbitmq_manager.MakeUri(configNam)

    creds = lib_credentials.GetCredentials("RabbitMQ", configNam)

    # cl = Client('localhost:12345', 'guest', 'guest')
    cl = Client(configNam, creds[0], creds[1])

    grph = cgiEnv.GetGraph()

    # >>> cl.get_all_vhosts()
    # http://localhost:12345/api/vhosts
    # [{u'name': u'/', u'tracing': False, u'messages_details': {u'rate': 0.0}, u'messages': 0, u'message_stats': {u'deliver_no_ack': 0, u'
    # publish_out': 0, u'get_no_ack': 13, u'return_unroutable': 0, u'confirm': 0, u'deliver_get': 13, u'publish': 13, u'confirm_details':
    # {u'rate': 0.0}, u'ack_details': {u'rate': 0.0}, u'get': 0, u'deliver': 0, u'publish_out_details': {u'rate': 0.0}, u'redeliver_detail
    # s': {u'rate': 0.0}, u'deliver_details': {u'rate': 0.0}, u'deliver_get_details': {u'rate': 0.0}, u'publish_details': {u'rate': 0.0},
    # u'publish_in_details': {u'rate': 0.0}, u'ack': 0, u'publish_in': 0, u'return_unroutable_details': {u'rate': 0.0}, u'get_details': {u
    # 'rate': 0.0}, u'get_no_ack_details': {u'rate': 0.0}, u'deliver_no_ack_details': {u'rate': 0.0}, u'redeliver': 0}, u'messages_unackno
    # wledged_details': {u'rate': 0.0}, u'messages_ready_details': {u'rate': 0.0}, u'messages_unacknowledged': 0, u'messages_ready': 0}]

    try:
        #
        listVHosts = cl.get_all_vhosts()
    except Exception as exc:
        lib_common.ErrorMessageHtml("Caught:" + str(exc))

    for objVHost in listVHosts:
        namVHost = objVHost["name"]
        logging.debug("q=%s", namVHost)

        nodeVHost = survol_rabbitmq_vhost.MakeUri(configNam, namVHost)

        try:
            grph.add((nodeVHost, lib_common.MakeProp("tracing"),
                      lib_util.NodeLiteral(objVHost["tracing"])))
        except KeyError:
            pass

        try:
            grph.add((nodeVHost, lib_common.MakeProp("messages"),
                      lib_util.NodeLiteral(objVHost["messages"])))
        except KeyError:
            pass

        # http://127.0.0.1:12345/#/vhosts//
        managementUrl = rabbitmq.ManagementUrlPrefix(configNam, "vhosts",
                                                     namVHost)

        grph.add((nodeVHost, lib_common.MakeProp("Management"),
                  lib_common.NodeUrl(managementUrl)))

        grph.add((nodeManager, lib_common.MakeProp("Virtual host"), nodeVHost))

    cgiEnv.OutCgiRdf()
예제 #14
0
def _get_rabbit_connection():
    """Helper giving us a rabbit connection from settings.BROKER_URL"""
    host_with_port = "{}:{}/api/".format(settings.RABBITMQ_HOST, settings.RABBITMQ_MANAGEMENT_PORT)
    if settings.BROKER_USE_SSL:
        scheme = 'https'
    else:
        scheme = 'http'
    return Client(host_with_port, settings.RABBITMQ_DEFAULT_USER, settings.RABBITMQ_DEFAULT_PASS, scheme=scheme)
예제 #15
0
 def get_host_action(self, vhost):
     for host in self.rabbit_config.hosts:
         cl = Client(f'{host}:15672', self.rabbit_config.username, self.rabbit_config.password)
         try:
             cl.is_alive(vhost)
             return host
         except APIError:
             pass
예제 #16
0
def check_queue(mpc, min_consumers, max_consumers, rabbitmq_server,
                rabbitmq_vhost, rabbitmq_queue, instance_group):
    cl = Client(rabbitmq_server, 'admin', 'rabbit4ever')
    try:
        messages = cl.get_queue(rabbitmq_vhost, rabbitmq_queue).get('messages')
    except:
        bash_delete_auto_resize = "sed -i '/" + rabbitmq_queue + " " + instance_group + " " + mpc + " /d' " + file_path
        os.system(bash_delete_auto_resize)
    else:
        bash_instance_group_info = "gcloud compute instance-groups managed describe " + instance_group + " --zone=us-central1-a"
        instance_group_info = subprocess.check_output(bash_instance_group_info,
                                                      shell=True)
        cur_size = re.findall("targetSize:.*", instance_group_info,
                              re.MULTILINE)
        if not cur_size:
            print("Instance group %s does not exist" % instance_group)
            bash_delete_auto_resize = "sed -i '/" + rabbitmq_queue + " " + instance_group + " " + mpc + " /d' " + file_path
            os.system(bash_delete_auto_resize)
        else:
            cur_max_replicas = re.findall("maxNumReplicas:.*",
                                          instance_group_info, re.MULTILINE)
            if max_consumers == 0:
                if not cur_max_replicas:
                    print(
                        "Auto scaling for instance group %s is already disabled"
                        % instance_group)
                else:
                    resize_instance_group(instance_group, 0, 0)
                    bash_delete_auto_resize = "sed -i '/" + rabbitmq_queue + " " + instance_group + " " + mpc + " /d' " + file_path
                    os.system(bash_delete_auto_resize)
            else:
                if messages == 0:
                    if not cur_max_replicas:
                        print(
                            "Auto scaling for instance group %s is already disabled"
                            % instance_group)
                    else:
                        resize_instance_group(instance_group, 0, 0)
                else:
                    consumers = cl.get_queue(rabbitmq_vhost,
                                             rabbitmq_queue).get('consumers')
                    if (messages / mpc) != consumers:
                        if not cur_max_replicas:
                            print(
                                "Auto scaling for instance group %s is disabled, going to resize instance group"
                                % instance_group)
                            resize_instance_group(instance_group,
                                                  min_consumers, max_consumers)
                        else:
                            cur_max_replicas = int(
                                cur_max_replicas[0].split(": ")[1])
                            max_replicas = max(cur_max_replicas, max_consumers)
                            min_replicas = min(
                                max(messages / mpc, min_consumers),
                                max_replicas)
                            resize_instance_group(instance_group, min_replicas,
                                                  max_replicas)
예제 #17
0
 def countMessagesQueue(self, vhost, queue):
     qtd = 0
     cl = Client('{}:{}'.format(self.host, self.web_port), self.user,
                 self.password)
     try:
         qtd = cl.get_queue_depth(vhost, queue)
     except HTTPError as e:
         logger.error(e)
         raise e
     return qtd
예제 #18
0
def rabbit_manager(request):
    config = request.config

    rabbit_ctl_uri = urlparse(config.getoption('RABBIT_CTL_URI'))
    host_port = '{0.hostname}:{0.port}'.format(rabbit_ctl_uri)

    rabbit = Client(host_port, rabbit_ctl_uri.username,
                    rabbit_ctl_uri.password)

    return rabbit
예제 #19
0
    def get_bindings(self):
        client = Client("localhost:15672", "guest", "guest")
        bindings = client.get_bindings()
        bindings_result = []

        for b in bindings:
            if b["source"] == "exchange_baby_monitor":
                bindings_result.append(b)

        return bindings_result
예제 #20
0
파일: utils.py 프로젝트: anupsl/pyApps
 def getRabbitmqQueueDetails(queueName, host='/'):
     cluster = constant.config['cluster']
     url = constant.rabbitmqCred[cluster]
     user = constant.rabbitmqCred['username']
     passwd = constant.rabbitmqCred['passwd']
     obj = Client(url, user, passwd)
     try:
         return obj.get_queue(vhost=host, name=queueName)
     except pyrabbit.http.HTTPError:
         return {}
예제 #21
0
def Main():

    cgiEnv = lib_common.CgiEnv()

    configNam = cgiEnv.GetId()

    nodeManager = survol_rabbitmq_manager.MakeUri(configNam)

    creds = lib_credentials.GetCredentials("RabbitMQ", configNam)

    # cl = Client('localhost:12345', 'guest', 'guest')
    cl = Client(configNam, creds[0], creds[1])

    grph = cgiEnv.GetGraph()

    # cl.is_alive()

    #>>> cl.get_users()
    #[{u'hashing_algorithm': u'rabbit_password_hashing_sha256', u'name': u'guest', u'tags': u'administrator', u'password_hash': u'xxxxxx'}]
    try:
        #
        listUsers = cl.get_users()
    except:
        #
        exc = sys.exc_info()[1]
        lib_common.ErrorMessageHtml("Caught:" + str(exc))

    for objUser in listUsers:
        namUser = objUser["name"]
        DEBUG("q=%s", namUser)

        nodeUser = survol_rabbitmq_user.MakeUri(configNam, namUser)

        try:
            grph.add((nodeUser, lib_common.MakeProp("Tags"),
                      lib_common.NodeLiteral(objUser["tags"])))
        except KeyError:
            pass

        try:
            grph.add((nodeUser, lib_common.MakeProp("Hashing algorithm"),
                      lib_common.NodeLiteral(objUser["hashing_algorithm"])))
        except KeyError:
            pass

        # http://127.0.0.1:12345/#/users/guest
        managementUrl = rabbitmq.ManagementUrlPrefix(configNam, "users",
                                                     namUser)

        grph.add((nodeUser, lib_common.MakeProp("Management"),
                  lib_common.NodeUrl(managementUrl)))

        grph.add((nodeManager, lib_common.MakeProp("User"), nodeUser))

    cgiEnv.OutCgiRdf()
예제 #22
0
def get_queue_depths(host, username, password, vhost):
    cl = Client(host, username, password)
    if not cl.is_alive():
        raise Exception("Failed to connect to rabbitmq")
    depths = {}
    queues = [q["name"] for q in cl.get_queues(vhost=vhost)]
    for queue in queues:
        if queue == "aliveness-test":
            continue
        depths[queue] = cl.get_queue_depth(vhost, queue)
    return depths
예제 #23
0
파일: collector.py 프로젝트: yfix/alco
 def connect(self):
     connections['default'].close()
     rabbitmq = ALCO_SETTINGS['RABBITMQ']
     self.amqp = Connection(**rabbitmq)
     self.redis = redis.Redis(**ALCO_SETTINGS['REDIS'])
     self.insert_thread = Thread(target=self.inserter_loop)
     self.insert_thread.start()
     hostname = '%s:%s' % (rabbitmq['host'],
                           ALCO_SETTINGS['RABBITMQ_API_PORT'])
     self.rabbit = Client(hostname, rabbitmq['userid'],
                          rabbitmq['password'])
     self.vhost = rabbitmq['virtual_host']
예제 #24
0
def get_rabbitmq_queue_length(q):
    """Fetch queue length from RabbitMQ for a given queue.

    Used periodically to decide if we want to queue more functions or not.

    Uses the Management HTTP API of RabbitMQ, since the Celery client doesn not have access to these counts.
    """

    from pyrabbit.api import Client

    cl = Client(settings.SNOOP_RABBITMQ_HTTP_URL, 'guest', 'guest')
    return cl.get_queue_depth('/', q)
예제 #25
0
async def monitor(request):
    #data loaded for the first time from the function call
    global refresh
    db = request.app['db']
    await db.collection.drop()
    
    if refresh == 0:
        
        #Client creation
        try:
            client = Client('localhost:15672', 'guest', 'guest')
        except:
            return {"result":"Client not created"}

        #get all the bindings()
        try:
            bindings = client.get_bindings()
            n = len(bindings)
        except:
            return {"result":"binding error"}   

        #final list of all the rows 
        result_list = []
        for i in range(n):
            #dict for storing values for each connection
            try:
                dict_each = {}
                vhost_name = bindings[i]['vhost']
                dict_each['vhost_name'] = vhost_name
                dict_each['exchange_name'] = bindings[i]['source']
                queue_name = bindings[i]['destination']
                dict_each['queue_name'] = queue_name
                dict_each['queue_size'] = client.get_queue_depth(vhost=vhost_name, name=queue_name)  
                result_list.append(dict_each)
            except:
                return {"result" : "data not found"}

        #insert data in the db
        try:
            await db.collection.insert_many(i for i in result_list)

        except:
            return {'result': "data not stored in the db"}
        refresh+=1
        return {'result_list': result_list}       

    #data retrieved from the database after refresh 
    if refresh>0:
        result_list = []
        async for document in db.collection.find():
            result_list.append(document)   
        return {"result_list" : result_list}
def get_queue_depths(host, username, password, vhost):
    """ Fetches queue depths from rabbitmq instance."""
    cl = Client(host, username, password)
    if not cl.is_alive():
        raise Exception("Failed to connect to rabbitmq")
    depths = {}
    queues = [q['name'] for q in cl.get_queues(vhost=vhost)]
    for queue in queues:
        if queue == "aliveness-test":  #pyrabbit
            continue
        elif queue.startswith('amq.gen-'):  #Anonymous queues
            continue
        depths[queue] = cl.get_queue_depth(vhost, queue)
    return depths
예제 #27
0
def get_queue_depths(host, username, password, vhost):
    cl = Client(host, username, password)
    if not cl.is_alive():
        raise Exception("Failed to connect to rabbitmq")
    depths = {}
    queues = [q['name'] for q in cl.get_queues(vhost=vhost)]
    for queue in queues:
        if queue == "aliveness-test":  #pyrabbit
            continue
        elif queue.endswith('.pidbox') or queue.startswith(
                'celeryev.'):  #celery
            continue
        depths[queue] = cl.get_queue_depth(vhost, queue)
    return depths
예제 #28
0
def get_client(cfg):
    """
    Get RabbitMQ client based on provided configuration or default settings.
    :param cfg: config dict
    :return: RabbitMQ client object
    """
    username_from_env = os.getenv('CHECK_RABBITMQ_QUEUES_USERNAME')
    password_from_env = os.getenv('CHECK_RABBITMQ_QUEUES_PASSWORD')

    client = Client('%s:%s' % (cfg.get('host', DEFAULT_HOSTNAME),
                               cfg.get('port', DEFAULT_PORT)),
                    username_from_env or cfg.get('username', DEFAULT_USERNAME),
                    password_from_env or cfg.get('password', DEFAULT_PASSWORD))
    return client
예제 #29
0
def Main():

    cgiEnv = lib_common.CgiEnv()

    configNam = cgiEnv.GetId()

    nodeManager = survol_rabbitmq_manager.MakeUri(configNam)

    creds = lib_credentials.GetCredentials("RabbitMQ", configNam)

    # cl = Client('localhost:12345', 'guest', 'guest')
    cl = Client(configNam, creds[0], creds[1])

    grph = cgiEnv.GetGraph()

    # cl.is_alive()
    try:
        #
        listQueues = cl.get_queues()
    except:
        #
        exc = sys.exc_info()[1]
        lib_common.ErrorMessageHtml("Caught:" + str(exc))

    for quList in listQueues:
        namQueue = quList["name"]
        DEBUG("q=%s", namQueue)

        namVHost = quList["vhost"]
        nodVHost = survol_rabbitmq_vhost.MakeUri(configNam, namVHost)

        nodeQueue = survol_rabbitmq_queue.MakeUri(configNam, namVHost,
                                                  namQueue)

        grph.add((nodeQueue, lib_common.MakeProp("vhost"),
                  lib_common.NodeLiteral(namVHost)))
        grph.add((nodeQueue, lib_common.MakeProp("vhost node"), nodVHost))

        managementUrl = rabbitmq.ManagementUrlPrefix(configNam, "queues",
                                                     namVHost, namQueue)

        grph.add((nodeQueue, lib_common.MakeProp("Management"),
                  lib_common.NodeUrl(managementUrl)))

        grph.add((nodeManager, lib_common.MakeProp("Queue"), nodeQueue))

    cgiEnv.OutCgiRdf()
예제 #30
0
def Main():

    cgiEnv = lib_common.CgiEnv()

    configNam = cgiEnv.m_entity_id_dict["Url"]
    # namVHost = cgiEnv.m_entity_id_dict["VHost"]

    nodeManager = survol_rabbitmq_manager.MakeUri(configNam)

    creds = lib_credentials.GetCredentials("RabbitMQ", configNam)

    # cl = Client('localhost:12345', 'guest', 'guest')
    cl = Client(configNam, creds[0], creds[1])

    grph = cgiEnv.GetGraph()

    try:
        #
        listExchanges = cl.get_exchanges()
    except:
        #
        exc = sys.exc_info()[1]
        lib_common.ErrorMessageHtml("Caught:" + str(exc))

    for objExchange in listExchanges:
        namExchange = objExchange["name"]
        DEBUG("namExchange=%s", namExchange)

        namVHost = objExchange["vhost"]
        nodeExchange = survol_rabbitmq_exchange.MakeUri(
            configNam, namVHost, namExchange)

        nodVHost = survol_rabbitmq_vhost.MakeUri(configNam, namVHost)
        grph.add(
            (nodeExchange, lib_common.MakeProp("virtual host node"), nodVHost))

        managementUrl = rabbitmq.ManagementUrlPrefix(configNam, "exchanges",
                                                     namVHost, namExchange)

        grph.add((nodeExchange, lib_common.MakeProp("Management"),
                  lib_common.NodeUrl(managementUrl)))

        grph.add((nodVHost, lib_common.MakeProp("Exchange"), nodeExchange))

    cgiEnv.OutCgiRdf()