]>
git.proxmox.com Git - ceph.git/blob - ceph/src/pybind/mgr/restful/module.py
18 from uuid
import uuid4
19 from pecan
import jsonify
, make_app
20 from OpenSSL
import crypto
21 from pecan
.rest
import RestController
22 from werkzeug
.serving
import make_server
, make_ssl_devcert
24 from hooks
import ErrorHook
25 from mgr_module
import MgrModule
, CommandResult
28 # Global instance to share
32 class CannotServe(Exception):
36 class CommandsRequest(object):
38 This class handles parallel as well as sequential execution of
39 commands. The class accept a list of iterables that should be
40 executed sequentially. Each iterable can contain several commands
41 that can be executed in parallel.
45 - run c1 and c2 in parallel
46 - wait for them to finish
47 - run c3 and c4 in parallel
48 - wait for them to finish
52 def __init__(self
, commands_arrays
):
53 self
.id = str(id(self
))
55 # Filter out empty sub-requests
56 commands_arrays
= [x
for x
in commands_arrays
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: %s", cs
)
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 six
.iteritems(rawkeys
):
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()
289 cert_tmp
.write(cert
.encode('utf-8'))
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()
298 pkey_tmp
.write(pkey
.encode('utf-8'))
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
365 with self
.requests_lock
:
366 request
= [x
for x
in self
.requests
if x
.is_running(tag
)]
368 if len(request
) != 1:
369 self
.log
.warn("Unknown request '%s'" % str(tag
))
374 if request
.is_ready():
377 self
.log
.debug("Unhandled notification type '%s'" % notify_type
)
380 def create_self_signed_cert(self
):
383 pkey
.generate_key(crypto
.TYPE_RSA
, 2048)
385 # create a self-signed cert
387 cert
.get_subject().O
= "IT"
388 cert
.get_subject().CN
= "ceph-restful"
389 cert
.set_serial_number(int(uuid4()))
390 cert
.gmtime_adj_notBefore(0)
391 cert
.gmtime_adj_notAfter(10*365*24*60*60)
392 cert
.set_issuer(cert
.get_subject())
393 cert
.set_pubkey(pkey
)
394 cert
.sign(pkey
, 'sha512')
397 crypto
.dump_certificate(crypto
.FILETYPE_PEM
, cert
),
398 crypto
.dump_privatekey(crypto
.FILETYPE_PEM
, pkey
)
402 def handle_command(self
, command
):
403 self
.log
.warn("Handling command: '%s'" % str(command
))
404 if command
['prefix'] == "restful create-key":
405 if command
['key_name'] in self
.keys
:
406 return 0, self
.keys
[command
['key_name']], ""
410 self
.keys
[command
['key_name']] = key
411 self
.set_config('keys/' + command
['key_name'], key
)
415 self
.keys
[command
['key_name']],
419 elif command
['prefix'] == "restful delete-key":
420 if command
['key_name'] in self
.keys
:
421 del self
.keys
[command
['key_name']]
422 self
.set_config('keys/' + command
['key_name'], None)
430 elif command
['prefix'] == "restful list-keys":
434 json
.dumps(self
.keys
, indent
=2),
438 elif command
['prefix'] == "restful create-self-signed-cert":
439 cert
, pkey
= self
.create_self_signed_cert()
440 self
.set_config(self
.get_mgr_id() + '/crt', cert
.decode('utf-8'))
441 self
.set_config(self
.get_mgr_id() + '/key', pkey
.decode('utf-8'))
446 "Restarting RESTful API server...",
450 elif command
['prefix'] == 'restful restart':
454 "Restarting RESTful API server...",
462 "Command not found '{0}'".format(command
['prefix'])
466 def get_doc_api(self
, root
, prefix
=''):
468 for _obj
in dir(root
):
469 obj
= getattr(root
, _obj
)
471 if isinstance(obj
, RestController
):
472 doc
.update(self
.get_doc_api(obj
, prefix
+ '/' + _obj
))
474 if getattr(root
, '_lookup', None) and isinstance(root
._lookup
('0')[0], RestController
):
475 doc
.update(self
.get_doc_api(root
._lookup
('0')[0], prefix
+ '/<arg>'))
477 prefix
= prefix
or '/'
480 for method
in 'get', 'post', 'patch', 'delete':
481 if getattr(root
, method
, None):
482 doc
[prefix
][method
.upper()] = inspect
.getdoc(getattr(root
, method
)).split('\n')
484 if len(doc
[prefix
]) == 0:
491 mon_map_mons
= self
.get('mon_map')['mons']
492 mon_status
= json
.loads(self
.get('mon_status')['json'])
494 # Add more information
495 for mon
in mon_map_mons
:
496 mon
['in_quorum'] = mon
['rank'] in mon_status
['quorum']
497 mon
['server'] = self
.get_metadata("mon", mon
['name'])['hostname']
498 mon
['leader'] = mon
['rank'] == mon_status
['quorum'][0]
503 def get_osd_pools(self
):
504 osds
= dict(map(lambda x
: (x
['osd'], []), self
.get('osd_map')['osds']))
505 pools
= dict(map(lambda x
: (x
['pool'], x
), self
.get('osd_map')['pools']))
506 crush_rules
= self
.get('osd_map_crush')['rules']
509 for pool_id
, pool
in pools
.items():
511 for rule
in [r
for r
in crush_rules
if r
['rule_id'] == pool
['crush_rule']]:
512 if rule
['min_size'] <= pool
['size'] <= rule
['max_size']:
513 pool_osds
= common
.crush_rule_osds(self
.get('osd_map_tree')['nodes'], rule
)
515 osds_by_pool
[pool_id
] = pool_osds
517 for pool_id
in pools
.keys():
518 for in_pool_id
in osds_by_pool
[pool_id
]:
519 osds
[in_pool_id
].append(pool_id
)
524 def get_osds(self
, pool_id
=None, ids
=None):
526 osd_map
= self
.get('osd_map')
527 osd_metadata
= self
.get('osd_metadata')
529 # Update the data with the additional info from the osd map
530 osds
= osd_map
['osds']
534 osds
= [x
for x
in osds
if str(x
['osd']) in ids
]
536 # Get list of pools per osd node
537 pools_map
= self
.get_osd_pools()
539 # map osd IDs to reweight
540 reweight_map
= dict([
541 (x
.get('id'), x
.get('reweight', None))
542 for x
in self
.get('osd_map_tree')['nodes']
545 # Build OSD data objects
547 osd
['pools'] = pools_map
[osd
['osd']]
548 osd
['server'] = osd_metadata
.get(str(osd
['osd']), {}).get('hostname', None)
550 osd
['reweight'] = reweight_map
.get(osd
['osd'], 0.0)
553 osd
['valid_commands'] = common
.OSD_IMPLEMENTED_COMMANDS
555 osd
['valid_commands'] = []
559 pool_id
= int(pool_id
)
560 osds
= [x
for x
in osds
if pool_id
in x
['pools']]
565 def get_osd_by_id(self
, osd_id
):
566 osd
= [x
for x
in self
.get('osd_map')['osds']
567 if x
['osd'] == osd_id
]
575 def get_pool_by_id(self
, pool_id
):
576 pool
= [x
for x
in self
.get('osd_map')['pools']
577 if x
['pool'] == pool_id
]
585 def submit_request(self
, _request
, **kwargs
):
586 with self
.requests_lock
:
587 request
= CommandsRequest(_request
)
588 self
.requests
.append(request
)
589 if kwargs
.get('wait', 0):
590 while not request
.is_finished():
595 def run_command(self
, command
):
596 # tag with 'seq' so that we can ingore these in notify function
597 result
= CommandResult('seq')
599 self
.send_command(result
, 'mon', '', json
.dumps(command
), 'seq')