summaryrefslogtreecommitdiffstats
path: root/src/cls/lock/cls_lock.cc
blob: 96d28461db421db16460d87257e4dc35ddd55b7a (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
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab

/** \file
 *
 * This is an OSD class that implements methods for object
 * advisory locking.
 *
 */

#include <errno.h>
#include <map>
#include <sstream>

#include "include/types.h"
#include "include/utime.h"
#include "objclass/objclass.h"

#include "common/errno.h"
#include "common/Clock.h"

#include "cls/lock/cls_lock_types.h"
#include "cls/lock/cls_lock_ops.h"

#include "global/global_context.h"

#include "include/compat.h"

using std::map;
using std::string;

using ceph::bufferlist;
using namespace rados::cls::lock;

CLS_VER(1,0)
CLS_NAME(lock)

#define LOCK_PREFIX    "lock."

static int clean_lock(cls_method_context_t hctx)
{
  int r = cls_cxx_remove(hctx);
  if (r < 0)
    return r;

  return 0;
}

static int read_lock(cls_method_context_t hctx,
		     const string& name,
		     lock_info_t *lock)
{
  bufferlist bl;
  string key = LOCK_PREFIX;
  key.append(name);
 
  int r = cls_cxx_getxattr(hctx, key.c_str(), &bl);
  if (r < 0) {
    if (r ==  -ENODATA) {
      *lock = lock_info_t();
      return 0;
    }
    if (r != -ENOENT) {
      CLS_ERR("error reading xattr %s: %d", key.c_str(), r);
    }
    return r;
  }

  try {
    auto it = bl.cbegin();
    decode(*lock, it);
  } catch (const ceph::buffer::error &err) {
    CLS_ERR("error decoding %s", key.c_str());
    return -EIO;
  }

  /* now trim expired locks */

  utime_t now = ceph_clock_now();

  auto iter = lock->lockers.begin();

  while (iter != lock->lockers.end()) {
    struct locker_info_t& info = iter->second;
    if (!info.expiration.is_zero() && info.expiration < now) {
      CLS_LOG(20, "expiring locker");
      iter = lock->lockers.erase(iter);
    } else {
      ++iter;
    }
  }

  if (lock->lockers.empty() && cls_lock_is_ephemeral(lock->lock_type)) {
    r = clean_lock(hctx);
    if (r < 0) {
      CLS_ERR("error, on read, cleaning lock object %s", cpp_strerror(r).c_str());
    }
  }

  return 0;
}

static int write_lock(cls_method_context_t hctx, const string& name, const lock_info_t& lock)
{
  using ceph::encode;
  string key = LOCK_PREFIX;
  key.append(name);

  bufferlist lock_bl;
  encode(lock, lock_bl, cls_get_client_features(hctx));

  int r = cls_cxx_setxattr(hctx, key.c_str(), &lock_bl);
  if (r < 0)
    return r;

  return 0;
}

/**
 * helper function to add a lock and update disk state.
 *
 * Input:
 * @param name Lock name
 * @param lock_type Type of lock (exclusive / shared)
 * @param duration Duration of lock (in seconds). Zero means it doesn't expire.
 * @param flags lock flags
 * @param cookie The cookie to set in the lock
 * @param tag The tag to match with the lock (can only lock with matching tags)
 * @param lock_description The lock description to set (if not empty)
 * @param locker_description The locker description
 *
 * @return 0 on success, or -errno on failure
 */
static int lock_obj(cls_method_context_t hctx,
                    const string& name,
                    ClsLockType lock_type,
                    utime_t duration,
                    const string& description,
                    uint8_t flags,
                    const string& cookie,
                    const string& tag)
{
  bool exclusive = cls_lock_is_exclusive(lock_type);
  lock_info_t linfo;
  bool fail_if_exists = (flags & LOCK_FLAG_MAY_RENEW) == 0;
  bool fail_if_does_not_exist = flags & LOCK_FLAG_MUST_RENEW;

  CLS_LOG(20,
	  "requested lock_type=%s fail_if_exists=%d fail_if_does_not_exist=%d",
	  cls_lock_type_str(lock_type), fail_if_exists, fail_if_does_not_exist);
  if (!cls_lock_is_valid(lock_type)) {
    return -EINVAL;
  }

  if (name.empty())
    return -EINVAL;

  if (!fail_if_exists && fail_if_does_not_exist) {
    // at most one of LOCK_FLAG_MAY_RENEW and LOCK_FLAG_MUST_RENEW may
    // be set since they have different implications if the lock does
    // not already exist
    return -EINVAL;
  }

  // see if there's already a locker
  int r = read_lock(hctx, name, &linfo);
  if (r < 0 && r != -ENOENT) {
    CLS_ERR("Could not read lock info: %s", cpp_strerror(r).c_str());
    return r;
  }

  auto& lockers = linfo.lockers;

  locker_id_t id;
  id.cookie = cookie;
  entity_inst_t inst;
  r = cls_get_request_origin(hctx, &inst);
  id.locker = inst.name;
  ceph_assert(r == 0);

  /* check this early, before we check fail_if_exists, otherwise we might
   * remove the locker entry and not check it later */
  if (lockers.size() && tag != linfo.tag) {
    CLS_LOG(20, "cannot take lock on object, conflicting tag");
    return -EBUSY;
  }

  ClsLockType existing_lock_type = linfo.lock_type;
  CLS_LOG(20, "existing_lock_type=%s", cls_lock_type_str(existing_lock_type));
  auto iter = lockers.find(id);
  if (iter != lockers.end()) {
    if (fail_if_exists && !fail_if_does_not_exist) {
      return -EEXIST;
    } else {
      lockers.erase(iter); // remove old entry
    }
  } else if (fail_if_does_not_exist) {
    return -ENOENT;
  }

  if (!lockers.empty()) {
    if (exclusive) {
      auto locker_lister =
	[&lockers]() -> std::string {
	  std::stringstream locker_list;
	  locker_list << lockers;
	  return locker_list.str();
	};
      CLS_LOG(20, "could not exclusive-lock object, already locked by %s",
	      locker_lister().c_str());
      return -EBUSY;
    }

    if (existing_lock_type != lock_type) {
      CLS_LOG(20, "cannot take lock on object, conflicting lock type");
      return -EBUSY;
    }
  }

  linfo.lock_type = lock_type;
  linfo.tag = tag;
  utime_t expiration;
  if (!duration.is_zero()) {
    expiration = ceph_clock_now();
    expiration += duration;

  }
  // make all addrs of type legacy, because v2 clients speak v2 or v1,
  // even depending on which OSD they are talking to, and the type
  // isn't what uniquely identifies them.  also, storing a v1 addr
  // here means that old clients who get this locker_info won't see an
  // old "msgr2:" prefix.
  inst.addr.set_type(entity_addr_t::TYPE_LEGACY);

  struct locker_info_t info(expiration, inst.addr, description);

  linfo.lockers[id] = info;

  r = write_lock(hctx, name, linfo);
  if (r < 0)
    return r;

  return 0;
}

/**
 * Set an exclusive lock on an object for the activating client, if possible.
 *
 * Input:
 * @param cls_lock_lock_op request input
 *
 * @returns 0 on success, -EINVAL if it can't decode the lock_cookie,
 * -EBUSY if the object is already locked, or -errno on (unexpected) failure.
 */
static int lock_op(cls_method_context_t hctx,
                   bufferlist *in, bufferlist *out)
{
  CLS_LOG(20, "lock_op");
  cls_lock_lock_op op;
  try {
    auto iter = in->cbegin();
    decode(op, iter);
  } catch (const ceph::buffer::error &err) {
    return -EINVAL;
  }

  return lock_obj(hctx,
                  op.name, op.type, op.duration, op.description,
                  op.flags, op.cookie, op.tag);
}

/**
 *  helper function to remove a lock from on disk and clean up state.
 *
 *  @param name The lock name
 *  @param locker The locker entity name
 *  @param cookie The user-defined cookie associated with the lock.
 *
 *  @return 0 on success, -ENOENT if there is no such lock (either
 *  entity or cookie is wrong), or -errno on other error.
 */
static int remove_lock(cls_method_context_t hctx,
		       const string& name,
		       entity_name_t& locker,
		       const string& cookie)
{
  // get current lockers
  lock_info_t linfo;
  int r = read_lock(hctx, name, &linfo);
  if (r < 0) {
    CLS_ERR("Could not read list of current lockers off disk: %s", cpp_strerror(r).c_str());
    return r;
  }

  auto& lockers = linfo.lockers;
  struct locker_id_t id(locker, cookie);

  // remove named locker from set
  auto iter = lockers.find(id);
  if (iter == lockers.end()) { // no such key
    CLS_LOG(10, "locker %s [name: %s.%ld, cookie: %s] does not exist", name.c_str(), 
            locker.type_str(), locker.num(), cookie.c_str());
    return -ENOENT;
  }
  lockers.erase(iter);

  if (cls_lock_is_ephemeral(linfo.lock_type)) {
    ceph_assert(lockers.empty());
    r = clean_lock(hctx);
  } else {
    r = write_lock(hctx, name, linfo);
  }

  return r;
}

/**
 * Unlock an object which the activating client currently has locked.
 *
 * Input:
 * @param cls_lock_unlock_op request input
 *
 * @return 0 on success, -EINVAL if it can't decode the cookie, -ENOENT
 * if there is no such lock (either entity or cookie is wrong), or
 * -errno on other (unexpected) error.
 */
static int unlock_op(cls_method_context_t hctx,
                     bufferlist *in, bufferlist *out)
{
  CLS_LOG(20, "unlock_op");
  cls_lock_unlock_op op;
  try {
    auto iter = in->cbegin();
    decode(op, iter);
  } catch (const ceph::buffer::error& err) {
    return -EINVAL;
  }

  entity_inst_t inst;
  int r = cls_get_request_origin(hctx, &inst);
  ceph_assert(r == 0);
  return remove_lock(hctx, op.name, inst.name, op.cookie);
}

/**
 * Break the lock on an object held by any client.
 *
 * Input:
 * @param cls_lock_break_op request input
 *
 * @return 0 on success, -EINVAL if it can't decode the locker and
 * cookie, -ENOENT if there is no such lock (either entity or cookie
 * is wrong), or -errno on other (unexpected) error.
 */
static int break_lock(cls_method_context_t hctx,
		      bufferlist *in, bufferlist *out)
{
  CLS_LOG(20, "break_lock");
  cls_lock_break_op op;
  try {
    auto iter = in->cbegin();
    decode(op, iter);
  } catch (const ceph::buffer::error& err) {
    return -EINVAL;
  }

  return remove_lock(hctx, op.name, op.locker, op.cookie);
}


/**
 * Retrieve lock info: lockers, tag, exclusive
 *
 * Input:
 * @param cls_lock_list_lockers_op request input
 *
 * Output:
 * @param cls_lock_list_lockers_reply result
 *
 * @return 0 on success, -errno on failure.
 */
static int get_info(cls_method_context_t hctx, bufferlist *in, bufferlist *out)
{
  CLS_LOG(20, "get_info");
  cls_lock_get_info_op op;
  try {
    auto iter = in->cbegin();
    decode(op, iter);
  } catch (const ceph::buffer::error& err) {
    return -EINVAL;
  }

  // get current lockers
  lock_info_t linfo;
  int r = read_lock(hctx, op.name, &linfo);
  if (r < 0) {
    CLS_ERR("Could not read lock info: %s", cpp_strerror(r).c_str());
    return r;
  }

  struct cls_lock_get_info_reply ret;

  for (auto iter = linfo.lockers.begin(); iter != linfo.lockers.end(); ++iter) {
    ret.lockers[iter->first] = iter->second;
  }
  ret.lock_type = linfo.lock_type;
  ret.tag = linfo.tag;

  encode(ret, *out, cls_get_client_features(hctx));

  return 0;
}


/**
 * Retrieve a list of locks for this object
 *
 * Input:
 * @param in is ignored.
 *
 * Output:
 * @param out contains encoded cls_list_locks_reply
 *
 * @return 0 on success, -errno on failure.
 */
static int list_locks(cls_method_context_t hctx, bufferlist *in, bufferlist *out)
{
  CLS_LOG(20, "list_locks");

  map<string, bufferlist> attrs;

  int r = cls_cxx_getxattrs(hctx, &attrs);
  if (r < 0)
    return r;

  cls_lock_list_locks_reply ret;

  size_t pos = sizeof(LOCK_PREFIX) - 1;
  for (auto iter = attrs.begin(); iter != attrs.end(); ++iter) {
    const string& attr = iter->first;
    if (attr.substr(0, pos).compare(LOCK_PREFIX) == 0) {
      ret.locks.push_back(attr.substr(pos));
    }
  }

  encode(ret, *out);

  return 0;
}

/**
 * Assert that the object is currently locked
 *
 * Input:
 * @param cls_lock_assert_op request input
 *
 * Output:
 * @param none
 *
 * @return 0 on success, -errno on failure.
 */
int assert_locked(cls_method_context_t hctx, bufferlist *in, bufferlist *out)
{
  CLS_LOG(20, "assert_locked");

  cls_lock_assert_op op;
  try {
    auto iter = in->cbegin();
    decode(op, iter);
  } catch (const ceph::buffer::error& err) {
    return -EINVAL;
  }

  if (!cls_lock_is_valid(op.type)) {
    return -EINVAL;
  }

  if (op.name.empty()) {
    return -EINVAL;
  }

  // see if there's already a locker
  lock_info_t linfo;
  int r = read_lock(hctx, op.name, &linfo);
  if (r < 0) {
    CLS_ERR("Could not read lock info: %s", cpp_strerror(r).c_str());
    return r;
  }

  if (linfo.lockers.empty()) {
    CLS_LOG(20, "object not locked");
    return -EBUSY;
  }

  if (linfo.lock_type != op.type) {
    CLS_LOG(20, "lock type mismatch: current=%s, assert=%s",
            cls_lock_type_str(linfo.lock_type), cls_lock_type_str(op.type));
    return -EBUSY;
  }

  if (linfo.tag != op.tag) {
    CLS_LOG(20, "lock tag mismatch: current=%s, assert=%s", linfo.tag.c_str(),
            op.tag.c_str());
    return -EBUSY;
  }

  entity_inst_t inst;
  r = cls_get_request_origin(hctx, &inst);
  ceph_assert(r == 0);

  locker_id_t id;
  id.cookie = op.cookie;
  id.locker = inst.name;

  auto iter = linfo.lockers.find(id);
  if (iter == linfo.lockers.end()) {
    CLS_LOG(20, "not locked by assert client");
    return -EBUSY;
  }
  return 0;
}

/**
 * Update the cookie associated with an object lock
 *
 * Input:
 * @param cls_lock_set_cookie_op request input
 *
 * Output:
 * @param none
 *
 * @return 0 on success, -errno on failure.
 */
int set_cookie(cls_method_context_t hctx, bufferlist *in, bufferlist *out)
{
  CLS_LOG(20, "set_cookie");

  cls_lock_set_cookie_op op;
  try {
    auto iter = in->cbegin();
    decode(op, iter);
  } catch (const ceph::buffer::error& err) {
    return -EINVAL;
  }

  if (!cls_lock_is_valid(op.type)) {
    return -EINVAL;
  }

  if (op.name.empty()) {
    return -EINVAL;
  }

  // see if there's already a locker
  lock_info_t linfo;
  int r = read_lock(hctx, op.name, &linfo);
  if (r < 0) {
    CLS_ERR("Could not read lock info: %s", cpp_strerror(r).c_str());
    return r;
  }

  if (linfo.lockers.empty()) {
    CLS_LOG(20, "object not locked");
    return -EBUSY;
  }

  if (linfo.lock_type != op.type) {
    CLS_LOG(20, "lock type mismatch: current=%s, assert=%s",
            cls_lock_type_str(linfo.lock_type), cls_lock_type_str(op.type));
    return -EBUSY;
  }

  if (linfo.tag != op.tag) {
    CLS_LOG(20, "lock tag mismatch: current=%s, assert=%s", linfo.tag.c_str(),
            op.tag.c_str());
    return -EBUSY;
  }

  entity_inst_t inst;
  r = cls_get_request_origin(hctx, &inst);
  ceph_assert(r == 0);

  locker_id_t id;
  id.cookie = op.cookie;
  id.locker = inst.name;

  map<locker_id_t, locker_info_t>::iterator iter = linfo.lockers.find(id);
  if (iter == linfo.lockers.end()) {
    CLS_LOG(20, "not locked by client");
    return -EBUSY;
  }

  id.cookie = op.new_cookie;
  if (linfo.lockers.count(id) != 0) {
    CLS_LOG(20, "lock cookie in-use");
    return -EBUSY;
  }

  locker_info_t locker_info(iter->second);
  linfo.lockers.erase(iter);

  linfo.lockers[id] = locker_info;
  r = write_lock(hctx, op.name, linfo);
  if (r < 0) {
    CLS_ERR("Could not update lock info: %s", cpp_strerror(r).c_str());
    return r;
  }
  return 0;
}

CLS_INIT(lock)
{
  CLS_LOG(20, "Loaded lock class!");

  cls_handle_t h_class;
  cls_method_handle_t h_lock_op;
  cls_method_handle_t h_unlock_op;
  cls_method_handle_t h_break_lock;
  cls_method_handle_t h_get_info;
  cls_method_handle_t h_list_locks;
  cls_method_handle_t h_assert_locked;
  cls_method_handle_t h_set_cookie;

  cls_register("lock", &h_class);
  cls_register_cxx_method(h_class, "lock",
                          CLS_METHOD_RD | CLS_METHOD_WR | CLS_METHOD_PROMOTE,
                          lock_op, &h_lock_op);
  cls_register_cxx_method(h_class, "unlock",
                          CLS_METHOD_RD | CLS_METHOD_WR | CLS_METHOD_PROMOTE,
                          unlock_op, &h_unlock_op);
  cls_register_cxx_method(h_class, "break_lock",
                          CLS_METHOD_RD | CLS_METHOD_WR,
                          break_lock, &h_break_lock);
  cls_register_cxx_method(h_class, "get_info",
                          CLS_METHOD_RD,
                          get_info, &h_get_info);
  cls_register_cxx_method(h_class, "list_locks",
                          CLS_METHOD_RD,
                          list_locks, &h_list_locks);
  cls_register_cxx_method(h_class, "assert_locked",
                          CLS_METHOD_RD | CLS_METHOD_PROMOTE,
                          assert_locked, &h_assert_locked);
  cls_register_cxx_method(h_class, "set_cookie",
                          CLS_METHOD_RD | CLS_METHOD_WR | CLS_METHOD_PROMOTE,
                          set_cookie, &h_set_cookie);

  return;
}