forked from ceph/ceph-iscsi-cli
-
Notifications
You must be signed in to change notification settings - Fork 0
/
rbd-target-api.py
executable file
·1672 lines (1303 loc) · 57.8 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 logging
import logging.handlers
import ssl
import OpenSSL
import threading
import time
import inspect
import re
import platform
from functools import wraps
from rpm import labelCompare
import rados
import werkzeug
from flask import Flask, jsonify, make_response, request
from rtslib_fb.utils import RTSLibError, normalize_wwn
import ceph_iscsi_config.settings as settings
from ceph_iscsi_config.gateway import GWTarget
from ceph_iscsi_config.group import Group
from ceph_iscsi_config.lun import LUN
from ceph_iscsi_config.client import GWClient, CHAP
from ceph_iscsi_config.common import Config
from ceph_iscsi_config.utils import (get_ip, this_host, ipv4_addresses,
gen_file_hash, valid_rpm)
from gwcli.utils import (this_host, APIRequest, valid_gateway,
valid_disk, valid_client, GatewayAPIError)
from gwcli.client import Client
app = Flask(__name__)
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
local_gw = ['127.0.0.1']
gw_names = [gw for gw in config.config['gateways']
if isinstance(config.config['gateways'][gw], dict)]
gw_ips = [get_ip(gw_name) for gw_name in gw_names] + \
local_gw + settings.config.trusted_ip_list
if request.remote_addr not in gw_ips:
return jsonify(message="API access not available to "
"{}".format(request.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.route('/api', methods=['GET'])
def get_api_info():
"""
Display all the available API endpoints
**UNRESTRICTED**
Examples:
curl --insecure --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: ipv4_addresses, checkconf and checkversions
**RESTRICTED**
Examples:
curl --insecure --user admin:admin -X GET http://192.168.122.69:5000/api/sysinfo/ipv4_addresses
"""
if query_type == 'ipv4_addresses':
return jsonify(data=ipv4_addresses()), 200
elif query_type == 'checkconf':
local_hash = gen_file_hash('/etc/ceph/iscsi-gateway.cfg')
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
@app.route('/api/target/<target_iqn>', methods=['PUT'])
@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
**RESTRICTED**
Examples:
curl --insecure --user admin:admin -X PUT http://192.168.122.69:5000/api/target/iqn.2003-01.com.redhat.iscsi-gw0
"""
if request.method == 'PUT':
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
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
return jsonify(message="Target defined successfully"), 200
else:
# return unrecognised request
return jsonify(message="Invalid method ({}) to target "
"API".format(request.method)), 405
@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
**RESTRICTED**
Examples:
curl --insecure --user admin:admin -X GET http://192.168.122.69:5000/api/config
"""
if request.method == 'GET':
return jsonify(config.config), 200
@app.route('/api/gateways', methods=['GET'])
@requires_restricted_auth
def gateways():
"""
Return the gateway subsection of the config object to the caller
**RESTRICTED**
Examples:
curl --insecure --user admin:admin -X GET http://192.168.122.69:5000/api/gateways
"""
if request.method == 'GET':
return jsonify(config.config['gateways']), 200
@app.route('/api/gateway/<gateway_name>', methods=['PUT'])
@requires_restricted_auth
def gateway(gateway_name=None):
"""
Define iscsi gateway(s) across node(s), adding TPGs, disks and clients
The call requires the following variables to be set;
:param gateway_name: (str) gateway name
:param ip_address: (str) ipv4 dotted quad for the address 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
**RESTRICTED**
Examples:
curl --insecure --user admin:admin -d ip_address=192.168.122.69 -X PUT http://192.168.122.69:5000/api/gateway/iscsi-gw0
"""
# 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
ip_address = request.form.get('ip_address')
nosync = request.form.get('nosync', False)
skipchecks = request.form.get('skipchecks', 'false')
# first confirm that the request is actually valid, if not return a 400
# error with the error description
current_config = config.config
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(gateway_name,
ip_address,
current_config)
if gateway_usable != 'ok':
return jsonify(message=gateway_usable), 400
resp_text = "Gateway added" # Assume the best!
http_mode = 'https' if settings.config.api_secure else 'http'
current_disks = config.config['disks']
current_clients = config.config['clients']
target_iqn = config.config['gateways'].get('iqn')
total_objects = (len(current_disks.keys()) +
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 = config.config['gateways'].get('ip_list', [])
gateway_ip_list.append(ip_address)
first_gateway = (len(gateway_ip_list) == 1)
if first_gateway:
gateways =['127.0.0.1']
else:
gateways = gateway_ip_list
api_vars = {"target_iqn": target_iqn,
"gateway_ip_list": ",".join(gateway_ip_list),
"mode": "target"}
resp_text, resp_code = call_api(gateways, '_gateway',
gateway_name,
http_method='put',
api_vars=api_vars)
if resp_code == 200:
# GW definition has been added, so before we declare victory we need
# to sync tpg's to the existing gateways and sync the disk and client
# configuration to the new gateway
if len(current_disks.keys()) > 0:
# there are disks in the environment, so we need to add them to the
# new tpg created when the new gateway was added
seed_gateways = [ip for ip in gateways if ip != ip_address]
resp_text, resp_code = seed_tpg(seed_gateways,
gateway_name,
api_vars)
if resp_code != 200:
return jsonify(message="TPG sync failed on existing gateways"), \
resp_code
# No check to see if the new gateway needs to be synchronised as part
# of this request
if nosync:
# no further action needed
return jsonify(message="Gateway creation {}".format(resp_text)), \
resp_code
else:
resp_text, resp_code = seed_disks(current_disks,
ip_address)
if resp_code != 200:
return jsonify(message="Disk mapping {}".format(resp_text)), \
resp_code
else:
# disks added, so seed the clients on the new gateway
resp_text, resp_code = seed_clients(current_clients,
ip_address)
else:
return jsonify(message="Gateway creation {}".format(resp_text)), \
resp_code
def seed_tpg(gateways, gateway_name, api_vars):
http_mode = 'https' if settings.config.api_secure else 'http'
state = 'succeeded'
rc = 200
api_vars['mode'] = 'map'
for gw in gateways:
logger.debug("Updating tpg on {}".format(gw))
gw_api = '{}://{}:{}/api/_gateway/{}'.format(http_mode,
gw,
settings.config.api_port,
gateway_name)
api = APIRequest(gw_api, data=api_vars)
api.put()
if api.response.status_code != 200:
state = 'failed'
rc = 500
break
return "TPG mapping {}".format(state), rc
def seed_disks(current_disks, gw_ip):
http_mode = 'https' if settings.config.api_secure else 'http'
state = 'succeeded'
for disk_key in current_disks:
this_disk = current_disks[disk_key]
disk_api = '{}://{}:{}/api/disk/{}'.format(http_mode,
gw_ip,
settings.config.api_port,
disk_key)
api_vars = {"pool": this_disk['pool'],
"size": "0G",
"owner": this_disk['owner'],
"mode": "sync"}
api = APIRequest(disk_api, data=api_vars)
api.put()
if api.response.status_code != 200:
state = 'failed'
break
logger.debug("added {} to gateway {}".format(disk_key,
gw_ip))
return "disk seeding on {} {}".format(gw_ip, state), \
api.response.status_code
def seed_clients(current_clients, gw_ip):
http_mode = 'https' if settings.config.api_secure else 'http'
state = 'succeeded'
local_gw = this_host()
for client_iqn in current_clients:
this_client = current_clients[client_iqn]
client_luns = this_client['luns']
lun_list = [(disk, client_luns[disk]['lun_id'])
for disk in client_luns]
srtd_list = Client.get_srtd_names(lun_list)
api_vars = {'chap': this_client['auth']['chap'],
'image_list': ','.join(srtd_list),
'committing_host': local_gw}
client_api = '{}://{}:{}/api/client/{}'.format(http_mode,
gw_ip,
settings.config.api_port,
client_iqn)
api = APIRequest(client_api,
data=api_vars)
api.put()
if api.response.status_code != 200:
state = 'failed'
break
logger.debug("client '{}' defined to GW {}".format(client_iqn,
gw_ip))
return "Client seeding to '{}' {}".format(gw_ip, state), \
api.response.status_code
@app.route('/api/_gateway/<gateway_name>', methods=['GET', 'PUT', 'DELETE'])
@requires_restricted_auth
def _gateway(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 gateway_name: (str) gateway name, normally the DNS name
**RESTRICTED**
"""
if request.method == 'GET':
if gateway_name in config.config['gateways']:
return jsonify(config.config['gateways'][gateway_name]), 200
else:
return jsonify(message="Gateway doesn't exist in the "
"configuration"), 404
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'])
target_iqn = str(request.form['target_iqn'])
target_mode = str(request.form.get('mode', 'target'))
gateway_ip_list = gateway_ips.split(',')
gateway = GWTarget(logger,
target_iqn,
gateway_ip_list)
if gateway.error:
logger.error("Unable to create an instance of the GWTarget class")
return jsonify(message="Failed to create the gateway"), 500
gateway.manage(target_mode)
if gateway.error:
logger.error("manage({}) logic failed for {}".format(target_mode,
gateway_name))
return jsonify(message="Failed to create the gateway"), 500
logger.info("created the gateway")
if target_mode == 'target':
# refresh only for target definitions, since that's when the config
# will actually change
logger.info("refreshing the configuration after the gateway "
"creation")
config.refresh()
return jsonify(message="Gateway defined/mapped"), 200
else:
# DELETE gateway request
gateway = GWTarget(logger,
config.config['gateways']['iqn'],
'')
if gateway.error:
return jsonify(message="Failed to connect to the gateway"), 500
gateway.manage('clearconfig')
if gateway.error:
logger.error("clearconfig failed for {} : "
"{}".format(gateway_name,
gateway.error_msg))
return jsonify(message="Unable to remove {} from the "
"configuration".format(gateway_name)), 400
else:
config.refresh()
return jsonify(message="Gateway removed successfully"), 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 --insecure --user admin:admin -d config=yes -X GET https://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 = config.config['disks'].keys()
response = {"disks": disk_names}
return jsonify(response), 200
@app.route('/api/disk/<image_id>', methods=['GET', 'PUT', 'DELETE'])
@requires_restricted_auth
def disk(image_id):
"""
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 image_id: (str) rbd image name of the format pool.image
: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
**RESTRICTED**
Examples:
curl --insecure --user admin:admin -d mode=create -d size=1g -d pool=rbd -d count=5 -X PUT https://192.168.122.69:5000/api/disk/rbd.new2_
curl --insecure --user admin:admin -X GET https://192.168.122.69:5000/api/disk/rbd.new2_1
curl --insecure --user admin:admin -X DELETE https://192.168.122.69:5000/api/disk/rbd.new2_1
"""
disk_regex = re.compile("[a-zA-Z0-9\-]+(\.)[a-zA-Z0-9\-]+")
if not disk_regex.search(image_id):
logger.debug("disk request rejected due to invalid image name")
return jsonify(message="image id format is invalid - must be "
"pool.image_name"), 400
local_gw = this_host()
logger.debug("this host is {}".format(local_gw))
if request.method == 'GET':
if image_id in config.config['disks']:
return jsonify(config.config["disks"][image_id]), 200
else:
return jsonify(message="rbd image {} not "
"found".format(image_id)), 404
# This is a create/resize operation, so first confirm the gateways
# are in place (we need gateways to perform the lun masking tasks
gateways = [key for key in config.config['gateways']
if isinstance(config.config['gateways'][key], dict)]
logger.debug("All gateways: {}".format(gateways))
# Any disk operation needs at least 2 gateways to be present
if len(gateways) < settings.config.minimum_gateways:
msg = "at least {} gateways must exist before disk operations " \
"are permitted".format(settings.config.minimum_gateways)
logger.warning("disk create request failed: {}".format(msg))
return jsonify(message=msg), 400
if request.method == 'PUT':
# at this point we have a disk request, and the gateways are available
# for the LUN masking operations
gateways.remove(local_gw)
logger.debug("Other gateways: {}".format(gateways))
# pool = request.form.get('pool')
size = request.form.get('size')
mode = request.form.get('mode')
count = request.form.get('count', '1')
pool, image_name = image_id.split('.')
disk_usable = valid_disk(pool=pool, image=image_name, size=size,
mode=mode, count=count)
if disk_usable != 'ok':
return jsonify(message=disk_usable), 400
suffixes = [n for n in range(1, int(count)+1)]
# make call to local api server first!
gateways.insert(0, '127.0.0.1')
for sfx in suffixes:
image_name = image_id if count == '1' else "{}{}".format(image_id,
sfx)
api_vars = {'pool': pool, 'size': size, 'owner': local_gw,
'mode': mode}
resp_text, resp_code = call_api(gateways, '_disk',
image_name,
http_method='put',
api_vars=api_vars)
if resp_code != 200:
return jsonify(message="disk create/update "
"{}".format(resp_text)), resp_code
return jsonify(message="disk create/update {}".format(resp_text)), \
resp_code
else:
# this is a DELETE request
pool_name, image_name = image_id.split('.')
disk_usable = valid_disk(mode='delete', pool=pool_name,
image=image_name)
if disk_usable != 'ok':
return jsonify(message=disk_usable), 400
api_vars = {'purge_host': local_gw}
# process other gateways first
gateways.remove(local_gw)
gateways.append(local_gw)
resp_text, resp_code = call_api(gateways, '_disk',
image_id,
http_method='delete',
api_vars=api_vars)
return jsonify(message="disk map deletion {}".format(resp_text)), \
resp_code
@app.route('/api/_disk/<image_id>', methods=['GET', 'PUT', 'DELETE'])
@requires_restricted_auth
def _disk(image_id):
"""
Manage a disk definition on the local gateway
Internal Use ONLY
Disks can be created and added to each gateway, or deleted through this
call
:param image_id: (str) of the form pool.image_name
**RESTRICTED**
"""
if request.method == 'GET':
if image_id in config.config['disks']:
return jsonify(config.config["disks"][image_id]), 200
else:
return jsonify(message="rbd image {} not "
"found".format(image_id)), 404
elif request.method == 'PUT':
# A put is for either a create or a resize
# put('http://127.0.0.1:5000/api/disk/rbd.ansible3',data={'pool': 'rbd','size': '3G','owner':'ceph-1'})
rqst_fields = set(request.form.keys())
if rqst_fields.issuperset(("pool", "size", "owner", "mode")):
image_name = str(image_id.split('.', 1)[1])
lun = LUN(logger,
str(request.form['pool']),
image_name,
str(request.form['size']),
str(request.form['owner']))
if lun.error:
logger.error("Unable to create a LUN instance"
" : {}".format(lun.error_msg))
return jsonify(message="Unable to establish LUN instance"), 500
if request.form['mode'] == 'create' and len(config.config['disks']) >= 256:
logger.error("LUN alloc problem - too many LUNs")
return jsonify(message="LUN allocation failure: too many LUNs"), 500
lun.allocate()
if lun.error:
logger.error("LUN alloc problem - {}".format(lun.error_msg))
return jsonify(message="LUN allocation failure"), 500
if request.form['mode'] == 'create':
# new disk is allocated, so refresh the local config object
config.refresh()
iqn = config.config['gateways']['iqn']
ip_list = config.config['gateways']['ip_list']
# Add the mapping for the lun to ensure the block device is
# present on all TPG's
gateway = GWTarget(logger,
iqn,
ip_list)
gateway.manage('map')
if gateway.error:
logger.error("LUN mapping failed : "
"{}".format(gateway.error_msg))
return jsonify(message="LUN map failed"), 500
return jsonify(message="LUN created"), 200
elif request.form['mode'] == 'resize':
return jsonify(message="LUN resized"), 200
else:
# this is an invalid request
return jsonify(message="Invalid Request - need to provide"
"pool, size and owner"), 400
else:
# DELETE request
# let's assume that the request has been validated by the caller
# if valid_request(request.remote_addr):
purge_host = request.form['purge_host']
logger.debug("delete request for disk image '{}'".format(image_id))
pool, image = image_id.split('.', 1)
lun = LUN(logger,
pool,
image,
'0G',
purge_host)
if lun.error:
# problem defining the LUN instance
logger.error("Error initialising the LUN : "
"{}".format(lun.error_msg))
return jsonify(message="Error establishing LUN instance"), 500
lun.remove_lun()
if lun.error:
if 'allocated to' in lun.error_msg:
# attempted to remove rbd that is still allocated to a client
status_code = 400
else:
status_code = 500
logger.error("LUN remove failed : {}".format(lun.error_msg))
return jsonify(message="Failed to remove the LUN"), status_code
config.refresh()
return jsonify(message="LUN removed"), 200
@app.route('/api/clients', methods=['GET'])
@requires_restricted_auth
def get_clients():
"""
List clients defined to the configuration.
This information will include auth information, hence the
restricted_auth wrapper
**RESTRICTED**
Examples:
curl --insecure --user admin:admin -X GET https://192.168.122.69:5000/api/clients
"""
client_list = config.config['clients'].keys()
response = {"clients": client_list}
return jsonify(response), 200
def _update_client(**kwargs):
"""
Handler function to apply the changes to a specific client definition
:param args:
"""
# convert the comma separated image_list string into a list for GWClient
if kwargs['images']:
image_list = str(kwargs['images']).split(',')
else:
image_list = []
client = GWClient(logger,
kwargs['client_iqn'],
image_list,
kwargs['chap'])
if client.error:
logger.error("Invalid client request - {}".format(client.error_msg))
return 400, "Invalid client request"
client.manage('present', committer=kwargs['committing_host'])
if client.error:
logger.error("client update failed on {} : "
"{}".format(kwargs['client_iqn'],
client.error_msg))
return 500, "Client update failed"
else:
config.refresh()
return 200, "Client configured successfully"
@app.route('/api/clientauth/<client_iqn>', methods=['PUT'])
@requires_restricted_auth
def clientauth(client_iqn):
"""
Coordinate client authentication changes across each gateway node
The following parameters are needed to manage client auth
:param client_iqn: (str) client IQN name
:param chap: (str) chap string of the form username/password or ''
username is 8-64 chars long containing any alphanumeric in [0-9a-zA-Z] and '.' ':' '@' '_' '-'
password is 12-16 chars long containing any alphanumeric in [0-9a-zA-Z] and '@' '-' '_'
**RESTRICTED**
Examples:
curl --insecure --user admin:admin -d chap='' -X PUT https://192.168.122.69:5000/api/clientauth/iqn.2017-08.org.ceph:iscsi-gw0
curl --insecure --user admin:admin -d chap=dmin1234/admin12345678 -X PUT https://192.168.122.69:5000/api/clientauth/iqn.2017-08.org.ceph:iscsi-gw0
"""
# http_mode = 'https' if settings.config.api_secure else 'http'
local_gw = this_host()
logger.debug("this host is {}".format(local_gw))
gateways = [key for key in config.config['gateways']
if isinstance(config.config['gateways'][key], dict)]
logger.debug("other gateways - {}".format(gateways))
gateways.remove(local_gw)
lun_list = config.config['clients'][client_iqn]['luns'].keys()
image_list = ','.join(lun_list)
chap = request.form.get('chap')
client_usable = valid_client(mode='auth', client_iqn=client_iqn, chap=chap)
if client_usable != 'ok':
logger.error("BAD auth request from {}".format(request.remote_addr))
return jsonify(message=client_usable), 400
api_vars = {"committing_host": local_gw,
"image_list": image_list,
"chap": chap}
gateways.insert(0, '127.0.0.1')
resp_text, resp_code = call_api(gateways, '_clientauth', client_iqn,
http_method='put',
api_vars=api_vars)
return jsonify(message="client auth {}".format(resp_text)), \
resp_code
@app.route('/api/_clientauth/<client_iqn>', methods=['PUT'])
@requires_restricted_auth
def _clientauth(client_iqn):
"""
Manage client authentication credentials on the local gateway
Internal Use ONLY
:param client_iqn: IQN of the client
**RESTRICTED**
"""
# PUT request to define/change authentication
image_list = request.form['image_list']
chap = request.form['chap']
committing_host = request.form['committing_host']
status_code, status_text = _update_client(client_iqn=client_iqn,
images=image_list,
chap=chap,
committing_host=committing_host)
return jsonify(message=status_text), status_code
@app.route('/api/clientlun/<client_iqn>', methods=['PUT', 'DELETE'])
@requires_restricted_auth
def clientlun(client_iqn):
"""
Coordinate the addition(PUT) and removal(DELETE) of a disk for a client
:param client_iqn: (str) IQN of the client
:param disk: (str) rbd image name of the format pool.image
**RESTRICTED**
Examples:
curl --insecure --user admin:admin -d disk=rbd.new2_1 -X PUT https://192.168.122.69:5000/api/clientlun/iqn.2017-08.org.ceph:iscsi-gw0
"""
# http_mode = 'https' if settings.config.api_secure else 'http'
local_gw = this_host()
logger.debug("this host is {}".format(local_gw))
gateways = [key for key in config.config['gateways']
if isinstance(config.config['gateways'][key], dict)]
logger.debug("other gateways - {}".format(gateways))
gateways.remove(local_gw)
disk = request.form.get('disk')
lun_list = config.config['clients'][client_iqn]['luns'].keys()
if request.method == 'PUT':
lun_list.append(disk)
else:
# this is a delete request
if disk in lun_list:
lun_list.remove(disk)
else:
return jsonify(message="disk not mapped to client"), 400
chap_obj = CHAP(config.config['clients'][client_iqn]['auth']['chap'])
chap = "{}/{}".format(chap_obj.user, chap_obj.password)
image_list = ','.join(lun_list)
client_usable = valid_client(mode='disk', client_iqn=client_iqn,
image_list=image_list)
if client_usable != 'ok':
logger.error("Bad disk request for client {} : "
"{}".format(client_iqn,
client_usable))
return jsonify(message=client_usable), 400
# committing host is the local LIO node
api_vars = {"committing_host": local_gw,
"image_list": image_list,
"chap": chap}
gateways.insert(0, '127.0.0.1')
resp_text, resp_code = call_api(gateways, '_clientlun', client_iqn,
http_method='put',
api_vars=api_vars)
return jsonify(message="client masking update {}".format(resp_text)), \
resp_code
@app.route('/api/_clientlun/<client_iqn>', methods=['GET', 'PUT'])
@requires_restricted_auth
def _clientlun(client_iqn):
"""
Manage the addition/removal of disks from a client on the local gateway
Internal Use ONLY
**RESTRICTED**
"""
if request.method == 'GET':
if client_iqn in config.config['clients']:
lun_config = config.config['clients'][client_iqn]['luns']
return jsonify(message=lun_config), 200
else:
return jsonify(message="Client does not exist"), 404
else:
# PUT request = new/updated disks for this client