]> git.proxmox.com Git - ceph.git/blob - ceph/src/mon/Monitor.h
import ceph pacific 16.2.5
[ceph.git] / ceph / src / mon / Monitor.h
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 /*
16 * This is the top level monitor. It runs on each machine in the Monitor
17 * Cluster. The election of a leader for the paxos algorithm only happens
18 * once per machine via the elector. There is a separate paxos instance (state)
19 * kept for each of the system components: Object Store Device (OSD) Monitor,
20 * Placement Group (PG) Monitor, Metadata Server (MDS) Monitor, and Client Monitor.
21 */
22
23 #ifndef CEPH_MONITOR_H
24 #define CEPH_MONITOR_H
25
26 #include <errno.h>
27 #include <cmath>
28 #include <string>
29 #include <array>
30
31 #include "include/types.h"
32 #include "include/health.h"
33 #include "msg/Messenger.h"
34
35 #include "common/Timer.h"
36
37 #include "health_check.h"
38 #include "MonMap.h"
39 #include "Elector.h"
40 #include "Paxos.h"
41 #include "Session.h"
42 #include "MonCommand.h"
43
44
45 #include "common/config_obs.h"
46 #include "common/LogClient.h"
47 #include "auth/AuthClient.h"
48 #include "auth/AuthServer.h"
49 #include "auth/cephx/CephxKeyServer.h"
50 #include "auth/AuthMethodList.h"
51 #include "auth/KeyRing.h"
52 #include "include/common_fwd.h"
53 #include "messages/MMonCommand.h"
54 #include "mon/MonitorDBStore.h"
55 #include "mgr/MgrClient.h"
56
57 #include "mon/MonOpRequest.h"
58 #include "common/WorkQueue.h"
59
60 using namespace TOPNSPC::common;
61
62 #define CEPH_MON_PROTOCOL 13 /* cluster internal */
63
64
65 enum {
66 l_cluster_first = 555000,
67 l_cluster_num_mon,
68 l_cluster_num_mon_quorum,
69 l_cluster_num_osd,
70 l_cluster_num_osd_up,
71 l_cluster_num_osd_in,
72 l_cluster_osd_epoch,
73 l_cluster_osd_bytes,
74 l_cluster_osd_bytes_used,
75 l_cluster_osd_bytes_avail,
76 l_cluster_num_pool,
77 l_cluster_num_pg,
78 l_cluster_num_pg_active_clean,
79 l_cluster_num_pg_active,
80 l_cluster_num_pg_peering,
81 l_cluster_num_object,
82 l_cluster_num_object_degraded,
83 l_cluster_num_object_misplaced,
84 l_cluster_num_object_unfound,
85 l_cluster_num_bytes,
86 l_cluster_last,
87 };
88
89 enum {
90 l_mon_first = 456000,
91 l_mon_num_sessions,
92 l_mon_session_add,
93 l_mon_session_rm,
94 l_mon_session_trim,
95 l_mon_num_elections,
96 l_mon_election_call,
97 l_mon_election_win,
98 l_mon_election_lose,
99 l_mon_last,
100 };
101
102 class PaxosService;
103
104 class AdminSocketHook;
105
106 #define COMPAT_SET_LOC "feature_set"
107
108 class Monitor : public Dispatcher,
109 public AuthClient,
110 public AuthServer,
111 public md_config_obs_t {
112 public:
113 int orig_argc = 0;
114 const char **orig_argv = nullptr;
115
116 // me
117 std::string name;
118 int rank;
119 Messenger *messenger;
120 ConnectionRef con_self;
121 ceph::mutex lock = ceph::make_mutex("Monitor::lock");
122 SafeTimer timer;
123 Finisher finisher;
124 ThreadPool cpu_tp; ///< threadpool for CPU intensive work
125
126 ceph::mutex auth_lock = ceph::make_mutex("Monitor::auth_lock");
127
128 /// true if we have ever joined a quorum. if false, we are either a
129 /// new cluster, a newly joining monitor, or a just-upgraded
130 /// monitor.
131 bool has_ever_joined;
132
133 PerfCounters *logger, *cluster_logger;
134 bool cluster_logger_registered;
135
136 void register_cluster_logger();
137 void unregister_cluster_logger();
138
139 MonMap *monmap;
140 uuid_d fingerprint;
141
142 std::set<entity_addrvec_t> extra_probe_peers;
143
144 LogClient log_client;
145 LogChannelRef clog;
146 LogChannelRef audit_clog;
147 KeyRing keyring;
148 KeyServer key_server;
149
150 AuthMethodList auth_cluster_required;
151 AuthMethodList auth_service_required;
152
153 CompatSet features;
154
155 std::vector<MonCommand> leader_mon_commands; // quorum leader's commands
156 std::vector<MonCommand> local_mon_commands; // commands i support
157 ceph::buffer::list local_mon_commands_bl; // encoded version of above
158
159 std::vector<MonCommand> prenautilus_local_mon_commands;
160 ceph::buffer::list prenautilus_local_mon_commands_bl;
161
162 Messenger *mgr_messenger;
163 MgrClient mgr_client;
164 uint64_t mgr_proxy_bytes = 0; // in-flight proxied mgr command message bytes
165 std::string gss_ktfile_client{};
166
167 private:
168 void new_tick();
169
170 // -- local storage --
171 public:
172 MonitorDBStore *store;
173 static const std::string MONITOR_NAME;
174 static const std::string MONITOR_STORE_PREFIX;
175
176 // -- monitor state --
177 private:
178 enum {
179 STATE_INIT = 1,
180 STATE_PROBING,
181 STATE_SYNCHRONIZING,
182 STATE_ELECTING,
183 STATE_LEADER,
184 STATE_PEON,
185 STATE_SHUTDOWN
186 };
187 int state = STATE_INIT;
188
189 public:
190 static const char *get_state_name(int s) {
191 switch (s) {
192 case STATE_PROBING: return "probing";
193 case STATE_SYNCHRONIZING: return "synchronizing";
194 case STATE_ELECTING: return "electing";
195 case STATE_LEADER: return "leader";
196 case STATE_PEON: return "peon";
197 case STATE_SHUTDOWN: return "shutdown";
198 default: return "???";
199 }
200 }
201 const char *get_state_name() const {
202 return get_state_name(state);
203 }
204
205 bool is_init() const { return state == STATE_INIT; }
206 bool is_shutdown() const { return state == STATE_SHUTDOWN; }
207 bool is_probing() const { return state == STATE_PROBING; }
208 bool is_synchronizing() const { return state == STATE_SYNCHRONIZING; }
209 bool is_electing() const { return state == STATE_ELECTING; }
210 bool is_leader() const { return state == STATE_LEADER; }
211 bool is_peon() const { return state == STATE_PEON; }
212
213 const utime_t &get_leader_since() const;
214
215 void prepare_new_fingerprint(MonitorDBStore::TransactionRef t);
216
217 std::vector<DaemonHealthMetric> get_health_metrics();
218
219 // -- elector --
220 private:
221 std::unique_ptr<Paxos> paxos;
222 Elector elector;
223 friend class Elector;
224
225 /// features we require of peers (based on on-disk compatset)
226 uint64_t required_features;
227
228 int leader; // current leader (to best of knowledge)
229 std::set<int> quorum; // current active set of monitors (if !starting)
230 ceph::mono_clock::time_point quorum_since; // when quorum formed
231 utime_t leader_since; // when this monitor became the leader, if it is the leader
232 utime_t exited_quorum; // time detected as not in quorum; 0 if in
233
234 // map of counts of connected clients, by type and features, for
235 // each quorum mon
236 std::map<int,FeatureMap> quorum_feature_map;
237
238 /**
239 * Intersection of quorum member's connection feature bits.
240 */
241 uint64_t quorum_con_features;
242 /**
243 * Intersection of quorum members mon-specific feature bits
244 */
245 mon_feature_t quorum_mon_features;
246
247 ceph_release_t quorum_min_mon_release{ceph_release_t::unknown};
248
249 std::set<std::string> outside_quorum;
250
251 bool stretch_mode_engaged{false};
252 bool degraded_stretch_mode{false};
253 bool recovering_stretch_mode{false};
254 string stretch_bucket_divider;
255 map<string, set<string>> dead_mon_buckets; // bucket->mon ranks, locations with no live mons
256 set<string> up_mon_buckets; // locations with a live mon
257 void do_stretch_mode_election_work();
258
259 bool session_stretch_allowed(MonSession *s, MonOpRequestRef& op);
260 void disconnect_disallowed_stretch_sessions();
261 void set_elector_disallowed_leaders(bool allow_election);
262
263 map <string,string> crush_loc;
264 bool need_set_crush_loc{false};
265 public:
266 bool is_stretch_mode() { return stretch_mode_engaged; }
267 bool is_degraded_stretch_mode() { return degraded_stretch_mode; }
268 bool is_recovering_stretch_mode() { return recovering_stretch_mode; }
269
270 /**
271 * This set of functions maintains the in-memory stretch state
272 * and sets up transitions of the map states by calling in to
273 * MonmapMonitor and OSDMonitor.
274 *
275 * The [maybe_]go_* functions are called on the leader to
276 * decide if transitions should happen; the trigger_* functions
277 * set up the map transitions; and the set_* functions actually
278 * change the memory state -- but these are only called
279 * via OSDMonitor::update_from_paxos, to guarantee consistent
280 * updates across the entire cluster.
281 */
282 void try_engage_stretch_mode();
283 void maybe_go_degraded_stretch_mode();
284 void trigger_degraded_stretch_mode(const set<string>& dead_mons,
285 const set<int>& dead_buckets);
286 void set_degraded_stretch_mode();
287 void go_recovery_stretch_mode();
288 void set_recovery_stretch_mode();
289 void trigger_healthy_stretch_mode();
290 void set_healthy_stretch_mode();
291 void enable_stretch_mode();
292 void set_mon_crush_location(const string& loc);
293
294
295 private:
296
297 /**
298 * @defgroup Monitor_h_scrub
299 * @{
300 */
301 version_t scrub_version; ///< paxos version we are scrubbing
302 std::map<int,ScrubResult> scrub_result; ///< results so far
303
304 /**
305 * trigger a cross-mon scrub
306 *
307 * Verify all mons are storing identical content
308 */
309 int scrub_start();
310 int scrub();
311 void handle_scrub(MonOpRequestRef op);
312 bool _scrub(ScrubResult *r,
313 std::pair<std::string,std::string> *start,
314 int *num_keys);
315 void scrub_check_results();
316 void scrub_timeout();
317 void scrub_finish();
318 void scrub_reset();
319 void scrub_update_interval(ceph::timespan interval);
320
321 Context *scrub_event; ///< periodic event to trigger scrub (leader)
322 Context *scrub_timeout_event; ///< scrub round timeout (leader)
323 void scrub_event_start();
324 void scrub_event_cancel();
325 void scrub_reset_timeout();
326 void scrub_cancel_timeout();
327
328 struct ScrubState {
329 std::pair<std::string,std::string> last_key; ///< last scrubbed key
330 bool finished;
331
332 ScrubState() : finished(false) { }
333 virtual ~ScrubState() { }
334 };
335 std::shared_ptr<ScrubState> scrub_state; ///< keeps track of current scrub
336
337 /**
338 * @defgroup Monitor_h_sync Synchronization
339 * @{
340 */
341 /**
342 * @} // provider state
343 */
344 struct SyncProvider {
345 entity_addrvec_t addrs;
346 uint64_t cookie; ///< unique cookie for this sync attempt
347 utime_t timeout; ///< when we give up and expire this attempt
348 version_t last_committed; ///< last paxos version on peer
349 std::pair<std::string,std::string> last_key; ///< last key sent to (or on) peer
350 bool full; ///< full scan?
351 MonitorDBStore::Synchronizer synchronizer; ///< iterator
352
353 SyncProvider() : cookie(0), last_committed(0), full(false) {}
354
355 void reset_timeout(CephContext *cct, int grace) {
356 timeout = ceph_clock_now();
357 timeout += grace;
358 }
359 };
360
361 std::map<std::uint64_t, SyncProvider> sync_providers; ///< cookie -> SyncProvider for those syncing from us
362 uint64_t sync_provider_count; ///< counter for issued cookies to keep them unique
363
364 /**
365 * @} // requester state
366 */
367 entity_addrvec_t sync_provider; ///< who we are syncing from
368 uint64_t sync_cookie; ///< 0 if we are starting, non-zero otherwise
369 bool sync_full; ///< true if we are a full sync, false for recent catch-up
370 version_t sync_start_version; ///< last_committed at sync start
371 Context *sync_timeout_event; ///< timeout event
372
373 /**
374 * floor for sync source
375 *
376 * When we sync we forget about our old last_committed value which
377 * can be dangerous. For example, if we have a cluster of:
378 *
379 * mon.a: lc 100
380 * mon.b: lc 80
381 * mon.c: lc 100 (us)
382 *
383 * If something forces us to sync (say, corruption, or manual
384 * intervention, or bug), we forget last_committed, and might abort.
385 * If mon.a happens to be down when we come back, we will see:
386 *
387 * mon.b: lc 80
388 * mon.c: lc 0 (us)
389 *
390 * and sync from mon.b, at which point a+b will both have lc 80 and
391 * come online with a majority holding out of date commits.
392 *
393 * Avoid this by preserving our old last_committed value prior to
394 * sync and never going backwards.
395 */
396 version_t sync_last_committed_floor;
397
398 /**
399 * Obtain the synchronization target prefixes in set form.
400 *
401 * We consider a target prefix all those that are relevant when
402 * synchronizing two stores. That is, all those that hold paxos service's
403 * versions, as well as paxos versions, or any control keys such as the
404 * first or last committed version.
405 *
406 * Given the current design, this function should return the name of all and
407 * any available paxos service, plus the paxos name.
408 *
409 * @returns a set of strings referring to the prefixes being synchronized
410 */
411 std::set<std::string> get_sync_targets_names();
412
413 /**
414 * Reset the monitor's sync-related data structures for syncing *from* a peer
415 */
416 void sync_reset_requester();
417
418 /**
419 * Reset sync state related to allowing others to sync from us
420 */
421 void sync_reset_provider();
422
423 /**
424 * Caled when a sync attempt times out (requester-side)
425 */
426 void sync_timeout();
427
428 /**
429 * Get the latest monmap for backup purposes during sync
430 */
431 void sync_obtain_latest_monmap(ceph::buffer::list &bl);
432
433 /**
434 * Start sync process
435 *
436 * Start pulling committed state from another monitor.
437 *
438 * @param entity where to pull committed state from
439 * @param full whether to do a full sync or just catch up on recent paxos
440 */
441 void sync_start(entity_addrvec_t &addrs, bool full);
442
443 public:
444 /**
445 * force a sync on next mon restart
446 */
447 void sync_force(ceph::Formatter *f);
448
449 private:
450 /**
451 * store critical state for safekeeping during sync
452 *
453 * We store a few things on the side that we don't want to get clobbered by sync. This
454 * includes the latest monmap and a lower bound on last_committed.
455 */
456 void sync_stash_critical_state(MonitorDBStore::TransactionRef tx);
457
458 /**
459 * reset the sync timeout
460 *
461 * This is used on the client to restart if things aren't progressing
462 */
463 void sync_reset_timeout();
464
465 /**
466 * trim stale sync provider state
467 *
468 * If someone is syncing from us and hasn't talked to us recently, expire their state.
469 */
470 void sync_trim_providers();
471
472 /**
473 * Complete a sync
474 *
475 * Finish up a sync after we've gotten all of the chunks.
476 *
477 * @param last_committed final last_committed value from provider
478 */
479 void sync_finish(version_t last_committed);
480
481 /**
482 * request the next chunk from the provider
483 */
484 void sync_get_next_chunk();
485
486 /**
487 * handle sync message
488 *
489 * @param m Sync message with operation type MMonSync::OP_START_CHUNKS
490 */
491 void handle_sync(MonOpRequestRef op);
492
493 void _sync_reply_no_cookie(MonOpRequestRef op);
494
495 void handle_sync_get_cookie(MonOpRequestRef op);
496 void handle_sync_get_chunk(MonOpRequestRef op);
497 void handle_sync_finish(MonOpRequestRef op);
498
499 void handle_sync_cookie(MonOpRequestRef op);
500 void handle_sync_forward(MonOpRequestRef op);
501 void handle_sync_chunk(MonOpRequestRef op);
502 void handle_sync_no_cookie(MonOpRequestRef op);
503
504 /**
505 * @} // Synchronization
506 */
507
508 std::list<Context*> waitfor_quorum;
509 std::list<Context*> maybe_wait_for_quorum;
510
511 /**
512 * @defgroup Monitor_h_TimeCheck Monitor Clock Drift Early Warning System
513 * @{
514 *
515 * We use time checks to keep track of any clock drifting going on in the
516 * cluster. This is accomplished by periodically ping each monitor in the
517 * quorum and register its response time on a map, assessing how much its
518 * clock has drifted. We also take this opportunity to assess the latency
519 * on response.
520 *
521 * This mechanism works as follows:
522 *
523 * - Leader sends out a 'PING' message to each other monitor in the quorum.
524 * The message is timestamped with the leader's current time. The leader's
525 * current time is recorded in a map, associated with each peon's
526 * instance.
527 * - The peon replies to the leader with a timestamped 'PONG' message.
528 * - The leader calculates a delta between the peon's timestamp and its
529 * current time and stashes it.
530 * - The leader also calculates the time it took to receive the 'PONG'
531 * since the 'PING' was sent, and stashes an approximate latency estimate.
532 * - Once all the quorum members have pong'ed, the leader will share the
533 * clock skew and latency maps with all the monitors in the quorum.
534 */
535 std::map<int, utime_t> timecheck_waiting;
536 std::map<int, double> timecheck_skews;
537 std::map<int, double> timecheck_latencies;
538 // odd value means we are mid-round; even value means the round has
539 // finished.
540 version_t timecheck_round;
541 unsigned int timecheck_acks;
542 utime_t timecheck_round_start;
543 friend class HealthMonitor;
544 /* When we hit a skew we will start a new round based off of
545 * 'mon_timecheck_skew_interval'. Each new round will be backed off
546 * until we hit 'mon_timecheck_interval' -- which is the typical
547 * interval when not in the presence of a skew.
548 *
549 * This variable tracks the number of rounds with skews since last clean
550 * so that we can report to the user and properly adjust the backoff.
551 */
552 uint64_t timecheck_rounds_since_clean;
553 /**
554 * Time Check event.
555 */
556 Context *timecheck_event;
557
558 void timecheck_start();
559 void timecheck_finish();
560 void timecheck_start_round();
561 void timecheck_finish_round(bool success = true);
562 void timecheck_cancel_round();
563 void timecheck_cleanup();
564 void timecheck_reset_event();
565 void timecheck_check_skews();
566 void timecheck_report();
567 void timecheck();
568 health_status_t timecheck_status(std::ostringstream &ss,
569 const double skew_bound,
570 const double latency);
571 void handle_timecheck_leader(MonOpRequestRef op);
572 void handle_timecheck_peon(MonOpRequestRef op);
573 void handle_timecheck(MonOpRequestRef op);
574
575 /**
576 * Returns 'true' if this is considered to be a skew; 'false' otherwise.
577 */
578 bool timecheck_has_skew(const double skew_bound, double *abs) const {
579 double abs_skew = std::fabs(skew_bound);
580 if (abs)
581 *abs = abs_skew;
582 return (abs_skew > g_conf()->mon_clock_drift_allowed);
583 }
584
585 /**
586 * @}
587 */
588 /**
589 * Handle ping messages from others.
590 */
591 void handle_ping(MonOpRequestRef op);
592
593 Context *probe_timeout_event = nullptr; // for probing
594
595 void reset_probe_timeout();
596 void cancel_probe_timeout();
597 void probe_timeout(int r);
598
599 void _apply_compatset_features(CompatSet &new_features);
600
601 public:
602 epoch_t get_epoch();
603 int get_leader() const { return leader; }
604 std::string get_leader_name() {
605 return quorum.empty() ? std::string() : monmap->get_name(leader);
606 }
607 const std::set<int>& get_quorum() const { return quorum; }
608 std::list<std::string> get_quorum_names() {
609 std::list<std::string> q;
610 for (auto p = quorum.begin(); p != quorum.end(); ++p)
611 q.push_back(monmap->get_name(*p));
612 return q;
613 }
614 uint64_t get_quorum_con_features() const {
615 return quorum_con_features;
616 }
617 mon_feature_t get_quorum_mon_features() const {
618 return quorum_mon_features;
619 }
620 uint64_t get_required_features() const {
621 return required_features;
622 }
623 mon_feature_t get_required_mon_features() const {
624 return monmap->get_required_features();
625 }
626 void apply_quorum_to_compatset_features();
627 void apply_monmap_to_compatset_features();
628 void calc_quorum_requirements();
629
630 void get_combined_feature_map(FeatureMap *fm);
631
632 private:
633 void _reset(); ///< called from bootstrap, start_, or join_election
634 void wait_for_paxos_write();
635 void _finish_svc_election(); ///< called by {win,lose}_election
636 void respawn();
637 public:
638 void bootstrap();
639 void join_election();
640 void start_election();
641 void win_standalone_election();
642 // end election (called by Elector)
643 void win_election(epoch_t epoch, const std::set<int>& q,
644 uint64_t features,
645 const mon_feature_t& mon_features,
646 ceph_release_t min_mon_release,
647 const std::map<int,Metadata>& metadata);
648 void lose_election(epoch_t epoch, std::set<int>& q, int l,
649 uint64_t features,
650 const mon_feature_t& mon_features,
651 ceph_release_t min_mon_release);
652 // end election (called by Elector)
653 void finish_election();
654
655 void update_logger();
656
657 /**
658 * Vector holding the Services serviced by this Monitor.
659 */
660 std::array<std::unique_ptr<PaxosService>, PAXOS_NUM> paxos_service;
661
662 class MDSMonitor *mdsmon() {
663 return (class MDSMonitor *)paxos_service[PAXOS_MDSMAP].get();
664 }
665
666 class MonmapMonitor *monmon() {
667 return (class MonmapMonitor *)paxos_service[PAXOS_MONMAP].get();
668 }
669
670 class OSDMonitor *osdmon() {
671 return (class OSDMonitor *)paxos_service[PAXOS_OSDMAP].get();
672 }
673
674 class AuthMonitor *authmon() {
675 return (class AuthMonitor *)paxos_service[PAXOS_AUTH].get();
676 }
677
678 class LogMonitor *logmon() {
679 return (class LogMonitor*) paxos_service[PAXOS_LOG].get();
680 }
681
682 class MgrMonitor *mgrmon() {
683 return (class MgrMonitor*) paxos_service[PAXOS_MGR].get();
684 }
685
686 class MgrStatMonitor *mgrstatmon() {
687 return (class MgrStatMonitor*) paxos_service[PAXOS_MGRSTAT].get();
688 }
689
690 class HealthMonitor *healthmon() {
691 return (class HealthMonitor*) paxos_service[PAXOS_HEALTH].get();
692 }
693
694 class ConfigMonitor *configmon() {
695 return (class ConfigMonitor*) paxos_service[PAXOS_CONFIG].get();
696 }
697
698 class KVMonitor *kvmon() {
699 return (class KVMonitor*) paxos_service[PAXOS_KV].get();
700 }
701
702 friend class Paxos;
703 friend class OSDMonitor;
704 friend class MDSMonitor;
705 friend class MonmapMonitor;
706 friend class LogMonitor;
707 friend class KVMonitor;
708
709 // -- sessions --
710 MonSessionMap session_map;
711 ceph::mutex session_map_lock = ceph::make_mutex("Monitor::session_map_lock");
712 AdminSocketHook *admin_hook;
713
714 template<typename Func, typename...Args>
715 void with_session_map(Func&& func) {
716 std::lock_guard l(session_map_lock);
717 std::forward<Func>(func)(session_map);
718 }
719 void send_latest_monmap(Connection *con);
720
721 // messages
722 void handle_get_version(MonOpRequestRef op);
723 void handle_subscribe(MonOpRequestRef op);
724 void handle_mon_get_map(MonOpRequestRef op);
725
726 static void _generate_command_map(cmdmap_t& cmdmap,
727 std::map<std::string,std::string> &param_str_map);
728 static const MonCommand *_get_moncommand(
729 const std::string &cmd_prefix,
730 const std::vector<MonCommand>& cmds);
731 bool _allowed_command(MonSession *s, const std::string& module,
732 const std::string& prefix,
733 const cmdmap_t& cmdmap,
734 const std::map<std::string,std::string>& param_str_map,
735 const MonCommand *this_cmd);
736 void get_mon_status(ceph::Formatter *f);
737 void _quorum_status(ceph::Formatter *f, std::ostream& ss);
738 bool _add_bootstrap_peer_hint(std::string_view cmd, const cmdmap_t& cmdmap,
739 std::ostream& ss);
740 void handle_tell_command(MonOpRequestRef op);
741 void handle_command(MonOpRequestRef op);
742 void handle_route(MonOpRequestRef op);
743
744 int get_mon_metadata(int mon, ceph::Formatter *f, std::ostream& err);
745 int print_nodes(ceph::Formatter *f, std::ostream& err);
746
747 // track metadata reported by win_election()
748 std::map<int, Metadata> mon_metadata;
749 std::map<int, Metadata> pending_metadata;
750
751 /**
752 *
753 */
754 struct health_cache_t {
755 health_status_t overall;
756 std::string summary;
757
758 void reset() {
759 // health_status_t doesn't really have a NONE value and we're not
760 // okay with setting something else (say, HEALTH_ERR). so just
761 // leave it be.
762 summary.clear();
763 }
764 } health_status_cache;
765
766 Context *health_tick_event = nullptr;
767 Context *health_interval_event = nullptr;
768
769 void health_tick_start();
770 void health_tick_stop();
771 ceph::real_clock::time_point health_interval_calc_next_update();
772 void health_interval_start();
773 void health_interval_stop();
774 void health_events_cleanup();
775
776 void health_to_clog_update_conf(const std::set<std::string> &changed);
777
778 void do_health_to_clog_interval();
779 void do_health_to_clog(bool force = false);
780
781 void log_health(
782 const health_check_map_t& updated,
783 const health_check_map_t& previous,
784 MonitorDBStore::TransactionRef t);
785
786 protected:
787
788 class HealthCheckLogStatus {
789 public:
790 health_status_t severity;
791 std::string last_message;
792 utime_t updated_at = 0;
793 HealthCheckLogStatus(health_status_t severity_,
794 const std::string &last_message_,
795 utime_t updated_at_)
796 : severity(severity_),
797 last_message(last_message_),
798 updated_at(updated_at_)
799 {}
800 };
801 std::map<std::string, HealthCheckLogStatus> health_check_log_times;
802
803 public:
804
805 void get_cluster_status(std::stringstream &ss, ceph::Formatter *f,
806 MonSession *session);
807
808 void reply_command(MonOpRequestRef op, int rc, const std::string &rs, version_t version);
809 void reply_command(MonOpRequestRef op, int rc, const std::string &rs, ceph::buffer::list& rdata, version_t version);
810
811 void reply_tell_command(MonOpRequestRef op, int rc, const std::string &rs);
812
813
814
815 void handle_probe(MonOpRequestRef op);
816 /**
817 * Handle a Probe Operation, replying with our name, quorum and known versions.
818 *
819 * We use the MMonProbe message class for anything and everything related with
820 * Monitor probing. One of the operations relates directly with the probing
821 * itself, in which we receive a probe request and to which we reply with
822 * our name, our quorum and the known versions for each Paxos service. Thus the
823 * redundant function name. This reply will obviously be sent to the one
824 * probing/requesting these infos.
825 *
826 * @todo Add @pre and @post
827 *
828 * @param m A Probe message, with an operation of type Probe.
829 */
830 void handle_probe_probe(MonOpRequestRef op);
831 void handle_probe_reply(MonOpRequestRef op);
832
833 // request routing
834 struct RoutedRequest {
835 uint64_t tid;
836 ceph::buffer::list request_bl;
837 MonSession *session;
838 ConnectionRef con;
839 uint64_t con_features;
840 MonOpRequestRef op;
841
842 RoutedRequest() : tid(0), session(NULL), con_features(0) {}
843 ~RoutedRequest() {
844 if (session)
845 session->put();
846 }
847 };
848 uint64_t routed_request_tid;
849 std::map<uint64_t, RoutedRequest*> routed_requests;
850
851 void forward_request_leader(MonOpRequestRef op);
852 void handle_forward(MonOpRequestRef op);
853 void send_reply(MonOpRequestRef op, Message *reply);
854 void no_reply(MonOpRequestRef op);
855 void resend_routed_requests();
856 void remove_session(MonSession *s);
857 void remove_all_sessions();
858 void waitlist_or_zap_client(MonOpRequestRef op);
859
860 void send_mon_message(Message *m, int rank);
861 /** can_change_external_state if we can do things like
862 * call elections as a result of the new map.
863 */
864 void notify_new_monmap(bool can_change_external_state=false);
865
866 public:
867 struct C_Command : public C_MonOp {
868 Monitor &mon;
869 int rc;
870 std::string rs;
871 ceph::buffer::list rdata;
872 version_t version;
873 C_Command(Monitor &_mm, MonOpRequestRef _op, int r, std::string s, version_t v) :
874 C_MonOp(_op), mon(_mm), rc(r), rs(s), version(v){}
875 C_Command(Monitor &_mm, MonOpRequestRef _op, int r, std::string s, ceph::buffer::list rd, version_t v) :
876 C_MonOp(_op), mon(_mm), rc(r), rs(s), rdata(rd), version(v){}
877
878 void _finish(int r) override {
879 auto m = op->get_req<MMonCommand>();
880 if (r >= 0) {
881 std::ostringstream ss;
882 if (!op->get_req()->get_connection()) {
883 ss << "connection dropped for command ";
884 } else {
885 MonSession *s = op->get_session();
886
887 // if client drops we may not have a session to draw information from.
888 if (s) {
889 ss << "from='" << s->name << " " << s->addrs << "' "
890 << "entity='" << s->entity_name << "' ";
891 } else {
892 ss << "session dropped for command ";
893 }
894 }
895 cmdmap_t cmdmap;
896 std::ostringstream ds;
897 string prefix;
898 cmdmap_from_json(m->cmd, &cmdmap, ds);
899 cmd_getval(cmdmap, "prefix", prefix);
900 if (prefix != "config set" && prefix != "config-key set")
901 ss << "cmd='" << m->cmd << "': finished";
902
903 mon.audit_clog->info() << ss.str();
904 mon.reply_command(op, rc, rs, rdata, version);
905 }
906 else if (r == -ECANCELED)
907 return;
908 else if (r == -EAGAIN)
909 mon.dispatch_op(op);
910 else
911 ceph_abort_msg("bad C_Command return value");
912 }
913 };
914
915 private:
916 class C_RetryMessage : public C_MonOp {
917 Monitor *mon;
918 public:
919 C_RetryMessage(Monitor *m, MonOpRequestRef op) :
920 C_MonOp(op), mon(m) { }
921
922 void _finish(int r) override {
923 if (r == -EAGAIN || r >= 0)
924 mon->dispatch_op(op);
925 else if (r == -ECANCELED)
926 return;
927 else
928 ceph_abort_msg("bad C_RetryMessage return value");
929 }
930 };
931
932 //ms_dispatch handles a lot of logic and we want to reuse it
933 //on forwarded messages, so we create a non-locking version for this class
934 void _ms_dispatch(Message *m);
935 bool ms_dispatch(Message *m) override {
936 std::lock_guard l{lock};
937 _ms_dispatch(m);
938 return true;
939 }
940 void dispatch_op(MonOpRequestRef op);
941 //mon_caps is used for un-connected messages from monitors
942 MonCap mon_caps;
943 bool get_authorizer(int dest_type, AuthAuthorizer **authorizer);
944 public: // for AuthMonitor msgr1:
945 int ms_handle_authentication(Connection *con) override;
946 private:
947 void ms_handle_accept(Connection *con) override;
948 bool ms_handle_reset(Connection *con) override;
949 void ms_handle_remote_reset(Connection *con) override {}
950 bool ms_handle_refused(Connection *con) override;
951
952 // AuthClient
953 int get_auth_request(
954 Connection *con,
955 AuthConnectionMeta *auth_meta,
956 uint32_t *method,
957 std::vector<uint32_t> *preferred_modes,
958 ceph::buffer::list *out) override;
959 int handle_auth_reply_more(
960 Connection *con,
961 AuthConnectionMeta *auth_meta,
962 const ceph::buffer::list& bl,
963 ceph::buffer::list *reply) override;
964 int handle_auth_done(
965 Connection *con,
966 AuthConnectionMeta *auth_meta,
967 uint64_t global_id,
968 uint32_t con_mode,
969 const ceph::buffer::list& bl,
970 CryptoKey *session_key,
971 std::string *connection_secret) override;
972 int handle_auth_bad_method(
973 Connection *con,
974 AuthConnectionMeta *auth_meta,
975 uint32_t old_auth_method,
976 int result,
977 const std::vector<uint32_t>& allowed_methods,
978 const std::vector<uint32_t>& allowed_modes) override;
979 // /AuthClient
980 // AuthServer
981 int handle_auth_request(
982 Connection *con,
983 AuthConnectionMeta *auth_meta,
984 bool more,
985 uint32_t auth_method,
986 const ceph::buffer::list& bl,
987 ceph::buffer::list *reply) override;
988 // /AuthServer
989
990 int write_default_keyring(ceph::buffer::list& bl);
991 void extract_save_mon_key(KeyRing& keyring);
992
993 void collect_metadata(Metadata *m);
994 int load_metadata();
995 void count_metadata(const std::string& field, ceph::Formatter *f);
996 void count_metadata(const std::string& field, std::map<std::string,int> *out);
997 // get_all_versions() gathers version information from daemons for health check
998 void get_all_versions(std::map<string, std::list<std::string>> &versions);
999 void get_versions(std::map<string, std::list<std::string>> &versions);
1000
1001 // features
1002 static CompatSet get_initial_supported_features();
1003 static CompatSet get_supported_features();
1004 static CompatSet get_legacy_features();
1005 /// read the ondisk features into the CompatSet pointed to by read_features
1006 static void read_features_off_disk(MonitorDBStore *store, CompatSet *read_features);
1007 void read_features();
1008 void write_features(MonitorDBStore::TransactionRef t);
1009
1010 OpTracker op_tracker;
1011
1012 public:
1013 Monitor(CephContext *cct_, std::string nm, MonitorDBStore *s,
1014 Messenger *m, Messenger *mgr_m, MonMap *map);
1015 ~Monitor() override;
1016
1017 static int check_features(MonitorDBStore *store);
1018
1019 // config observer
1020 const char** get_tracked_conf_keys() const override;
1021 void handle_conf_change(const ConfigProxy& conf,
1022 const std::set<std::string> &changed) override;
1023
1024 void update_log_clients();
1025 int sanitize_options();
1026 int preinit();
1027 int init();
1028 void init_paxos();
1029 void refresh_from_paxos(bool *need_bootstrap);
1030 void shutdown();
1031 void tick();
1032
1033 void handle_signal(int sig);
1034
1035 int mkfs(ceph::buffer::list& osdmapbl);
1036
1037 /**
1038 * check cluster_fsid file
1039 *
1040 * @return EEXIST if file exists and doesn't match, 0 on match, or negative error code
1041 */
1042 int check_fsid();
1043
1044 /**
1045 * write cluster_fsid file
1046 *
1047 * @return 0 on success, or negative error code
1048 */
1049 int write_fsid();
1050 int write_fsid(MonitorDBStore::TransactionRef t);
1051
1052 int do_admin_command(std::string_view command, const cmdmap_t& cmdmap,
1053 ceph::Formatter *f,
1054 std::ostream& err,
1055 std::ostream& out);
1056
1057 private:
1058 // don't allow copying
1059 Monitor(const Monitor& rhs);
1060 Monitor& operator=(const Monitor &rhs);
1061
1062 public:
1063 static void format_command_descriptions(const std::vector<MonCommand> &commands,
1064 ceph::Formatter *f,
1065 uint64_t features,
1066 ceph::buffer::list *rdata);
1067
1068 const std::vector<MonCommand> &get_local_commands(mon_feature_t f) {
1069 if (f.contains_all(ceph::features::mon::FEATURE_NAUTILUS)) {
1070 return local_mon_commands;
1071 } else {
1072 return prenautilus_local_mon_commands;
1073 }
1074 }
1075 const ceph::buffer::list& get_local_commands_bl(mon_feature_t f) {
1076 if (f.contains_all(ceph::features::mon::FEATURE_NAUTILUS)) {
1077 return local_mon_commands_bl;
1078 } else {
1079 return prenautilus_local_mon_commands_bl;
1080 }
1081 }
1082 void set_leader_commands(const std::vector<MonCommand>& cmds) {
1083 leader_mon_commands = cmds;
1084 }
1085
1086 bool is_keyring_required();
1087 };
1088
1089 #define CEPH_MON_FEATURE_INCOMPAT_BASE CompatSet::Feature (1, "initial feature set (~v.18)")
1090 #define CEPH_MON_FEATURE_INCOMPAT_GV CompatSet::Feature (2, "global version sequencing (v0.52)")
1091 #define CEPH_MON_FEATURE_INCOMPAT_SINGLE_PAXOS CompatSet::Feature (3, "single paxos with k/v store (v0.\?)")
1092 #define CEPH_MON_FEATURE_INCOMPAT_OSD_ERASURE_CODES CompatSet::Feature(4, "support erasure code pools")
1093 #define CEPH_MON_FEATURE_INCOMPAT_OSDMAP_ENC CompatSet::Feature(5, "new-style osdmap encoding")
1094 #define CEPH_MON_FEATURE_INCOMPAT_ERASURE_CODE_PLUGINS_V2 CompatSet::Feature(6, "support isa/lrc erasure code")
1095 #define CEPH_MON_FEATURE_INCOMPAT_ERASURE_CODE_PLUGINS_V3 CompatSet::Feature(7, "support shec erasure code")
1096 #define CEPH_MON_FEATURE_INCOMPAT_KRAKEN CompatSet::Feature(8, "support monmap features")
1097 #define CEPH_MON_FEATURE_INCOMPAT_LUMINOUS CompatSet::Feature(9, "luminous ondisk layout")
1098 #define CEPH_MON_FEATURE_INCOMPAT_MIMIC CompatSet::Feature(10, "mimic ondisk layout")
1099 #define CEPH_MON_FEATURE_INCOMPAT_NAUTILUS CompatSet::Feature(11, "nautilus ondisk layout")
1100 #define CEPH_MON_FEATURE_INCOMPAT_OCTOPUS CompatSet::Feature(12, "octopus ondisk layout")
1101 #define CEPH_MON_FEATURE_INCOMPAT_PACIFIC CompatSet::Feature(13, "pacific ondisk layout")
1102 // make sure you add your feature to Monitor::get_supported_features
1103
1104
1105 /* Callers use:
1106 *
1107 * new C_MonContext{...}
1108 *
1109 * instead of
1110 *
1111 * new C_MonContext(...)
1112 *
1113 * because of gcc bug [1].
1114 *
1115 * [1] https://gcc.gnu.org/bugzilla/show_bug.cgi?id=85883
1116 */
1117 template<typename T>
1118 class C_MonContext : public LambdaContext<T> {
1119 public:
1120 C_MonContext(const Monitor* m, T&& f) :
1121 LambdaContext<T>(std::forward<T>(f)),
1122 mon(m)
1123 {}
1124 void finish(int r) override {
1125 if (mon->is_shutdown())
1126 return;
1127 LambdaContext<T>::finish(r);
1128 }
1129 private:
1130 const Monitor* mon;
1131 };
1132
1133 #endif