Add 'geissonator/openbmc-events/' from commit '23da2739fc6fc375146d6fcf0e13de5eec8e6c0c'

git-subtree-dir: geissonator/openbmc-events
git-subtree-mainline: 2581388036ea7c35eea1db8343fbe51ff622ef71
git-subtree-split: 23da2739fc6fc375146d6fcf0e13de5eec8e6c0c
diff --git a/geissonator/openbmc-events/LICENSE b/geissonator/openbmc-events/LICENSE
new file mode 100644
index 0000000..cf1ab25
--- /dev/null
+++ b/geissonator/openbmc-events/LICENSE
@@ -0,0 +1,24 @@
+This is free and unencumbered software released into the public domain.
+
+Anyone is free to copy, modify, publish, use, compile, sell, or
+distribute this software, either in source code form or as a compiled
+binary, for any purpose, commercial or non-commercial, and by any
+means.
+
+In jurisdictions that recognize copyright laws, the author or authors
+of this software dedicate any and all copyright interest in the
+software to the public domain. We make this dedication for the benefit
+of the public at large and to the detriment of our heirs and
+successors. We intend this dedication to be an overt act of
+relinquishment in perpetuity of all present and future rights to this
+software under copyright law.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
+OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
+ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
+OTHER DEALINGS IN THE SOFTWARE.
+
+For more information, please refer to <http://unlicense.org>
diff --git a/geissonator/openbmc-events/README.md b/geissonator/openbmc-events/README.md
new file mode 100644
index 0000000..5a2bef1
--- /dev/null
+++ b/geissonator/openbmc-events/README.md
@@ -0,0 +1,5 @@
+# openbmc-events
+
+openbmc-event: Tool to query error events on the target server
+
+openbmc-sfw: Tool to query and update HOST and BMC images on the target server
diff --git a/geissonator/openbmc-events/openbmc-events b/geissonator/openbmc-events/openbmc-events
new file mode 100755
index 0000000..49ba69d
--- /dev/null
+++ b/geissonator/openbmc-events/openbmc-events
@@ -0,0 +1,208 @@
+#!/bin/env python
+
+import argparse
+import requests
+import json
+
+import urllib3
+from warnings import catch_warnings
+urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
+
+
+class BMC:
+    def __init__(self, server):
+        self.url = "https://{0}/".format(server)
+        self.session = requests.Session()
+        self.login()
+
+    def login(self):
+        r = self.session.post(self.url + 'login',
+                              json={'data': ['root', '0penBmc']},
+                              verify=False)
+        j = r.json()
+        if j['status'] != 'ok':
+            raise Exception("Failed to login: \n" + r.text)
+
+    def list_events(self):
+        r = self.session.get(self.url + 'xyz/openbmc_project/logging/entry/',
+                             verify=False)
+        j = r.json()
+        if j['message'] == '404 Not Found':
+            print "No error logs on system\n"
+            return
+        if j['status'] != 'ok':
+            raise Exception("Failed to query entries: \n" + r.text)
+
+        events = j['data']
+        events.sort(key=lambda x: int(x.split("/")[-1]))
+
+        return events
+
+    def get_event(self, event):
+        r = self.session.get(self.url + event, verify=False)
+
+        j = r.json()
+        if j['status'] != 'ok':
+            raise Exception("Failed to get event " + event + ": \n" + r.text)
+
+        return j['data']
+    
+    def clear_event(self,event):
+        r = self.session.delete(self.url + event)
+        j = r.json()
+        if j['status'] != 'ok':
+            raise Exception("Failed to clear event " + event + ": \n" + r.text)
+
+    def clear_all_events(self):
+        r = self.session.post(self.url + 'xyz/openbmc_project/logging/action/deleteall',
+                             headers={'Content-Type': 'application/json'},
+                             data='{"data":[]}',
+                             verify=False)
+        j = r.json()
+        if j['status'] != 'ok':
+            raise Exception("Failed to clear all events\n" + r.text)
+
+    def list_dumps(self):
+        r = self.session.get(self.url + 'xyz/openbmc_project/dump/entry/',
+                             verify=False)
+        j = r.json()
+        if j['status'] != 'ok':
+            raise Exception("Failed to list dumps: \n" + r.text)
+
+        dumps = j['data']
+        dumps.sort(key=lambda x: int(x.split("/")[-1]))
+
+        return dumps
+    
+    def create_dump(self):
+        r = self.session.post(self.url + 'xyz/openbmc_project/dump/action/CreateDump')
+        j = r.json()
+        if j['status'] != 'ok':
+            raise Exception("Failed to create dump: \n" + r.text)
+        
+    def get_dump(self,dump):
+        r = self.session.get(self.url + dump,
+                             verify=False)
+        j = r.json()
+        if j['status'] != 'ok':
+            raise Exception("Failed to get dump " + event + ": \n" + r.text)
+
+    def clear_dump(self,dump):
+        r = self.session.delete(self.url + dump)
+        j = r.json()
+        if j['status'] != 'ok':
+            raise Exception("Failed to clear dump " + dump + ": \n" + r.text)        
+
+def do_list_events(args):
+    s = BMC(server=args.server)
+    try:
+        for e in s.list_events():
+            print(e)
+    except:
+        # ignore if we get nothing back
+        return;
+
+
+def do_view_event(args):
+    s = BMC(server=args.server)
+    print json.dumps(s.get_event(args.event), indent=4)
+
+def do_clear_event(args):
+    s = BMC(server=args.server)
+    s.clear_event(args.event)
+
+def do_clear_all_events(args):
+    s = BMC(server=args.server)
+    s.clear_all_events()
+
+def do_list_dumps(args):
+    s = BMC(server=args.server)
+    for e in s.list_dumps():
+        print(e)
+
+def do_create_dump(args):
+    s = BMC(server=args.server)
+    s.create_dump()
+    
+def do_get_dump(args):
+    s = BMC(server=args.server)
+    s.get_dump(args.dump)
+
+def do_clear_dump(args):
+    s = BMC(server=args.server)
+    s.clear_dump(args.dump)
+
+def do_get_esel(args):
+    s = BMC(server=args.server)
+    e = s.get_event(args.event)
+    if e['Message'] != 'org.open_power.Error.Host.Event' and\
+       e['Message'] != 'org.open_power.Error.Host.Event.Event':
+        raise Exception("Event is not from Host: " + e['Message'])
+    for d in e['AdditionalData']:
+        data = d.split("=")
+        tag = data.pop(0)
+        if tag != 'ESEL':
+            continue
+        data = "=".join(data)
+        if args.binary:
+            data = data.split(" ")
+            if '' == data[-1]:
+                data.pop()
+            data = "".join(map(lambda x: chr(int(x, 16)), data))
+        print(data)
+
+
+parser = argparse.ArgumentParser()
+parser.add_argument('--server', help='hostname or IP of BMC', type=str,
+                    required=True)
+
+subparsers = parser.add_subparsers()
+
+list_events = subparsers.add_parser('list', help='List all events on BMC')
+list_events.set_defaults(func=do_list_events)
+
+view_event = subparsers.add_parser(
+    'view', help='View all data for an individual event')
+view_event.add_argument('event', help='The event to view')
+view_event.set_defaults(func=do_view_event)
+
+get_esel = subparsers.add_parser(
+    'get-esel', help='Extract OpenPOWER eSEL data for an individual event')
+get_esel.add_argument('event', help='The event to get eSEL from')
+get_esel.add_argument('--binary', help='Print event in raw binary',
+                      action='store_const', const=True)
+get_esel.set_defaults(func=do_get_esel)
+
+clear_event = subparsers.add_parser(
+    'clear', help="Clear individual event")
+clear_event.add_argument('event', help="The event to clear")
+clear_event.set_defaults(func=do_clear_event)
+
+clear_all_events = subparsers.add_parser(
+    'clear-all', help="Clear all event")
+clear_all_events.set_defaults(func=do_clear_all_events)
+
+list_dumps = subparsers.add_parser(
+    'list-dumps', help="List all dumps")
+list_dumps.set_defaults(func=do_list_dumps)
+
+create_dump = subparsers.add_parser(
+    'create-dump', help="Create a dump")
+create_dump.set_defaults(func=do_create_dump)
+
+get_dump = subparsers.add_parser(
+    'get-dump', help="Get a dump")
+get_dump.add_argument('dump', help="The dump to get")
+get_dump.set_defaults(func=do_get_dump)
+
+clear_dump = subparsers.add_parser(
+    'clear-dump', help="Clear individual dump")
+clear_dump.add_argument('dump', help="The dump to clear")
+clear_dump.set_defaults(func=do_clear_dump)
+
+args = parser.parse_args()
+
+if 'func' in args:
+    args.func(args)
+else:
+    parser.print_help()
diff --git a/geissonator/openbmc-events/openbmc-sensors b/geissonator/openbmc-events/openbmc-sensors
new file mode 100755
index 0000000..c54dc97
--- /dev/null
+++ b/geissonator/openbmc-events/openbmc-sensors
@@ -0,0 +1,75 @@
+#!/bin/env python
+
+import argparse
+import requests
+import json
+
+import urllib3
+urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
+
+
+class BMC:
+    def __init__(self, server):
+        self.url = "https://{0}/".format(server)
+        self.session = requests.Session()
+        self.login()
+
+    def login(self):
+        r = self.session.post(self.url + 'login',
+                              json={'data': ['root', '0penBmc']},
+                              verify=False)
+        j = r.json()
+        if j['status'] != 'ok':
+            raise Exception("Failed to login: \n" + r.text)
+
+    def list_all(self):
+        r = self.session.get(self.url + 'xyz/openbmc_project/sensors/enumerate',
+                             verify=False)
+        j = r.json()
+        if j['status'] != 'ok':
+            raise Exception("Failed to query sensors: \n" + r.text)
+
+        sensors = j['data']
+        #sensors.sort(key=lambda x: int(x.split("/")[-1]))
+
+        return sensors
+
+    def get_sensor(self, sensor):
+        r = self.session.get(self.url + sensor, verify=False)
+
+        j = r.json()
+        if j['status'] != 'ok':
+            raise Exception("Failed to get sensor " + sensor + ": \n" + r.text)
+
+        return j['data']      
+
+def do_list_all(args):
+    s = BMC(server=args.server)
+    for e in s.list_all():
+        print(e)
+
+def do_view_sensor(args):
+    s = BMC(server=args.server)
+    print(s.get_sensor(args.sensor))
+    print json.dumps(s.get_sensor(args.sensor), indent=4)
+
+parser = argparse.ArgumentParser()
+parser.add_argument('--server', help='hostname or IP of BMC', type=str,
+                    required=True)
+
+subparsers = parser.add_subparsers()
+
+list_all_sensors = subparsers.add_parser('list', help='List all sensors on BMC')
+list_all_sensors.set_defaults(func=do_list_all)
+
+view_sensor = subparsers.add_parser(
+    'view', help='View all data for an individual sensor')
+view_sensor.add_argument('sensor', help='The sensor to view')
+view_sensor.set_defaults(func=do_view_sensor)
+
+args = parser.parse_args()
+
+if 'func' in args:
+    args.func(args)
+else:
+    parser.print_help()
diff --git a/geissonator/openbmc-events/openbmc-sfw b/geissonator/openbmc-events/openbmc-sfw
new file mode 100755
index 0000000..67a8ec3
--- /dev/null
+++ b/geissonator/openbmc-events/openbmc-sfw
@@ -0,0 +1,256 @@
+#!/usr/bin/env python
+
+import argparse
+import requests
+import tarfile
+import time
+import json
+
+class BMC:
+    def __init__(self, server):
+        self.url = "https://{0}/".format(server)
+        self.session = requests.Session()
+        self.login()
+
+    def login(self):
+        r = self.session.post(self.url + 'login',
+                              json={'data': ['root', '0penBmc']},
+                              verify=False)
+        j = r.json()
+        if j['status'] != 'ok':
+            raise Exception("Failed to login: \n" + r.text)
+
+    def list_sfw(self):
+        r = self.session.get(self.url + 'xyz/openbmc_project/software/',
+                             verify=False)
+        j = r.json()
+        if j['status'] != 'ok':
+            raise Exception("Failed to query software: \n" + r.text)
+
+        events = j['data']
+
+        return events
+
+    def get_image(self, image):
+        r = self.session.get(self.url + image, verify=False)
+
+        j = r.json()
+        if j['status'] != 'ok':
+            raise Exception("Failed to get image " + image + ": \n" + r.text)
+
+        return j['data']
+
+    def upload_image(self, image):
+
+        data = open(image,'rb').read()
+        r = self.session.post(self.url + "/upload/image",
+                              data=data,
+                              headers={'Content-Type': 'application/octet-stream'},
+                              verify=False)
+        j = r.json()
+        if j['status'] != 'ok':
+            raise Exception("Failed to get event " + image + ": \n" + r.text)
+
+        return j['data']
+
+    def activate_image(self, image_id):
+        r = self.session.put(self.url + "/xyz/openbmc_project/software/" + image_id + "/attr/RequestedActivation",
+                             json={'data': 'xyz.openbmc_project.Software.Activation.RequestedActivations.Active'},
+                             verify=False)
+
+        j = r.json()
+        if j['status'] != 'ok':
+            raise Exception("Failed to activate image " + image_id + ": \n" + r.text)
+
+        return j['data']
+
+    def set_priority(self, image_id, priority):
+        r = self.session.put(self.url + "/xyz/openbmc_project/software/" + image_id + "/attr/Priority",
+                             json={'data': int(priority)},
+                             verify=False)
+
+        j = r.json()
+        if j['status'] != 'ok':
+            raise Exception("Failed to set priority of image " + image_id + ": \n" + r.text)
+
+        return j['data']
+
+    def delete_image(self, image_id):
+        r = self.session.post(self.url + "/xyz/openbmc_project/software/" + image_id + "/action/delete",
+                            headers={'Content-Type': 'application/json'},
+                            data='{"data":[]}',
+                            verify=False)
+
+        j = r.json()
+        if j['status'] != 'ok':
+            raise Exception("Failed to delete image " + image_id + ": \n" + r.text)
+
+        return j['data']
+
+    def update_auto(self, image, reboot):
+        image_version = self.__get_image_version(image)
+        self.upload_image(image)
+        image_id = self.__wait_for_image_id(image_version)
+        self.activate_image(image_id)
+        self.__wait_for_activation(image_id)
+        if reboot:
+            self.reboot()
+
+    def reboot(self):
+        r = self.session.post(
+            self.url + '/org/openbmc/control/bmc0/action/warmReset',
+            headers={'Content-Type': 'application/json'},
+            data='{"data":[]}',
+            verify=False)
+
+        j = r.json()
+        if j['status'] != 'ok':
+            raise Exception("Failed to reboot BMC:\n" + r.text)
+
+    def __get_image_version(self, image_file_path):
+        # Open up the manfest file.
+        image_tar = tarfile.open(name=image_file_path, mode='r')
+        manifest = image_tar.extractfile('MANIFEST')
+
+        # Find version line.
+        for line in manifest:
+            if line.startswith('version='):
+                manifest.close()
+                image_tar.close()
+                return line.split('version=', 1)[1].strip()
+
+        # If we didn't find the version line, print an error and return false.
+        manifest.close()
+        image_tar.close()
+        raise Exception("Could not find version line in image manifest")
+
+    def __wait_for_image_id(self, image_version):
+        # Try 8 times, once every 15 seconds.
+        for attempt in range(8):
+            software = self.list_sfw()
+            # Look for our the image with the given version in software
+            for path in software:
+                image = self.get_image(path)
+                if 'Version' in image and image_version == image['Version']:
+                    return path.split('/')[-1]
+            time.sleep(15)
+        return False
+
+    def __wait_for_activation(self, image_id):
+        # Keep waiting until the image is active or activation fails.
+        active = False
+        while not active:
+            image = self.get_image("/xyz/openbmc_project/software/" + image_id)
+            if 'xyz.openbmc_project.Software.Activation.Activations.Active' \
+                    == image['Activation']:
+                print 'Activation Progress: 100%'
+                active = True
+            elif 'xyz.openbmc_project.Software.Activation.Activations.Activating' \
+                    == image['Activation']:
+                print 'Activation Progress: ' + str(image['Progress']) + '%'
+            else:
+                raise Exception("Image activation failed. The BMC has set " \
+                    + "the'Activation' property to " + image['Activation'])
+            time.sleep(15)
+
+def do_list_sfw(args):
+    s = BMC(server=args.server)
+    for e in s.list_sfw():
+        if (e == '/xyz/openbmc_project/software/active'):
+            continue
+        if (e == '/xyz/openbmc_project/software/functional'):
+            continue
+        info = s.get_image(e)
+        if (((info['Purpose'] == 'xyz.openbmc_project.Software.Version.VersionPurpose.BMC') and 
+             (args.bmc or not args.host)) or \
+           ((info['Purpose'] == 'xyz.openbmc_project.Software.Version.VersionPurpose.Host') and
+            (args.host or not args.bmc))):
+            print(e)
+            print json.dumps(info, indent=4)
+
+def do_view_image(args):
+    s = BMC(server=args.server)
+    print json.dumps(s.get_image(args.image), indent=4)
+
+def do_upload_image(args):
+    s = BMC(server=args.server)
+    s.upload_image(args.image)
+
+def do_activate_image(args):
+    s = BMC(server=args.server)
+    s.activate_image(args.image_id)
+
+def do_update_auto(args):
+    s = BMC(server=args.server)
+    s.update_auto(args.image, args.reboot)
+
+def do_delete_image(args):
+    s = BMC(server=args.server)
+    s.delete_image(args.image_id)
+
+def do_set_priority(args):
+    s = BMC(server=args.server)
+    s.set_priority(args.image_id,args.priority)
+
+parser = argparse.ArgumentParser()
+parser.add_argument('--server', help='hostname or IP of BMC', type=str,
+                    required=True)
+parser.add_argument('--suppress-insecure-warnings', '-I', action="store_true",
+                    default=False)
+
+subparsers = parser.add_subparsers()
+list_events = subparsers.add_parser('list', help='List all software images on BMC')
+list_events.set_defaults(func=do_list_sfw)
+list_events.add_argument(
+    '--bmc',
+    action='store_true',
+    default=False,
+    help='Set if you want to see BMC images')
+list_events.add_argument(
+    '--host',
+    action='store_true',
+    default=False,
+    help='Set if you want to see Host images')
+
+image_view = subparsers.add_parser('view', help='View info of input image')
+image_view.add_argument('image', help='The image to analyze')
+image_view.set_defaults(func=do_view_image)
+
+image_upload = subparsers.add_parser('upload', help='Upload input image')
+image_upload.add_argument('image', help='The image to upload')
+image_upload.set_defaults(func=do_upload_image)
+
+image_activate = subparsers.add_parser('activate', help='Activate input image id')
+image_activate.add_argument('image_id', help='The image id to activate')
+image_activate.set_defaults(func=do_activate_image)
+
+image_update_auto = subparsers.add_parser('update_auto', help='Upload and '
+    + 'activate an image, and then reboot the BMC to apply the update '
+    + 'if necessary')
+image_update_auto.add_argument('image', help='The image to update to')
+image_update_auto.add_argument(
+    '--reboot',
+    action='store_true',
+    default=False,
+    help='Set if the BMC should reboot after the update')
+image_update_auto.set_defaults(func=do_update_auto)
+
+image_delete = subparsers.add_parser('delete', help='Delete input image id')
+image_delete.add_argument('image_id', help='The image id to delete')
+image_delete.set_defaults(func=do_delete_image)
+
+image_priority = subparsers.add_parser('priority', help='Set priority of input image')
+image_priority.add_argument('image_id', help='The image id to set priority of')
+image_priority.add_argument('priority', help='The priority to set')
+image_priority.set_defaults(func=do_set_priority)
+
+args = parser.parse_args()
+
+if args.suppress_insecure_warnings:
+    from requests.packages.urllib3.exceptions import InsecureRequestWarning
+    requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
+
+if 'func' in args:
+    args.func(args)
+else:
+    parser.print_help()