collector.py 19.5 KB
Newer Older
M
Matteo Merli 已提交
1 2
#!/usr/bin/env python
#
3 4 5 6 7 8 9
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements.  See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership.  The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License.  You may obtain a copy of the License at
M
Matteo Merli 已提交
10
#
11
#   http://www.apache.org/licenses/LICENSE-2.0
M
Matteo Merli 已提交
12
#
13 14 15 16 17 18
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied.  See the License for the
# specific language governing permissions and limitations
# under the License.
M
Matteo Merli 已提交
19 20 21
#


22
import logging
M
Matteo Merli 已提交
23 24 25 26 27 28 29 30 31 32 33 34
import os
import django
import requests
import pytz
import multiprocessing
import traceback
import sys
from django.utils import timezone
from django.utils.dateparse import parse_datetime
from django.db import connection
import time
import argparse
35
import random
M
Matteo Merli 已提交
36 37

current_milli_time = lambda: int(round(time.time() * 1000))
38
logger = logging.getLogger(__name__)
M
Matteo Merli 已提交
39 40 41 42

def get(base_url, path):
    if base_url.endswith('/'): path = path[1:]
    return requests.get(base_url + path,
43 44 45 46
                        headers=http_headers,
                        proxies=http_proxyes,
                        ).json()

M
Matteo Merli 已提交
47 48 49 50 51 52 53 54 55 56

def parse_date(d):
    if d:
        dt = parse_datetime(d)
        if dt.tzinfo:
            # There is already the timezone set
            return dt
        else:
            # Assume UTC if no timezone
            return pytz.timezone('UTC').localize(parse_datetime(d))
57 58 59
    else:
        return None

M
Matteo Merli 已提交
60 61 62 63 64 65 66 67 68 69 70 71

# Fetch the stats for a given broker
def fetch_broker_stats(cluster, broker_url, timestamp):
    try:
        _fetch_broker_stats(cluster, broker_url, timestamp)
    except Exception as e:
        traceback.print_exc(file=sys.stderr)
        raise e


def _fetch_broker_stats(cluster, broker_host_port, timestamp):
    broker_url = 'http://%s/' % broker_host_port
72
    logger.info('Getting stats for %s' % broker_host_port)
M
Matteo Merli 已提交
73 74

    broker, _ = Broker.objects.get_or_create(
75 76 77
        url=broker_host_port,
        cluster=cluster
    )
M
Matteo Merli 已提交
78 79 80 81 82 83
    active_broker = ActiveBroker(broker=broker, timestamp=timestamp)
    active_broker.save()

    # Get topics stats
    topics_stats = get(broker_url, '/admin/broker-stats/destinations')

84
    clusters = dict((cluster.name, cluster) for cluster in Cluster.objects.all())
M
Matteo Merli 已提交
85

86 87 88 89 90 91 92 93
    db_create_bundles = []
    db_update_bundles = []
    db_create_topics = []
    db_update_topics = []
    db_create_subscriptions = []
    db_update_subscriptions = []
    db_create_consumers = []
    db_update_consumers = []
M
Matteo Merli 已提交
94 95 96 97 98 99 100
    db_replication = []

    for namespace_name, bundles_stats in topics_stats.items():
        property_name = namespace_name.split('/')[0]
        property, _ = Property.objects.get_or_create(name=property_name)

        namespace, _ = Namespace.objects.get_or_create(
101
            name=namespace_name,
102 103
            property=property,
            timestamp=timestamp)
M
Matteo Merli 已提交
104 105 106 107 108
        namespace.clusters.add(cluster)
        namespace.save()

        for bundle_range, topics_stats in bundles_stats.items():

109
            bundle = Bundle.objects.filter(
110 111 112
                cluster_id=cluster.id,
                namespace_id=namespace.id,
                range=bundle_range)
113 114 115 116 117 118 119
            if bundle:
                temp_bundle = bundle.first()
                temp_bundle.timestame = timestamp
                db_update_bundles.append(temp_bundle)
                bundle = temp_bundle
            else:
                bundle = Bundle(
120 121 122 123 124
                    broker=broker,
                    namespace=namespace,
                    range=bundle_range,
                    cluster=cluster,
                    timestamp=timestamp)
