collector.cpp 15.5 KB
Newer Older
gejun's avatar
gejun committed
1
// Copyright (c) 2015 Baidu, Inc.
gejun's avatar
gejun committed
2 3 4 5 6 7 8 9 10 11 12 13 14 15
// 
// Licensed 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
// 
//     http://www.apache.org/licenses/LICENSE-2.0
// 
// 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.

// Author: Ge,Jun (gejun@baidu.com)
gejun's avatar
gejun committed
16 17 18 19
// Date: Mon Dec 14 19:12:30 CST 2015

#include <map>
#include <gflags/gflags.h>
20
#include "butil/memory/singleton_on_pthread_once.h"
gejun's avatar
gejun committed
21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99
#include "bvar/bvar.h"
#include "bvar/collector.h"

namespace bvar {

// TODO: Do we need to expose this flag? Dumping thread may dump different
// kind of samples, users are unlikely to make good decisions on this value.
DEFINE_int32(bvar_collector_max_pending_samples, 1000,
             "Destroy unprocessed samples when they're too many");

DEFINE_int32(bvar_collector_expected_per_second, 1000,
             "Expected number of samples to be collected per second");

// CAUTION: Don't change this value unless you know exactly what it means.
static const int64_t COLLECTOR_GRAB_INTERVAL_US = 100000L; // 100ms

BAIDU_CASSERT(!(COLLECTOR_SAMPLING_BASE & (COLLECTOR_SAMPLING_BASE - 1)),
              must_be_power_of_2);

// Combine two circular linked list into one.
struct CombineCollected {
    void operator()(Collected* & s1, Collected* s2) const {
        if (s2 == NULL) {
            return;
        }
        if (s1 == NULL) {
            s1 = s2;
            return;
        }
        s1->InsertBeforeAsList(s2);
    }
};

// A thread and a special bvar to collect samples submitted.
class Collector : public bvar::Reducer<Collected*, CombineCollected> {
public:
    Collector();
    ~Collector();

    int64_t last_active_cpuwide_us() const { return _last_active_cpuwide_us; }

    void wakeup_grab_thread();

private:
    // The thread for collecting TLS submissions.
    void grab_thread();

    // The thread for calling user's callbacks.
    void dump_thread();

    // Adjust speed_limit if grab_thread collected too many in one round.
    void update_speed_limit(CollectorSpeedLimit* speed_limit,
                            size_t* last_ngrab, size_t cur_ngrab,
                            int64_t interval_us);

    static void* run_grab_thread(void* arg) {
        static_cast<Collector*>(arg)->grab_thread();
        return NULL;
    }

    static void* run_dump_thread(void* arg) {
        static_cast<Collector*>(arg)->dump_thread();
        return NULL;
    }

    static int64_t get_pending_count(void* arg) {
        Collector* d = static_cast<Collector*>(arg);
        return d->_ngrab - d->_ndump - d->_ndrop;
    }
    
private:
    // periodically modified by grab_thread, accessed by every submit.
    // Make sure that this cacheline does not include frequently modified field.
    int64_t _last_active_cpuwide_us;
    
