]> git.proxmox.com Git - ceph.git/blame - ceph/src/mds/MDBalancer.cc
update sources to v12.2.3
[ceph.git] / ceph / src / mds / MDBalancer.cc
CommitLineData
7c673cae
FG
1// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
2// vim: ts=8 sw=2 smarttab
3/*
4 * Ceph - scalable distributed file system
5 *
6 * Copyright (C) 2004-2006 Sage Weil <sage@newdream.net>
7 *
8 * This is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU Lesser General Public
10 * License version 2.1, as published by the Free Software
11 * Foundation. See file COPYING.
12 *
13 */
14
15#include "include/compat.h"
16#include "mdstypes.h"
17
18#include "MDBalancer.h"
19#include "MDSRank.h"
20#include "mon/MonClient.h"
21#include "MDSMap.h"
22#include "CInode.h"
23#include "CDir.h"
24#include "MDCache.h"
25#include "Migrator.h"
26#include "Mantle.h"
27
28#include "include/Context.h"
29#include "msg/Messenger.h"
30#include "messages/MHeartbeat.h"
31
32#include <fstream>
33#include <iostream>
34#include <vector>
35#include <map>
36using std::map;
37using std::vector;
38
39#include "common/config.h"
40#include "common/errno.h"
41
42#define dout_context g_ceph_context
43#define dout_subsys ceph_subsys_mds
44#undef dout_prefix
45#define dout_prefix *_dout << "mds." << mds->get_nodeid() << ".bal "
46#undef dout
47#define dout(lvl) \
48 do {\
49 auto subsys = ceph_subsys_mds;\
50 if ((dout_context)->_conf->subsys.should_gather(ceph_subsys_mds_balancer, lvl)) {\
51 subsys = ceph_subsys_mds_balancer;\
52 }\
53 dout_impl(dout_context, subsys, lvl) dout_prefix
54#undef dendl
55#define dendl dendl_impl; } while (0)
56
57
58#define MIN_LOAD 50 // ??
59#define MIN_REEXPORT 5 // will automatically reexport
60#define MIN_OFFLOAD 10 // point at which i stop trying, close enough
61
62
63/* This function DOES put the passed message before returning */
64int MDBalancer::proc_message(Message *m)
65{
66 switch (m->get_type()) {
67
68 case MSG_MDS_HEARTBEAT:
69 handle_heartbeat(static_cast<MHeartbeat*>(m));
70 break;
71
72 default:
b32b8144 73 derr << " balancer unknown message " << m->get_type() << dendl_impl;
7c673cae
FG
74 assert(0 == "balancer unknown message");
75 }
76
77 return 0;
78}
79
80void MDBalancer::handle_export_pins(void)
81{
82 auto &q = mds->mdcache->export_pin_queue;
83 auto it = q.begin();
84 dout(20) << "export_pin_queue size=" << q.size() << dendl;
85 while (it != q.end()) {
31f18b77
FG
86 auto cur = it++;
87 CInode *in = *cur;
7c673cae 88 assert(in->is_dir());
31f18b77
FG
89 mds_rank_t export_pin = in->get_export_pin(false);
90
91 bool remove = true;
92 list<CDir*> dfls;
93 in->get_dirfrags(dfls);
94 for (auto dir : dfls) {
95 if (!dir->is_auth())
96 continue;
97
98 if (export_pin == MDS_RANK_NONE) {
99 if (dir->state_test(CDir::STATE_AUXSUBTREE)) {
100 if (dir->is_frozen() || dir->is_freezing()) {
101 // try again later
102 remove = false;
103 continue;
104 }
105 dout(10) << " clear auxsubtree on " << *dir << dendl;
106 dir->state_clear(CDir::STATE_AUXSUBTREE);
107 mds->mdcache->try_subtree_merge(dir);
108 }
109 } else if (export_pin == mds->get_nodeid()) {
110 if (dir->state_test(CDir::STATE_CREATING) ||
111 dir->is_frozen() || dir->is_freezing()) {
112 // try again later
113 remove = false;
114 continue;
115 }
116 if (!dir->is_subtree_root()) {
117 dir->state_set(CDir::STATE_AUXSUBTREE);
118 mds->mdcache->adjust_subtree_auth(dir, mds->get_nodeid());
119 dout(10) << " create aux subtree on " << *dir << dendl;
120 } else if (!dir->state_test(CDir::STATE_AUXSUBTREE)) {
121 dout(10) << " set auxsubtree bit on " << *dir << dendl;
122 dir->state_set(CDir::STATE_AUXSUBTREE);
123 }
124 } else {
125 mds->mdcache->migrator->export_dir(dir, export_pin);
126 remove = false;
7c673cae
FG
127 }
128 }
31f18b77
FG
129
130 if (remove) {
131 in->state_clear(CInode::STATE_QUEUEDEXPORTPIN);
132 q.erase(cur);
7c673cae
FG
133 }
134 }
135
136 set<CDir *> authsubs;
137 mds->mdcache->get_auth_subtrees(authsubs);
138 for (auto &cd : authsubs) {
139 mds_rank_t export_pin = cd->inode->get_export_pin();
140 dout(10) << "auth tree " << *cd << " export_pin=" << export_pin << dendl;
141 if (export_pin >= 0 && export_pin != mds->get_nodeid()) {
142 dout(10) << "exporting auth subtree " << *cd->inode << " to " << export_pin << dendl;
143 mds->mdcache->migrator->export_dir(cd, export_pin);
144 }
145 }
146}
147
148void MDBalancer::tick()
149{
150 static int num_bal_times = g_conf->mds_bal_max;
151 static utime_t first = ceph_clock_now();
152 utime_t now = ceph_clock_now();
153 utime_t elapsed = now;
154 elapsed -= first;
155
156 if (g_conf->mds_bal_export_pin) {
157 handle_export_pins();
158 }
159
160 // sample?
161 if ((double)now - (double)last_sample > g_conf->mds_bal_sample_interval) {
162 dout(15) << "tick last_sample now " << now << dendl;
163 last_sample = now;
164 }
165
166 // balance?
167 if (last_heartbeat == utime_t())
168 last_heartbeat = now;
169 if (mds->get_nodeid() == 0 &&
170 g_conf->mds_bal_interval > 0 &&
171 (num_bal_times ||
172 (g_conf->mds_bal_max_until >= 0 &&
173 elapsed.sec() > g_conf->mds_bal_max_until)) &&
174 mds->is_active() &&
175 now.sec() - last_heartbeat.sec() >= g_conf->mds_bal_interval) {
176 last_heartbeat = now;
177 send_heartbeat();
178 num_bal_times--;
179 }
180}
181
182
183
184
185class C_Bal_SendHeartbeat : public MDSInternalContext {
186public:
187 explicit C_Bal_SendHeartbeat(MDSRank *mds_) : MDSInternalContext(mds_) { }
188 void finish(int f) override {
189 mds->balancer->send_heartbeat();
190 }
191};
192
193
194double mds_load_t::mds_load()
195{
196 switch(g_conf->mds_bal_mode) {
197 case 0:
198 return
199 .8 * auth.meta_load() +
200 .2 * all.meta_load() +
201 req_rate +
202 10.0 * queue_len;
203
204 case 1:
205 return req_rate + 10.0*queue_len;
206
207 case 2:
208 return cpu_load_avg;
209
210 }
211 ceph_abort();
212 return 0;
213}
214
215mds_load_t MDBalancer::get_load(utime_t now)
216{
217 mds_load_t load(now);
218
219 if (mds->mdcache->get_root()) {
220 list<CDir*> ls;
221 mds->mdcache->get_root()->get_dirfrags(ls);
222 for (list<CDir*>::iterator p = ls.begin();
223 p != ls.end();
224 ++p) {
225 load.auth.add(now, mds->mdcache->decayrate, (*p)->pop_auth_subtree_nested);
226 load.all.add(now, mds->mdcache->decayrate, (*p)->pop_nested);
227 }
228 } else {
229 dout(20) << "get_load no root, no load" << dendl;
230 }
231
232 load.req_rate = mds->get_req_rate();
233 load.queue_len = messenger->get_dispatch_queue_len();
234
235 ifstream cpu(PROCPREFIX "/proc/loadavg");
236 if (cpu.is_open())
237 cpu >> load.cpu_load_avg;
238 else
b32b8144 239 derr << "input file " PROCPREFIX "'/proc/loadavg' not found" << dendl_impl;
7c673cae
FG
240
241 dout(15) << "get_load " << load << dendl;
242 return load;
243}
244
245/*
246 * Read synchronously from RADOS using a timeout. We cannot do daemon-local
247 * fallbacks (i.e. kick off async read when we are processing the map and
248 * check status when we get here) with the way the mds is structured.
249 */
250int MDBalancer::localize_balancer()
251{
252 /* reset everything */
253 bool ack = false;
254 int r = 0;
255 bufferlist lua_src;
256 Mutex lock("lock");
257 Cond cond;
258
259 /* we assume that balancer is in the metadata pool */
260 object_t oid = object_t(mds->mdsmap->get_balancer());
261 object_locator_t oloc(mds->mdsmap->get_metadata_pool());
262 ceph_tid_t tid = mds->objecter->read(oid, oloc, 0, 0, CEPH_NOSNAP, &lua_src, 0,
263 new C_SafeCond(&lock, &cond, &ack, &r));
264 dout(15) << "launched non-blocking read tid=" << tid
265 << " oid=" << oid << " oloc=" << oloc << dendl;
266
267 /* timeout: if we waste half our time waiting for RADOS, then abort! */
268 double t = ceph_clock_now() + g_conf->mds_bal_interval/2;
269 utime_t timeout;
270 timeout.set_from_double(t);
271 lock.Lock();
272 int ret_t = cond.WaitUntil(lock, timeout);
273 lock.Unlock();
274
275 /* success: store the balancer in memory and set the version. */
276 if (!r) {
277 if (ret_t == ETIMEDOUT) {
278 mds->objecter->op_cancel(tid, -ECANCELED);
279 return -ETIMEDOUT;
280 }
281 bal_code.assign(lua_src.to_str());
282 bal_version.assign(oid.name);
b32b8144 283 dout(10) << "localized balancer, bal_code=" << bal_code << dendl;
7c673cae
FG
284 }
285 return r;
286}
287
288void MDBalancer::send_heartbeat()
289{
290 utime_t now = ceph_clock_now();
291
292 if (mds->is_cluster_degraded()) {
293 dout(10) << "send_heartbeat degraded" << dendl;
294 return;
295 }
296
297 if (!mds->mdcache->is_open()) {
298 dout(5) << "not open" << dendl;
299 mds->mdcache->wait_for_open(new C_Bal_SendHeartbeat(mds));
300 return;
301 }
302
303 mds_load.clear();
304 if (mds->get_nodeid() == 0)
305 beat_epoch++;
306
307 // my load
308 mds_load_t load = get_load(now);
309 map<mds_rank_t, mds_load_t>::value_type val(mds->get_nodeid(), load);
310 mds_load.insert(val);
311
312 // import_map -- how much do i import from whom
313 map<mds_rank_t, float> import_map;
314 set<CDir*> authsubs;
315 mds->mdcache->get_auth_subtrees(authsubs);
316 for (set<CDir*>::iterator it = authsubs.begin();
317 it != authsubs.end();
318 ++it) {
319 CDir *im = *it;
320 mds_rank_t from = im->inode->authority().first;
321 if (from == mds->get_nodeid()) continue;
322 if (im->get_inode()->is_stray()) continue;
323 import_map[from] += im->pop_auth_subtree.meta_load(now, mds->mdcache->decayrate);
324 }
325 mds_import_map[ mds->get_nodeid() ] = import_map;
326
327
328 dout(5) << "mds." << mds->get_nodeid() << " epoch " << beat_epoch << " load " << load << dendl;
329 for (map<mds_rank_t, float>::iterator it = import_map.begin();
330 it != import_map.end();
331 ++it) {
332 dout(5) << " import_map from " << it->first << " -> " << it->second << dendl;
333 }
334
335
336 set<mds_rank_t> up;
337 mds->get_mds_map()->get_up_mds_set(up);
338 for (set<mds_rank_t>::iterator p = up.begin(); p != up.end(); ++p) {
339 if (*p == mds->get_nodeid())
340 continue;
341 MHeartbeat *hb = new MHeartbeat(load, beat_epoch);
342 hb->get_import_map() = import_map;
343 messenger->send_message(hb,
344 mds->mdsmap->get_inst(*p));
345 }
346}
347
348/* This function DOES put the passed message before returning */
349void MDBalancer::handle_heartbeat(MHeartbeat *m)
350{
351 typedef map<mds_rank_t, mds_load_t> mds_load_map_t;
352
353 mds_rank_t who = mds_rank_t(m->get_source().num());
354 dout(25) << "=== got heartbeat " << m->get_beat() << " from " << m->get_source().num() << " " << m->get_load() << dendl;
355
356 if (!mds->is_active())
357 goto out;
358
359 if (!mds->mdcache->is_open()) {
360 dout(10) << "opening root on handle_heartbeat" << dendl;
361 mds->mdcache->wait_for_open(new C_MDS_RetryMessage(mds, m));
362 return;
363 }
364
365 if (mds->is_cluster_degraded()) {
366 dout(10) << " degraded, ignoring" << dendl;
367 goto out;
368 }
369
370 if (who == 0) {
371 dout(20) << " from mds0, new epoch" << dendl;
372 beat_epoch = m->get_beat();
373 send_heartbeat();
374
375 mds->mdcache->show_subtrees();
376 }
377
378 {
379 // set mds_load[who]
380 mds_load_map_t::value_type val(who, m->get_load());
381 pair < mds_load_map_t::iterator, bool > rval (mds_load.insert(val));
382 if (!rval.second) {
383 rval.first->second = val.second;
384 }
385 }
386 mds_import_map[ who ] = m->get_import_map();
387
7c673cae
FG
388 {
389 unsigned cluster_size = mds->get_mds_map()->get_num_in_mds();
390 if (mds_load.size() == cluster_size) {
391 // let's go!
392 //export_empties(); // no!
393
394 /* avoid spamming ceph -w if user does not turn mantle on */
395 if (mds->mdsmap->get_balancer() != "") {
396 int r = mantle_prep_rebalance();
31f18b77 397 if (!r) goto out;
7c673cae
FG
398 mds->clog->warn() << "using old balancer; mantle failed for "
399 << "balancer=" << mds->mdsmap->get_balancer()
400 << " : " << cpp_strerror(r);
401 }
402 prep_rebalance(m->get_beat());
403 }
404 }
405
406 // done
407 out:
408 m->put();
409}
410
411
412void MDBalancer::export_empties()
413{
414 dout(5) << "export_empties checking for empty imports" << dendl;
415
416 std::set<CDir *> subtrees;
417 mds->mdcache->get_fullauth_subtrees(subtrees);
418 for (auto &dir : subtrees) {
419 if (dir->is_freezing() || dir->is_frozen())
420 continue;
421
422 if (!dir->inode->is_base() &&
423 !dir->inode->is_stray() &&
424 dir->get_num_head_items() == 0)
425 mds->mdcache->migrator->export_empty_import(dir);
426 }
427}
428
429
430
431double MDBalancer::try_match(balance_state_t& state, mds_rank_t ex, double& maxex,
432 mds_rank_t im, double& maxim)
433{
434 if (maxex <= 0 || maxim <= 0) return 0.0;
435
436 double howmuch = MIN(maxex, maxim);
437 if (howmuch <= 0) return 0.0;
438
439 dout(5) << " - mds." << ex << " exports " << howmuch << " to mds." << im << dendl;
440
441 if (ex == mds->get_nodeid())
442 state.targets[im] += howmuch;
443
444 state.exported[ex] += howmuch;
445 state.imported[im] += howmuch;
446
447 maxex -= howmuch;
448 maxim -= howmuch;
449
450 return howmuch;
451}
452
453void MDBalancer::queue_split(const CDir *dir, bool fast)
454{
455 dout(10) << __func__ << " enqueuing " << *dir
456 << " (fast=" << fast << ")" << dendl;
457
458 assert(mds->mdsmap->allows_dirfrags());
459 const dirfrag_t frag = dir->dirfrag();
460
461 auto callback = [this, frag](int r) {
462 if (split_pending.erase(frag) == 0) {
463 // Someone beat me to it. This can happen in the fast splitting
464 // path, because we spawn two contexts, one with mds->timer and
465 // one with mds->queue_waiter. The loser can safely just drop
466 // out.
467 return;
468 }
469
470 CDir *split_dir = mds->mdcache->get_dirfrag(frag);
471 if (!split_dir) {
472 dout(10) << "drop split on " << frag << " because not in cache" << dendl;
473 return;
474 }
475 if (!split_dir->is_auth()) {
476 dout(10) << "drop split on " << frag << " because non-auth" << dendl;
477 return;
478 }
479
480 // Pass on to MDCache: note that the split might still not
481 // happen if the checks in MDCache::can_fragment fail.
482 dout(10) << __func__ << " splitting " << *split_dir << dendl;
483 mds->mdcache->split_dir(split_dir, g_conf->mds_bal_split_bits);
484 };
485
486 bool is_new = false;
487 if (split_pending.count(frag) == 0) {
488 split_pending.insert(frag);
489 is_new = true;
490 }
491
492 if (fast) {
493 // Do the split ASAP: enqueue it in the MDSRank waiters which are
494 // run at the end of dispatching the current request
495 mds->queue_waiter(new MDSInternalContextWrapper(mds,
496 new FunctionContext(callback)));
497 } else if (is_new) {
498 // Set a timer to really do the split: we don't do it immediately
499 // so that bursts of ops on a directory have a chance to go through
500 // before we freeze it.
501 mds->timer.add_event_after(g_conf->mds_bal_fragment_interval,
502 new FunctionContext(callback));
503 }
504}
505
506void MDBalancer::queue_merge(CDir *dir)
507{
508 const auto frag = dir->dirfrag();
509 auto callback = [this, frag](int r) {
510 assert(frag.frag != frag_t());
511
512 // frag must be in this set because only one context is in flight
513 // for a given frag at a time (because merge_pending is checked before
514 // starting one), and this context is the only one that erases it.
515 merge_pending.erase(frag);
516
517 CDir *dir = mds->mdcache->get_dirfrag(frag);
518 if (!dir) {
519 dout(10) << "drop merge on " << frag << " because not in cache" << dendl;
520 return;
521 }
522 assert(dir->dirfrag() == frag);
523
524 if(!dir->is_auth()) {
525 dout(10) << "drop merge on " << *dir << " because lost auth" << dendl;
526 return;
527 }
528
529 dout(10) << "merging " << *dir << dendl;
530
531 CInode *diri = dir->get_inode();
532
533 frag_t fg = dir->get_frag();
534 while (fg != frag_t()) {
535 frag_t sibfg = fg.get_sibling();
536 list<CDir*> sibs;
537 bool complete = diri->get_dirfrags_under(sibfg, sibs);
538 if (!complete) {
539 dout(10) << " not all sibs under " << sibfg << " in cache (have " << sibs << ")" << dendl;
540 break;
541 }
542 bool all = true;
543 for (list<CDir*>::iterator p = sibs.begin(); p != sibs.end(); ++p) {
544 CDir *sib = *p;
545 if (!sib->is_auth() || !sib->should_merge()) {
546 all = false;
547 break;
548 }
549 }
550 if (!all) {
551 dout(10) << " not all sibs under " << sibfg << " " << sibs << " should_merge" << dendl;
552 break;
553 }
554 dout(10) << " all sibs under " << sibfg << " " << sibs << " should merge" << dendl;
555 fg = fg.parent();
556 }
557
558 if (fg != dir->get_frag())
559 mds->mdcache->merge_dir(diri, fg);
560 };
561
562 if (merge_pending.count(frag) == 0) {
563 dout(20) << __func__ << " enqueued dir " << *dir << dendl;
564 merge_pending.insert(frag);
565 mds->timer.add_event_after(g_conf->mds_bal_fragment_interval,
566 new FunctionContext(callback));
567 } else {
568 dout(20) << __func__ << " dir already in queue " << *dir << dendl;
569 }
570}
571
572void MDBalancer::prep_rebalance(int beat)
573{
574 balance_state_t state;
575
576 if (g_conf->mds_thrash_exports) {
577 //we're going to randomly export to all the mds in the cluster
578 set<mds_rank_t> up_mds;
579 mds->get_mds_map()->get_up_mds_set(up_mds);
580 for (const auto &rank : up_mds) {
581 state.targets[rank] = 0.0;
582 }
583 } else {
584 int cluster_size = mds->get_mds_map()->get_num_in_mds();
585 mds_rank_t whoami = mds->get_nodeid();
586 rebalance_time = ceph_clock_now();
587
588 dout(5) << " prep_rebalance: cluster loads are" << dendl;
589
590 mds->mdcache->migrator->clear_export_queue();
591
592 // rescale! turn my mds_load back into meta_load units
593 double load_fac = 1.0;
594 map<mds_rank_t, mds_load_t>::iterator m = mds_load.find(whoami);
595 if ((m != mds_load.end()) && (m->second.mds_load() > 0)) {
596 double metald = m->second.auth.meta_load(rebalance_time, mds->mdcache->decayrate);
597 double mdsld = m->second.mds_load();
598 load_fac = metald / mdsld;
599 dout(7) << " load_fac is " << load_fac
600 << " <- " << m->second.auth << " " << metald
601 << " / " << mdsld
602 << dendl;
603 }
604
605 double total_load = 0.0;
606 multimap<double,mds_rank_t> load_map;
607 for (mds_rank_t i=mds_rank_t(0); i < mds_rank_t(cluster_size); i++) {
608 map<mds_rank_t, mds_load_t>::value_type val(i, mds_load_t(ceph_clock_now()));
609 std::pair < map<mds_rank_t, mds_load_t>::iterator, bool > r(mds_load.insert(val));
610 mds_load_t &load(r.first->second);
611
612 double l = load.mds_load() * load_fac;
613 mds_meta_load[i] = l;
614
615 if (whoami == 0)
b32b8144 616 dout(5) << " mds." << i
7c673cae
FG
617 << " " << load
618 << " = " << load.mds_load()
619 << " ~ " << l << dendl;
620
621 if (whoami == i) my_load = l;
622 total_load += l;
623
624 load_map.insert(pair<double,mds_rank_t>( l, i ));
625 }
626
627 // target load
628 target_load = total_load / (double)cluster_size;
629 dout(5) << "prep_rebalance: my load " << my_load
630 << " target " << target_load
631 << " total " << total_load
632 << dendl;
633
634 // under or over?
635 if (my_load < target_load * (1.0 + g_conf->mds_bal_min_rebalance)) {
636 dout(5) << " i am underloaded or barely overloaded, doing nothing." << dendl;
637 last_epoch_under = beat_epoch;
638 mds->mdcache->show_subtrees();
639 return;
640 }
641
7c673cae
FG
642 // am i over long enough?
643 if (last_epoch_under && beat_epoch - last_epoch_under < 2) {
644 dout(5) << " i am overloaded, but only for " << (beat_epoch - last_epoch_under) << " epochs" << dendl;
645 return;
646 }
647
648 dout(5) << " i am sufficiently overloaded" << dendl;
649
650
651 // first separate exporters and importers
652 multimap<double,mds_rank_t> importers;
653 multimap<double,mds_rank_t> exporters;
654 set<mds_rank_t> importer_set;
655 set<mds_rank_t> exporter_set;
656
657 for (multimap<double,mds_rank_t>::iterator it = load_map.begin();
658 it != load_map.end();
659 ++it) {
660 if (it->first < target_load) {
661 dout(15) << " mds." << it->second << " is importer" << dendl;
662 importers.insert(pair<double,mds_rank_t>(it->first,it->second));
663 importer_set.insert(it->second);
664 } else {
665 dout(15) << " mds." << it->second << " is exporter" << dendl;
666 exporters.insert(pair<double,mds_rank_t>(it->first,it->second));
667 exporter_set.insert(it->second);
668 }
669 }
670
671
672 // determine load transfer mapping
673
674 if (true) {
675 // analyze import_map; do any matches i can
676
677 dout(15) << " matching exporters to import sources" << dendl;
678
679 // big -> small exporters
680 for (multimap<double,mds_rank_t>::reverse_iterator ex = exporters.rbegin();
681 ex != exporters.rend();
682 ++ex) {
683 double maxex = get_maxex(state, ex->second);
684 if (maxex <= .001) continue;
685
686 // check importers. for now, just in arbitrary order (no intelligent matching).
687 for (map<mds_rank_t, float>::iterator im = mds_import_map[ex->second].begin();
688 im != mds_import_map[ex->second].end();
689 ++im) {
690 double maxim = get_maxim(state, im->first);
691 if (maxim <= .001) continue;
692 try_match(state, ex->second, maxex, im->first, maxim);
693 if (maxex <= .001) break;
694 }
695 }
696 }
697
698 // old way
699 if (beat % 2 == 1) {
700 dout(15) << " matching big exporters to big importers" << dendl;
701 // big exporters to big importers
702 multimap<double,mds_rank_t>::reverse_iterator ex = exporters.rbegin();
703 multimap<double,mds_rank_t>::iterator im = importers.begin();
704 while (ex != exporters.rend() &&
705 im != importers.end()) {
706 double maxex = get_maxex(state, ex->second);
707 double maxim = get_maxim(state, im->second);
708 if (maxex < .001 || maxim < .001) break;
709 try_match(state, ex->second, maxex, im->second, maxim);
710 if (maxex <= .001) ++ex;
711 if (maxim <= .001) ++im;
712 }
713 } else { // new way
714 dout(15) << " matching small exporters to big importers" << dendl;
715 // small exporters to big importers
716 multimap<double,mds_rank_t>::iterator ex = exporters.begin();
717 multimap<double,mds_rank_t>::iterator im = importers.begin();
718 while (ex != exporters.end() &&
719 im != importers.end()) {
720 double maxex = get_maxex(state, ex->second);
721 double maxim = get_maxim(state, im->second);
722 if (maxex < .001 || maxim < .001) break;
723 try_match(state, ex->second, maxex, im->second, maxim);
724 if (maxex <= .001) ++ex;
725 if (maxim <= .001) ++im;
726 }
727 }
728 }
729 try_rebalance(state);
730}
731
7c673cae
FG
732int MDBalancer::mantle_prep_rebalance()
733{
734 balance_state_t state;
735
736 /* refresh balancer if it has changed */
737 if (bal_version != mds->mdsmap->get_balancer()) {
738 bal_version.assign("");
739 int r = localize_balancer();
740 if (r) return r;
741
742 /* only spam the cluster log from 1 mds on version changes */
743 if (mds->get_nodeid() == 0)
744 mds->clog->info() << "mantle balancer version changed: " << bal_version;
745 }
746
747 /* prepare for balancing */
748 int cluster_size = mds->get_mds_map()->get_num_in_mds();
749 rebalance_time = ceph_clock_now();
750 mds->mdcache->migrator->clear_export_queue();
751
752 /* fill in the metrics for each mds by grabbing load struct */
753 vector < map<string, double> > metrics (cluster_size);
754 for (mds_rank_t i=mds_rank_t(0);
755 i < mds_rank_t(cluster_size);
756 i++) {
757 map<mds_rank_t, mds_load_t>::value_type val(i, mds_load_t(ceph_clock_now()));
758 std::pair < map<mds_rank_t, mds_load_t>::iterator, bool > r(mds_load.insert(val));
759 mds_load_t &load(r.first->second);
760
761 metrics[i] = {{"auth.meta_load", load.auth.meta_load()},
762 {"all.meta_load", load.all.meta_load()},
763 {"req_rate", load.req_rate},
764 {"queue_len", load.queue_len},
765 {"cpu_load_avg", load.cpu_load_avg}};
766 }
767
768 /* execute the balancer */
769 Mantle mantle;
770 int ret = mantle.balance(bal_code, mds->get_nodeid(), metrics, state.targets);
771 dout(2) << " mantle decided that new targets=" << state.targets << dendl;
772
773 /* mantle doesn't know about cluster size, so check target len here */
774 if ((int) state.targets.size() != cluster_size)
775 return -EINVAL;
776 else if (ret)
777 return ret;
778
779 try_rebalance(state);
780 return 0;
781}
782
783
784
785void MDBalancer::try_rebalance(balance_state_t& state)
786{
7c673cae
FG
787 if (g_conf->mds_thrash_exports) {
788 dout(5) << "mds_thrash is on; not performing standard rebalance operation!"
789 << dendl;
790 return;
791 }
792
793 // make a sorted list of my imports
794 map<double,CDir*> import_pop_map;
795 multimap<mds_rank_t,CDir*> import_from_map;
796 set<CDir*> fullauthsubs;
797
798 mds->mdcache->get_fullauth_subtrees(fullauthsubs);
799 for (set<CDir*>::iterator it = fullauthsubs.begin();
800 it != fullauthsubs.end();
801 ++it) {
802 CDir *im = *it;
803 if (im->get_inode()->is_stray()) continue;
804
805 double pop = im->pop_auth_subtree.meta_load(rebalance_time, mds->mdcache->decayrate);
806 if (g_conf->mds_bal_idle_threshold > 0 &&
807 pop < g_conf->mds_bal_idle_threshold &&
808 im->inode != mds->mdcache->get_root() &&
809 im->inode->authority().first != mds->get_nodeid()) {
b32b8144 810 dout(5) << " exporting idle (" << pop << ") import " << *im
7c673cae
FG
811 << " back to mds." << im->inode->authority().first
812 << dendl;
813 mds->mdcache->migrator->export_dir_nicely(im, im->inode->authority().first);
814 continue;
815 }
816
817 import_pop_map[ pop ] = im;
818 mds_rank_t from = im->inode->authority().first;
819 dout(15) << " map: i imported " << *im << " from " << from << dendl;
820 import_from_map.insert(pair<mds_rank_t,CDir*>(from, im));
821 }
822
823
824
825 // do my exports!
826 set<CDir*> already_exporting;
827
828 for (auto &it : state.targets) {
829 mds_rank_t target = it.first;
830 double amount = it.second;
831
832 if (amount < MIN_OFFLOAD) continue;
833 if (amount / target_load < .2) continue;
834
835 dout(5) << "want to send " << amount << " to mds." << target
836 //<< " .. " << (*it).second << " * " << load_fac
837 << " -> " << amount
838 << dendl;//" .. fudge is " << fudge << dendl;
839 double have = 0.0;
840
841
842 mds->mdcache->show_subtrees();
843
844 // search imports from target
845 if (import_from_map.count(target)) {
846 dout(5) << " aha, looking through imports from target mds." << target << dendl;
847 pair<multimap<mds_rank_t,CDir*>::iterator, multimap<mds_rank_t,CDir*>::iterator> p =
848 import_from_map.equal_range(target);
849 while (p.first != p.second) {
850 CDir *dir = (*p.first).second;
851 dout(5) << "considering " << *dir << " from " << (*p.first).first << dendl;
852 multimap<mds_rank_t,CDir*>::iterator plast = p.first++;
853
854 if (dir->inode->is_base() ||
855 dir->inode->is_stray())
856 continue;
857 if (dir->is_freezing() || dir->is_frozen()) continue; // export pbly already in progress
858 double pop = dir->pop_auth_subtree.meta_load(rebalance_time, mds->mdcache->decayrate);
859 assert(dir->inode->authority().first == target); // cuz that's how i put it in the map, dummy
860
861 if (pop <= amount-have) {
b32b8144 862 dout(5) << "reexporting " << *dir
7c673cae
FG
863 << " pop " << pop
864 << " back to mds." << target << dendl;
865 mds->mdcache->migrator->export_dir_nicely(dir, target);
866 have += pop;
867 import_from_map.erase(plast);
868 import_pop_map.erase(pop);
869 } else {
870 dout(5) << "can't reexport " << *dir << ", too big " << pop << dendl;
871 }
872 if (amount-have < MIN_OFFLOAD) break;
873 }
874 }
875 if (amount-have < MIN_OFFLOAD) {
876 continue;
877 }
878
879 // any other imports
880 if (false)
881 for (map<double,CDir*>::iterator import = import_pop_map.begin();
882 import != import_pop_map.end();
883 import++) {
884 CDir *imp = (*import).second;
885 if (imp->inode->is_base() ||
886 imp->inode->is_stray())
887 continue;
888
889 double pop = (*import).first;
890 if (pop < amount-have || pop < MIN_REEXPORT) {
b32b8144 891 dout(5) << "reexporting " << *imp
7c673cae
FG
892 << " pop " << pop
893 << " back to mds." << imp->inode->authority()
894 << dendl;
895 have += pop;
896 mds->mdcache->migrator->export_dir_nicely(imp, imp->inode->authority().first);
897 }
898 if (amount-have < MIN_OFFLOAD) break;
899 }
900 if (amount-have < MIN_OFFLOAD) {
901 //fudge = amount-have;
902 continue;
903 }
904
905 // okay, search for fragments of my workload
906 set<CDir*> candidates;
907 mds->mdcache->get_fullauth_subtrees(candidates);
908
909 list<CDir*> exports;
910
911 for (set<CDir*>::iterator pot = candidates.begin();
912 pot != candidates.end();
913 ++pot) {
914 if ((*pot)->get_inode()->is_stray()) continue;
915 find_exports(*pot, amount, exports, have, already_exporting);
916 if (have > amount-MIN_OFFLOAD)
917 break;
918 }
919 //fudge = amount - have;
920
921 for (list<CDir*>::iterator it = exports.begin(); it != exports.end(); ++it) {
b32b8144 922 dout(5) << " - exporting "
7c673cae
FG
923 << (*it)->pop_auth_subtree
924 << " "
925 << (*it)->pop_auth_subtree.meta_load(rebalance_time, mds->mdcache->decayrate)
926 << " to mds." << target
927 << " " << **it
928 << dendl;
929 mds->mdcache->migrator->export_dir_nicely(*it, target);
930 }
931 }
932
933 dout(5) << "rebalance done" << dendl;
934 mds->mdcache->show_subtrees();
935}
936
7c673cae
FG
937void MDBalancer::find_exports(CDir *dir,
938 double amount,
939 list<CDir*>& exports,
940 double& have,
941 set<CDir*>& already_exporting)
942{
943 double need = amount - have;
944 if (need < amount * g_conf->mds_bal_min_start)
945 return; // good enough!
946 double needmax = need * g_conf->mds_bal_need_max;
947 double needmin = need * g_conf->mds_bal_need_min;
948 double midchunk = need * g_conf->mds_bal_midchunk;
949 double minchunk = need * g_conf->mds_bal_minchunk;
950
951 list<CDir*> bigger_rep, bigger_unrep;
952 multimap<double, CDir*> smaller;
953
954 double dir_pop = dir->pop_auth_subtree.meta_load(rebalance_time, mds->mdcache->decayrate);
955 dout(7) << " find_exports in " << dir_pop << " " << *dir << " need " << need << " (" << needmin << " - " << needmax << ")" << dendl;
956
957 double subdir_sum = 0;
958 for (CDir::map_t::iterator it = dir->begin();
959 it != dir->end();
960 ++it) {
961 CInode *in = it->second->get_linkage()->get_inode();
962 if (!in) continue;
963 if (!in->is_dir()) continue;
964
965 list<CDir*> dfls;
966 in->get_dirfrags(dfls);
967 for (list<CDir*>::iterator p = dfls.begin();
968 p != dfls.end();
969 ++p) {
970 CDir *subdir = *p;
971 if (!subdir->is_auth()) continue;
972 if (already_exporting.count(subdir)) continue;
973
974 if (subdir->is_frozen()) continue; // can't export this right now!
975
976 // how popular?
977 double pop = subdir->pop_auth_subtree.meta_load(rebalance_time, mds->mdcache->decayrate);
978 subdir_sum += pop;
979 dout(15) << " subdir pop " << pop << " " << *subdir << dendl;
980
981 if (pop < minchunk) continue;
982
983 // lucky find?
984 if (pop > needmin && pop < needmax) {
985 exports.push_back(subdir);
986 already_exporting.insert(subdir);
987 have += pop;
988 return;
989 }
990
991 if (pop > need) {
992 if (subdir->is_rep())
993 bigger_rep.push_back(subdir);
994 else
995 bigger_unrep.push_back(subdir);
996 } else
997 smaller.insert(pair<double,CDir*>(pop, subdir));
998 }
999 }
1000 dout(15) << " sum " << subdir_sum << " / " << dir_pop << dendl;
1001
1002 // grab some sufficiently big small items
1003 multimap<double,CDir*>::reverse_iterator it;
1004 for (it = smaller.rbegin();
1005 it != smaller.rend();
1006 ++it) {
1007
1008 if ((*it).first < midchunk)
1009 break; // try later
1010
1011 dout(7) << " taking smaller " << *(*it).second << dendl;
1012
1013 exports.push_back((*it).second);
1014 already_exporting.insert((*it).second);
1015 have += (*it).first;
1016 if (have > needmin)
1017 return;
1018 }
1019
1020 // apprently not enough; drill deeper into the hierarchy (if non-replicated)
1021 for (list<CDir*>::iterator it = bigger_unrep.begin();
1022 it != bigger_unrep.end();
1023 ++it) {
1024 dout(15) << " descending into " << **it << dendl;
1025 find_exports(*it, amount, exports, have, already_exporting);
1026 if (have > needmin)
1027 return;
1028 }
1029
1030 // ok fine, use smaller bits
1031 for (;
1032 it != smaller.rend();
1033 ++it) {
1034 dout(7) << " taking (much) smaller " << it->first << " " << *(*it).second << dendl;
1035
1036 exports.push_back((*it).second);
1037 already_exporting.insert((*it).second);
1038 have += (*it).first;
1039 if (have > needmin)
1040 return;
1041 }
1042
1043 // ok fine, drill into replicated dirs
1044 for (list<CDir*>::iterator it = bigger_rep.begin();
1045 it != bigger_rep.end();
1046 ++it) {
1047 dout(7) << " descending into replicated " << **it << dendl;
1048 find_exports(*it, amount, exports, have, already_exporting);
1049 if (have > needmin)
1050 return;
1051 }
1052
1053}
1054
1055void MDBalancer::hit_inode(utime_t now, CInode *in, int type, int who)
1056{
1057 // hit inode
1058 in->pop.get(type).hit(now, mds->mdcache->decayrate);
1059
1060 if (in->get_parent_dn())
1061 hit_dir(now, in->get_parent_dn()->get_dir(), type, who);
1062}
1063
1064void MDBalancer::maybe_fragment(CDir *dir, bool hot)
1065{
1066 // split/merge
1067 if (g_conf->mds_bal_frag && g_conf->mds_bal_fragment_interval > 0 &&
1068 !dir->inode->is_base() && // not root/base (for now at least)
1069 dir->is_auth()) {
1070
1071 // split
1072 if (g_conf->mds_bal_split_size > 0 &&
1073 mds->mdsmap->allows_dirfrags() &&
1074 (dir->should_split() || hot))
1075 {
1076 if (split_pending.count(dir->dirfrag()) == 0) {
1077 queue_split(dir, false);
1078 } else {
1079 if (dir->should_split_fast()) {
1080 queue_split(dir, true);
1081 } else {
1082 dout(10) << __func__ << ": fragment already enqueued to split: "
1083 << *dir << dendl;
1084 }
1085 }
1086 }
1087
1088 // merge?
1089 if (dir->get_frag() != frag_t() && dir->should_merge() &&
1090 merge_pending.count(dir->dirfrag()) == 0) {
1091 queue_merge(dir);
1092 }
1093 }
1094}
1095
1096void MDBalancer::hit_dir(utime_t now, CDir *dir, int type, int who, double amount)
1097{
1098 // hit me
1099 double v = dir->pop_me.get(type).hit(now, amount);
1100
1101 const bool hot = (v > g_conf->mds_bal_split_rd && type == META_POP_IRD) ||
1102 (v > g_conf->mds_bal_split_wr && type == META_POP_IWR);
1103
1104 dout(20) << "hit_dir " << type << " pop is " << v << ", frag " << dir->get_frag()
1105 << " size " << dir->get_frag_size() << dendl;
1106
1107 maybe_fragment(dir, hot);
1108
1109 // replicate?
1110 if (type == META_POP_IRD && who >= 0) {
1111 dir->pop_spread.hit(now, mds->mdcache->decayrate, who);
1112 }
1113
1114 double rd_adj = 0.0;
1115 if (type == META_POP_IRD &&
1116 dir->last_popularity_sample < last_sample) {
1117 double dir_pop = dir->pop_auth_subtree.get(type).get(now, mds->mdcache->decayrate); // hmm??
1118 dir->last_popularity_sample = last_sample;
1119 double pop_sp = dir->pop_spread.get(now, mds->mdcache->decayrate);
1120 dir_pop += pop_sp * 10;
1121
1122 //if (dir->ino() == inodeno_t(0x10000000002))
1123 if (pop_sp > 0) {
1124 dout(20) << "hit_dir " << type << " pop " << dir_pop << " spread " << pop_sp
1125 << " " << dir->pop_spread.last[0]
1126 << " " << dir->pop_spread.last[1]
1127 << " " << dir->pop_spread.last[2]
1128 << " " << dir->pop_spread.last[3]
1129 << " in " << *dir << dendl;
1130 }
1131
1132 if (dir->is_auth() && !dir->is_ambiguous_auth()) {
1133 if (!dir->is_rep() &&
1134 dir_pop >= g_conf->mds_bal_replicate_threshold) {
1135 // replicate
1136 double rdp = dir->pop_me.get(META_POP_IRD).get(now, mds->mdcache->decayrate);
1137 rd_adj = rdp / mds->get_mds_map()->get_num_in_mds() - rdp;
1138 rd_adj /= 2.0; // temper somewhat
1139
b32b8144 1140 dout(5) << "replicating dir " << *dir << " pop " << dir_pop << " .. rdp " << rdp << " adj " << rd_adj << dendl;
7c673cae
FG
1141
1142 dir->dir_rep = CDir::REP_ALL;
1143 mds->mdcache->send_dir_updates(dir, true);
1144
1145 // fixme this should adjust the whole pop hierarchy
1146 dir->pop_me.get(META_POP_IRD).adjust(rd_adj);
1147 dir->pop_auth_subtree.get(META_POP_IRD).adjust(rd_adj);
1148 }
1149
1150 if (dir->ino() != 1 &&
1151 dir->is_rep() &&
1152 dir_pop < g_conf->mds_bal_unreplicate_threshold) {
1153 // unreplicate
b32b8144 1154 dout(5) << "unreplicating dir " << *dir << " pop " << dir_pop << dendl;
7c673cae
FG
1155
1156 dir->dir_rep = CDir::REP_NONE;
1157 mds->mdcache->send_dir_updates(dir);
1158 }
1159 }
1160 }
1161
1162 // adjust ancestors
1163 bool hit_subtree = dir->is_auth(); // current auth subtree (if any)
1164 bool hit_subtree_nested = dir->is_auth(); // all nested auth subtrees
1165
1166 while (true) {
1167 dir->pop_nested.get(type).hit(now, amount);
1168 if (rd_adj != 0.0)
1169 dir->pop_nested.get(META_POP_IRD).adjust(now, mds->mdcache->decayrate, rd_adj);
1170
1171 if (hit_subtree) {
1172 dir->pop_auth_subtree.get(type).hit(now, amount);
1173 if (rd_adj != 0.0)
1174 dir->pop_auth_subtree.get(META_POP_IRD).adjust(now, mds->mdcache->decayrate, rd_adj);
1175 }
1176
1177 if (hit_subtree_nested) {
1178 dir->pop_auth_subtree_nested.get(type).hit(now, mds->mdcache->decayrate, amount);
1179 if (rd_adj != 0.0)
1180 dir->pop_auth_subtree_nested.get(META_POP_IRD).adjust(now, mds->mdcache->decayrate, rd_adj);
1181 }
1182
1183 if (dir->is_subtree_root())
1184 hit_subtree = false; // end of auth domain, stop hitting auth counters.
1185
1186 if (dir->inode->get_parent_dn() == 0) break;
1187 dir = dir->inode->get_parent_dn()->get_dir();
1188 }
1189}
1190
1191
1192/*
1193 * subtract off an exported chunk.
1194 * this excludes *dir itself (encode_export_dir should have take care of that)
1195 * we _just_ do the parents' nested counters.
1196 *
1197 * NOTE: call me _after_ forcing *dir into a subtree root,
1198 * but _before_ doing the encode_export_dirs.
1199 */
1200void MDBalancer::subtract_export(CDir *dir, utime_t now)
1201{
1202 dirfrag_load_vec_t subload = dir->pop_auth_subtree;
1203
1204 while (true) {
1205 dir = dir->inode->get_parent_dir();
1206 if (!dir) break;
1207
1208 dir->pop_nested.sub(now, mds->mdcache->decayrate, subload);
1209 dir->pop_auth_subtree_nested.sub(now, mds->mdcache->decayrate, subload);
1210 }
1211}
1212
1213
1214void MDBalancer::add_import(CDir *dir, utime_t now)
1215{
1216 dirfrag_load_vec_t subload = dir->pop_auth_subtree;
1217
1218 while (true) {
1219 dir = dir->inode->get_parent_dir();
1220 if (!dir) break;
1221
1222 dir->pop_nested.add(now, mds->mdcache->decayrate, subload);
1223 dir->pop_auth_subtree_nested.add(now, mds->mdcache->decayrate, subload);
1224 }
1225}
1226
224ce89b
WB
1227void MDBalancer::handle_mds_failure(mds_rank_t who)
1228{
1229 if (0 == who) {
1230 last_epoch_under = 0;
1231 }
1232}