125
                db_create_bundles.append(bundle)
126

M
Matteo Merli 已提交
127
            for topic_name, stats in topics_stats['persistent'].items():
128 129 130 131 132 133 134 135
                topic = Topic.objects.filter(
                    cluster_id=cluster.id,
                    bundle_id=bundle.id,
                    namespace_id=namespace.id,
                    broker_id=broker.id,
                    name=topic_name)
                if topic:
                    temp_topic = topic.first()
136 137 138 139 140 141
                    temp_topic.timestamp = timestamp
                    temp_topic.averageMsgSize = stats['averageMsgSize']
                    temp_topic.msgRateIn = stats['msgRateIn']
                    temp_topic.msgRateOut = stats['msgRateOut']
                    temp_topic.msgThroughputIn = stats['msgThroughputIn']
                    temp_topic.msgThroughputOut = stats['msgThroughputOut']
142
                    temp_topic.pendingAddEntriesCount = stats['pendingAddEntriesCount']
143 144
                    temp_topic.producerCount = stats['producerCount']
                    temp_topic.storageSize = stats['storageSize']
145 146 147 148
                    db_update_topics.append(temp_topic)
                    topic = temp_topic
                else:
                    topic = Topic(
149 150 151 152 153 154 155 156 157 158 159 160 161 162 163
                        broker=broker,
                        active_broker=active_broker,
                        name=topic_name,
                        namespace=namespace,
                        bundle=bundle,
                        cluster=cluster,
                        timestamp=timestamp,
                        averageMsgSize=stats['averageMsgSize'],
                        msgRateIn=stats['msgRateIn'],
                        msgRateOut=stats['msgRateOut'],
                        msgThroughputIn=stats['msgThroughputIn'],
                        msgThroughputOut=stats['msgThroughputOut'],
                        pendingAddEntriesCount=stats['pendingAddEntriesCount'],
                        producerCount=stats['producerCount'],
                        storageSize=stats['storageSize']
164 165
                    )
                    db_create_topics.append(topic)
M
Matteo Merli 已提交
166 167 168 169 170 171
                totalBacklog = 0
                numSubscriptions = 0
                numConsumers = 0

                for subscription_name, subStats in stats['subscriptions'].items():
                    numSubscriptions += 1
172
                    subscription = Subscription.objects.filter(
173 174 175
                        topic_id=topic.id,
                        namespace_id=namespace.id,
                        name=subscription_name)
176 177
                    if subscription:
                        temp_subscription = subscription.first()
178 179 180 181
                        temp_subscription.timestamp = timestamp
                        temp_subscription.msgBacklog = subStats['msgBacklog']
                        temp_subscription.msgRateExpired = subStats['msgRateExpired']
                        temp_subscription.msgRateOut = subStats['msgRateOut']
182 183 184
                        temp_subscription.msgRateRedeliver = subStats.get('msgRateRedeliver', 0)
                        temp_subscription.msgThroughputOut = subStats['msgThroughputOut']
                        temp_subscription.subscriptionType = subStats['type'][0]
185
                        temp_subscription.unackedMessages = subStats.get('unackedMessages', 0)
186 187 188 189
                        db_update_subscriptions.append(temp_subscription)
                        subscription = temp_subscription
                    else:
                        subscription = Subscription(
190 191 192 193 194 195 196 197 198 199 200
                            topic=topic,
                            name=subscription_name,
                            namespace=namespace,
                            timestamp=timestamp,
                            msgBacklog=subStats['msgBacklog'],
                            msgRateExpired=subStats['msgRateExpired'],
                            msgRateOut=subStats['msgRateOut'],
                            msgRateRedeliver=subStats.get('msgRateRedeliver', 0),
                            msgThroughputOut=subStats['msgThroughputOut'],
                            subscriptionType=subStats['type'][0],
                            unackedMessages=subStats.get('unackedMessages', 0),
201 202
                        )
                        db_create_subscriptions.append(subscription)
M
Matteo Merli 已提交
203 204 205 206 207

                    totalBacklog += subStats['msgBacklog']

                    for consStats in subStats['consumers']:
                        numConsumers += 1
