summaryrefslogtreecommitdiffstats
path: root/src/mgr/Mgr.cc
blob: cdbbb9d0953cd94fdc64a73cb34f609ca8c40b06 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
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
100
101
102
103
104
105
106
107
108
109
110
111
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
152
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
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
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
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
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
304
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
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
/*
 * Ceph - scalable distributed file system
 *
 * Copyright (C) 2016 John Spray <john.spray@redhat.com>
 *
 * This is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License version 2.1, as published by the Free Software
 * Foundation.  See file COPYING.
 */

#include <Python.h>

#include "osdc/Objecter.h"
#include "common/errno.h"
#include "mon/MonClient.h"
#include "include/stringify.h"
#include "global/global_context.h"
#include "global/signal_handler.h"

#include "mgr/MgrContext.h"

#include "MgrPyModule.h"
#include "DaemonServer.h"
#include "messages/MMgrBeacon.h"
#include "messages/MMgrDigest.h"
#include "messages/MCommand.h"
#include "messages/MCommandReply.h"

#include "Mgr.h"

#define dout_context g_ceph_context
#define dout_subsys ceph_subsys_mgr
#undef dout_prefix
#define dout_prefix *_dout << "mgr " << __func__ << " "


Mgr::Mgr(MonClient *monc_, Messenger *clientm_, Objecter *objecter_,
	 LogChannelRef clog_, LogChannelRef audit_clog_) :
  monc(monc_),
  objecter(objecter_),
  client_messenger(clientm_),
  lock("Mgr::lock"),
  timer(g_ceph_context, lock),
  finisher(g_ceph_context, "Mgr", "mgr-fin"),
  waiting_for_fs_map(NULL),
  py_modules(daemon_state, cluster_state, *monc, finisher),
  cluster_state(monc, nullptr),
  server(monc, daemon_state, cluster_state, py_modules, clog_, audit_clog_),
  initialized(false),
  initializing(false)
{
  cluster_state.set_objecter(objecter);
}


Mgr::~Mgr()
{
  assert(waiting_for_fs_map == nullptr);
}


/**
 * Context for completion of metadata mon commands: take
 * the result and stash it in DaemonStateIndex
 */
class MetadataUpdate : public Context
{
  DaemonStateIndex &daemon_state;
  DaemonKey key;

public:
  bufferlist outbl;
  std::string outs;

  MetadataUpdate(DaemonStateIndex &daemon_state_, const DaemonKey &key_)
    : daemon_state(daemon_state_), key(key_) {}

  void finish(int r) override
  {
    daemon_state.clear_updating(key);
    if (r == 0) {
      if (key.first == CEPH_ENTITY_TYPE_MDS) {
        json_spirit::mValue json_result;
        bool read_ok = json_spirit::read(
            outbl.to_str(), json_result);
        if (!read_ok) {
          dout(1) << "mon returned invalid JSON for "
                  << ceph_entity_type_name(key.first)
                  << "." << key.second << dendl;
          return;
        }

        json_spirit::mObject daemon_meta = json_result.get_obj();

        DaemonStatePtr state;
        if (daemon_state.exists(key)) {
          state = daemon_state.get(key);
          // TODO lock state
          daemon_meta.erase("name");
          daemon_meta.erase("hostname");
          state->metadata.clear();
          for (const auto &i : daemon_meta) {
            state->metadata[i.first] = i.second.get_str();
          }
        } else {
          state = std::make_shared<DaemonState>(daemon_state.types);
          state->key = key;
          state->hostname = daemon_meta.at("hostname").get_str();

          for (const auto &i : daemon_meta) {
            state->metadata[i.first] = i.second.get_str();
          }

          daemon_state.insert(state);
        }
      } else if (key.first == CEPH_ENTITY_TYPE_OSD) {
      } else {
        ceph_abort();
      }
    } else {
      dout(1) << "mon failed to return metadata for "
              << ceph_entity_type_name(key.first)
              << "." << key.second << ": " << cpp_strerror(r) << dendl;
    }
  }
};


void Mgr::background_init()
{
  Mutex::Locker l(lock);
  assert(!initializing);
  assert(!initialized);
  initializing = true;

  finisher.start();

  finisher.queue(new FunctionContext([this](int r){
    init();
  }));
}

