swevm / scaleio-py

ScaleIO API Bindings
Apache License 2.0
13 stars 14 forks source link

output as json #33

Open suslikas opened 8 years ago

suslikas commented 8 years ago

Hi,

Ease for any just put out what you get, then any who will use you code can make decision with output format better: json, xml, or just re-parse to k:v plain text.

Example:

    @property                                                   
    def get_json_system(self):                                  
        self._check_login()                                     
        response = self._do_get("{}/{}".format(self._api_url, "types/System/instances")).json()
        return response                                         

    def get_json_system_relationships_statistics(self, id):
        self._check_login()
        response = self._do_get("{}/{}".format(self._api_url, "instances/System::" + id + "/relationships/Statistics")).json()
        return response
system_id = sio.get_json_system[0]['id']
totalwritebwc = sio.get_json_system_relationships_statistics(system_id)['totalWriteBwc']
print json.dumps(totalwritebwc)

Result:

python /root/scio.py | jq
{
  "numOccured": 12612,
  "numSeconds": 5,
  "totalWeightInKb": 264807
}
suslikas commented 8 years ago

Short example how it can work - auto discovery and metric wrapper for zabbix.

$ cat /srv/scio/scio.py 
#!/usr/bin/python

import json
import time
import sys
import getopt
import requests

from pprint import pprint
from adform_scaleiopy.scaleio import ScaleIO
from requests.packages.urllib3.exceptions import InsecureRequestWarning

requests.packages.urllib3.disable_warnings(InsecureRequestWarning)

sio = ScaleIO("https://1.1.1.1/api","admin","admin",False,"ERROR")

def main(argv):
  arg_key = False
  arg_val = False
  try:
    opts, args = getopt.getopt(argv,"h",["discovery=","show="])
    if len(opts) is 0 and len(args) is 0:
      raise getopt.GetoptError("")
  except getopt.GetoptError:
    print '"scio.py -h" for help'
    sys.exit(2)
  for opt, arg in opts:
    if opt == '-h':
      print 'scio.py --show=all'
      print 'scio.py --show=key'
      print 'scio.py --discovery=yes'
      sys.exit()
    else:
      arg_key = opt
      arg_val = arg
  return ({'val':arg_val,'key':arg_key})

if __name__ == "__main__":
  arg = main(sys.argv[1:])

  if arg['key']:
    system_id = sio.get_json_system[0]['id']
    system_statistic = sio.get_json_system_relationships_statistics(system_id)
    #system_statistic = sio.get_json_instances_system(system_id)
    #system_statistic = sio.get_json_system_relationships_protectiondomain(system_id)
    #system_statistic = sio.get_json_system_relationships_sdc(system_id)
    #system_statistic = sio.get_json_system_relationships_scsiInitiator(system_id)

    if arg['key'] == '--show':
      stat_json = {}
      for k, v in system_statistic.items():
        if type(v) is dict:
          for k1, v1 in v.items():
            if type (v1) is int:
              v_name = "%s-%s" % (k,k1)
              stat_json.update({v_name:v1})
        elif type (v) is int:
          stat_json.update({k:v})

      if arg['val'] == 'all':
        print json.dumps(stat_json)
      elif arg['val'] in stat_json:
        print json.dumps({arg['val']:stat_json[arg['val']]})
      else:
        print json.dumps({"error":"key " + arg['val'] + " not found"})

    if arg['key'] == '--discovery':
      discovery_list = []
      discovery_json = {}
      for k, v in system_statistic.items():
        if type(v) is dict:
          for k1, v1 in v.items():
            if type (v1) is int:
              v_name = "%s-%s" % (k,k1)
              discovery_json={"{#SIOPARAMS}":v_name}
              discovery_list.append(discovery_json)
        elif type (v) is int:
          discovery_json={"{#SIOPARAMS}":k}
          discovery_list.append(discovery_json)

      print json.dumps({"data":discovery_list})

sys.exit()

P.S. I'm not code on python.