-
Notifications
You must be signed in to change notification settings - Fork 59
/
rbd-target-api.py
3024 lines (2497 loc) · 114 KB
/
rbd-target-api.py
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
#!/usr/bin/env python
import sys
import os
import signal
import json
import logging
import logging.handlers
from logging.handlers import RotatingFileHandler
import ssl
import operator
import OpenSSL
import tempfile
import threading
import time
import inspect
import copy
from functools import (reduce, wraps)
import rados
import rbd
import werkzeug
from flask import Flask, jsonify, request
from rtslib_fb.utils import RTSLibError, normalize_wwn
import ceph_iscsi_config.settings as settings
from ceph_iscsi_config.gateway_setting import IntSetting, EnumSetting
from ceph_iscsi_config.gateway import CephiSCSIGateway
from ceph_iscsi_config.discovery import Discovery
from ceph_iscsi_config.target import GWTarget
from ceph_iscsi_config.group import Group
from ceph_iscsi_config.lun import RBDDev, LUN
from ceph_iscsi_config.client import GWClient, CHAP
from ceph_iscsi_config.common import Config
from ceph_iscsi_config.utils import (normalize_ip_literal, resolve_ip_addresses,
ip_addresses, read_os_release, encryption_available,
CephiSCSIError, this_host)
from ceph_iscsi_config.device_status import DeviceStatusWatcher
from gwcli.utils import (APIRequest, valid_gateway, valid_client,
valid_credentials, get_remote_gateways, valid_snapshot_name,
GatewayAPIError)
app = Flask(__name__)
# workaround for https://github.com/pallets/flask/issues/2549
app.config['JSONIFY_PRETTYPRINT_REGULAR'] = False
def requires_basic_auth(f):
"""
wrapper function to check authentication credentials are valid
"""
@wraps(f)
def decorated(*args, **kwargs):
# check credentials supplied in the http request are valid
auth = request.authorization
if not auth:
return jsonify(message="Missing credentials"), 401
if auth.username != settings.config.api_user or \
auth.password != settings.config.api_password:
return jsonify(message="username/password mismatch with the "
"configuration file"), 401
return f(*args, **kwargs)
return decorated
def requires_restricted_auth(f):
"""
Wrapper function which checks both auth credentials and source IP
address to validate the request
"""
@wraps(f)
def decorated(*args, **kwargs):
# First check that the source of the request is actually valid
gw_names = [gw for gw in config.config['gateways']
if isinstance(config.config['gateways'][gw], dict)]
gw_names.append('localhost')
for _, target in config.config['targets'].items():
gw_names += target.get('ip_list', [])
gw_ips = reduce(operator.concat,
[resolve_ip_addresses(gw_name) for gw_name in gw_names]) + \
settings.config.trusted_ip_list
# remove interface scope suffix and IPv4-over-IPv6 prefix
remote_addr = request.remote_addr.rsplit('%', 1)[0]
remote_addr = remote_addr.split('::ffff:', 1)[-1]
if remote_addr not in gw_ips:
return jsonify(message="API access not available to "
"{}".format(remote_addr)), 403
# check credentials supplied in the http request are valid
auth = request.authorization
if not auth:
return jsonify(message="Missing credentials"), 401
if auth.username != settings.config.api_user or \
auth.password != settings.config.api_password:
return jsonify(message="username/password mismatch with the "
"configuration file"), 401
return f(*args, **kwargs)
return decorated
@app.errorhandler(Exception)
def unhandled_exception(e):
logger.exception("Unhandled Exception")
return jsonify(message="Unhandled exception: {}".format(e)), 500
@app.route('/api', methods=['GET'])
def get_api_info():
"""
Display all the available API endpoints
**UNRESTRICTED**
Examples:
curl --user admin:admin -X GET http://192.168.122.69:5000/api
"""
links = []
sorted_rules = sorted(app.url_map.iter_rules(),
key=lambda x: x.rule, reverse=False)
for rule in sorted_rules:
url = rule.rule
if rule.endpoint == 'static':
continue
else:
func_doc = inspect.getdoc(globals()[rule.endpoint])
if func_doc:
doc = func_doc.split('\n')
if any(path_entry.startswith('_')
for path_entry in url.split('/')):
continue
else:
url_desc = "{} : {}".format(url,
doc[0])
doc = doc[1:]
else:
url_desc = "{} : {}".format(url,
"Missing description - FIXME!")
doc = []
callable_methods = [method for method in rule.methods
if method not in ['OPTIONS', 'HEAD']]
api_methods = "Methods: {}".format(','.join(callable_methods))
links.append((url_desc, api_methods, doc))
return jsonify(api=links), 200
@app.route('/api/sysinfo/<query_type>', methods=['GET'])
@requires_basic_auth
def get_sys_info(query_type=None):
"""
Provide system information based on the query_type
Valid query types are: ip_addresses, checkconf and checkversions
**RESTRICTED**
Examples:
curl --user admin:admin -X GET http://192.168.122.69:5000/api/sysinfo/ip_addresses
"""
if query_type == 'ip_addresses':
return jsonify(data=ip_addresses()), 200
if query_type == 'hostname':
return jsonify(data=this_host()), 200
elif query_type == 'checkconf':
local_hash = settings.config.hash()
return jsonify(data=local_hash), 200
elif query_type == 'checkversions':
config_errors = pre_reqs_errors()
if config_errors:
return jsonify(data=config_errors), 500
else:
return jsonify(data='checks passed'), 200
else:
# Request Unknown
return jsonify(message="Unknown /sysinfo query"), 404
def _parse_controls(controls_json, settings_list):
return settings.Settings.normalize_controls(json.loads(controls_json),
settings_list)
def parse_target_controls(request):
tpg_controls = {}
client_controls = {}
if 'controls' not in request.form:
return tpg_controls, client_controls
controls = _parse_controls(request.form['controls'], GWTarget.SETTINGS)
for k, v in controls.items():
if GWClient.SETTINGS.get(k):
client_controls[k] = v
else:
tpg_controls[k] = v
logger.debug("controls tpg {} acl {}".format(tpg_controls, client_controls))
return tpg_controls, client_controls
@app.route('/api/targets', methods=['GET'])
@requires_restricted_auth
def get_targets():
"""
List targets defined in the configuration.
**RESTRICTED**
Examples:
curl --user admin:admin -X GET http://192.168.122.69:5000/api/targets
"""
return jsonify({'targets': list(config.config['targets'].keys())}), 200
@app.route('/api/target/<target_iqn>', methods=['PUT', 'DELETE'])
@requires_restricted_auth
def target(target_iqn=None):
"""
Handle the definition of the iscsi target name
The target is added to the configuration object, seeding the configuration
for ALL gateways
:param target_iqn: IQN of the target each gateway will use
:param mode: (str) 'reconfigure'
:param controls: (JSON dict) valid control overrides
**RESTRICTED**
Examples:
curl --user admin:admin
-X PUT http://192.168.122.69:5000/api/target/iqn.2003-01.com.redhat.iscsi-gw0
curl --user admin:admin -d mode=reconfigure -d controls='{cmdsn_depth=128}'
-X PUT http://192.168.122.69:5000/api/target/iqn.2003-01.com.redhat.iscsi-gw0
"""
try:
target_iqn, iqn_type = normalize_wwn(['iqn'], target_iqn)
except RTSLibError as err:
err_str = "Invalid iqn {} - {}".format(target_iqn, err)
return jsonify(message=err_str), 500
if request.method == 'PUT':
mode = request.form.get('mode', None)
if mode not in [None, 'reconfigure']:
logger.error("Unexpected mode provided")
return jsonify(message="Unexpected mode provided for {} - "
"{}".format(target_iqn, mode)), 500
try:
tpg_controls, client_controls = parse_target_controls(request)
except ValueError as err:
logger.error("Unexpected or invalid controls")
return jsonify(message="Unexpected or invalid controls - "
"{}".format(err)), 500
if mode == 'reconfigure':
target_config = config.config['targets'].get(target_iqn, None)
if target_config is None:
return jsonify(message="Target: {} is not defined."
"".format(target_iqn)), 400
gateway_ip_list = []
target = GWTarget(logger,
str(target_iqn),
gateway_ip_list)
if target.error:
logger.error("Unable to create an instance of the GWTarget class")
return jsonify(message="GWTarget problem - "
"{}".format(target.error_msg)), 500
orig_tpg_controls = {}
orig_client_controls = {}
for k, v in tpg_controls.items():
orig_tpg_controls[k] = getattr(target, k)
setattr(target, k, v)
for k, v in client_controls.items():
orig_client_controls[k] = getattr(target, k)
setattr(target, k, v)
target.manage('init')
if target.error:
logger.error("Failure during gateway 'init' processing")
return jsonify(message="iscsi target 'init' process failed "
"for {} - {}".format(target_iqn,
target.error_msg)), 500
if mode is None:
config.refresh()
return jsonify(message="Target defined successfully"), 200
if not tpg_controls and not client_controls:
return jsonify(message="Target reconfigured."), 200
# This is a reconfigure operation, so first confirm the gateways
# are in place (we need defined gateways)
target_config = config.config['targets'][target_iqn]
try:
gateways = get_remote_gateways(target_config['portals'], logger)
except CephiSCSIError as err:
logger.warning("target operation request failed: {}".format(err))
return jsonify(message="{}".format(err)), 400
# We perform the reconfigure locally here to make sure the values are valid
# and simplify error cleanup
resp_text = local_target_reconfigure(target_iqn, tpg_controls,
client_controls)
if "ok" != resp_text:
reset_resp = local_target_reconfigure(target_iqn, orig_tpg_controls,
orig_client_controls)
if "ok" != reset_resp:
logger.error("Failed to reset target controls - "
"{}".format(reset_resp))
return jsonify(message="{}".format(resp_text)), 500
resp_text, resp_code = call_api(gateways, '_target', target_iqn,
http_method='put',
api_vars=request.form)
if resp_code != 200:
return jsonify(message="{}".format(resp_text)), resp_code
try:
target.commit_controls()
except CephiSCSIError as err:
logger.error("Control commit failed during gateway 'reconfigure'")
return jsonify(message="Could not commit controls - {}".format(err)), 500
config.refresh()
return jsonify(message="Target reconfigured."), 200
else:
# DELETE target request
config.refresh()
hostnames = None
if target_iqn in config.config['targets']:
target_config = config.config['targets'][target_iqn]
hostnames = target_config['portals'].keys()
if not hostnames:
hostnames = [this_host()]
resp_text, resp_code = call_api(hostnames, '_target',
'{}'.format(target_iqn),
http_method='delete')
if resp_code != 200:
return jsonify(message="{}".format(resp_text)), resp_code
return jsonify(message="Target deleted."), 200
def local_target_reconfigure(target_iqn, tpg_controls, client_controls):
config.refresh()
target = GWTarget(logger, str(target_iqn), [])
if target.error:
logger.error("Unable to create an instance of the GWTarget class")
return target.error_msg
for k, v in tpg_controls.items():
setattr(target, k, v)
if target.exists():
target.load_config()
if target.error:
logger.error("Unable to refresh tpg state")
return target.error_msg
try:
target.update_tpg_controls()
except RTSLibError as err:
logger.error("Unable to update tpg control - {}".format(err))
return "Unable to update tpg control - {}".format(err)
# re-apply client control overrides
error_msg = "ok"
target_config = config.config['targets'][target_iqn]
for client_iqn in target_config['clients']:
client_metadata = target_config['clients'][client_iqn]
image_list = list(client_metadata['luns'].keys())
client_auth_config = client_metadata['auth']
client_chap = CHAP(client_auth_config['username'],
client_auth_config['password'],
client_auth_config['password_encryption_enabled'])
if client_chap.error:
logger.debug("Password decode issue : "
"{}".format(client_chap.error_msg))
halt("Unable to decode password for {}".format(client_iqn))
client_chap_mutual = CHAP(client_auth_config['mutual_username'],
client_auth_config['mutual_password'],
client_auth_config['mutual_password_encryption_enabled'])
if client_chap_mutual.error:
logger.debug("Password decode issue : "
"{}".format(client_chap_mutual.error_msg))
halt("Unable to decode password for {}".format(client_iqn))
client = GWClient(logger, client_iqn, image_list, client_chap.user, client_chap.password,
client_chap_mutual.user, client_chap_mutual.password, target_iqn)
if client.error:
logger.error("Could not create client. Control override failed "
"{} - {}".format(client_iqn, client.error_msg))
error_msg = client.error_msg
continue
for k, v in client_controls.items():
setattr(client, k, v)
client.manage('reconfigure')
if client.error:
logger.error("Unable to update client control - "
"{} - {}".format(client_iqn, client.error_msg))
error_msg = client.error_msg
if "Invalid argument" in client.error_msg:
# Kernel/rtslib reported EINVAL so immediately fail
return client.error_msg
if error_msg != "ok":
return "Unable to update client control - {}".format(error_msg)
return "ok"
def delete_gateway(gateway_name, target_iqn):
ceph_gw = CephiSCSIGateway(logger, config)
if gateway_name is None or gateway_name == ceph_gw.hostname:
ceph_gw.delete_target(target_iqn)
ceph_gw.remove_from_config(target_iqn)
else:
# To maintain the tpg ordering completely tear down the target
# and rebuild it with the new ordering.
ceph_gw.redefine_target(target_iqn)
@app.route('/api/_target/<target_iqn>', methods=['PUT', 'DELETE'])
@requires_restricted_auth
def _target(target_iqn=None):
if request.method == 'PUT':
mode = request.form.get('mode', None)
if mode not in ['reconfigure']:
logger.error("Unexpected mode provided")
return jsonify(message="Unexpected mode provided for {} - "
"{}".format(target_iqn, mode)), 500
try:
tpg_controls, client_controls = parse_target_controls(request)
except ValueError as err:
logger.error("Unexpected or invalid controls")
return jsonify(message="Unexpected or invalid controls - "
"{}".format(err)), 500
resp_text = local_target_reconfigure(target_iqn, tpg_controls,
client_controls)
if "ok" != resp_text:
return jsonify(message="{}".format(resp_text)), 500
return jsonify(message="Target reconfigured successfully"), 200
else:
# DELETE target request
target = GWTarget(logger, target_iqn, '')
if target.error:
return jsonify(message="Failed to access target"), 500
target.manage('clearconfig')
if target.error:
logger.error("clearconfig failed: "
"{}".format(target.error_msg))
return jsonify(message=target.error_msg), 400
else:
config.refresh()
return jsonify(message="Gateway removed successfully"), 200
@app.route('/api/config', methods=['GET'])
@requires_restricted_auth
def get_config():
"""
Return the complete config object to the caller (must be authenticated)
WARNING: Contents will include any defined CHAP credentials
:param decrypt_passwords: (bool) if true, passwords will be decrypted
**RESTRICTED**
Examples:
curl --user admin:admin -X GET http://192.168.122.69:5000/api/config
"""
if request.method == 'GET':
config.refresh()
decrypt_passwords = request.args.get('decrypt_passwords', 'false')
result_config = copy.deepcopy(config.config)
if decrypt_passwords.lower() == 'true':
discovery_auth_config = result_config['discovery_auth']
chap = CHAP(discovery_auth_config['username'],
discovery_auth_config['password'],
discovery_auth_config['password_encryption_enabled'])
discovery_auth_config['password'] = chap.password
chap = CHAP(discovery_auth_config['mutual_username'],
discovery_auth_config['mutual_password'],
discovery_auth_config['mutual_password_encryption_enabled'])
discovery_auth_config['mutual_password'] = chap.password
for _, target in result_config['targets'].items():
target_auth_config = target['auth']
chap = CHAP(target_auth_config['username'],
target_auth_config['password'],
target_auth_config['password_encryption_enabled'])
target_auth_config['password'] = chap.password
chap = CHAP(target_auth_config['mutual_username'],
target_auth_config['mutual_password'],
target_auth_config['mutual_password_encryption_enabled'])
target_auth_config['mutual_password'] = chap.password
for _, client in target['clients'].items():
auth_config = client['auth']
chap = CHAP(auth_config['username'],
auth_config['password'],
auth_config['password_encryption_enabled'])
auth_config['password'] = chap.password
chap = CHAP(auth_config['mutual_username'],
auth_config['mutual_password'],
auth_config['mutual_password_encryption_enabled'])
auth_config['mutual_password'] = chap.password
return jsonify(result_config), 200
@app.route('/api/gateways/<target_iqn>', methods=['GET'])
@requires_restricted_auth
def gateways(target_iqn=None):
"""
Return the gateway subsection of the config object to the caller
**RESTRICTED**
Examples:
curl --user admin:admin -X GET
http://192.168.122.69:5000/api/gateways/iqn.2003-01.com.redhat.iscsi-gw
"""
try:
target_iqn, iqn_type = normalize_wwn(['iqn'], target_iqn)
except RTSLibError as err:
err_str = "Invalid iqn {} - {}".format(target_iqn, err)
return jsonify(message=err_str), 500
target_config = config.config['targets'][target_iqn]
if request.method == 'GET':
return jsonify(target_config['portals']), 200
@app.route('/api/gateway/<target_iqn>/<gateway_name>', methods=['PUT', 'DELETE'])
@requires_restricted_auth
def gateway(target_iqn=None, gateway_name=None):
"""
Define (PUT) or delete (DELETE) iscsi gateway(s) across node(s), adding
TPGs, disks and clients.
gateway_name and target_iqn are required by all calls. The rest are
required for PUT only.
:param target_iqn: (str) target iqn
:param gateway_name: (str) gateway name
:param ip_address: (str) IPv4/IPv6 addresses iSCSI should use
:param nosync: (bool) whether to sync the LIO objects to the new gateway
default: FALSE
:param skipchecks: (bool) whether to skip OS/software versions checks
default: FALSE
:param force: (bool) if True will force removal of gateway.
**RESTRICTED**
Examples:
curl --user admin:admin -d ip_address=192.168.122.69
-X PUT http://192.168.122.69:5000/api/gateway/iqn.2003-01.com.redhat.iscsi-gw/gateway1
curl --user admin:admin
-X DELETE http://192.168.122.69:5000/api/gateway/iqn.2003-01.com.redhat.iscsi-gw/gateway1
"""
# the definition of a gateway into an existing configuration can apply the
# running config to the new host. The downside is that this sync task
# could take a while if there are 100's of disks/clients. Future work should
# aim to make this synchronisation of the new gateway an async task
try:
target_iqn, iqn_type = normalize_wwn(['iqn'], target_iqn)
except RTSLibError as err:
err_str = "Invalid iqn {} - {}".format(target_iqn, err)
return jsonify(message=err_str), 500
# first confirm that the request is actually valid, if not return a 400
# error with the error description
config.refresh()
current_config = config.config
target_config = config.config['targets'][target_iqn]
if request.method == 'PUT':
if gateway_name in target_config['portals']:
err_str = "Gateway already exists in configuration"
logger.error(err_str)
return jsonify(message=err_str), 400
ip_address = request.form.get('ip_address').split(',')
nosync = request.form.get('nosync', 'false')
skipchecks = request.form.get('skipchecks', 'false')
if skipchecks.lower() == 'true':
logger.warning("Gateway request received, with validity checks "
"disabled")
gateway_usable = 'ok'
else:
logger.info("gateway validation needed for {}".format(gateway_name))
gateway_usable = valid_gateway(target_iqn,
gateway_name,
ip_address,
current_config)
if gateway_usable != 'ok':
return jsonify(message=gateway_usable), 400
current_disks = target_config['disks']
current_clients = target_config['clients']
total_objects = len(current_disks) + len(current_clients.keys())
# if the config is empty, it doesn't matter what nosync is set to
if total_objects == 0:
nosync = 'true'
gateway_ip_list = target_config.get('ip_list', [])
gateway_ip_list += ip_address
op = 'creation'
api_vars = {"gateway_ip_list": ",".join(gateway_ip_list),
"nosync": nosync}
elif request.method == 'DELETE':
if gateway_name not in current_config['gateways']:
err_str = "Gateway does not exist in configuration"
logger.error(err_str)
return jsonify(message=err_str), 404
op = 'deletion'
api_vars = None
else:
return jsonify(message="Unsupported request type."), 400
gateways = list(target_config['portals'].keys())
first_gateway = (len(gateways) == 0)
if first_gateway:
gateways = ['localhost']
elif request.method == 'DELETE':
gateways.remove(gateway_name)
if gateway_name != this_host() and request.form.get('force', 'false').lower() == 'true':
# The gw we want to delete is down and the user has decided to
# force the deletion, so we do the config modification locally
# then only tell the other gws to update their state.
try:
ceph_gw = CephiSCSIGateway(logger, config, gateway_name)
ceph_gw.remove_from_config(target_iqn)
except CephiSCSIError as err:
return jsonify(message="Could not update config: {}.".format(err)), 400
else:
# Update the deleted gw first, so the other gws see the updated
# portal list
gateways.insert(0, gateway_name)
else:
# Update the new gw first, so other gws see the updated gateways list.
gateways.insert(0, gateway_name)
resp_text, resp_code = call_api(gateways, '_gateway',
'{}/{}'.format(target_iqn, gateway_name),
http_method=request.method.lower(),
api_vars=api_vars)
config.refresh()
return jsonify(message="Gateway {} {}".format(op, resp_text)), resp_code
@app.route('/api/_gateway/<target_iqn>/<gateway_name>',
methods=['GET', 'PUT', 'DELETE'])
@requires_restricted_auth
def _gateway(target_iqn=None, gateway_name=None):
"""
Manage the local iSCSI gateway definition
Internal Use ONLY
Gateways may be be added(PUT), queried (GET) or deleted (DELETE) from
the configuration
:param target_iqn: (str) target iqn
:param gateway_name: (str) gateway name, normally the DNS name
**RESTRICTED**
"""
config.refresh()
target_config = config.config['targets'][target_iqn]
if request.method == 'GET':
if gateway_name in target_config['portals']:
return jsonify(target_config['portals'][gateway_name]), 200
else:
return jsonify(message="Gateway doesn't exist in the "
"configuration"), 404
elif request.method == 'DELETE':
try:
delete_gateway(gateway_name, target_iqn)
except CephiSCSIError as err:
return jsonify(message="Gateway deletion failed: {}.".format(err)), 400
return jsonify(message="Gateway deleted."), 200
elif request.method == 'PUT':
# the parameters need to be cast to str for compatibility
# with the comparison logic in common.config.add_item
logger.debug("Attempting create of gateway {}".format(gateway_name))
gateway_ips = str(request.form['gateway_ip_list'])
nosync = str(request.form.get('nosync', 'false'))
gateway_ip_list = gateway_ips.split(',')
target_only = False
if nosync.lower() == 'true':
target_only = True
try:
ceph_gw = CephiSCSIGateway(logger, config)
ceph_gw.define_target(target_iqn, gateway_ip_list, target_only)
except CephiSCSIError as err:
err_msg = "Could not create target on gateway: {}".format(err)
logger.error(err_msg)
return jsonify(message=err_msg), 500
return jsonify(message="Gateway defined/mapped"), 200
@app.route('/api/targetlun/<target_iqn>', methods=['PUT', 'DELETE'])
@requires_restricted_auth
def target_disk(target_iqn=None):
"""
Coordinate the addition(PUT) and removal(DELETE) of a disk for a target
:param target_iqn: (str) IQN of the target
:param disk: (str) rbd image name on the format pool/image
**RESTRICTED**
Examples:
curl --user admin:admin -d disk=rbd/new2_1
-X PUT http://192.168.122.69:5000/api/targetlun/iqn.2003-01.com.redhat.iscsi-gw
curl --user admin:admin -d disk=rbd/new2_1
-X DELETE http://192.168.122.69:5000/api/targetlun/iqn.2003-01.com.redhat.iscsi-gw
"""
try:
target_iqn, iqn_type = normalize_wwn(['iqn'], target_iqn)
except RTSLibError as err:
err_str = "Invalid iqn {} - {}".format(target_iqn, err)
return jsonify(message=err_str), 500
target_config = config.config['targets'][target_iqn]
portals = [key for key in target_config['portals']]
# Any disk operation needs at least 2 gateways to be present
if len(portals) < settings.config.minimum_gateways:
msg = "at least {} gateways must exist before disk mapping operations " \
"are permitted".format(settings.config.minimum_gateways)
logger.warning("disk add request failed: {}".format(msg))
return jsonify(message=msg), 400
try:
gateways = get_remote_gateways(target_config['portals'], logger)
except CephiSCSIError as err:
return jsonify(message="{}".format(err)), 400
local_gw = this_host()
disk = request.form.get('disk')
if request.method == 'PUT':
if disk not in config.config['disks']:
return jsonify(message="Disk {} is not defined in the configuration".format(disk)), 400
for iqn, target in config.config['targets'].items():
if disk in target['disks']:
return jsonify(message="Disk {} cannot be used because it is already mapped on "
"target {}".format(disk, iqn)), 400
pool, image_name = disk.split('/')
try:
backstore = config.config['disks'][disk]
rbd_image = RBDDev(image_name, 0, backstore, pool)
size = rbd_image.current_size
logger.debug("{} size is {}".format(disk, size))
except rbd.ImageNotFound:
return jsonify(message="Image {} not found".format(disk)), 400
owner = LUN.get_owner(config.config['gateways'], target_config['portals'])
logger.debug("{} owner will be {}".format(disk, owner))
lun_id = request.form.get('lun_id')
if lun_id is not None:
try:
lun_id_int = int(lun_id)
except ValueError:
return jsonify(message="Lun id must be a number"), 400
for target_disk in target_config['disks'].values():
if lun_id_int == target_disk['lun_id']:
return jsonify(message="Lun id {} already in use".format(lun_id)), 400
api_vars = {
'disk': disk,
'lun_id': lun_id,
'owner': owner,
'allocating_host': local_gw
}
# process local gateway first
gateways.insert(0, local_gw)
resp_text, resp_code = call_api(gateways, '_targetlun',
'{}'.format(target_iqn),
http_method='put',
api_vars=api_vars)
if resp_code != 200:
return jsonify(message="Add target LUN mapping failed - "
"{}".format(resp_text)), resp_code
else:
# this is a DELETE request
if disk not in config.config['disks']:
return jsonify(message="Disk {} is not defined in the "
"configuration".format(disk)), 400
if disk not in target_config['disks']:
return jsonify(message="Disk {} is not defined in target "
"{}".format(disk, target_iqn)), 400
for group_name, group in target_config['groups'].items():
if disk in group['disks']:
return jsonify(message="Disk {} belongs to group "
"{}".format(disk, group_name)), 400
api_vars = {
'disk': disk,
'purge_host': local_gw
}
# process other gateways first
gateways.append(local_gw)
resp_text, resp_code = call_api(gateways, '_targetlun',
'{}'.format(target_iqn),
http_method='delete',
api_vars=api_vars)
if resp_code != 200:
return jsonify(message="Delete target LUN mapping failed - "
"{}".format(resp_text)), resp_code
return jsonify(message="Target LUN mapping updated successfully"), 200
@app.route('/api/_targetlun/<target_iqn>', methods=['PUT', 'DELETE'])
@requires_restricted_auth
def _target_disk(target_iqn=None):
"""
Manage the addition/removal of disks from a target on the local gateway
Internal Use ONLY
**RESTRICTED**
"""
config.refresh()
disk = request.form.get('disk')
pool, image = disk.split('/', 1)
disk_config = config.config['disks'][disk]
backstore = disk_config['backstore']
backstore_object_name = disk_config['backstore_object_name']
if request.method == 'PUT':
target_config = config.config['targets'][target_iqn]
ip_list = target_config.get('ip_list', [])
gateway = GWTarget(logger,
target_iqn,
ip_list)
if gateway.error:
logger.error("LUN mapping failed : "
"{}".format(gateway.error_msg))
return jsonify(message="LUN map failed"), 500
owner = request.form.get('owner')
allocating_host = request.form.get('allocating_host')
rbd_image = RBDDev(image, 0, backstore, pool)
size = rbd_image.current_size
lun = LUN(logger,
pool,
image,
size,
allocating_host,
backstore,
backstore_object_name)
if lun.error:
logger.error("Error initializing the LUN : "
"{}".format(lun.error_msg))
return jsonify(message="Error establishing LUN instance"), 500
lun_id = request.form.get('lun_id')
if lun_id is not None:
lun_id = int(lun_id)
try:
lun.map_lun(gateway, owner, disk, lun_id)
except CephiSCSIError as err:
status_code = 400 if str(err) else 500
logger.error("LUN add failed : {}".format(err))
return jsonify(message="Failed to add the LUN - "
"{}".format(err)), status_code
else:
# DELETE gateway request
purge_host = request.form['purge_host']
logger.debug("delete request for disk image '{}'".format(disk))
lun = LUN(logger,
pool,
image,
0,
purge_host,
backstore,
backstore_object_name)
if lun.error:
logger.error("Error initializing the LUN : "
"{}".format(lun.error_msg))
return jsonify(message="Error establishing LUN instance"), 500
lun.unmap_lun(target_iqn)
if lun.error:
status_code = 400 if lun.error_msg else 500
logger.error("LUN remove failed : {}".format(lun.error_msg))
return jsonify(message="Failed to remove the LUN - "
"{}".format(lun.error_msg)), status_code
config.refresh()
return jsonify(message="LUN mapped"), 200
@app.route('/api/disks')
@requires_restricted_auth
def get_disks():
"""
Show the rbd disks defined to the gateways
:param config: (str) 'yes' to list the config info of all disks, default is 'no'
**RESTRICTED**
Examples:
curl --user admin:admin -d config=yes -X GET http://192.168.122.69:5000/api/disks
"""
conf = request.form.get('config', 'no')
if conf.lower() == "yes":
disk_names = config.config['disks']
response = {"disks": disk_names}
else:
disk_names = list(config.config['disks'].keys())
response = {"disks": disk_names}
return jsonify(response), 200
@app.route('/api/disk/<pool>/<image>', methods=['GET', 'PUT', 'DELETE'])
@requires_restricted_auth
def disk(pool, image):
"""
Coordinate the create/delete of rbd images across the gateway nodes
This method calls the corresponding disk api entrypoints across each
gateway. Processing is done serially: creation is done locally first,
then other gateways - whereas, rbd deletion is performed first against
remote gateways and then the local machine is used to perform the actual
rbd delete.
:param pool: (str) pool name
:param image: (str) rbd image name
:param mode: (str) 'create' or 'resize' the rbd image
:param size: (str) the size of the rbd image
:param pool: (str) the pool name the rbd image will be in
:param count: (str) the number of images will be created
:param owner: (str) the owner of the rbd image
:param controls: (JSON dict) valid control overrides
:param preserve_image: (bool, 'true/false') do NOT delete RBD image
:param create_image: (bool, 'true/false') create RBD image if not exists, true as default
:param backstore: (str) lio backstore
:param wwn: (str) unit serial number
**RESTRICTED**
Examples:
curl --user admin:admin -d mode=create -d size=1g -d pool=rbd -d count=5