]>
git.proxmox.com Git - ceph.git/blob - ceph/src/pybind/mgr/restful/module.py
17 from uuid
import uuid4
18 from pecan
import jsonify
, make_app
19 from OpenSSL
import crypto
20 from pecan
.rest
import RestController
21 from werkzeug
.serving
import make_server
, make_ssl_devcert
23 from hooks
import ErrorHook
24 from mgr_module
import MgrModule
, CommandResult
26 # Global instance to share
30 class CannotServe(Exception):
34 class CommandsRequest(object):
36 This class handles parallel as well as sequential execution of
37 commands. The class accept a list of iterables that should be
38 executed sequentially. Each iterable can contain several commands
39 that can be executed in parallel.
43 - run c1 and c2 in parallel
44 - wait for them to finish
45 - run c3 and c4 in parallel
46 - wait for them to finish
50 def __init__(self
, commands_arrays
):
51 self
.id = str(id(self
))
53 # Filter out empty sub-requests
54 commands_arrays
= filter(
55 lambda x
: len(x
) != 0,
60 self
.waiting
= commands_arrays
[1:]
64 self
.lock
= threading
.RLock()
65 if not len(commands_arrays
):
69 # Process first iteration of commands_arrays in parallel
70 results
= self
.run(commands_arrays
[0])
72 self
.running
.extend(results
)
75 def run(self
, commands
):
77 A static method that will execute the given list of commands in
78 parallel and will return the list of command results.
81 # Gather the results (in parallel)
83 for index
in range(len(commands
)):
84 tag
= '%s:%d' % (str(self
.id), index
)
87 result
= CommandResult(tag
)
88 result
.command
= common
.humanify_command(commands
[index
])
89 results
.append(result
)
92 instance
.send_command(result
, 'mon', '', json
.dumps(commands
[index
]), tag
)
103 # Run a next iteration of commands
104 commands
= self
.waiting
[0]
105 self
.waiting
= self
.waiting
[1:]
107 self
.running
.extend(self
.run(commands
))
110 def finish(self
, tag
):
112 for index
in range(len(self
.running
)):
113 if self
.running
[index
].tag
== tag
:
114 if self
.running
[index
].r
== 0:
115 self
.finished
.append(self
.running
.pop(index
))
117 self
.failed
.append(self
.running
.pop(index
))
124 def is_running(self
, tag
):
125 for result
in self
.running
:
126 if result
.tag
== tag
:
133 return not self
.running
and self
.waiting
136 def is_waiting(self
):
137 return bool(self
.waiting
)
140 def is_finished(self
):
142 return not self
.running
and not self
.waiting
145 def has_failed(self
):
146 return bool(self
.failed
)
151 if not self
.is_finished():
154 if self
.has_failed():
165 'command': x
.command
,
173 'command': x
.command
,
181 lambda y
: common
.humanify_command(y
),
188 'command': x
.command
,
194 'is_waiting': self
.is_waiting(),
195 'is_finished': self
.is_finished(),
196 'has_failed': self
.has_failed(),
197 'state': self
.get_state(),
202 class Module(MgrModule
):
205 "cmd": "restful create-key name=key_name,type=CephString",
206 "desc": "Create an API key with this name",
210 "cmd": "restful delete-key name=key_name,type=CephString",
211 "desc": "Delete an API key with this name",
215 "cmd": "restful list-keys",
216 "desc": "List all API keys",
220 "cmd": "restful create-self-signed-cert",
221 "desc": "Create localized self signed certificate",
225 "cmd": "restful restart",
226 "desc": "Restart API server",
231 def __init__(self
, *args
, **kwargs
):
232 super(Module
, self
).__init
__(*args
, **kwargs
)
237 self
.requests_lock
= threading
.RLock()
240 self
.disable_auth
= False
244 self
.stop_server
= False
245 self
.serve_event
= threading
.Event()
249 while not self
.stop_server
:
252 self
.server
.socket
.close()
253 except CannotServe
as cs
:
254 self
.log
.warn("server not running: {0}".format(cs
.message
))
256 self
.log
.error(str(traceback
.format_exc()))
258 # Wait and clear the threading event
259 self
.serve_event
.wait()
260 self
.serve_event
.clear()
262 def refresh_keys(self
):
264 rawkeys
= self
.get_config_prefix('keys/') or {}
265 for k
, v
in rawkeys
.iteritems():
266 self
.keys
[k
[5:]] = v
# strip of keys/ prefix
269 # Load stored authentication keys
272 jsonify
._instance
= jsonify
.GenericJSON(
275 separators
=(',', ': '),
278 server_addr
= self
.get_localized_config('server_addr', '::')
279 if server_addr
is None:
280 raise CannotServe('no server_addr configured; try "ceph config-key set mgr/restful/server_addr <ip>"')
282 server_port
= int(self
.get_localized_config('server_port', '8003'))
283 self
.log
.info('server_addr: %s server_port: %d',
284 server_addr
, server_port
)
286 cert
= self
.get_localized_config("crt")
288 cert_tmp
= tempfile
.NamedTemporaryFile()
291 cert_fname
= cert_tmp
.name
293 cert_fname
= self
.get_localized_config('crt_file')
295 pkey
= self
.get_localized_config("key")
297 pkey_tmp
= tempfile
.NamedTemporaryFile()
300 pkey_fname
= pkey_tmp
.name
302 pkey_fname
= self
.get_localized_config('key_file')
304 if not cert_fname
or not pkey_fname
:
305 raise CannotServe('no certificate configured')
306 if not os
.path
.isfile(cert_fname
):
307 raise CannotServe('certificate %s does not exist' % cert_fname
)
308 if not os
.path
.isfile(pkey_fname
):
309 raise CannotServe('private key %s does not exist' % pkey_fname
)
311 # Publish the URI that others may use to access the service we're
312 # about to start serving
313 self
.set_uri("https://{0}:{1}/".format(
314 socket
.gethostname() if server_addr
== "::" else server_addr
,
318 # Create the HTTPS werkzeug server serving pecan app
319 self
.server
= make_server(
323 root
='restful.api.Root',
324 hooks
= [ErrorHook()], # use a callable if pecan >= 0.3.2
326 ssl_context
=(cert_fname
, pkey_fname
),
329 self
.server
.serve_forever()
334 self
.stop_server
= True
336 self
.server
.shutdown()
337 self
.serve_event
.set()
339 self
.log
.error(str(traceback
.format_exc()))
346 self
.server
.shutdown()
347 self
.serve_event
.set()
349 self
.log
.error(str(traceback
.format_exc()))
352 def notify(self
, notify_type
, tag
):
354 self
._notify
(notify_type
, tag
)
356 self
.log
.error(str(traceback
.format_exc()))
359 def _notify(self
, notify_type
, tag
):
360 if notify_type
== "command":
361 # we can safely skip all the sequential commands
366 lambda x
: x
.is_running(tag
),
369 if len(request
) != 1:
370 self
.log
.warn("Unknown request '%s'" % str(tag
))
375 if request
.is_ready():
378 self
.log
.debug("Unhandled notification type '%s'" % notify_type
)
381 def create_self_signed_cert(self
):
384 pkey
.generate_key(crypto
.TYPE_RSA
, 2048)
386 # create a self-signed cert
388 cert
.get_subject().O
= "IT"
389 cert
.get_subject().CN
= "ceph-restful"
390 cert
.set_serial_number(int(uuid4()))
391 cert
.gmtime_adj_notBefore(0)
392 cert
.gmtime_adj_notAfter(10*365*24*60*60)
393 cert
.set_issuer(cert
.get_subject())
394 cert
.set_pubkey(pkey
)
395 cert
.sign(pkey
, 'sha512')
398 crypto
.dump_certificate(crypto
.FILETYPE_PEM
, cert
),
399 crypto
.dump_privatekey(crypto
.FILETYPE_PEM
, pkey
)
403 def handle_command(self
, command
):
404 self
.log
.warn("Handling command: '%s'" % str(command
))
405 if command
['prefix'] == "restful create-key":
406 if command
['key_name'] in self
.keys
:
407 return 0, self
.keys
[command
['key_name']], ""
411 self
.keys
[command
['key_name']] = key
412 self
.set_config('keys/' + command
['key_name'], key
)
416 self
.keys
[command
['key_name']],
420 elif command
['prefix'] == "restful delete-key":
421 if command
['key_name'] in self
.keys
:
422 del self
.keys
[command
['key_name']]
423 self
.set_config('keys/' + command
['key_name'], None)
431 elif command
['prefix'] == "restful list-keys":
435 json
.dumps(self
.keys
, indent
=2),
439 elif command
['prefix'] == "restful create-self-signed-cert":
440 cert
, pkey
= self
.create_self_signed_cert()
442 self
.set_config(self
.get_mgr_id() + '/crt', cert
)
443 self
.set_config(self
.get_mgr_id() + '/key', pkey
)
448 "Restarting RESTful API server...",
452 elif command
['prefix'] == 'restful restart':
456 "Restarting RESTful API server...",
464 "Command not found '{0}'".format(command
['prefix'])
468 def get_doc_api(self
, root
, prefix
=''):
470 for _obj
in dir(root
):
471 obj
= getattr(root
, _obj
)
473 if isinstance(obj
, RestController
):
474 doc
.update(self
.get_doc_api(obj
, prefix
+ '/' + _obj
))
476 if getattr(root
, '_lookup', None) and isinstance(root
._lookup
('0')[0], RestController
):
477 doc
.update(self
.get_doc_api(root
._lookup
('0')[0], prefix
+ '/<arg>'))
479 prefix
= prefix
or '/'
482 for method
in 'get', 'post', 'patch', 'delete':
483 if getattr(root
, method
, None):
484 doc
[prefix
][method
.upper()] = inspect
.getdoc(getattr(root
, method
)).split('\n')
486 if len(doc
[prefix
]) == 0:
493 mon_map_mons
= self
.get('mon_map')['mons']
494 mon_status
= json
.loads(self
.get('mon_status')['json'])
496 # Add more information
497 for mon
in mon_map_mons
:
498 mon
['in_quorum'] = mon
['rank'] in mon_status
['quorum']
499 mon
['server'] = self
.get_metadata("mon", mon
['name'])['hostname']
500 mon
['leader'] = mon
['rank'] == mon_status
['quorum'][0]
505 def get_osd_pools(self
):
506 osds
= dict(map(lambda x
: (x
['osd'], []), self
.get('osd_map')['osds']))
507 pools
= dict(map(lambda x
: (x
['pool'], x
), self
.get('osd_map')['pools']))
508 crush_rules
= self
.get('osd_map_crush')['rules']
511 for pool_id
, pool
in pools
.items():
513 for rule
in [r
for r
in crush_rules
if r
['rule_id'] == pool
['crush_rule']]:
514 if rule
['min_size'] <= pool
['size'] <= rule
['max_size']:
515 pool_osds
= common
.crush_rule_osds(self
.get('osd_map_tree')['nodes'], rule
)
517 osds_by_pool
[pool_id
] = pool_osds
519 for pool_id
in pools
.keys():
520 for in_pool_id
in osds_by_pool
[pool_id
]:
521 osds
[in_pool_id
].append(pool_id
)
526 def get_osds(self
, pool_id
=None, ids
=None):
528 osd_map
= self
.get('osd_map')
529 osd_metadata
= self
.get('osd_metadata')
531 # Update the data with the additional info from the osd map
532 osds
= osd_map
['osds']
537 lambda x
: str(x
['osd']) in ids
,
541 # Get list of pools per osd node
542 pools_map
= self
.get_osd_pools()
544 # map osd IDs to reweight
545 reweight_map
= dict([
546 (x
.get('id'), x
.get('reweight', None))
547 for x
in self
.get('osd_map_tree')['nodes']
550 # Build OSD data objects
552 osd
['pools'] = pools_map
[osd
['osd']]
553 osd
['server'] = osd_metadata
.get(str(osd
['osd']), {}).get('hostname', None)
555 osd
['reweight'] = reweight_map
.get(osd
['osd'], 0.0)
558 osd
['valid_commands'] = common
.OSD_IMPLEMENTED_COMMANDS
560 osd
['valid_commands'] = []
564 pool_id
= int(pool_id
)
566 lambda x
: pool_id
in x
['pools'],
573 def get_osd_by_id(self
, osd_id
):
575 lambda x
: x
['osd'] == osd_id
,
576 self
.get('osd_map')['osds']
585 def get_pool_by_id(self
, pool_id
):
587 lambda x
: x
['pool'] == pool_id
,
588 self
.get('osd_map')['pools'],
597 def submit_request(self
, _request
, **kwargs
):
598 request
= CommandsRequest(_request
)
599 with self
.requests_lock
:
600 self
.requests
.append(request
)
601 if kwargs
.get('wait', 0):
602 while not request
.is_finished():
607 def run_command(self
, command
):
608 # tag with 'seq' so that we can ingore these in notify function
609 result
= CommandResult('seq')
611 self
.send_command(result
, 'mon', '', json
.dumps(command
), 'seq')