Giter Club home page Giter Club logo

zenoss-rm-api's Introduction

Overview

This repository is a fork of https://github.com/amccurdy/zenoss_api and currently the original python library ZenAPIConnector.py still exists in this repo. A new python library zenApiLib.py has been introduced with this forked repo.

zenApiLib

File: zenApiLib.py

Description: New python library introduced in this git-hub repository

Functionality:

  • leverages python logging library
  • paging api support; leverage router methods 'limit' parameter to break large results queries into manageable chunks
  • api result error checking
    • Content-Type JSON, return decoded json object
    • Content-Type HTML, return error w/ HTML page title
    • Misc
  • api call error checking
    • Validate specified Router exists
    • Validate called method exists
  • backward compatibility w/ zenoss_api.ZenAPIConnector.ZenAPIConnector
  • support multiple zenoss instance definitions in credential file
    • credential file name defaults to 'creds.cfg' and same directory as zenApiLib.py file
    • ability to specify credential file
  • 'zenApiCli.py' script available. For simple, command line API interaction. Can be easily incorporated with existing shell scripts.

Pre-requisites:

This python library depends on the following: Python 2.7, requests, pyOpenSSL, ndg-httpsclient, pyasn1

You can install those quickly with pip:

yum -y install python-pip
pip install requests pyOpenSSL ndg-httpsclient pyasn1

Environment:

If your script(s) are not in the same directory as zenApiLib.py or the standard python lib directories, then update your $PYTHONPATH environment variable to include that directory.

Note: The credentials creds.cfg file by default is expected to be in the same directory as zenApiLib.py. A different location can be specified at instantiation.

Usage:

zenApiCli.py

  1. Script help output:

    $ ./zenApiCli.py --help
      usage: zenApiCli.py [-h] [-v LOGLEVEL] [-t TIMEOUT] -r routerName -m
                          routerMethodName [-c credsSection] [-p credsFilePath]
                          [-d KEY1=VAL1,KEY2=VAL2...] [-x fieldName.fieldName...]
    
      Command Line Interface to Zennos JSON API, can be used to make simple API
      calls.
    
      optional arguments:
        -h, --help            show this help message and exit
        -v LOGLEVEL           Set script logging level (DEBUG=10, INFO=20, WARN=30,
                              *ERROR=40, CRTITICAL=50
        -t TIMEOUT            Override API call creds file timeout setting
        -r routerName         API router name
        -m routerMethodName   API router method to use
        -c credsSection       zenApiLib credential configuration section (default)
        -p credsFilePath      Default location being the same directory as the
                              zenApiLib.pyfile
        -d KEY1=VAL1,KEY2=VAL2...
                              Parameters to pass to router's method function
        -x fieldName.fieldName...
                              Return value from API result field. Default:
                              'result.success'. Special keyword 'all' to dump API
                              results.
    
  2. Send an event:

    ./zenApiCli.py -r EventsRouter -m add_event -d summary="this is a test",component="test" -d device="Null" -d severity=4,evclass="/Status" -d evclasskey="sma"
    
  3. Get device's productionState value:

    ./zenApiCli.py -r DeviceRouter -m getDevices -d uid="/zport/dmd/Devices/ControlCenter" -d params="{'ipAddress': '10.88.111.223'}" -x result.devices.0.productionState
    
  4. Get all devices in a deviceClass and their statuses:

    ./zenApiCli.py -r DeviceRouter -m getDevices -d uid="/zport/dmd/Devices",keys='["name","status"]' -x result.devices.*.name -x result.devices.*.status
    

zenApiLib.py

Once the zenApiLib library is imported you can then instantiate zenConnector a few different ways:

  1. get all triggers

    import zenApiLib
    zenApi = zenApiLib.zenConnector()
    zenApi.setRouter('TriggersRouter')
    print zenApi.callMethod('getTriggers')
    
  2. get all devices

    import zenApiLib
    dr = zenApiLib.zenConnector(routerName = 'DeviceRouter')
    print dr.callMethod('getDevices')
    
  3. copy trigger from one zenoss instance to another

    import zenApiLib
    tr5 = zenApiLib.zenConnector(section = '5x', routerName = 'TriggersRouter')
    tr6 = zenApiLib.zenConnector(section = '6x', routerName = 'TriggersRouter')
    migrate = tr5.callMethod('getTrigger', uuid = "e9ac462f-a80e-4f62-83e2-5f410818d782")
    # TODO: below is incorrect, but you get the general idea
    tr6.callMethod('addTrigger' **dict(migrate['result'])
    
  4. get all devices, via multiple queries. limits max number of results per query to two.

    import zenApiLib
    dr = zenApiLib.zenConnector(routerName = 'DeviceRouter')
    for apiResp in dr.pagingMethodCall('getDevices', limit = 2, keys = ["productionState", "id"]):
       print apiResp
    
  5. send an event & check success

    import zenApiLib
    er = zenApiLib.zenConnector(routerName = 'EventsRouter')
    evtResp = er.callMethod('add_event', 
        summary = "Device in Maintenance too long !",
        device ="localhost",
        component = "",
        severity = 2,
        evclasskey = "",
        evclass = "/Status/Zenoss"
    )
    if not evtResp['result']['success']:
        print("sendEvent - nonSucessful results\n%s" % evtResp)
    

API Router Helper Libraries:

Files: zenApiDeviceRouterHelper.py, zenApiImpactRouterHelper.py

Helper libraries that are router specific, should contain common, repeatbly used functionality.

zenoss-rm-api's People

Contributors

amccurdy avatar chorejasbob avatar jlampe avatar kiddico avatar linkslice avatar pjohnston avatar stevepc avatar sxanness avatar williamdean avatar zensaiello avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

zenoss-rm-api's Issues

need to be able to pass in config

thanks for this, helps alot...one thing that would be nice.

Im hoping to be able to pass my own config in from a secure credential store using types.SimpleNamespace or argparse.NameSpace or maybe even a copy of another ZenAPIConnector instance... as the config.

seems like the way it is constructed its going to be a bit hacky to pass in a . i will try to clone the repo and see if i can make a couple of changes to see what you think.

zenApiLib -- creds.cfg

Is it possible to use also credsections with the zenApiLib as with zenApiCli?

I have different environments, and it would be nice to be able to specify this somewhere.

Update library for Python 3

Hello

Are there any plans to update this library to support Python 3?

I can see a pull request from last year that includes these changes. Any reason why it hasn't been implemented?

A couple improvements

Would help if its easier to not automatically call the introspection router. Also will help if its easier to pass in the config as any basic object so its less bound to the creds file. That would make it easier to secure.

timeouts /errors not being handled sometimes?

I havent seen this issue before...i have been working alot with this helper library in the past week. im not sure if its limited to this router or not but today when i started trying to call methods in the router i started getting what im assuming is maybe a unhandled timeout calling introspection router?

the calls are good, it works sometimes, other times it doesnt.

doing this:

mr = zenApiLib.zenConnector(routerName="MonitorRouter")
mr.callMethod('getCollector', collectorString='localhost')

It looks like maybe the tree/monitor router may respond slowly perhaps or sometimes it throws errors.. it works sometimes othertimes it throws an error like the method doesnt exist however it does exist because i get returns sometimes...

when it fails i see this:

112 method[0],
113 self._routerName,
--> 114 sorted(self._routersInfo[self._routerName]['methods'].keys())
115 ))
116 if self.log.getEffectiveLevel() == 10:

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.