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
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
/*
* rbd-nbd - RBD in userspace
*
* Copyright (C) 2015 - 2016 Kylin Corporation
*
* Author: Yunchuan Wen <yunchuan.wen@kylin-cloud.com>
* Li Wang <li.wang@kylin-cloud.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 "include/int_types.h"
#include <stdio.h>
#include <stdlib.h>
#include <stddef.h>
#include <errno.h>
#include <fcntl.h>
#include <string.h>
#include <sys/types.h>
#include <unistd.h>
#include <linux/nbd.h>
#include <linux/fs.h>
#include <sys/ioctl.h>
#include <sys/socket.h>
#include "nbd-netlink.h"
#include <libnl3/netlink/genl/genl.h>
#include <libnl3/netlink/genl/ctrl.h>
#include <libnl3/netlink/genl/mngt.h>
#include <fstream>
#include <iostream>
#include <memory>
#include <regex>
#include <boost/algorithm/string/predicate.hpp>
#include "common/Formatter.h"
#include "common/Preforker.h"
#include "common/TextTable.h"
#include "common/ceph_argparse.h"
#include "common/config.h"
#include "common/dout.h"
#include "common/errno.h"
#include "common/module.h"
#include "common/safe_io.h"
#include "common/version.h"
#include "global/global_init.h"
#include "global/signal_handler.h"
#include "include/rados/librados.hpp"
#include "include/rbd/librbd.hpp"
#include "include/stringify.h"
#include "include/xlist.h"
#include "mon/MonClient.h"
#define dout_context g_ceph_context
#define dout_subsys ceph_subsys_rbd
#undef dout_prefix
#define dout_prefix *_dout << "rbd-nbd: "
struct Config {
int nbds_max = 0;
int max_part = 255;
int timeout = -1;
bool exclusive = false;
bool readonly = false;
bool set_max_part = false;
bool try_netlink = false;
std::string poolname;
std::string nsname;
std::string imgname;
std::string snapname;
std::string devpath;
std::string format;
bool pretty_format = false;
};
static void usage()
{
std::cout << "Usage: rbd-nbd [options] map <image-or-snap-spec> Map an image to nbd device\n"
<< " unmap <device|image-or-snap-spec> Unmap nbd device\n"
<< " [options] list-mapped List mapped nbd devices\n"
<< "Map options:\n"
<< " --device <device path> Specify nbd device path (/dev/nbd{num})\n"
<< " --read-only Map read-only\n"
<< " --nbds_max <limit> Override for module param nbds_max\n"
<< " --max_part <limit> Override for module param max_part\n"
<< " --exclusive Forbid writes by other clients\n"
<< " --timeout <seconds> Set nbd request timeout\n"
<< " --try-netlink Use the nbd netlink interface\n"
<< "\n"
<< "List options:\n"
<< " --format plain|json|xml Output format (default: plain)\n"
<< " --pretty-format Pretty formatting (json and xml)\n"
<< std::endl;
generic_server_usage();
}
static int nbd = -1;
static int nbd_index = -1;
enum Command {
None,
Connect,
Disconnect,
List
};
static Command cmd = None;
#define RBD_NBD_BLKSIZE 512UL
#define HELP_INFO 1
#define VERSION_INFO 2
#ifdef CEPH_BIG_ENDIAN
#define ntohll(a) (a)
#elif defined(CEPH_LITTLE_ENDIAN)
#define ntohll(a) swab(a)
#else
#error "Could not determine endianess"
#endif
#define htonll(a) ntohll(a)
static int parse_args(vector<const char*>& args, std::ostream *err_msg,
Command *command, Config *cfg);
static int netlink_resize(int nbd_index, uint64_t size);
class NBDServer
{
private:
int fd;
librbd::Image ℑ
public:
NBDServer(int _fd, librbd::Image& _image)
: fd(_fd)
, image(_image)
, disconnect_lock("NBDServer::DisconnectLocker")
, lock("NBDServer::Locker")
, reader_thread(*this, &NBDServer::reader_entry)
, writer_thread(*this, &NBDServer::writer_entry)
, started(false)
{}
private:
Mutex disconnect_lock;
Cond disconnect_cond;
std::atomic<bool> terminated = { false };
void shutdown()
{
bool expected = false;
if (terminated.compare_exchange_strong(expected, true)) {
::shutdown(fd, SHUT_RDWR);
Mutex::Locker l(lock);
cond.Signal();
}
}
struct IOContext
{
xlist<IOContext*>::item item;
NBDServer *server = nullptr;
struct nbd_request request;
struct nbd_reply reply;
bufferlist data;
int command = 0;
IOContext()
: item(this)
{}
};
friend std::ostream &operator<<(std::ostream &os, const IOContext &ctx);
Mutex lock;
Cond cond;
xlist<IOContext*> io_pending;
xlist<IOContext*> io_finished;
void io_start(IOContext *ctx)
{
Mutex::Locker l(lock);
io_pending.push_back(&ctx->item);
}
void io_finish(IOContext *ctx)
{
Mutex::Locker l(lock);
ceph_assert(ctx->item.is_on_list());
ctx->item.remove_myself();
io_finished.push_back(&ctx->item);
cond.Signal();
}
IOContext *wait_io_finish()
{
Mutex::Locker l(lock);
while(io_finished.empty() && !terminated)
cond.Wait(lock);
if (io_finished.empty())
return NULL;
IOContext *ret = io_finished.front();
io_finished.pop_front();
return ret;
}
void wait_clean()
{
ceph_assert(!reader_thread.is_started());
Mutex::Locker l(lock);
while(!io_pending.empty())
cond.Wait(lock);
while(!io_finished.empty()) {
std::unique_ptr<IOContext> free_ctx(io_finished.front());
io_finished.pop_front();
}
}
static void aio_callback(librbd::completion_t cb, void *arg)
{
librbd::RBD::AioCompletion *aio_completion =
reinterpret_cast<librbd::RBD::AioCompletion*>(cb);
IOContext *ctx = reinterpret_cast<IOContext *>(arg);
int ret = aio_completion->get_return_value();
dout(20) << __func__ << ": " << *ctx << dendl;
if (ret == -EINVAL) {
// if shrinking an image, a pagecache writeback might reference
// extents outside of the range of the new image extents
dout(0) << __func__ << ": masking IO out-of-bounds error" << dendl;
ctx->data.clear();
ret = 0;
}
if (ret < 0) {
ctx->reply.error = htonl(-ret);
} else if ((ctx->command == NBD_CMD_READ) &&
ret < static_cast<int>(ctx->request.len)) {
int pad_byte_count = static_cast<int> (ctx->request.len) - ret;
ctx->data.append_zero(pad_byte_count);
dout(20) << __func__ << ": " << *ctx << ": Pad byte count: "
<< pad_byte_count << dendl;
ctx->reply.error = htonl(0);
} else {
ctx->reply.error = htonl(0);
}
ctx->server->io_finish(ctx);
aio_completion->release();
}
void reader_entry()
{
while (!terminated) {
std::unique_ptr<IOContext> ctx(new IOContext());
ctx->server = this;
dout(20) << __func__ << ": waiting for nbd request" << dendl;
int r = safe_read_exact(fd, &ctx->request, sizeof(struct nbd_request));
if (r < 0) {
derr << "failed to read nbd request header: " << cpp_strerror(r)
<< dendl;
goto signal;
}
if (ctx->request.magic != htonl(NBD_REQUEST_MAGIC)) {
derr << "invalid nbd request header" << dendl;
goto signal;
}
ctx->request.from = ntohll(ctx->request.from);
ctx->request.type = ntohl(ctx->request.type);
ctx->request.len = ntohl(ctx->request.len);
ctx->reply.magic = htonl(NBD_REPLY_MAGIC);
memcpy(ctx->reply.handle, ctx->request.handle, sizeof(ctx->reply.handle));
ctx->command = ctx->request.type & 0x0000ffff;
dout(20) << *ctx << ": start" << dendl;
switch (ctx->command)
{
case NBD_CMD_DISC:
// NBD_DO_IT will return when pipe is closed
dout(0) << "disconnect request received" << dendl;
goto signal;
case NBD_CMD_WRITE:
bufferptr ptr(ctx->request.len);
r = safe_read_exact(fd, ptr.c_str(), ctx->request.len);
if (r < 0) {
derr << *ctx << ": failed to read nbd request data: "
<< cpp_strerror(r) << dendl;
goto signal;
}
ctx->data.push_back(ptr);
break;
}
IOContext *pctx = ctx.release();
io_start(pctx);
librbd::RBD::AioCompletion *c = new librbd::RBD::AioCompletion(pctx, aio_callback);
switch (pctx->command)
{
case NBD_CMD_WRITE:
image.aio_write(pctx->request.from, pctx->request.len, pctx->data, c);
break;
case NBD_CMD_READ:
image.aio_read(pctx->request.from, pctx->request.len, pctx->data, c);
break;
case NBD_CMD_FLUSH:
image.aio_flush(c);
break;
case NBD_CMD_TRIM:
image.aio_discard(pctx->request.from, pctx->request.len, c);
break;
default:
derr << *pctx << ": invalid request command" << dendl;
c->release();
goto signal;
}
}
dout(20) << __func__ << ": terminated" << dendl;
signal:
Mutex::Locker l(disconnect_lock);
disconnect_cond.Signal();
}
void writer_entry()
{
while (!terminated) {
dout(20) << __func__ << ": waiting for io request" << dendl;
std::unique_ptr<IOContext> ctx(wait_io_finish());
if (!ctx) {
dout(20) << __func__ << ": no io requests, terminating" << dendl;
return;
}
dout(20) << __func__ << ": got: " << *ctx << dendl;
int r = safe_write(fd, &ctx->reply, sizeof(struct nbd_reply));
if (r < 0) {
derr << *ctx << ": failed to write reply header: " << cpp_strerror(r)
<< dendl;
return;
}
if (ctx->command == NBD_CMD_READ && ctx->reply.error == htonl(0)) {
r = ctx->data.write_fd(fd);
if (r < 0) {
derr << *ctx << ": failed to write replay data: " << cpp_strerror(r)
<< dendl;
return;
}
}
dout(20) << *ctx << ": finish" << dendl;
}
dout(20) << __func__ << ": terminated" << dendl;
}
class ThreadHelper : public Thread
{
public:
typedef void (NBDServer::*entry_func)();
private:
NBDServer &server;
entry_func func;
public:
ThreadHelper(NBDServer &_server, entry_func _func)
:server(_server)
,func(_func)
{}
protected:
void* entry() override
{
(server.*func)();
server.shutdown();
return NULL;
}
} reader_thread, writer_thread;
bool started;
public:
void start()
{
if (!started) {
dout(10) << __func__ << ": starting" << dendl;
started = true;
reader_thread.create("rbd_reader");
writer_thread.create("rbd_writer");
}
}
void wait_for_disconnect()
{
if (!started)
return;
Mutex::Locker l(disconnect_lock);
disconnect_cond.Wait(disconnect_lock);
}
~NBDServer()
{
if (started) {
dout(10) << __func__ << ": terminating" << dendl;
shutdown();
reader_thread.join();
writer_thread.join();
wait_clean();
started = false;
}
}
};
std::ostream &operator<<(std::ostream &os, const NBDServer::IOContext &ctx) {
os << "[" << std::hex << ntohll(*((uint64_t *)ctx.request.handle));
switch (ctx.command)
{
case NBD_CMD_WRITE:
os << " WRITE ";
break;
case NBD_CMD_READ:
os << " READ ";
break;
case NBD_CMD_FLUSH:
os << " FLUSH ";
break;
case NBD_CMD_TRIM:
os << " TRIM ";
break;
default:
os << " UNKNOWN(" << ctx.command << ") ";
break;
}
os << ctx.request.from << "~" << ctx.request.len << " "
<< std::dec << ntohl(ctx.reply.error) << "]";
return os;
}
class NBDWatchCtx : public librbd::UpdateWatchCtx
{
private:
int fd;
int nbd_index;
bool use_netlink;
librados::IoCtx &io_ctx;
librbd::Image ℑ
unsigned long size;
public:
NBDWatchCtx(int _fd,
int _nbd_index,
bool _use_netlink,
librados::IoCtx &_io_ctx,
librbd::Image &_image,
unsigned long _size)
: fd(_fd)
, nbd_index(_nbd_index)
, use_netlink(_use_netlink)
, io_ctx(_io_ctx)
, image(_image)
, size(_size)
{ }
~NBDWatchCtx() override {}
void handle_notify() override
{
librbd::image_info_t info;
if (image.stat(info, sizeof(info)) == 0) {
unsigned long new_size = info.size;
int ret;
if (new_size != size) {
dout(5) << "resize detected" << dendl;
if (ioctl(fd, BLKFLSBUF, NULL) < 0)
derr << "invalidate page cache failed: " << cpp_strerror(errno)
<< dendl;
if (use_netlink) {
ret = netlink_resize(nbd_index, new_size);
} else {
ret = ioctl(fd, NBD_SET_SIZE, new_size);
if (ret < 0)
derr << "resize failed: " << cpp_strerror(errno) << dendl;
}
if (!ret)
size = new_size;
if (ioctl(fd, BLKRRPART, NULL) < 0) {
derr << "rescan of partition table failed: " << cpp_strerror(errno)
<< dendl;
}
if (image.invalidate_cache() < 0)
derr << "invalidate rbd cache failed" << dendl;
}
}
}
};
class NBDListIterator {
public:
bool get(int *pid, Config *cfg) {
while (true) {
std::string nbd_path = "/sys/block/nbd" + stringify(m_index);
if(access(nbd_path.c_str(), F_OK) != 0) {
return false;
}
*cfg = Config();
cfg->devpath = "/dev/nbd" + stringify(m_index++);
std::ifstream ifs;
ifs.open(nbd_path + "/pid", std::ifstream::in);
if (!ifs.is_open()) {
continue;
}
ifs >> *pid;
int r = get_mapped_info(*pid, cfg);
if (r < 0) {
continue;
}
return true;
}
}
private:
int m_index = 0;
int get_mapped_info(int pid, Config *cfg) {
int r;
std::string path = "/proc/" + stringify(pid) + "/cmdline";
std::ifstream ifs;
std::string cmdline;
std::vector<const char*> args;
ifs.open(path.c_str(), std::ifstream::in);
if (!ifs.is_open())
return -1;
ifs >> cmdline;
for (unsigned i = 0; i < cmdline.size(); i++) {
const char *arg = &cmdline[i];
if (i == 0) {
if (strcmp(basename(arg) , "rbd-nbd") != 0) {
return -EINVAL;
}
} else {
args.push_back(arg);
}
while (cmdline[i] != '\0') {
i++;
}
}
std::ostringstream err_msg;
Command command;
r = parse_args(args, &err_msg, &command, cfg);
if (r < 0) {
return r;
}
if (command != Connect) {
return -ENOENT;
}
return 0;
}
};
static int load_module(Config *cfg)
{
ostringstream param;
int ret;
if (cfg->nbds_max)
param << "nbds_max=" << cfg->nbds_max;
if (cfg->max_part)
param << " max_part=" << cfg->max_part;
if (!access("/sys/module/nbd", F_OK)) {
if (cfg->nbds_max || cfg->set_max_part)
cerr << "rbd-nbd: ignoring kernel module parameter options: nbd module already loaded"
<< std::endl;
return 0;
}
ret = module_load("nbd", param.str().c_str());
if (ret < 0)
cerr << "rbd-nbd: failed to load nbd kernel module: " << cpp_strerror(-ret)
<< std::endl;
return ret;
}
static int check_device_size(int nbd_index, unsigned long expected_size)
{
// There are bugs with some older kernel versions that result in an
// overflow for large image sizes. This check is to ensure we are
// not affected.
unsigned long size = 0;
std::string path = "/sys/block/nbd" + stringify(nbd_index) + "/size";
std::ifstream ifs;
ifs.open(path.c_str(), std::ifstream::in);
if (!ifs.is_open()) {
cerr << "rbd-nbd: failed to open " << path << std::endl;
return -EINVAL;
}
ifs >> size;
size *= RBD_NBD_BLKSIZE;
if (size == 0) {
// Newer kernel versions will report real size only after nbd
// connect. Assume this is the case and return success.
return 0;
}
if (size != expected_size) {
cerr << "rbd-nbd: kernel reported invalid device size (" << size
<< ", expected " << expected_size << ")" << std::endl;
return -EINVAL;
}
return 0;
}
static int parse_nbd_index(const std::string& devpath)
{
int index, ret;
ret = sscanf(devpath.c_str(), "/dev/nbd%d", &index);
if (ret <= 0) {
// mean an early matching failure. But some cases need a negative value.
if (ret == 0)
ret = -EINVAL;
cerr << "rbd-nbd: invalid device path: " << devpath
<< " (expected /dev/nbd{num})" << std::endl;
return ret;
}
return index;
}
static int try_ioctl_setup(Config *cfg, int fd, uint64_t size, uint64_t flags)
{
int index = 0, r;
if (cfg->devpath.empty()) {
char dev[64];
const char *path = "/sys/module/nbd/parameters/nbds_max";
int nbds_max = -1;
if (access(path, F_OK) == 0) {
std::ifstream ifs;
ifs.open(path, std::ifstream::in);
if (ifs.is_open()) {
ifs >> nbds_max;
ifs.close();
}
}
while (true) {
snprintf(dev, sizeof(dev), "/dev/nbd%d", index);
nbd = open(dev, O_RDWR);
if (nbd < 0) {
if (nbd == -EPERM && nbds_max != -1 && index < (nbds_max-1)) {
++index;
continue;
}
r = nbd;
cerr << "rbd-nbd: failed to find unused device" << std::endl;
goto done;
}
r = ioctl(nbd, NBD_SET_SOCK, fd);
if (r < 0) {
close(nbd);
++index;
continue;
}
cfg->devpath = dev;
break;
}
} else {
r = parse_nbd_index(cfg->devpath);
if (r < 0)
goto done;
index = r;
nbd = open(cfg->devpath.c_str(), O_RDWR);
if (nbd < 0) {
r = nbd;
cerr << "rbd-nbd: failed to open device: " << cfg->devpath << std::endl;
goto done;
}
r = ioctl(nbd, NBD_SET_SOCK, fd);
if (r < 0) {
r = -errno;
cerr << "rbd-nbd: the device " << cfg->devpath << " is busy" << std::endl;
close(nbd);
goto done;
}
}
r = ioctl(nbd, NBD_SET_BLKSIZE, RBD_NBD_BLKSIZE);
if (r < 0) {
r = -errno;
goto close_nbd;
}
r = ioctl(nbd, NBD_SET_SIZE, size);
if (r < 0) {
r = -errno;
goto close_nbd;
}
ioctl(nbd, NBD_SET_FLAGS, flags);
if (cfg->timeout >= 0) {
r = ioctl(nbd, NBD_SET_TIMEOUT, (unsigned long)cfg->timeout);
if (r < 0) {
r = -errno;
cerr << "rbd-nbd: failed to set timeout: " << cpp_strerror(r)
<< std::endl;
goto close_nbd;
}
}
dout(10) << "ioctl setup complete for " << cfg->devpath << dendl;
nbd_index = index;
return 0;
close_nbd:
if (r < 0) {
ioctl(nbd, NBD_CLEAR_SOCK);
cerr << "rbd-nbd: failed to map, status: " << cpp_strerror(-r) << std::endl;
}
close(nbd);
done:
return r;
}
static void netlink_cleanup(struct nl_sock *sock)
{
if (!sock)
return;
nl_close(sock);
nl_socket_free(sock);
}
static struct nl_sock *netlink_init(int *id)
{
struct nl_sock *sock;
int ret;
sock = nl_socket_alloc();
if (!sock) {
cerr << "rbd-nbd: Could not allocate netlink socket." << std::endl;
return NULL;
}
ret = genl_connect(sock);
if (ret < 0) {
cerr << "rbd-nbd: Could not connect netlink socket. Error " << ret
<< std::endl;
goto free_sock;
}
*id = genl_ctrl_resolve(sock, "nbd");
if (*id < 0)
// nbd netlink interface not supported.
goto close_sock;
return sock;
close_sock:
nl_close(sock);
free_sock:
nl_socket_free(sock);
return NULL;
}
static int netlink_disconnect(int index)
{
struct nl_sock *sock;
struct nl_msg *msg;
int ret, nl_id;
sock = netlink_init(&nl_id);
if (!sock)
// Try ioctl
return 1;
nl_socket_modify_cb(sock, NL_CB_VALID, NL_CB_CUSTOM, genl_handle_msg, NULL);
msg = nlmsg_alloc();
if (!msg) {
cerr << "rbd-nbd: Could not allocate netlink message." << std::endl;
goto free_sock;
}
if (!genlmsg_put(msg, NL_AUTO_PORT, NL_AUTO_SEQ, nl_id, 0, 0,
NBD_CMD_DISCONNECT, 0)) {
cerr << "rbd-nbd: Could not setup message." << std::endl;
goto nla_put_failure;
}
NLA_PUT_U32(msg, NBD_ATTR_INDEX, index);
ret = nl_send_sync(sock, msg);
netlink_cleanup(sock);
if (ret < 0) {
cerr << "rbd-nbd: netlink disconnect failed: " << nl_geterror(-ret)
<< std::endl;
return -EIO;
}
return 0;
nla_put_failure:
nlmsg_free(msg);
free_sock:
netlink_cleanup(sock);
return -EIO;
}
static int netlink_disconnect_by_path(const std::string& devpath)
{
int index;
index = parse_nbd_index(devpath);
if (index < 0)
return index;
return netlink_disconnect(index);
}
static int netlink_resize(int nbd_index, uint64_t size)
{
struct nl_sock *sock;
struct nl_msg *msg;
int nl_id, ret;
sock = netlink_init(&nl_id);
if (!sock) {
cerr << "rbd-nbd: Netlink interface not supported." << std::endl;
return 1;
}
nl_socket_modify_cb(sock, NL_CB_VALID, NL_CB_CUSTOM, genl_handle_msg, NULL);
msg = nlmsg_alloc();
if (!msg) {
cerr << "rbd-nbd: Could not allocate netlink message." << std::endl;
goto free_sock;
}
if (!genlmsg_put(msg, NL_AUTO_PORT, NL_AUTO_SEQ, nl_id, 0, 0,
NBD_CMD_RECONFIGURE, 0)) {
cerr << "rbd-nbd: Could not setup message." << std::endl;
goto free_msg;
}
NLA_PUT_U32(msg, NBD_ATTR_INDEX, nbd_index);
NLA_PUT_U64(msg, NBD_ATTR_SIZE_BYTES, size);
ret = nl_send_sync(sock, msg);
if (ret < 0) {
cerr << "rbd-nbd: netlink resize failed: " << nl_geterror(ret) << std::endl;
goto free_sock;
}
netlink_cleanup(sock);
dout(10) << "netlink resize complete for nbd" << nbd_index << dendl;
return 0;
nla_put_failure:
free_msg:
nlmsg_free(msg);
free_sock:
netlink_cleanup(sock);
return -EIO;
}
static int netlink_connect_cb(struct nl_msg *msg, void *arg)
{
struct genlmsghdr *gnlh = (struct genlmsghdr *)nlmsg_data(nlmsg_hdr(msg));
Config *cfg = (Config *)arg;
struct nlattr *msg_attr[NBD_ATTR_MAX + 1];
uint32_t index;
int ret;
ret = nla_parse(msg_attr, NBD_ATTR_MAX, genlmsg_attrdata(gnlh, 0),
genlmsg_attrlen(gnlh, 0), NULL);
if (ret) {
cerr << "rbd-nbd: Unsupported netlink reply" << std::endl;
return -NLE_MSGTYPE_NOSUPPORT;
}
if (!msg_attr[NBD_ATTR_INDEX]) {
cerr << "rbd-nbd: netlink connect reply missing device index." << std::endl;
return -NLE_MSGTYPE_NOSUPPORT;
}
index = nla_get_u32(msg_attr[NBD_ATTR_INDEX]);
cfg->devpath = "/dev/nbd" + stringify(index);
nbd_index = index;
return NL_OK;
}
static int netlink_connect(Config *cfg, struct nl_sock *sock, int nl_id, int fd,
uint64_t size, uint64_t flags)
{
struct nlattr *sock_attr;
struct nlattr *sock_opt;
struct nl_msg *msg;
int ret;
nl_socket_modify_cb(sock, NL_CB_VALID, NL_CB_CUSTOM, netlink_connect_cb, cfg);
msg = nlmsg_alloc();
if (!msg) {
cerr << "rbd-nbd: Could not allocate netlink message." << std::endl;
return -ENOMEM;
}
if (!genlmsg_put(msg, NL_AUTO_PORT, NL_AUTO_SEQ, nl_id, 0, 0, NBD_CMD_CONNECT,
0)) {
cerr << "rbd-nbd: Could not setup message." << std::endl;
goto free_msg;
}
if (!cfg->devpath.empty()) {
ret = parse_nbd_index(cfg->devpath);
if (ret < 0)
goto free_msg;
NLA_PUT_U32(msg, NBD_ATTR_INDEX, ret);
}
if (cfg->timeout >= 0)
NLA_PUT_U64(msg, NBD_ATTR_TIMEOUT, cfg->timeout);
NLA_PUT_U64(msg, NBD_ATTR_SIZE_BYTES, size);
NLA_PUT_U64(msg, NBD_ATTR_BLOCK_SIZE_BYTES, RBD_NBD_BLKSIZE);
NLA_PUT_U64(msg, NBD_ATTR_SERVER_FLAGS, flags);
sock_attr = nla_nest_start(msg, NBD_ATTR_SOCKETS);
if (!sock_attr) {
cerr << "rbd-nbd: Could not init sockets in netlink message." << std::endl;
goto free_msg;
}
sock_opt = nla_nest_start(msg, NBD_SOCK_ITEM);
if (!sock_opt) {
cerr << "rbd-nbd: Could not init sock in netlink message." << std::endl;
goto free_msg;
}
NLA_PUT_U32(msg, NBD_SOCK_FD, fd);
nla_nest_end(msg, sock_opt);
nla_nest_end(msg, sock_attr);
ret = nl_send_sync(sock, msg);
if (ret < 0) {
cerr << "rbd-nbd: netlink connect failed: " << nl_geterror(ret)
<< std::endl;
return -EIO;
}
dout(10) << "netlink connect complete for " << cfg->devpath << dendl;
return 0;
nla_put_failure:
free_msg:
nlmsg_free(msg);
return -EIO;
}
static int try_netlink_setup(Config *cfg, int fd, uint64_t size, uint64_t flags)
{
struct nl_sock *sock;
int nl_id, ret;
sock = netlink_init(&nl_id);
if (!sock) {
cerr << "rbd-nbd: Netlink interface not supported. Using ioctl interface."
<< std::endl;
return 1;
}
dout(10) << "netlink interface supported." << dendl;
ret = netlink_connect(cfg, sock, nl_id, fd, size, flags);
netlink_cleanup(sock);
if (ret != 0)
return ret;
nbd = open(cfg->devpath.c_str(), O_RDWR);
if (nbd < 0) {
cerr << "rbd-nbd: failed to open device: " << cfg->devpath << std::endl;
return nbd;
}
return 0;
}
static void handle_signal(int signum)
{
int ret;
ceph_assert(signum == SIGINT || signum == SIGTERM);
derr << "*** Got signal " << sig_str(signum) << " ***" << dendl;
if (nbd < 0 || nbd_index < 0) {
dout(20) << __func__ << ": " << "disconnect not needed." << dendl;
return;
}
dout(20) << __func__ << ": " << "sending NBD_DISCONNECT" << dendl;
ret = netlink_disconnect(nbd_index);
if (ret == 1)
ret = ioctl(nbd, NBD_DISCONNECT);
if (ret != 0) {
derr << "rbd-nbd: disconnect failed. Error: " << ret << dendl;
} else {
dout(20) << __func__ << ": " << "disconnected" << dendl;
}
}
static NBDServer *start_server(int fd, librbd::Image& image)
{
NBDServer *server;
server = new NBDServer(fd, image);
server->start();
init_async_signal_handler();
register_async_signal_handler(SIGHUP, sighup_handler);
register_async_signal_handler_oneshot(SIGINT, handle_signal);
register_async_signal_handler_oneshot(SIGTERM, handle_signal);
return server;
}
static void run_server(Preforker& forker, NBDServer *server, bool netlink_used)
{
if (g_conf()->daemonize) {
global_init_postfork_finish(g_ceph_context);
forker.daemonize();
}
if (netlink_used)
server->wait_for_disconnect();
else
ioctl(nbd, NBD_DO_IT);
unregister_async_signal_handler(SIGHUP, sighup_handler);
unregister_async_signal_handler(SIGINT, handle_signal);
unregister_async_signal_handler(SIGTERM, handle_signal);
shutdown_async_signal_handler();
}
static int do_map(int argc, const char *argv[], Config *cfg)
{
int r;
librados::Rados rados;
librbd::RBD rbd;
librados::IoCtx io_ctx;
librbd::Image image;
int read_only = 0;
unsigned long flags;
unsigned long size;
bool use_netlink;
int fd[2];
librbd::image_info_t info;
Preforker forker;
NBDServer *server;
vector<const char*> args;
argv_to_vec(argc, argv, args);
if (args.empty()) {
cerr << argv[0] << ": -h or --help for usage" << std::endl;
exit(1);
}
if (ceph_argparse_need_usage(args)) {
usage();
exit(0);
}
auto cct = global_init(NULL, args, CEPH_ENTITY_TYPE_CLIENT,
CODE_ENVIRONMENT_DAEMON,
CINIT_FLAG_UNPRIVILEGED_DAEMON_DEFAULTS);
g_ceph_context->_conf.set_val_or_die("pid_file", "");
if (global_init_prefork(g_ceph_context) >= 0) {
std::string err;
r = forker.prefork(err);
if (r < 0) {
cerr << err << std::endl;
return r;
}
if (forker.is_parent()) {
if (forker.parent_wait(err) != 0) {
return -ENXIO;
}
return 0;
}
global_init_postfork_start(g_ceph_context);
}
common_init_finish(g_ceph_context);
global_init_chdir(g_ceph_context);
if (socketpair(AF_UNIX, SOCK_STREAM, 0, fd) == -1) {
r = -errno;
goto close_ret;
}
r = rados.init_with_context(g_ceph_context);
if (r < 0)
goto close_fd;
r = rados.connect();
if (r < 0)
goto close_fd;
r = rados.ioctx_create(cfg->poolname.c_str(), io_ctx);
if (r < 0)
goto close_fd;
io_ctx.set_namespace(cfg->nsname);
r = rbd.open(io_ctx, image, cfg->imgname.c_str());
if (r < 0)
goto close_fd;
if (cfg->exclusive) {
r = image.lock_acquire(RBD_LOCK_MODE_EXCLUSIVE);
if (r < 0) {
cerr << "rbd-nbd: failed to acquire exclusive lock: " << cpp_strerror(r)
<< std::endl;
goto close_fd;
}
}
if (!cfg->snapname.empty()) {
r = image.snap_set(cfg->snapname.c_str());
if (r < 0)
goto close_fd;
}
r = image.stat(info, sizeof(info));
if (r < 0)
goto close_fd;
flags = NBD_FLAG_SEND_FLUSH | NBD_FLAG_SEND_TRIM | NBD_FLAG_HAS_FLAGS;
if (!cfg->snapname.empty() || cfg->readonly) {
flags |= NBD_FLAG_READ_ONLY;
read_only = 1;
}
if (info.size > ULONG_MAX) {
r = -EFBIG;
cerr << "rbd-nbd: image is too large (" << byte_u_t(info.size)
<< ", max is " << byte_u_t(ULONG_MAX) << ")" << std::endl;
goto close_fd;
}
size = info.size;
r = load_module(cfg);
if (r < 0)
goto close_fd;
server = start_server(fd[1], image);
use_netlink = cfg->try_netlink;
if (use_netlink) {
r = try_netlink_setup(cfg, fd[0], size, flags);
if (r < 0) {
goto free_server;
} else if (r == 1) {
use_netlink = false;
}
}
if (!use_netlink) {
r = try_ioctl_setup(cfg, fd[0], size, flags);
if (r < 0)
goto free_server;
}
r = check_device_size(nbd_index, size);
if (r < 0)
goto close_nbd;
r = ioctl(nbd, BLKROSET, (unsigned long) &read_only);
if (r < 0) {
r = -errno;
goto close_nbd;
}
{
uint64_t handle;
NBDWatchCtx watch_ctx(nbd, nbd_index, use_netlink, io_ctx, image,
info.size);
r = image.update_watch(&watch_ctx, &handle);
if (r < 0)
goto close_nbd;
cout << cfg->devpath << std::endl;
run_server(forker, server, use_netlink);
r = image.update_unwatch(handle);
ceph_assert(r == 0);
}
close_nbd:
if (r < 0) {
if (use_netlink) {
netlink_disconnect(nbd_index);
} else {
ioctl(nbd, NBD_CLEAR_SOCK);
cerr << "rbd-nbd: failed to map, status: " << cpp_strerror(-r)
<< std::endl;
}
}
close(nbd);
free_server:
delete server;
close_fd:
close(fd[0]);
close(fd[1]);
close_ret:
image.close();
io_ctx.close();
rados.shutdown();
forker.exit(r < 0 ? EXIT_FAILURE : 0);
// Unreachable;
return r;
}
static int do_unmap(Config *cfg)
{
int r, nbd;
/*
* The netlink disconnect call supports devices setup with netlink or ioctl,
* so we always try that first.
*/
r = netlink_disconnect_by_path(cfg->devpath);
if (r != 1)
return r;
nbd = open(cfg->devpath.c_str(), O_RDWR);
if (nbd < 0) {
cerr << "rbd-nbd: failed to open device: " << cfg->devpath << std::endl;
return nbd;
}
r = ioctl(nbd, NBD_DISCONNECT);
if (r < 0) {
cerr << "rbd-nbd: the device is not used" << std::endl;
}
close(nbd);
return r;
}
static int parse_imgpath(const std::string &imgpath, Config *cfg,
std::ostream *err_msg) {
std::regex pattern("^(?:([^/]+)/(?:([^/@]+)/)?)?([^@]+)(?:@([^/@]+))?$");
std::smatch match;
if (!std::regex_match(imgpath, match, pattern)) {
std::cerr << "rbd-nbd: invalid spec '" << imgpath << "'" << std::endl;
return -EINVAL;
}
if (match[1].matched) {
cfg->poolname = match[1];
}
if (match[2].matched) {
cfg->nsname = match[2];
}
cfg->imgname = match[3];
if (match[4].matched)
cfg->snapname = match[4];
return 0;
}
static int do_list_mapped_devices(const std::string &format, bool pretty_format)
{
bool should_print = false;
std::unique_ptr<ceph::Formatter> f;
TextTable tbl;
if (format == "json") {
f.reset(new JSONFormatter(pretty_format));
} else if (format == "xml") {
f.reset(new XMLFormatter(pretty_format));
} else if (!format.empty() && format != "plain") {
std::cerr << "rbd-nbd: invalid output format: " << format << std::endl;
return -EINVAL;
}
if (f) {
f->open_array_section("devices");
} else {
tbl.define_column("id", TextTable::LEFT, TextTable::LEFT);
tbl.define_column("pool", TextTable::LEFT, TextTable::LEFT);
tbl.define_column("namespace", TextTable::LEFT, TextTable::LEFT);
tbl.define_column("image", TextTable::LEFT, TextTable::LEFT);
tbl.define_column("snap", TextTable::LEFT, TextTable::LEFT);
tbl.define_column("device", TextTable::LEFT, TextTable::LEFT);
}
int pid;
Config cfg;
NBDListIterator it;
while (it.get(&pid, &cfg)) {
if (f) {
f->open_object_section("device");
f->dump_int("id", pid);
f->dump_string("pool", cfg.poolname);
f->dump_string("namespace", cfg.nsname);
f->dump_string("image", cfg.imgname);
f->dump_string("snap", cfg.snapname);
f->dump_string("device", cfg.devpath);
f->close_section();
} else {
should_print = true;
if (cfg.snapname.empty()) {
cfg.snapname = "-";
}
tbl << pid << cfg.poolname << cfg.nsname << cfg.imgname << cfg.snapname
<< cfg.devpath << TextTable::endrow;
}
}
if (f) {
f->close_section(); // devices
f->flush(std::cout);
}
if (should_print) {
std::cout << tbl;
}
return 0;
}
static bool find_mapped_dev_by_spec(Config *cfg) {
int pid;
Config c;
NBDListIterator it;
while (it.get(&pid, &c)) {
if (c.poolname == cfg->poolname && c.nsname == cfg->nsname &&
c.imgname == cfg->imgname && c.snapname == cfg->snapname) {
*cfg = c;
return true;
}
}
return false;
}
static int parse_args(vector<const char*>& args, std::ostream *err_msg,
Command *command, Config *cfg) {
std::string conf_file_list;
std::string cluster;
CephInitParameters iparams = ceph_argparse_early_args(
args, CEPH_ENTITY_TYPE_CLIENT, &cluster, &conf_file_list);
ConfigProxy config{false};
config->name = iparams.name;
config->cluster = cluster;
if (!conf_file_list.empty()) {
config.parse_config_files(conf_file_list.c_str(), nullptr, 0);
} else {
config.parse_config_files(nullptr, nullptr, 0);
}
config.parse_env(CEPH_ENTITY_TYPE_CLIENT);
config.parse_argv(args);
cfg->poolname = config.get_val<std::string>("rbd_default_pool");
std::vector<const char*>::iterator i;
std::ostringstream err;
for (i = args.begin(); i != args.end(); ) {
if (ceph_argparse_flag(args, i, "-h", "--help", (char*)NULL)) {
return HELP_INFO;
} else if (ceph_argparse_flag(args, i, "-v", "--version", (char*)NULL)) {
return VERSION_INFO;
} else if (ceph_argparse_witharg(args, i, &cfg->devpath, "--device", (char *)NULL)) {
} else if (ceph_argparse_witharg(args, i, &cfg->nbds_max, err, "--nbds_max", (char *)NULL)) {
if (!err.str().empty()) {
*err_msg << "rbd-nbd: " << err.str();
return -EINVAL;
}
if (cfg->nbds_max < 0) {
*err_msg << "rbd-nbd: Invalid argument for nbds_max!";
return -EINVAL;
}
} else if (ceph_argparse_witharg(args, i, &cfg->max_part, err, "--max_part", (char *)NULL)) {
if (!err.str().empty()) {
*err_msg << "rbd-nbd: " << err.str();
return -EINVAL;
}
if ((cfg->max_part < 0) || (cfg->max_part > 255)) {
*err_msg << "rbd-nbd: Invalid argument for max_part(0~255)!";
return -EINVAL;
}
cfg->set_max_part = true;
} else if (ceph_argparse_flag(args, i, "--read-only", (char *)NULL)) {
cfg->readonly = true;
} else if (ceph_argparse_flag(args, i, "--exclusive", (char *)NULL)) {
cfg->exclusive = true;
} else if (ceph_argparse_witharg(args, i, &cfg->timeout, err, "--timeout",
(char *)NULL)) {
if (!err.str().empty()) {
*err_msg << "rbd-nbd: " << err.str();
return -EINVAL;
}
if (cfg->timeout < 0) {
*err_msg << "rbd-nbd: Invalid argument for timeout!";
return -EINVAL;
}
} else if (ceph_argparse_witharg(args, i, &cfg->format, err, "--format",
(char *)NULL)) {
} else if (ceph_argparse_flag(args, i, "--pretty-format", (char *)NULL)) {
cfg->pretty_format = true;
} else if (ceph_argparse_flag(args, i, "--try-netlink", (char *)NULL)) {
cfg->try_netlink = true;
} else {
++i;
}
}
Command cmd = None;
if (args.begin() != args.end()) {
if (strcmp(*args.begin(), "map") == 0) {
cmd = Connect;
} else if (strcmp(*args.begin(), "unmap") == 0) {
cmd = Disconnect;
} else if (strcmp(*args.begin(), "list-mapped") == 0) {
cmd = List;
} else {
*err_msg << "rbd-nbd: unknown command: " << *args.begin();
return -EINVAL;
}
args.erase(args.begin());
}
if (cmd == None) {
*err_msg << "rbd-nbd: must specify command";
return -EINVAL;
}
switch (cmd) {
case Connect:
if (args.begin() == args.end()) {
*err_msg << "rbd-nbd: must specify image-or-snap-spec";
return -EINVAL;
}
if (parse_imgpath(*args.begin(), cfg, err_msg) < 0) {
return -EINVAL;
}
args.erase(args.begin());
break;
case Disconnect:
if (args.begin() == args.end()) {
*err_msg << "rbd-nbd: must specify nbd device or image-or-snap-spec";
return -EINVAL;
}
if (boost::starts_with(*args.begin(), "/dev/")) {
cfg->devpath = *args.begin();
} else {
if (parse_imgpath(*args.begin(), cfg, err_msg) < 0) {
return -EINVAL;
}
if (!find_mapped_dev_by_spec(cfg)) {
*err_msg << "rbd-nbd: " << *args.begin() << " is not mapped";
return -ENOENT;
}
}
args.erase(args.begin());
break;
default:
//shut up gcc;
break;
}
if (args.begin() != args.end()) {
*err_msg << "rbd-nbd: unknown args: " << *args.begin();
return -EINVAL;
}
*command = cmd;
return 0;
}
static int rbd_nbd(int argc, const char *argv[])
{
int r;
Config cfg;
vector<const char*> args;
argv_to_vec(argc, argv, args);
std::ostringstream err_msg;
r = parse_args(args, &err_msg, &cmd, &cfg);
if (r == HELP_INFO) {
usage();
return 0;
} else if (r == VERSION_INFO) {
std::cout << pretty_version_to_str() << std::endl;
return 0;
} else if (r < 0) {
cerr << err_msg.str() << std::endl;
return r;
}
switch (cmd) {
case Connect:
if (cfg.imgname.empty()) {
cerr << "rbd-nbd: image name was not specified" << std::endl;
return -EINVAL;
}
r = do_map(argc, argv, &cfg);
if (r < 0)
return -EINVAL;
break;
case Disconnect:
r = do_unmap(&cfg);
if (r < 0)
return -EINVAL;
break;
case List:
r = do_list_mapped_devices(cfg.format, cfg.pretty_format);
if (r < 0)
return -EINVAL;
break;
default:
usage();
break;
}
return 0;
}
int main(int argc, const char *argv[])
{
int r = rbd_nbd(argc, argv);
if (r < 0) {
return EXIT_FAILURE;
}
return 0;
}
|