208 209 210 211 212
                        consumer = Consumer.objects.filter(
                            subscription_id=subscription.id,
                            consumerName=consStats.get('consumerName'))
                        if consumer:
                            temp_consumer = consumer.first()
213 214
                            temp_consumer.timestamp = timestamp
                            temp_consumer.address = consStats['address']
215
                            temp_consumer.availablePermits = consStats.get('availablePermits', 0)
216 217
                            temp_consumer.connectedSince = parse_date(consStats.get('connectedSince'))
                            temp_consumer.msgRateOut = consStats.get('msgRateOut', 0)
218 219
                            temp_consumer.msgRateRedeliver = consStats.get('msgRateRedeliver', 0)
                            temp_consumer.msgThroughputOut = consStats.get('msgThroughputOut', 0)
220 221 222
                            temp_consumer.unackedMessages = consStats.get('unackedMessages', 0)
                            temp_consumer.blockedConsumerOnUnackedMsgs = consStats.get('blockedConsumerOnUnackedMsgs',
                                                                                       False)
223 224 225 226
                            db_update_consumers.append(temp_consumer)
                            consumer = temp_consumer
                        else:
                            consumer = Consumer(
227 228 229 230 231 232 233 234 235 236 237
                                subscription=subscription,
                                timestamp=timestamp,
                                address=consStats['address'],
                                availablePermits=consStats.get('availablePermits', 0),
                                connectedSince=parse_date(consStats.get('connectedSince')),
                                consumerName=consStats.get('consumerName'),
                                msgRateOut=consStats.get('msgRateOut', 0),
                                msgRateRedeliver=consStats.get('msgRateRedeliver', 0),
                                msgThroughputOut=consStats.get('msgThroughputOut', 0),
                                unackedMessages=consStats.get('unackedMessages', 0),
                                blockedConsumerOnUnackedMsgs=consStats.get('blockedConsumerOnUnackedMsgs', False)
238 239
                            )
                            db_create_consumers.append(consumer)
M
Matteo Merli 已提交
240 241 242 243 244 245 246 247 248 249 250 251 252

                topic.backlog = totalBacklog
                topic.subscriptionCount = numSubscriptions
                topic.consumerCount = numConsumers

                replicationMsgIn = 0
                replicationMsgOut = 0
                replicationThroughputIn = 0
                replicationThroughputOut = 0
                replicationBacklog = 0

                for remote_cluster, replStats in stats['replication'].items():
                    replication = Replication(
253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268
                        timestamp=timestamp,
                        topic=topic,
                        local_cluster=cluster,
                        remote_cluster=clusters[remote_cluster],

                        msgRateIn=replStats['msgRateIn'],
                        msgRateOut=replStats['msgRateOut'],
                        msgThroughputIn=replStats['msgThroughputIn'],
                        msgThroughputOut=replStats['msgThroughputOut'],
                        replicationBacklog=replStats['replicationBacklog'],
                        connected=replStats['connected'],
                        replicationDelayInSeconds=replStats['replicationDelayInSeconds'],
                        msgRateExpired=replStats['msgRateExpired'],

                        inboundConnectedSince=parse_date(replStats.get('inboundConnectedSince')),
                        outboundConnectedSince=parse_date(replStats.get('outboundConnectedSince')),
M
Matteo Merli 已提交
269 270 271 272
                    )

                    db_replication.append(replication)

273 274 275
                    replicationMsgIn += replication.msgRateIn
                    replicationMsgOut += replication.msgRateOut
                    replicationThroughputIn += replication.msgThroughputIn
M
Matteo Merli 已提交
276
                    replicationThroughputOut += replication.msgThroughputOut
277
                    replicationBacklog += replication.replicationBacklog
M
Matteo Merli 已提交
278 279 280 281 282 283 284 285 286 287 288 289 290

                topic.replicationRateIn = replicationMsgIn
                topic.replicationRateOut = replicationMsgOut
                topic.replicationThroughputIn = replicationThroughputIn
                topic.replicationThroughputOut = replicationThroughputOut
                topic.replicationBacklog = replicationBacklog
                topic.localRateIn = topic.msgRateIn - replicationMsgIn
                topic.localRateOut = topic.msgRateOut - replicationMsgOut
                topic.localThroughputIn = topic.msgThroughputIn - replicationThroughputIn
                topic.localThroughputOut = topic.msgThroughputIn - replicationThroughputOut

    if connection.vendor == 'postgresql':
        # Bulk insert into db
291
        Bundle.objects.bulk_create(db_create_bundles, batch_size=10000)
M
Matteo Merli 已提交
292 293

        # Trick to refresh primary keys after previous bulk import
294 295
        for topic in db_create_topics: topic.bundle = topic.bundle
        Topic.objects.bulk_create(db_create_topics, batch_size=10000)
M
Matteo Merli 已提交
296

297 298
        for subscription in db_create_subscriptions: subscription.topic = subscription.topic
        Subscription.objects.bulk_create(db_create_subscriptions, batch_size=10000)
M
Matteo Merli 已提交
299

300 301
        for consumer in db_create_consumers: consumer.subscription = consumer.subscription
        Consumer.objects.bulk_create(db_create_consumers, batch_size=10000)
M
Matteo Merli 已提交
302 303 304 305

        for replication in db_replication: replication.topic = replication.topic
        Replication.objects.bulk_create(db_replication, batch_size=10000)

306 307 308 309 310
        update_or_create_object(
            db_update_bundles,
            db_update_topics,
            db_update_consumers,
            db_update_subscriptions)
M
Matteo Merli 已提交
311

312 313 314 315 316 317 318 319 320 321 322
    else:
        update_or_create_object(
            db_create_bundles,
            db_create_topics,
            db_create_consumers,
            db_create_subscriptions)
        update_or_create_object(
            db_update_bundles,
            db_update_topics,
            db_update_consumers,
            db_update_subscriptions)
M
Matteo Merli 已提交
323 324 325 326 327

        for replication in db_replication:
            replication.topic = replication.topic
            replication.save()

328 329 330 331 332 333 334 335 336 337 338 339
    tenants = get(broker_url, '/admin/v2/tenants')
    for tenant_name in tenants:
        namespaces = get(broker_url, '/admin/v2/namespaces/' + tenant_name)
        for namespace_name in namespaces:
            property, _ = Property.objects.get_or_create(name=tenant_name)
            namespace, _ = Namespace.objects.get_or_create(
                name=namespace_name,
                property=property,
                timestamp=timestamp)
            namespace.clusters.add(cluster)
            namespace.save()

340

341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358
def update_or_create_object(db_bundles, db_topics, db_consumers, db_subscriptions):
    # For DB providers we have to insert or update one by one
    # to be able to retrieve the PK of the newly inserted records
    for bundle in db_bundles:
        bundle.save()

    for topic in db_topics:
        topic.bundle = topic.bundle
        topic.save()

    for subscription in db_subscriptions:
        subscription.topic = subscription.topic
        subscription.save()

    for consumer in db_consumers:
        consumer.subscription = consumer.subscription
        consumer.save()

M
Matteo Merli 已提交
359 360

def fetch_stats():
361
    logger.info("Begin fetch stats")
M
Matteo Merli 已提交
362 363 364 365 366 367
    timestamp = current_milli_time()

    pool = multiprocessing.Pool(args.workers)

    futures = []

368
    for cluster_name in get(args.serviceUrl, '/admin/v2/clusters'):
M
Matteo Merli 已提交
369 370
        if cluster_name == 'global': continue

371
        cluster_url = get(args.serviceUrl, '/admin/v2/clusters/' + cluster_name)['serviceUrl']
372 373 374 375 376 377 378 379 380
        if cluster_url.find(',')>=0:
            cluster_url_list = cluster_url.split(',')
            index = random.randint(0,len(cluster_url_list)-1)
            if index==0:
                cluster_url = cluster_url_list[index]
            else:
                protocol = ("https://" if(cluster_url.find("https")>=0) else "http://")
                cluster_url = protocol+cluster_url_list[index]

381
        logger.info('Cluster:{} -> {}'.format(cluster_name, cluster_url))