void Mgr::init()
{
  Mutex::Locker l(lock);
  assert(initializing);
  assert(!initialized);

  // Start communicating with daemons to learn statistics etc
  int r = server.init(monc->get_global_id(), client_messenger->get_myaddr());
  if (r < 0) {
    derr << "Initialize server fail"<< dendl;
    return;
  }
  dout(4) << "Initialized server at " << server.get_myaddr() << dendl;

  // Preload all daemon metadata (will subsequently keep this
  // up to date by watching maps, so do the initial load before
  // we subscribe to any maps)
  dout(4) << "Loading daemon metadata..." << dendl;
  load_all_metadata();

  // Preload config keys (`get` for plugins is to be a fast local
  // operation, we we don't have to synchronize these later because
  // all sets will come via mgr)
  load_config();

  // Start Objecter and wait for OSD map
  lock.Unlock();  // Drop lock because OSDMap dispatch calls into my ms_dispatch
  objecter->wait_for_osd_map();
  lock.Lock();

  // Populate PGs in ClusterState
  objecter->with_osdmap([this](const OSDMap &osd_map) {
    cluster_state.notify_osdmap(osd_map);
  });

  // Subscribe to OSDMap update to pass on to ClusterState
  objecter->maybe_request_map();

  monc->sub_want("mgrdigest", 0, 0);

  // Prepare to receive FSMap and request it
  dout(4) << "requesting FSMap..." << dendl;
  C_SaferCond cond;
  waiting_for_fs_map = &cond;
  monc->sub_want("fsmap", 0, 0);
  monc->renew_subs();

  // Wait for FSMap
  dout(4) << "waiting for FSMap..." << dendl;
  lock.Unlock();
  cond.wait();
  lock.Lock();
  waiting_for_fs_map = nullptr;
  dout(4) << "Got FSMap." << dendl;

  // Wait for MgrDigest...?
  // TODO

  // assume finisher already initialized in background_init

  py_modules.init();
  py_modules.start();

  dout(4) << "Complete." << dendl;
  initializing = false;
  initialized = true;
}

void Mgr::load_all_metadata()
{
  assert(lock.is_locked_by_me());

  JSONCommand mds_cmd;
  mds_cmd.run(monc, "{\"prefix\": \"mds metadata\"}");
  JSONCommand osd_cmd;
  osd_cmd.run(monc, "{\"prefix\": \"osd metadata\"}");
  JSONCommand mon_cmd;
  mon_cmd.run(monc, "{\"prefix\": \"mon metadata\"}");

  mds_cmd.wait();
  osd_cmd.wait();
  mon_cmd.wait();

  assert(mds_cmd.r == 0);
  assert(mon_cmd.r == 0);
  assert(osd_cmd.r == 0);

  for (auto &metadata_val : mds_cmd.json_result.get_array()) {
    json_spirit::mObject daemon_meta = metadata_val.get_obj();
    if (daemon_meta.count("hostname") == 0) {
      dout(1) << "Skipping incomplete metadata entry" << dendl;
      continue;
    }

    DaemonStatePtr dm = std::make_shared<DaemonState>(daemon_state.types);
    dm->key = DaemonKey(CEPH_ENTITY_TYPE_MDS,
                        daemon_meta.at("name").get_str());
    dm->hostname = daemon_meta.at("hostname").get_str();

    daemon_meta.erase("name");
    daemon_meta.erase("hostname");

    for (const auto &i : daemon_meta) {
      dm->metadata[i.first] = i.second.get_str();
    }

    daemon_state.insert(dm);
  }

  for (auto &metadata_val : mon_cmd.json_result.get_array()) {
    json_spirit::mObject daemon_meta = metadata_val.get_obj();
    if (daemon_meta.count("hostname") == 0) {
      dout(1) << "Skipping incomplete metadata entry" << dendl;
      continue;
    }

    DaemonStatePtr dm = std::make_shared<DaemonState>(daemon_state.types);
    dm->key = DaemonKey(CEPH_ENTITY_TYPE_MON,
                        daemon_meta.at("name").get_str());
    dm->hostname = daemon_meta.at("hostname").get_str();

    daemon_meta.erase("name");
    daemon_meta.erase("hostname");

    for (const auto &i : daemon_meta) {
      dm->metadata[i.first] = i.second.get_str();
    }

    daemon_state.insert(dm);
  }

  for (auto &osd_metadata_val : osd_cmd.json_result.get_array()) {
    json_spirit::mObject osd_metadata = osd_metadata_val.get_obj();
    if (osd_metadata.count("hostname") == 0) {
      dout(1) << "Skipping incomplete metadata entry" << dendl;
      continue;
    }
    dout(4) << osd_metadata.at("hostname").get_str() << dendl;

    DaemonStatePtr dm = std::make_shared<DaemonState>(daemon_state.types);
    dm->key = DaemonKey(CEPH_ENTITY_TYPE_OSD,
                        stringify(osd_metadata.at("id").get_int()));
    dm->hostname = osd_metadata.at("hostname").get_str();

    osd_metadata.erase("id");
    osd_metadata.erase("hostname");

    for (const auto &i : osd_metadata) {
      dm->metadata[i.first] = i.second.get_str();
    }

    daemon_state.insert(dm);
  }
}

