molteniron/molteniron/molteniron

399 lines
13 KiB
Python
Executable File

#! /usr/bin/env python
"""
This is the MoltenIron Command Line client that speaks to
a MoltenIron server.
"""
# Copyright (c) 2016 IBM Corporation.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
# implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# pylint: disable-msg=C0103
# pylint: disable=redefined-outer-name
from __future__ import print_function
import argparse
import json
import os
import sys
import yaml
if (sys.version_info >= (3, 0)):
import http.client # noqa
else:
import httplib # noqa
DEBUG = False
# Create a decorator pattern that maintains a registry
def makeRegistrar():
"""Decorator that keeps track of tagged functions."""
registry = {}
def registrar(func):
"""Store the function pointer."""
registry[func.__name__] = func
# normally a decorator returns a wrapped function,
# but here we return func unmodified, after registering it
return func
registrar.all = registry
return registrar
# Create the decorator
command = makeRegistrar()
class MoltenIron(object):
"""This is the MoltenIron client object."""
def __init__(self):
self.conf = None
self.argv = None
self.parser = None
self.request = None
self.response_str = None
self.response_json = None
def setup_conf(self, _conf):
"""Sets the class variable to what is passed in. """
self.conf = _conf
def setup_argv(self, _argv):
"""Sets the class variable to what is passed in. """
self.argv = _argv
def setup_parser(self, _parser):
"""Sets the class variable to what is passed in. """
self.parser = _parser
def _setup_response(self):
""" """
if self.request is not None:
return
# Call the function specified on the command line!
self.request = self.argv.func()
# Send the request and print the response
self.response_str = self.send(self.request)
self.response_json = json.loads(self.response_str)
def send(self, request):
"""Send the generated request """
ip = str(self.conf['serverIP'])
port = int(self.conf['mi_port'])
if (sys.version_info > (3, 0)):
connection = http.client.HTTPConnection(ip, port) # noqa
else:
connection = httplib.HTTPConnection(ip, port) # noqa
connection.request('POST', '/', json.dumps(request))
response = connection.getresponse()
return response.read()
def get_response(self):
"""Returns the response from the server """
self._setup_response()
return self.response_str
def get_response_map(self):
"""Returns the response from the server """
self._setup_response()
return self.response_json
@command
def add(self, subparsers=None):
"""Generate a request to add a node to the MoltenIron database """
if subparsers is not None:
sp = subparsers.add_parser("add",
help="Add a node to the MoltenIron"
" database.")
sp.add_argument("name",
help="Name of the baremetal node")
sp.add_argument("ipmi_ip",
help="IP for issuing IPMI commands to"
" this node")
sp.add_argument("ipmi_user",
help="IPMI username used when issuing"
" IPMI commands to this node")
sp.add_argument("ipmi_password",
help="IPMI password used when"
" issuing IPMI commands to this node")
sp.add_argument("allocation_pool",
help="Comma separated list of"
" IPs to be used in deployment")
sp.add_argument("port_hwaddr",
help="MAC address of port on"
" machine to use during deployment")
sp.add_argument("cpu_arch",
help="Architecture of the node")
sp.add_argument("cpus",
type=int,
help="Number of CPUs on the node")
sp.add_argument("ram_mb",
type=int,
help="Amount of RAM (in MiB)"
" that the node has")
sp.add_argument("disk_gb",
type=int,
help="Amount of disk (in GiB)"
" that the node has")
sp.set_defaults(func=self.add)
return
# Make a map of our arguments
request = vars(self.argv)
# But delete the class function pointer. json can't serialize it!
del request['func']
request['method'] = 'add'
return request
@command
def allocate(self, subparsers=None):
"""Generate request to checkout a node from the MoltenIron database """
if subparsers is not None:
sp = subparsers.add_parser("allocate",
help="Checkout a node in MoltenIron."
" Returns the node's info.")
sp.add_argument("owner_name",
help="Name of the requester")
sp.add_argument("number_of_nodes",
type=int,
help="How many nodes to reserve")
sp.set_defaults(func=self.allocate)
return
# Make a map of our arguments
request = vars(self.argv)
# But delete the class function pointer. json can't serialize it!
del request['func']
request['method'] = 'allocate'
return request
@command
def release(self, subparsers=None):
"""Generate a request to release an allocated node from the MoltenIron
database
"""
if subparsers is not None:
sp = subparsers.add_parser("release",
help="Given an owner name, release the"
" allocated node, returning it to"
" the available state.")
sp.add_argument("owner_name",
help="Name of the owner who"
" currently owns the nodes to be released")
sp.set_defaults(func=self.release)
return
# Make a map of our arguments
request = vars(self.argv)
# But delete the class function pointer. json can't serialize it!
del request['func']
request['method'] = 'release'
return request
@command
def get_field(self, subparsers=None):
"""Generate a request to return a field of data from an owned node from
the MoltenIron database
"""
if subparsers is not None:
sp = subparsers.add_parser("get_field",
help="Given an owner name and the name"
" of a field, get the value of"
" the field.")
sp.add_argument("owner_name",
help="Name of the owner who currently"
" owns the nodes to get the field from")
sp.add_argument("field_name",
help="Name of the field to retrieve"
" the value from")
sp.set_defaults(func=self.get_field)
return
# Make a map of our arguments
request = vars(self.argv)
# But delete the class function pointer. json can't serialize it!
del request['func']
request['method'] = 'get_field'
return request
@command
def set_field(self, subparsers=None):
"""Generate request to set a field of data from an id in the MoltenIron
database
"""
if subparsers is not None:
sp = subparsers.add_parser("set_field",
help="Given an id, set a field with a"
" value.")
sp.add_argument("id",
help="Id of the entry")
sp.add_argument("key",
help="Field name to set")
sp.add_argument("value",
help="Field value to set")
sp.set_defaults(func=self.set_field)
return
# Make a map of our arguments
request = vars(self.argv)
# But delete the class function pointer. json can't serialize it!
del request['func']
request['method'] = 'set_field'
return request
@command
def status(self, subparsers=None):
"""Return status """
if subparsers is not None:
sp = subparsers.add_parser("status",
help="Return a list of current"
" MoltenIron Node database"
" entries.")
sp.add_argument("-t",
"--type",
action="store",
type=str,
default="human",
dest="type",
help="Either human (the default) or csv")
sp.set_defaults(func=self.status)
return
# Make a map of our arguments
request = vars(self.argv)
# But delete the class function pointer. json can't serialize it!
del request['func']
request['method'] = 'status'
return request
@command
def delete_db(self, subparsers=None):
"""Delete all database entries"""
if subparsers is not None:
sp = subparsers.add_parser("delete_db",
help="Delete every entry in the"
" MoltenIron Node database.")
sp.set_defaults(func=self.delete_db)
return
# Make a map of our arguments
request = vars(self.argv)
# But delete the class function pointer. json can't serialize it!
del request['func']
request['method'] = 'delete_db'
return request
if __name__ == "__main__":
mi = MoltenIron()
parser = argparse.ArgumentParser(description="Molteniron CLI tool")
parser.add_argument("-c",
"--conf-dir",
action="store",
type=str,
dest="conf_dir",
help="The directory where configuration is stored")
parser.add_argument("-o",
"--output",
action="store",
type=str,
default="json",
dest="output",
help="The output should be json (the default)"
" or result (only the result string)")
subparsers = parser.add_subparsers(help="sub-command help")
# Register all decorated class functions by telling them argparse
# is running
for (cmd_name, cmd_func) in list(command.all.items()):
func = getattr(mi, cmd_name)
func(subparsers) # Tell the function to setup for argparse
args = parser.parse_args()
output = args.output.upper().lower()
if output == "json":
pass
elif output == "result":
pass
else:
parser.error("Unknown output type %s" % (output, ))
if args.conf_dir:
if not os.path.isdir(args.conf_dir):
msg = "Error: %s is not a valid directory" % (args.conf_dir, )
print(msg, file=sys.stderr)
sys.exit(1)
yaml_file = os.path.realpath("%s/conf.yaml" % (args.conf_dir, ))
else:
yaml_file = "/usr/local/etc/molteniron/conf.yaml"
with open(yaml_file, "r") as fobj:
conf = yaml.load(fobj)
mi.setup_conf(conf)
mi.setup_argv(args)
mi.setup_parser(parser)
ret = mi.get_response()
json_ret = json.loads(ret)
if output == "json":
print(json_ret)
elif output == "result":
print(json_ret["result"])
try:
rc = mi.get_response_map()['status']
except KeyError:
print("Error: Server returned: %s" % (mi.get_response_map(),))
rc = 444
if rc == 200:
exit(0)
else:
exit(rc)