    bool _created;      // Mark validness of _grab_thread.
    bool _stop;         // Set to true in dtor.
    pthread_t _grab_thread;     // For joining.
    pthread_t _dump_thread;
100
    int64_t _ngrab BAIDU_CACHELINE_ALIGNMENT;
gejun's avatar
gejun committed
101 102 103 104
    int64_t _ndrop;
    int64_t _ndump;
    pthread_mutex_t _dump_thread_mutex;
    pthread_cond_t _dump_thread_cond;
105
    butil::LinkNode<Collected> _dump_root;
gejun's avatar
gejun committed
106 107 108 109 110
    pthread_mutex_t _sleep_mutex;
    pthread_cond_t _sleep_cond;
};

Collector::Collector()
111
    : _last_active_cpuwide_us(butil::cpuwide_time_us())
gejun's avatar
gejun committed
112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151
    , _created(false)
    , _stop(false)
    , _grab_thread(0)
    , _dump_thread(0)
    , _ngrab(0)
    , _ndrop(0)
    , _ndump(0) {
    pthread_mutex_init(&_dump_thread_mutex, NULL);
    pthread_cond_init(&_dump_thread_cond, NULL);
    pthread_mutex_init(&_sleep_mutex, NULL);
    pthread_cond_init(&_sleep_cond, NULL);
    int rc = pthread_create(&_grab_thread, NULL, run_grab_thread, this);
    if (rc != 0) {
        LOG(ERROR) << "Fail to create Collector, " << berror(rc);
    } else {
        _created = true;
    }
}

Collector::~Collector() {
    if (_created) {
        _stop = true;
        pthread_join(_grab_thread, NULL);
        _created = false;
    }
    pthread_mutex_destroy(&_dump_thread_mutex);
    pthread_cond_destroy(&_dump_thread_cond);
    pthread_mutex_destroy(&_sleep_mutex);
    pthread_cond_destroy(&_sleep_cond);
}

template <typename T>
static T deref_value(void* arg) {
    return *(T*)arg;
}

// for limiting samples returning NULL in speed_limit()
static CollectorSpeedLimit g_null_speed_limit = BVAR_COLLECTOR_SPEED_LIMIT_INITIALIZER;

void Collector::grab_thread() {
152
    _last_active_cpuwide_us = butil::cpuwide_time_us();
gejun's avatar
gejun committed
153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192
    int64_t last_before_update_sl = _last_active_cpuwide_us;

    // This is the thread for collecting TLS submissions. User's callbacks are
    // called inside the separate _dump_thread to prevent a slow callback
    // (caused by busy disk generally) from blocking collecting code too long
    // that pending requests may explode memory.
    CHECK_EQ(0, pthread_create(&_dump_thread, NULL, run_dump_thread, this));

    // vars
    bvar::PassiveStatus<int64_t> pending_sampled_data(
        "bvar_collector_pending_samples", get_pending_count, this);
    double busy_seconds = 0;
    bvar::PassiveStatus<double> busy_seconds_var(deref_value<double>, &busy_seconds);
    bvar::PerSecond<bvar::PassiveStatus<double> > busy_seconds_second(
        "bvar_collector_grab_thread_usage", &busy_seconds_var);

    bvar::PassiveStatus<int64_t> ngrab_var(deref_value<int64_t>, &_ngrab);
    bvar::PerSecond<bvar::PassiveStatus<int64_t> > ngrab_second(
        "bvar_collector_grab_second", &ngrab_var);

    // Maps for calculating speed limit.
    typedef std::map<CollectorSpeedLimit*, size_t> GrapMap;
    GrapMap last_ngrab_map;
    GrapMap ngrab_map;
    // Map for group samples by preprocessors.
    typedef std::map<CollectorPreprocessor*, std::vector<Collected*> >
        PreprocessorMap;
    PreprocessorMap prep_map;

    // The main loop.
    while (!_stop) {
        const int64_t abstime = _last_active_cpuwide_us + COLLECTOR_GRAB_INTERVAL_US;

        // Clear and reuse vectors in prep_map, don't clear prep_map directly.
        for (PreprocessorMap::iterator it = prep_map.begin(); it != prep_map.end();
             ++it) {
            it->second.clear();
        }

        // Collect TLS submissions and give them to dump_thread.
193
        butil::LinkNode<Collected>* head = this->reset();
gejun's avatar
gejun committed
194
        if (head) {
195
            butil::LinkNode<Collected> tmp_root;
gejun's avatar
gejun committed
196 197 198 199
            head->InsertBeforeAsList(&tmp_root);
            head = NULL;
            
            // Group samples by preprocessors.
200 201
            for (butil::LinkNode<Collected>* p = tmp_root.next(); p != &tmp_root;) {
                butil::LinkNode<Collected>* saved_next = p->next();
gejun's avatar
gejun committed
202 203 204 205 206 207
                p->RemoveFromList();
                CollectorPreprocessor* prep = p->value()->preprocessor();
                prep_map[prep].push_back(p->value());
                p = saved_next;
            }
            // Iterate prep_map
208
            butil::LinkNode<Collected> root;
gejun's avatar
gejun committed
209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241
            for (PreprocessorMap::iterator it = prep_map.begin();
                 it != prep_map.end(); ++it) {
                std::vector<Collected*> & list = it->second;
                if (it->second.empty()) {
                    // don't call preprocessor when there's no samples.
                    continue;
                }
                if (it->first != NULL) {
                    it->first->process(list);
                }
                for (size_t i = 0; i < list.size(); ++i) {
                    Collected* p = list[i];
                    CollectorSpeedLimit* speed_limit = p->speed_limit();
                    if (speed_limit == NULL) {
                        ++ngrab_map[&g_null_speed_limit];
                    } else {
                        // Add up the samples of certain type.
                        ++ngrab_map[speed_limit];
                    }
                    // Drop samples if dump_thread is too busy.
                    // FIXME: equal probabilities to drop.
                    ++_ngrab;
                    if (_ngrab >= _ndrop + _ndump +
                        FLAGS_bvar_collector_max_pending_samples) {
                        ++_ndrop;
                        p->destroy();
                    } else {
                        p->InsertBefore(&root);
                    }
                }
            }
            // Give the samples to dump_thread
            if (root.next() != &root) {  // non empty
242
                butil::LinkNode<Collected>* head2 = root.next();
gejun's avatar
gejun committed
243 244 245 246 247 248
                root.RemoveFromList();
                BAIDU_SCOPED_LOCK(_dump_thread_mutex);
                head2->InsertBeforeAsList(&_dump_root);
                pthread_cond_signal(&_dump_thread_cond);
            }
        }
249
        int64_t now = butil::cpuwide_time_us();
gejun's avatar
gejun committed
250 251 252 253 254 255 256 257
        int64_t interval = now - last_before_update_sl;
        last_before_update_sl = now;
        for (GrapMap::iterator it = ngrab_map.begin();
             it != ngrab_map.end(); ++it) {
            update_speed_limit(it->first, &last_ngrab_map[it->first],
                               it->second, interval);
        }
        
258
        now = butil::cpuwide_time_us();
gejun's avatar
gejun committed
259 260 261 262 263 264
        // calcuate thread usage.
        busy_seconds += (now - _last_active_cpuwide_us) / 1000000.0;
        _last_active_cpuwide_us = now;

        // sleep for the next round.
        if (!_stop && abstime > now) {
265
            timespec abstimespec = butil::microseconds_from_now(abstime - now);
gejun's avatar
gejun committed
266 267 268 269
            pthread_mutex_lock(&_sleep_mutex);
            pthread_cond_timedwait(&_sleep_cond, &_sleep_mutex, &abstimespec);
            pthread_mutex_unlock(&_sleep_mutex);
        }
270
        _last_active_cpuwide_us = butil::cpuwide_time_us();
gejun's avatar
gejun committed
271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303
    }
    // make sure _stop is true, we may have other reasons to quit above loop
    {
        BAIDU_SCOPED_LOCK(_dump_thread_mutex);
        _stop = true; 
        pthread_cond_signal(&_dump_thread_cond);
    }
    CHECK_EQ(0, pthread_join(_dump_thread, NULL));
}

void Collector::wakeup_grab_thread() {
    pthread_mutex_lock(&_sleep_mutex);
    pthread_cond_signal(&_sleep_cond);
    pthread_mutex_unlock(&_sleep_mutex);
}

// Adjust speed_limit to match collected samples per second
void Collector::update_speed_limit(CollectorSpeedLimit* sl,
                                   size_t* last_ngrab, size_t cur_ngrab,
                                   int64_t interval_us) {
    // FIXME: May become too large at startup.
    const size_t round_ngrab = cur_ngrab - *last_ngrab;
    if (round_ngrab == 0) {
        return;
    }
    *last_ngrab = cur_ngrab;
    if (interval_us < 0) {
        interval_us = 0;
    }
    size_t new_sampling_range = 0;
    const size_t old_sampling_range = sl->sampling_range;
    if (!sl->ever_grabbed) {
        if (sl->first_sample_real_us) {
304
            interval_us = butil::gettimeofday_us() - sl->first_sample_real_us;
gejun's avatar
gejun committed
305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345
            if (interval_us < 0) {
                interval_us = 0;
            }
        } else {
            // Rare. the timestamp is still not set or visible yet. Just
            // use the default interval which may make the calculated
            // sampling_range larger.
        }
        new_sampling_range = FLAGS_bvar_collector_expected_per_second
            * interval_us * COLLECTOR_SAMPLING_BASE / (1000000L * round_ngrab);
    } else {
        // NOTE: the multiplications are unlikely to overflow.
        new_sampling_range = FLAGS_bvar_collector_expected_per_second
            * interval_us * old_sampling_range / (1000000L * round_ngrab);
        // Don't grow or shrink too fast.
        if (interval_us < 1000000L) {
            new_sampling_range =
                (new_sampling_range * interval_us +
                 old_sampling_range * (1000000L - interval_us)) / 1000000L;
        }
    }
    // Make sure new value is sane.
    if (new_sampling_range == 0) {
        new_sampling_range = 1;
    } else if (new_sampling_range > COLLECTOR_SAMPLING_BASE) {
        new_sampling_range = COLLECTOR_SAMPLING_BASE;
    }

    // NOTE: don't update unmodified fields in sl to avoid meaningless
    // flushing of the cacheline. 
    if (new_sampling_range != old_sampling_range) {
        sl->sampling_range = new_sampling_range;
    }
    if (!sl->ever_grabbed) {
        sl->ever_grabbed = true;
    }
}

size_t is_collectable_before_first_time_grabbed(CollectorSpeedLimit* sl) {
    if (!sl->ever_grabbed) {
        int before_add = sl->count_before_grabbed.fetch_add(
346
            1, butil::memory_order_relaxed);
gejun's avatar
gejun committed
347
        if (before_add == 0) {
348
            sl->first_sample_real_us = butil::gettimeofday_us();
gejun's avatar
gejun committed
349
        } else if (before_add >= FLAGS_bvar_collector_expected_per_second) {
350
            butil::get_leaky_singleton<Collector>()->wakeup_grab_thread();
gejun's avatar
gejun committed
351 352 353 354 355 356 357
        }
    }
    return sl->sampling_range;
}

// Call user's callbacks in this thread.
void Collector::dump_thread() {
358
    int64_t last_ns = butil::cpuwide_time_ns();
gejun's avatar
gejun committed
359 360 361 362 363 364 365 366 367 368 369

    // vars
    double busy_seconds = 0;
    bvar::PassiveStatus<double> busy_seconds_var(deref_value<double>, &busy_seconds);
    bvar::PerSecond<bvar::PassiveStatus<double> > busy_seconds_second(
        "bvar_collector_dump_thread_usage", &busy_seconds_var);

    bvar::PassiveStatus<int64_t> ndumped_var(deref_value<int64_t>, &_ndump);
    bvar::PerSecond<bvar::PassiveStatus<int64_t> > ndumped_second(
        "bvar::collector_dump_second", &ndumped_var);

370
    butil::LinkNode<Collected> root;
gejun's avatar
gejun committed
371 372 373 374 375 376
    size_t round = 0;

    // The main loop
    while (!_stop) {
        ++round;
        // Get new samples set by grab_thread.
377
        butil::LinkNode<Collected>* newhead = NULL;
gejun's avatar
gejun committed
378 379 380
        {
            BAIDU_SCOPED_LOCK(_dump_thread_mutex);
            while (!_stop && _dump_root.next() == &_dump_root) {
381
                const int64_t now_ns = butil::cpuwide_time_ns();
gejun's avatar
gejun committed
382 383
                busy_seconds += (now_ns - last_ns) / 1000000000.0;
                pthread_cond_wait(&_dump_thread_cond, &_dump_thread_mutex);
384
                last_ns = butil::cpuwide_time_ns();
gejun's avatar
gejun committed
385 386 387 388 389 390 391 392 393 394 395
            }
            if (_stop) {
                break;
            }
            newhead = _dump_root.next();
            _dump_root.RemoveFromList();
        }
        CHECK(newhead != &_dump_root);
        newhead->InsertBeforeAsList(&root);

        // Call callbacks.
396
        for (butil::LinkNode<Collected>* p = root.next(); !_stop && p != &root;) {
gejun's avatar
gejun committed
397
            // We remove p from the list, save next first.
398
            butil::LinkNode<Collected>* saved_next = p->next();
gejun's avatar
gejun committed
399 400 401 402 403 404 405 406 407 408
            p->RemoveFromList();
            Collected* s = p->value();
            s->dump_and_destroy(round);
            ++_ndump;
            p = saved_next;
        }
    }
}

void Collected::submit(int64_t cpuwide_us) {
409
    Collector* d = butil::get_leaky_singleton<Collector>();
gejun's avatar
gejun committed
410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432
    // Destroy the sample in-place if the grab_thread did not run for twice
    // of the normal interval. This also applies to the situation that
    // grab_thread aborts due to severe errors.
    // Collector::_last_active_cpuwide_us is periodically modified by grab_thread,
    // cache bouncing is tolerable.
    if (cpuwide_us < d->last_active_cpuwide_us() + COLLECTOR_GRAB_INTERVAL_US * 2) {
        *d << this;
    } else {
        destroy();
    }
}

static double get_sampling_ratio(void* arg) {
    return ((const CollectorSpeedLimit*)arg)->sampling_range /
        (double)COLLECTOR_SAMPLING_BASE;
}

DisplaySamplingRatio::DisplaySamplingRatio(const char* name,
                                           const CollectorSpeedLimit* sl)
    : _var(name, get_sampling_ratio, (void*)sl) {
}

}  // namespace bvar