void Mgr::load_config()
{
  assert(lock.is_locked_by_me());

  dout(10) << "listing keys" << dendl;
  JSONCommand cmd;
  cmd.run(monc, "{\"prefix\": \"config-key list\"}");

  cmd.wait();
  assert(cmd.r == 0);

  std::map<std::string, std::string> loaded;
  
  for (auto &key_str : cmd.json_result.get_array()) {
    std::string const key = key_str.get_str();
    dout(20) << "saw key '" << key << "'" << dendl;

    const std::string config_prefix = PyModules::config_prefix;

    if (key.substr(0, config_prefix.size()) == config_prefix) {
      dout(20) << "fetching '" << key << "'" << dendl;
      Command get_cmd;
      std::ostringstream cmd_json;
      cmd_json << "{\"prefix\": \"config-key get\", \"key\": \"" << key << "\"}";
      get_cmd.run(monc, cmd_json.str());
      get_cmd.wait();
      assert(get_cmd.r == 0);

      loaded[key] = get_cmd.outbl.to_str();
    }
  }

  py_modules.insert_config(loaded);
}

void Mgr::shutdown()
{
  // FIXME: pre-empt init() if it is currently running, so that it will
  // give up the lock for us.
  Mutex::Locker l(lock);

  // First stop the server so that we're not taking any more incoming requests
  server.shutdown();

  // after the messenger is stopped, signal modules to shutdown via finisher
  py_modules.shutdown();

  // Then stop the finisher to ensure its enqueued contexts aren't going
  // to touch references to the things we're about to tear down
  finisher.wait_for_empty();
  finisher.stop();
}

void Mgr::handle_osd_map()
{
  assert(lock.is_locked_by_me());

  std::set<std::string> names_exist;

  /**
   * When we see a new OSD map, inspect the entity addrs to
   * see if they have changed (service restart), and if so
   * reload the metadata.
   */
  objecter->with_osdmap([this, &names_exist](const OSDMap &osd_map) {
    for (unsigned int osd_id = 0; osd_id < osd_map.get_num_osds(); ++osd_id) {
      if (!osd_map.exists(osd_id)) {
        continue;
      }

      // Remember which OSDs exist so that we can cull any that don't
      names_exist.insert(stringify(osd_id));

      // Consider whether to update the daemon metadata (new/restarted daemon)
      bool update_meta = false;
      const auto k = DaemonKey(CEPH_ENTITY_TYPE_OSD, stringify(osd_id));
      if (daemon_state.is_updating(k)) {
        continue;
      }

      if (daemon_state.exists(k)) {
        auto metadata = daemon_state.get(k);
        auto addr_iter = metadata->metadata.find("front_addr");
        if (addr_iter != metadata->metadata.end()) {
          const std::string &metadata_addr = addr_iter->second;
          const auto &map_addr = osd_map.get_addr(osd_id);

          if (metadata_addr != stringify(map_addr)) {
            dout(4) << "OSD[" << osd_id << "] addr change " << metadata_addr
                    << " != " << stringify(map_addr) << dendl;
            update_meta = true;
          } else {
            dout(20) << "OSD[" << osd_id << "] addr unchanged: "
                     << metadata_addr << dendl;
          }
        } else {
          // Awkward case where daemon went into DaemonState because it
          // sent us a report but its metadata didn't get loaded yet
          update_meta = true;
        }
      } else {
        update_meta = true;
      }

      if (update_meta) {
        daemon_state.notify_updating(k);
        auto c = new MetadataUpdate(daemon_state, k);
        std::ostringstream cmd;
        cmd << "{\"prefix\": \"osd metadata\", \"id\": "
            << osd_id << "}";
        monc->start_mon_command(
            {cmd.str()},
            {}, &c->outbl, &c->outs, c);
      }
    }

    cluster_state.notify_osdmap(osd_map);
  });

  // TODO: same culling for MonMap and FSMap
  daemon_state.cull(CEPH_ENTITY_TYPE_OSD, names_exist);
}

