Commit 2c33ccfe authored by Rafael Monnerat's avatar Rafael Monnerat

slapos/slap: Add API to get Computer information

parent cde0ec75
...@@ -110,6 +110,8 @@ setup(name=name, ...@@ -110,6 +110,8 @@ setup(name=name,
'configure client = slapos.cli.configure_client:ConfigureClientCommand', 'configure client = slapos.cli.configure_client:ConfigureClientCommand',
'service info = slapos.cli.info:InfoCommand', 'service info = slapos.cli.info:InfoCommand',
'service list = slapos.cli.list:ListCommand', 'service list = slapos.cli.list:ListCommand',
'computer list = slapos.cli.computer_list:ListCommand',
'computer info = slapos.cli.computer_info:InfoCommand',
'supply = slapos.cli.supply:SupplyCommand', 'supply = slapos.cli.supply:SupplyCommand',
'remove = slapos.cli.remove:RemoveCommand', 'remove = slapos.cli.remove:RemoveCommand',
'request = slapos.cli.request:RequestCommand', 'request = slapos.cli.request:RequestCommand',
......
# -*- coding: utf-8 -*-
##############################################################################
#
# Copyright (c) 2010-2014 Vifib SARL and Contributors.
# All Rights Reserved.
#
# WARNING: This program as such is intended to be used by professional
# programmers who take the whole responsibility of assessing all potential
# consequences resulting from its eventual inadequacies and bugs
# End users who are looking for a ready-to-use solution with commercial
# guarantees and support are strongly adviced to contract a Free Software
# Service Company
#
# This program is Free Software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public License
# as published by the Free Software Foundation; either version 2.1
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
#
##############################################################################
import logging
import pprint
import sys
from slapos.cli.config import ClientConfigCommand
from slapos.client import init, ClientConfig
from slapos.slap import ResourceNotReady, NotFoundError
def resetLogger(logger):
"""Remove all formatters, log files, etc."""
if not getattr(logger, 'parent', None):
return
handler = logger.parent.handlers[0]
logger.parent.removeHandler(handler)
logger.addHandler(logging.StreamHandler(sys.stdout))
class InfoCommand(ClientConfigCommand):
"""get information of an computer"""
def get_parser(self, prog_name):
ap = super(InfoCommand, self).get_parser(prog_name)
ap.add_argument('reference',
help='Your computer reference')
return ap
def take_action(self, args):
configp = self.fetch_config(args)
conf = ClientConfig(args, configp)
local = init(conf, self.app.log)
exit_code = do_info(self.app.log, conf, local)
if exit_code != 0:
exit(exit_code)
def do_info(logger, conf, local):
resetLogger(logger)
try:
computer = local['slap'].registerComputer(conf.reference).getInformation()
except ResourceNotReady:
logger.warning('Computer does not exist or is not ready yet.')
return(2)
except NotFoundError:
logger.warning('Computer %s does not exist.', conf.reference)
return(2)
import pdb;pdb.set_trace()
logger.info('Computer Reference: %s', computer._reference)
# -*- coding: utf-8 -*-
##############################################################################
#
# Copyright (c) 2010-2014 Vifib SARL and Contributors.
# All Rights Reserved.
#
# WARNING: This program as such is intended to be used by professional
# programmers who take the whole responsibility of assessing all potential
# consequences resulting from its eventual inadequacies and bugs
# End users who are looking for a ready-to-use solution with commercial
# guarantees and support are strongly adviced to contract a Free Software
# Service Company
#
# This program is Free Software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public License
# as published by the Free Software Foundation; either version 2.1
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
#
##############################################################################
import logging
import sys
import six
from slapos.cli.config import ClientConfigCommand
from slapos.client import init, ClientConfig
def resetLogger(logger):
"""Remove all formatters, log files, etc."""
if not getattr(logger, 'parent', None):
return
handler = logger.parent.handlers[0]
logger.parent.removeHandler(handler)
logger.addHandler(logging.StreamHandler(sys.stdout))
class ListCommand(ClientConfigCommand):
"""request an instance and get status and parameters of instance"""
def get_parser(self, prog_name):
ap = super(ListCommand, self).get_parser(prog_name)
return ap
def take_action(self, args):
configp = self.fetch_config(args)
conf = ClientConfig(args, configp)
local = init(conf, self.app.log)
do_list(self.app.log, conf, local)
def do_list(logger, conf, local):
resetLogger(logger)
computer_dict = local['slap'].getComputerDict()
if computer_dict == {}:
logger.info('No existing computer.')
return
logger.info('List of Computers:')
for title, computer in six.iteritems(computer_dict):
logger.info('%s %s', computer._reference, title)
...@@ -301,18 +301,13 @@ class HateoasNavigator(object): ...@@ -301,18 +301,13 @@ class HateoasNavigator(object):
return self._extractPropertyFromFormDict(document_dict) return self._extractPropertyFromFormDict(document_dict)
def getDocumentAndHateoas(self, relative_url, view='view'): def jio_getAttachment(self, key, action, options):
site_document = self.getRootDocument() pass
return expand(
site_document['_links']['traverse']['href'],
dict(relative_url=relative_url, view=view)
)
def getMeDocument(self): def getMeDocument(self):
person_relative_url = self.getRelativeUrlFromUrn( person_relative_url = self.getRelativeUrlFromUrn(
self.getRootDocument()['_links']['me']['href']) self.getRootDocument()['_links']['me']['href'])
person_url = self.getDocumentAndHateoas(person_relative_url) return self.jio_get(person_relative_url)
return json.loads(self.GET(person_url))
class SlapHateoasNavigator(HateoasNavigator): class SlapHateoasNavigator(HateoasNavigator):
def _getHostingSubscriptionList(self, title=None, select_list=["title", "url_string"]): def _getHostingSubscriptionList(self, title=None, select_list=["title", "url_string"]):
...@@ -325,6 +320,20 @@ class SlapHateoasNavigator(HateoasNavigator): ...@@ -325,6 +320,20 @@ class SlapHateoasNavigator(HateoasNavigator):
return result['data']['rows'] return result['data']['rows']
def _getComputerList(self, title=None, reference=None, select_list=["title", "reference"]):
query_str = 'portal_type:"Computer" AND validation_state:validated'
if title is not None:
query_str += ' AND title:="%s"' % title
if reference is not None:
query_str += ' AND reference:="%s"' % reference
result = self.jio_allDocs(
query={"query" : query_str, "select_list": select_list})
return result['data']['rows']
def _hateoas_getRelatedHostingSubscription(self): def _hateoas_getRelatedHostingSubscription(self):
action_object_slap_list = self.getMeDocument()['_links']['action_object_slap'] action_object_slap_list = self.getMeDocument()['_links']['action_object_slap']
getter_link = self.hateoasGetLinkFromLinks(action_object_slap_list, 'getHateoasRelatedHostingSubscription') getter_link = self.hateoasGetLinkFromLinks(action_object_slap_list, 'getHateoasRelatedHostingSubscription')
...@@ -361,11 +370,24 @@ class SlapHateoasNavigator(HateoasNavigator): ...@@ -361,11 +370,24 @@ class SlapHateoasNavigator(HateoasNavigator):
return hosting_subscription_dict return hosting_subscription_dict
def getComputerDict(self):
computer_list = self._getComputerList()
computer_dict = {}
for computer_json in computer_list:
computer = TempDocument()
for key, value in computer_json.iteritems():
if key in ['_links']:
continue
setattr(computer, '_%s' % key, value)
computer_dict[computer._title] = computer
return computer_dict
def getHostingSubscriptionRootSoftwareInstanceInformation(self, reference): def getHostingSubscriptionRootSoftwareInstanceInformation(self, reference):
hosting_subscription_list = self._getHostingSubscriptionList(title=reference, hosting_subscription_list = self._getHostingSubscriptionList(title=reference,
select_list=["title", "relative_url"]) select_list=["title", "relative_url"])
assert len(hosting_subscription_list) == 1, \ assert len(hosting_subscription_list) <= 1, \
"There are more them one Hosting Subscription for this reference" "There are more them one Hosting Subscription for this reference"
for hosting_subscription_candidate in hosting_subscription_list: for hosting_subscription_candidate in hosting_subscription_list:
...@@ -376,7 +398,6 @@ class SlapHateoasNavigator(HateoasNavigator): ...@@ -376,7 +398,6 @@ class SlapHateoasNavigator(HateoasNavigator):
if hosting_subscription_jio_key is None: if hosting_subscription_jio_key is None:
raise NotFoundError('This document does not exist.') raise NotFoundError('This document does not exist.')
return self.jio_get(hosting_subscription_jio_key) return self.jio_get(hosting_subscription_jio_key)
def getRelatedInstanceInformation(self, reference): def getRelatedInstanceInformation(self, reference):
...@@ -386,14 +407,22 @@ class SlapHateoasNavigator(HateoasNavigator): ...@@ -386,14 +407,22 @@ class SlapHateoasNavigator(HateoasNavigator):
instance = self._hateoasGetInformation(instance_url) instance = self._hateoasGetInformation(instance_url)
return instance return instance
def _hateoas_getComputer(self, reference): def _getComputer(self, reference):
content_list = json.loads(result)['_embedded']['contents'] computer_list = self._getComputerList(reference=reference,
if len(content_list) == 0: select_list=["reference", "relative_url"])
raise Exception('No Computer found.')
assert len(computer_list) <= 1, \
"There are more them one Computer for this reference"
for computer_candidate in computer_list:
if computer_candidate.get("reference") == reference:
computer_jio_key = computer_candidate['relative_url']
break
if computer_jio_key is None:
raise NotFoundError('This computer does not exist.')
computer_relative_url = content_list[0]["relative_url"] return self.jio_get(computer_jio_key)
getter_url = self.getDocumentAndHateoas(computer_relative_url)
return json.loads(self.GET(getter_url))
def getSoftwareInstallationList(self, computer_guid=None): def getSoftwareInstallationList(self, computer_guid=None):
computer = self._hateoas_getComputer(computer_guid) \ computer = self._hateoas_getComputer(computer_guid) \
......
...@@ -362,6 +362,19 @@ class Computer(SlapDocument): ...@@ -362,6 +362,19 @@ class Computer(SlapDocument):
'computer_id': self._computer_id}) 'computer_id': self._computer_id})
return loads(xml) return loads(xml)
def getInformation(self):
if not getattr(self, '_hateoas_navigator', None):
raise Exception('SlapOS Master Hateoas API required for this operation is not availble.')
raw_information = self._hateoas_navigator._getComputer(reference=self._computer_id)
computer = Computer(self._computer_id)
for key, value in six.iteritems(raw_information["data"]):
if key in ['_links']:
continue
setattr(computer, '_%s' % key, value)
return computer
def parsed_error_message(status, body, path): def parsed_error_message(status, body, path):
m = re.search('(Error Value:\n.*)', body, re.MULTILINE) m = re.search('(Error Value:\n.*)', body, re.MULTILINE)
...@@ -796,3 +809,9 @@ class slap: ...@@ -796,3 +809,9 @@ class slap:
if not getattr(self, '_hateoas_navigator', None): if not getattr(self, '_hateoas_navigator', None):
raise Exception('SlapOS Master Hateoas API required for this operation is not availble.') raise Exception('SlapOS Master Hateoas API required for this operation is not availble.')
return self._hateoas_navigator.getHostingSubscriptionDict() return self._hateoas_navigator.getHostingSubscriptionDict()
def getComputerDict(self):
if not getattr(self, '_hateoas_navigator', None):
raise Exception('SlapOS Master Hateoas API required for this operation is not availble.')
return self._hateoas_navigator.getComputerDict()
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