collector.py 18.9 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 102
            name=namespace_name,
            property=property)
M
Matteo Merli 已提交
103 104 105 106 107
        namespace.clusters.add(cluster)
        namespace.save()

        for bundle_range, topics_stats in bundles_stats.items():

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

M
Matteo Merli 已提交
126
            for topic_name, stats in topics_stats['persistent'].items():
127 128 129 130 131 132 133 134
                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()
135 136 137 138 139 140
                    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']
141
                    temp_topic.pendingAddEntriesCount = stats['pendingAddEntriesCount']
142 143
                    temp_topic.producerCount = stats['producerCount']
                    temp_topic.storageSize = stats['storageSize']
144 145 146 147
                    db_update_topics.append(temp_topic)
                    topic = temp_topic
                else:
                    topic = Topic(
148 149 150 151 152 153 154 155 156 157 158 159 160 161 162
                        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']
163 164
                    )
                    db_create_topics.append(topic)
M
Matteo Merli 已提交
165 166 167 168 169 170
                totalBacklog = 0
                numSubscriptions = 0
                numConsumers = 0

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

                    totalBacklog += subStats['msgBacklog']

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

                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(
252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267
                        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 已提交
268 269 270 271
                    )

                    db_replication.append(replication)

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

                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
290
        Bundle.objects.bulk_create(db_create_bundles, batch_size=10000)
M
Matteo Merli 已提交
291 292

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

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

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

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

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

311 312 313 314 315 316 317 318 319 320 321
    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 已提交
322 323 324 325 326

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

327

328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345
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 已提交
346 347

def fetch_stats():
348
    logger.info("Begin fetch stats")
M
Matteo Merli 已提交
349 350 351 352 353 354
    timestamp = current_milli_time()

    pool = multiprocessing.Pool(args.workers)

    futures = []

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

358
        cluster_url = get(args.serviceUrl, '/admin/v2/clusters/' + cluster_name)['serviceUrl']
359 360 361 362 363 364 365 366 367
        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]

368
        logger.info('Cluster:{} -> {}'.format(cluster_name, cluster_url))
M
Matteo Merli 已提交
369 370 371 372 373 374 375 376
        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:
377
            for broker_host_port in get(cluster.serviceUrl, '/admin/v2/brokers/' + cluster.name):
M
Matteo Merli 已提交
378 379 380
                f = pool.apply_async(fetch_broker_stats, (cluster, broker_host_port, timestamp))
                futures.append(f)
        except Exception as e:
381
            logger.error('ERROR: ', e)
M
Matteo Merli 已提交
382 383 384 385 386 387 388 389 390 391 392 393

    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()
394 395
    logger.info("Finished fetch stats")

M
Matteo Merli 已提交
396 397

def purge_db():
398
    logger.info("Begin purge db")
M
Matteo Merli 已提交
399 400 401 402
    now = current_milli_time()
    ttl_minutes = args.purge
    threshold = now - (ttl_minutes * 60 * 1000)

403 404 405 406 407 408
    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()
    logger.info("Finsihed purge db")

M
Matteo Merli 已提交
409 410

def collect_and_purge():
411
    logger.info('Starting stats collection')
M
Matteo Merli 已提交
412 413
    fetch_stats()
    purge_db()
414 415
    logger.info('Finished collecting stats')

M
Matteo Merli 已提交
416 417 418 419 420 421 422 423 424 425 426

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',
427
                        help="Connect using a HTTP proxy", dest="proxy")
M
Matteo Merli 已提交
428
    parser.add_argument('--header', action="append", dest="header",
429
                        help='Add an additional HTTP header to all requests')
M
Matteo Merli 已提交
430
    parser.add_argument('--purge', action="store", dest="purge", type=int, default=60,
431
                        help='Purge statistics older than PURGE minutes. (default: 60min)')
M
Matteo Merli 已提交
432 433

    parser.add_argument('--workers', action="store", dest="workers", type=int, default=64,
434
                        help='Number of worker processes to be used to fetch the stats (default: 64)')
M
Matteo Merli 已提交
435 436 437 438 439 440

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

    global http_headers
    http_headers = {}
441 442 443 444
    jwt_token = os.getenv("JWT_TOKEN", None)
    if jwt_token is not None:
        http_headers = {
            "Authorization": "Bearer {}".format(jwt_token)}
M
Matteo Merli 已提交
445 446
    if args.header:
        http_headers = dict(x.split(': ') for x in args.header)
447
        logger.info(http_headers)
M
Matteo Merli 已提交
448 449 450 451 452 453 454 455 456 457 458

    global http_proxyes
    http_proxyes = {}
    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()
459
        time.sleep(int(os.getenv("COLLECTION_INTERVAL", 60)))