bool Mgr::ms_dispatch(Message *m)
{
  dout(4) << *m << dendl;
  Mutex::Locker l(lock);

  switch (m->get_type()) {
    case MSG_MGR_DIGEST:
      handle_mgr_digest(static_cast<MMgrDigest*>(m));
      break;
    case CEPH_MSG_MON_MAP:
      // FIXME: we probably never get called here because MonClient
      // has consumed the message.  For consuming OSDMap we need
      // to be the tail dispatcher, but to see MonMap we would
      // need to be at the head.
      // Result is that ClusterState has access to monmap (it reads
      // from monclient anyway), but we don't see notifications.  Hook
      // into MonClient to get notifications instead of messing
      // with message delivery to achieve it?
      ceph_abort();

      py_modules.notify_all("mon_map", "");
      break;
    case CEPH_MSG_FS_MAP:
      py_modules.notify_all("fs_map", "");
      handle_fs_map((MFSMap*)m);
      m->put();
      break;
    case CEPH_MSG_OSD_MAP:
      handle_osd_map();

      py_modules.notify_all("osd_map", "");

      // Continuous subscribe, so that we can generate notifications
      // for our MgrPyModules
      objecter->maybe_request_map();
      m->put();
      break;

    default:
      return false;
  }
  return true;
}


void Mgr::handle_fs_map(MFSMap* m)
{
  assert(lock.is_locked_by_me());

  const FSMap &new_fsmap = m->get_fsmap();

  if (waiting_for_fs_map) {
    waiting_for_fs_map->complete(0);
    waiting_for_fs_map = NULL;
  }

  // TODO: callers (e.g. from python land) are potentially going to see
  // the new fsmap before we've bothered populating all the resulting
  // daemon_state.  Maybe we should block python land while we're making
  // this kind of update?
  
  cluster_state.set_fsmap(new_fsmap);

  auto mds_info = new_fsmap.get_mds_info();
  for (const auto &i : mds_info) {
    const auto &info = i.second;

    const auto k = DaemonKey(CEPH_ENTITY_TYPE_MDS, info.name);
    if (daemon_state.is_updating(k)) {
      continue;
    }

    bool update = false;
    if (daemon_state.exists(k)) {
      auto metadata = daemon_state.get(k);
      // FIXME: nothing stopping old daemons being here, they won't have
      // addr: need to handle case of pre-ceph-mgr daemons that don't have
      // the fields we expect
      if (metadata->metadata.empty() ||
	  metadata->metadata.count("addr") == 0) {
        update = true;
      } else {
        auto metadata_addr = metadata->metadata.at("addr");
        const auto map_addr = info.addr;
        update = metadata_addr != stringify(map_addr);
        if (update) {
          dout(4) << "MDS[" << info.name << "] addr change " << metadata_addr
                  << " != " << stringify(map_addr) << dendl;
        }
      }
    } else {
      update = true;
    }

    if (update) {
      daemon_state.notify_updating(k);
      auto c = new MetadataUpdate(daemon_state, k);
      std::ostringstream cmd;
      cmd << "{\"prefix\": \"mds metadata\", \"who\": \""
          << info.name << "\"}";
      monc->start_mon_command(
          {cmd.str()},
          {}, &c->outbl, &c->outs, c);
    }
  }
}


void Mgr::handle_mgr_digest(MMgrDigest* m)
{
  dout(10) << m->mon_status_json.length() << dendl;
  dout(10) << m->health_json.length() << dendl;
  cluster_state.load_digest(m);
  py_modules.notify_all("mon_status", "");
  py_modules.notify_all("health", "");

  // Hack: use this as a tick/opportunity to prompt python-land that
  // the pgmap might have changed since last time we were here.
  py_modules.notify_all("pg_summary", "");
  
  m->put();
}