M
Matteo Merli 已提交
382 383 384 385 386 387 388 389
        cluster, created = Cluster.objects.get_or_create(name=cluster_name)
        if cluster_url != cluster.serviceUrl:
            cluster.serviceUrl = cluster_url
            cluster.save()

    # Get the list of brokers for each cluster
    for cluster in Cluster.objects.all():
        try:
390
            for broker_host_port in get(cluster.serviceUrl, '/admin/v2/brokers/' + cluster.name):
M
Matteo Merli 已提交
391 392 393
                f = pool.apply_async(fetch_broker_stats, (cluster, broker_host_port, timestamp))
                futures.append(f)
        except Exception as e:
394
            logger.error('ERROR: ', e)
M
Matteo Merli 已提交
395 396 397 398 399 400 401 402 403 404 405 406

    pool.close()

    for f in futures:
        f.get()

    pool.join()

    # Update Timestamp in DB
    latest, _ = LatestTimestamp.objects.get_or_create(name='latest')
    latest.timestamp = timestamp
    latest.save()
407 408
    logger.info("Finished fetch stats")

M
Matteo Merli 已提交
409 410

def purge_db():
411
    logger.info("Begin purge db")
M
Matteo Merli 已提交
412 413 414 415
    now = current_milli_time()
    ttl_minutes = args.purge
    threshold = now - (ttl_minutes * 60 * 1000)

416 417 418 419
    Bundle.objects.filter(timestamp__lt=threshold).delete()
    Topic.objects.filter(timestamp__lt=threshold).delete()
    Subscription.objects.filter(timestamp__lt=threshold).delete()
    Consumer.objects.filter(timestamp__lt=threshold).delete()
420 421
    Namespace.objects.filter(timestamp__lt=threshold).delete()
    logger.info("Finished purge db")
422

M
Matteo Merli 已提交
423 424

def collect_and_purge():
425
    logger.info('Starting stats collection')
M
Matteo Merli 已提交
426 427
    fetch_stats()
    purge_db()
428 429
    logger.info('Finished collecting stats')

M
Matteo Merli 已提交
430 431 432 433 434 435 436 437 438 439 440

if __name__ == "__main__":
    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "dashboard.settings")
    django.setup()

    from stats.models import *

    parser = argparse.ArgumentParser(description='Pulsar Stats collector')
    parser.add_argument(action="store", dest="serviceUrl", help='Service URL of one cluster in the Pulsar instance')

    parser.add_argument('--proxy', action='store',
441
                        help="Connect using a HTTP proxy", dest="proxy")
M
Matteo Merli 已提交
442
    parser.add_argument('--header', action="append", dest="header",
443
                        help='Add an additional HTTP header to all requests')
M
Matteo Merli 已提交
444
    parser.add_argument('--purge', action="store", dest="purge", type=int, default=60,
445
                        help='Purge statistics older than PURGE minutes. (default: 60min)')
M
Matteo Merli 已提交
446 447

    parser.add_argument('--workers', action="store", dest="workers", type=int, default=64,
448
                        help='Number of worker processes to be used to fetch the stats (default: 64)')
M
Matteo Merli 已提交
449 450 451 452 453 454

    global args
    args = parser.parse_args(sys.argv[1:])

    global http_headers
    http_headers = {}
455 456 457 458
    jwt_token = os.getenv("JWT_TOKEN", None)
    if jwt_token is not None:
        http_headers = {
            "Authorization": "Bearer {}".format(jwt_token)}
M
Matteo Merli 已提交
459 460
    if args.header:
        http_headers = dict(x.split(': ') for x in args.header)
461
        logger.info(http_headers)
M
Matteo Merli 已提交
462 463

    global http_proxyes
464
    http_proxyes = { "no_proxy": os.getenv("NO_PROXY", "") }
M
Matteo Merli 已提交
465 466 467 468 469 470 471 472
    if args.proxy:
        http_proxyes['http'] = args.proxy
        http_proxyes['https'] = args.proxy

    # Schedule a new collection every 1min
    while True:
        p = multiprocessing.Process(target=collect_and_purge)
        p.start()
473
        time.sleep(int(os.getenv("COLLECTION_INTERVAL", 60)))