Commit f05131a8 authored by Cédric Le Ninivin's avatar Cédric Le Ninivin

slap command line: update request and supply to use jIO API

parent 1673c4c2
...@@ -27,6 +27,7 @@ ...@@ -27,6 +27,7 @@
# #
############################################################################## ##############################################################################
import json
import pprint import pprint
from slapos.cli.config import ClientConfigCommand from slapos.cli.config import ClientConfigCommand
...@@ -105,19 +106,46 @@ def do_request(logger, conf, local): ...@@ -105,19 +106,46 @@ def do_request(logger, conf, local):
if conf.software_url in local: if conf.software_url in local:
conf.software_url = local[conf.software_url] conf.software_url = local[conf.software_url]
try: try:
partition = local['slap'].registerOpenOrder().request( if local['slap'].jio_api_connector:
software_release=conf.software_url, request_dict = {
partition_reference=conf.reference, "title": conf.reference,
partition_parameter_kw=conf.parameters, "portal_type": "Software Instance",
software_type=conf.type, "software_release_uri": conf.software_url,
filter_kw=conf.node, }
state=conf.state, if conf.state:
shared=conf.slave request_dict['state'] = conf.state
) if conf.slave:
logger.info('Instance requested.\nState is : %s.', partition.getState()) request_dict["shared"] = True
logger.info('Connection parameters of instance are:') if conf.node:
logger.info(pprint.pformat(partition.getConnectionParameterDict())) request_dict["sla_parameters"] = conf.node
logger.info('You can rerun the command to get up-to-date information.') if conf.parameters:
request_dict["parameters"] = json.dumps(conf.parameters)
if conf.type:
request_dict["software_type"] = conf.type
partition_dict = local['slap'].jio_api_connector.post(request_dict)
if "$schema" in partition_dict and "error-response-schema.json" in partition_dict["$schema"]:
logger.warning('Server Response: %s' % json.dumps(partition_dict, indent=2))
logger.warning('Instance requested. Master is provisioning it. Please rerun in a '
'couple of minutes to get connection information.')
exit(2)
logger.info('Instance requested.\nState is : %s.', partition_dict["state"])
logger.info('Connection parameters of instance are:')
logger.info(pprint.pformat(partition_dict["connection_parameters"]))
logger.info('You can rerun the command to get up-to-date information.')
else:
partition = local['slap'].registerOpenOrder().request(
software_release=conf.software_url,
partition_reference=conf.reference,
partition_parameter_kw=conf.parameters,
software_type=conf.type,
filter_kw=conf.node,
state=conf.state,
shared=conf.slave
)
logger.info('Instance requested.\nState is : %s.', partition.getState())
logger.info('Connection parameters of instance are:')
logger.info(pprint.pformat(partition.getConnectionParameterDict()))
logger.info('You can rerun the command to get up-to-date information.')
except ResourceNotReady: except ResourceNotReady:
logger.warning('Instance requested. Master is provisioning it. Please rerun in a ' logger.warning('Instance requested. Master is provisioning it. Please rerun in a '
'couple of minutes to get connection information.') 'couple of minutes to get connection information.')
......
...@@ -27,6 +27,8 @@ ...@@ -27,6 +27,8 @@
# #
############################################################################## ##############################################################################
import json
from slapos.cli.config import ClientConfigCommand from slapos.cli.config import ClientConfigCommand
from slapos.client import init, ClientConfig, _getSoftwareReleaseFromSoftwareString from slapos.client import init, ClientConfig, _getSoftwareReleaseFromSoftwareString
...@@ -63,10 +65,21 @@ def do_supply(logger, software_release, computer_id, local): ...@@ -63,10 +65,21 @@ def do_supply(logger, software_release, computer_id, local):
software_release = _getSoftwareReleaseFromSoftwareString( software_release = _getSoftwareReleaseFromSoftwareString(
logger, software_release, local['product']) logger, software_release, local['product'])
if local['slap'].jio_api_connector:
local['supply']( software_installation = local['slap'].jio_api_connector.post({
software_release=software_release, "portal_type": "Software Installation",
computer_guid=computer_id, "software_release_uri": software_release,
state='available' "compute_node_id": computer_id,
) "state": 'available'
})
if "$schema" in software_installation and "error-response-schema.json" in software_installation["$schema"]:
logger.warning('Issue during the request. Server Response: %s' % json.dumps(software_installation, indent=2))
logger.warning('Message: %s' % software_installation.get("message", ""))
exit(2)
else:
local['supply'](
software_release=software_release,
computer_guid=computer_id,
state='available'
)
logger.info('Done.') logger.info('Done.')
...@@ -88,7 +88,8 @@ class ConnectionHelper: ...@@ -88,7 +88,8 @@ class ConnectionHelper:
self.session = CacheControl(self.uncached_session, self.session = CacheControl(self.uncached_session,
cache=FileCache(os.path.expanduser("~/.slapos_cached_get"))) cache=FileCache(os.path.expanduser("~/.slapos_cached_get")))
def do_request(self, method, path, params=None, data=None, headers=None): def do_request(self, method, path, params=None, data=None, headers=None,
expect_json_error=False):
url = parse.urljoin(self.slapgrid_uri, path) url = parse.urljoin(self.slapgrid_uri, path)
if headers is None: if headers is None:
headers = {} headers = {}
...@@ -108,7 +109,7 @@ class ConnectionHelper: ...@@ -108,7 +109,7 @@ class ConnectionHelper:
# Old behavior was to pass empty parameters as "None" value. # Old behavior was to pass empty parameters as "None" value.
# Behavior kept for compatibility with old slapproxies (< v1.3.3). # Behavior kept for compatibility with old slapproxies (< v1.3.3).
# Can be removed when old slapproxies are no longer in use. # Can be removed when old slapproxies are no longer in use.
if data: if data and isinstance(data, dict):
for k, v in six.iteritems(data): for k, v in six.iteritems(data):
if v is None: if v is None:
data[k] = 'None' data[k] = 'None'
...@@ -133,6 +134,8 @@ class ConnectionHelper: ...@@ -133,6 +134,8 @@ class ConnectionHelper:
"enabled on your machine and that the server is available. The " "enabled on your machine and that the server is available. The "
"original error was:\n%s" % exc) "original error was:\n%s" % exc)
except requests.HTTPError as exc: except requests.HTTPError as exc:
if expect_json_error and not int(exc.response.status_code) >= 500:
return req
if exc.response.status_code == requests.status_codes.codes.not_found: if exc.response.status_code == requests.status_codes.codes.not_found:
msg = url msg = url
if params: if params:
......
...@@ -719,7 +719,34 @@ class SlapConnectionHelper(ConnectionHelper): ...@@ -719,7 +719,34 @@ class SlapConnectionHelper(ConnectionHelper):
return loads(xml) return loads(xml)
class JioAPIConnectionHelper(ConnectionHelper):
def apiCall(self, path, data):
req = self.do_request(requests.post,
path=path,
data=json.dumps(data),
headers={'Content-type': 'application/json'},
expect_json_error=True)
return req.json()
def get(self, data):
return self.apiCall(path="get/",
data=data)
def post(self, data):
return self.apiCall(path="post/",
data=data)
def put(self, data):
return self.apiCall(path="put/",
data=data)
def allDocs(self, data):
return self.apiCall(path="allDocs/",
data=data)
getHateoasUrl_cache = {} getHateoasUrl_cache = {}
getjIOAPI_cache = {}
@implementer(interface.slap) @implementer(interface.slap)
class slap: class slap:
...@@ -727,10 +754,10 @@ class slap: ...@@ -727,10 +754,10 @@ class slap:
key_file=None, cert_file=None, key_file=None, cert_file=None,
master_ca_file=None, master_ca_file=None,
timeout=60, timeout=60,
slapgrid_rest_uri=None): slapgrid_rest_uri=None,
slapgrid_jio_uri=None):
if master_ca_file: if master_ca_file:
raise NotImplementedError('Master certificate not verified in this version: %s' % master_ca_file) raise NotImplementedError('Master certificate not verified in this version: %s' % master_ca_file)
self._connection_helper = SlapConnectionHelper( self._connection_helper = SlapConnectionHelper(
slapgrid_uri, key_file, cert_file, master_ca_file, timeout) slapgrid_uri, key_file, cert_file, master_ca_file, timeout)
...@@ -755,6 +782,27 @@ class slap: ...@@ -755,6 +782,27 @@ class slap:
else: else:
self._hateoas_navigator = None self._hateoas_navigator = None
if not slapgrid_jio_uri:
getjIOAPI_cache_key = (slapgrid_uri, key_file, cert_file, master_ca_file, timeout)
try:
slapgrid_jio_uri = getjIOAPI_cache[getjIOAPI_cache_key]
except KeyError:
pass
if not slapgrid_jio_uri:
try:
slapgrid_jio_uri = getjIOAPI_cache[getjIOAPI_cache_key] = \
bytes2str(self._connection_helper.GET('getJIOAPIUrl'))
except:
pass
if slapgrid_jio_uri:
self.jio_api_connector = JioAPIConnectionHelper(
slapgrid_jio_uri,
key_file, cert_file,
master_ca_file, timeout
)
else:
self.jio_api_connector = None
# XXX-Cedric: this method is never used and thus should be removed. # XXX-Cedric: this method is never used and thus should be removed.
def registerSoftwareRelease(self, software_release): def registerSoftwareRelease(self, software_release):
""" """
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment