[![Documentation Status](https://readthedocs.org/projects/hbez/badge/?version=latest)](http://hbez.readthedocs.io)
[![UnitTest Status](https://travis-ci.org/Juniper/healthbot-py-client.svg?branch=master)](https://travis-ci.org/Juniper/healthbot-py-client)

# HealthBot Python Client

This repo contains a Python package to control HealthBot

The purpose of this package is to provide a Python library that 
automates the provisioning of the HealthBot server.

# Examples




# Import HbEZ library


```python
from jnpr.healthbot import HealthBotClient
from pprint import pprint
```

## Opening connection

```python
hb = HealthBotClient('xx.xx.xx.xxx', 'xxxxx', 'xxxxx', port=nnnn)
hb.open()
```

### using Python `with`context manager
* Takes care of login and logout with access tokens

```python
with HealthBotClient('xx.xx.xx.xxx', 'xxxxx', 'xxxxx', port=nnnn) as hb:
    pprint(hb.device.get_ids())
```

# Use Case: Device


```python
pprint(hb.device.get_ids())
```

    ['edge', 'srx', 'qfx', 'mx-edge', 'core', 'node', 'demo']


### Getting help for any given function


```python
help(hb.device.get_ids)
```

    Help on method get_ids in module jnpr.healthbot.modules.devices:
    
    get_ids() method of jnpr.healthbot.modules.devices.Device instance
        Return Device IDs for all the devices in HealthBot system
        
        :return: list of device IDs
        
        Example:
        ::
        
            from jnpr.healthbot import HealthBotClient
            hb = HealthBotClient('xx.xxx.x.xx', 'xxxx', 'xxxx', port=nnnn)
            print(hb.device.get_ids())
    


### Get config related to given device-id


```python
# Get config related to given device-id
obj = hb.device.get('demo')
```


```python
obj.host
```




    'xx.xxx.x.xx'




```python
pprint(obj)
```

    {'authentication': {'password': {'password': 'xxx',
                                     'username': 'xxxx'}},
     'description': None,
     'device_id': 'demo',
     'host': 'xx.xxx.x.xx',
     'i_agent': None,
     'open_config': None,
     'snmp': None,
     'system_id': 'test:HbEZ',
     'variable': None,
     'vendor': None}


### get facts for the given device id


```python
# Get device facts of a given device id
pprint(hb.device.get_facts('demo'))
```

    {'device-id': 'demo',
     'facts': {'fpc': [],
               'hostname': 'R1_re0',
               'junos-info': [{'last-reboot-reason': 'Router rebooted after a '
                                                     'normal shutdown.',
                               'mastership-state': 'master',
                               'model': 'RE-VMX',
                               'name': 're0',
                               'status': 'OK',
                               'up-time': '98 days, 3 minutes, 49 seconds',
                               'version-info': {'build': '0',
                                                'major': [19, 3],
                                                'minor': ['20190421_dev_common'],
                                                'type': 'I'}}],
               'platform': 'MX960',
               'platform-info': [{'name': 're0', 'platform': 'MX960'}],
               'product': 'MX',
               'release': '19.3-20190421_dev_common.0.84473',
               'serial-number': 'xxxx'}}


### Add a new device


```python
from jnpr.healthbot import DeviceSchema

ds = DeviceSchema(device_id='demo', host='xx.xxx.x.xx',
                  authentication={"password": {"password": "xxxx", "username": "xxxx"}})
print(hb.device.add(schema=ds))
```

    True



```python
help(DeviceSchema)
```

    Help on class DeviceSchema in module jnpr.healthbot.swagger.models.device_schema:
    
    class DeviceSchema(builtins.object)
     |  NOTE: This class is auto generated by the swagger code generator program.
     |  
     |  Do not edit the class manually.
     |  
     |  Methods defined here:
     |  
     |  __eq__(self, other)
     |      Returns true if both objects are equal
     |  
     |  __init__(self, authentication=None, description=None, device_id=None, host=None, i_agent=None, open_config=None, snmp=None, system_id=None, variable=None, vendor=None)
     |      DeviceSchema - a model defined in Swagger
     |  
     |  __ne__(self, other)
     |      Returns true if both objects are not equal
     |  
     |  __repr__(self)
     |      For `print` and `pprint`
     |  
     |  to_dict(self)
     |      Returns the model properties as a dict
     |  
     |  to_str(self)
     |      Returns the string representation of the model
     |  
     |  ----------------------------------------------------------------------
     |  Data descriptors defined here:
     |  
     |  __dict__
     |      dictionary for instance variables (if defined)
     |  
     |  __weakref__
     |      list of weak references to the object (if defined)
     |  
     |  authentication
     |      Gets the authentication of this DeviceSchema.  # noqa: E501
     |      
     |      
     |      :return: The authentication of this DeviceSchema.  # noqa: E501
     |      :rtype: DeviceSchemaAuthentication
     |  
     |  description
     |      Gets the description of this DeviceSchema.  # noqa: E501
     |      
     |      Description about the device  # noqa: E501
     |      
     |      :return: The description of this DeviceSchema.  # noqa: E501
     |      :rtype: str
     |  
     |  device_id
     |      Gets the device_id of this DeviceSchema.  # noqa: E501
     |      
     |      Identifier for the device. Should be of pattern [a-zA-Z][a-zA-Z0-9_-]*  # noqa: E501
     |      
     |      :return: The device_id of this DeviceSchema.  # noqa: E501
     |      :rtype: str
     |  
     |  host
     |      Gets the host of this DeviceSchema.  # noqa: E501
     |      
     |      Name or IP the device  # noqa: E501
     |      
     |      :return: The host of this DeviceSchema.  # noqa: E501
     |      :rtype: str
     |  
     |  i_agent
     |      Gets the i_agent of this DeviceSchema.  # noqa: E501
     |      
     |      
     |      :return: The i_agent of this DeviceSchema.  # noqa: E501
     |      :rtype: DeviceSchemaIAgent
     |  
     |  open_config
     |      Gets the open_config of this DeviceSchema.  # noqa: E501
     |      
     |      
     |      :return: The open_config of this DeviceSchema.  # noqa: E501
     |      :rtype: DeviceSchemaOpenconfig
     |  
     |  snmp
     |      Gets the snmp of this DeviceSchema.  # noqa: E501
     |      
     |      
     |      :return: The snmp of this DeviceSchema.  # noqa: E501
     |      :rtype: DeviceSchemaSnmp
     |  
     |  system_id
     |      Gets the system_id of this DeviceSchema.  # noqa: E501
     |      
     |      ID which is sent in the JTI UDP messages  # noqa: E501
     |      
     |      :return: The system_id of this DeviceSchema.  # noqa: E501
     |      :rtype: str
     |  
     |  variable
     |      Gets the variable of this DeviceSchema.  # noqa: E501
     |      
     |      Playbook variable configuration  # noqa: E501
     |      
     |      :return: The variable of this DeviceSchema.  # noqa: E501
     |      :rtype: list[DeviceSchemaVariable]
     |  
     |  vendor
     |      Gets the vendor of this DeviceSchema.  # noqa: E501
     |      
     |      
     |      :return: The vendor of this DeviceSchema.  # noqa: E501
     |      :rtype: DeviceSchemaVendor
     |  
     |  ----------------------------------------------------------------------
     |  Data and other attributes defined here:
     |  
     |  __hash__ = None
     |  
     |  attribute_map = {'authentication': 'authentication', 'description': 'd...
     |  
     |  swagger_types = {'authentication': 'DeviceSchemaAuthentication', 'desc...
    



```python
dev = hb.device.get('demo')
pprint(dev)
```

    {'authentication': {'password': {'password': 'xxxx',
                                     'username': 'xxxx'}},
     'description': None,
     'device_id': 'demo',
     'host': 'xx.xxx.x.xx',
     'i_agent': None,
     'open_config': None,
     'snmp': None,
     'system_id': None,
     'variable': None,
     'vendor': None}


### By default, get() returns uncommited data (from candidate DB)


```python
pprint(hb.device.get('demo', uncommitted=False))
```

    {
      "detail": "Device id demo not found",
      "status": 404
    }
    



    ---------------------------------------------------------------------------

    HTTPError                                 Traceback (most recent call last)

    <ipython-input-25-13c8b67cdb5c> in <module>
    ----> 1 pprint(hb.device.get('demo', uncommitted=False))
    

    ~/Coding/git.juniper.net.iceberg/healthbot-py-client/lib/jnpr/healthbot/modules/devices.py in get(self, device_id, uncommitted)
        217             if response.status_code != 200:
        218                 logger.error(response.text)
    --> 219             response.raise_for_status()
        220             return self.hbot._create_schema(response, DeviceSchema)
        221         else:


    /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/requests/models.py in raise_for_status(self)
        933 
        934         if http_error_msg:
    --> 935             raise HTTPError(http_error_msg, response=self)
        936 
        937     def close(self):


    HTTPError: 404 Client Error: NOT FOUND for url: https://10.209.7.33:8080/api/v1/device/demo


### Why we choose to go with Schema. We can easily access and edit any attribute. 


```python
# Existing system_id
print (dev.system_id)
```

    None



```python
# Editing system_id
dev.system_id = "Demo:HbEZ"
```


```python
print(hb.device.update(dev))
```

    True


### HealthBot API provide commit and rollback config


```python
hb.commit()
```




    True




```python
dev = hb.device.get('demo')
pprint(dev)
```

    {'authentication': {'password': {'password': 'xxxx',
                                     'username': 'xxxx'}},
     'description': None,
     'device_id': 'demo',
     'host': 'xx.xxx.x.xx',
     'i_agent': None,
     'open_config': None,
     'snmp': None,
     'system_id': 'Demo:HbEZ',
     'variable': None,
     'vendor': None}



```python
print(dev.system_id)
```

    Demo:HbEZ



```python
# To delete a device
hb.device.delete('demo')

# if a device is part of device group, to make sure we delete it first from device group
hb.device.delete('demo', force=True)
```

# Use Case: Devices

### Get details of all devices in System


```python
# Get config details of all the device
obj = hb.device.get()
```


```python
obj
```




    [{'authentication': {'password': {'password': 'xxxx',
                                      'username': 'xxxx'}},
      'description': None,
      'device_id': 'xxxx',
      'host': 'xx.xxx.x.xx',
      'i_agent': None,
      'open_config': {'port': 32767},
      'snmp': None,
      'system_id': None,
      'variable': [],
      'vendor': {'juniper': {'operating-system': 'junos'}}},
     {'authentication': {'password': {'password': 'xxxx',
                                      'username': 'xxxx'}},
      'description': None,
      'device_id': 'xxx',
      'host': 'xx.xxx.x.xx9',
      'i_agent': {'port': 830},
      'open_config': {'port': 32767},
      'snmp': None,
      'system_id': None,
      'variable': [],
      'vendor': {'juniper': {'operating-system': 'junos'}}},
     {'authentication': {'password': {'password': 'xxxx',
                                      'username': 'xxxx'}},
      'description': None,
      'device_id': 'xxx',
      'host': 'xx.xxx.x.xx',
      'i_agent': {'port': 830},
      'open_config': {'port': 32767},
      'snmp': None,
      'system_id': 'changed description',
      'variable': [],
      'vendor': {'juniper': {'operating-system': 'junos'}}},
     {'authentication': {'password': {'password': 'xxxx',
                                      'username': 'xxxx'}},
      'description': None,
      'device_id': 'demo',
      'host': 'xx.xxx.x.xx',
      'i_agent': None,
      'open_config': None,
      'snmp': None,
      'system_id': 'Demo:HbEZ',
      'variable': None,
      'vendor': None},
     {'authentication': {'password': {'password': 'xxxx',
                                      'username': 'xxxx'}},
      'description': None,
      'device_id': 'vmx_db',
      'host': 'xx.xxx.x.xx',
      'i_agent': {'port': 830},
      'open_config': {'port': 32767},
      'snmp': None,
      'system_id': None,
      'variable': [],
      'vendor': {'juniper': {'operating-system': 'junos'}}},
     {'authentication': {'password': {'password': 'xxxx',
                                      'username': 'xxxx'}},
      'description': None,
      'device_id': 'core_db',
      'host': 'xx.xxx.x.xx',
      'i_agent': {'port': 830},
      'open_config': {'port': 32767},
      'snmp': None,
      'system_id': None,
      'variable': [],
      'vendor': {'juniper': {'operating-system': 'junos'}}},
     {'authentication': {'password': {'password': 'xxxx',
                                      'username': 'xxxx'}},
      'description': None,
      'device_id': 'node1',
      'host': 'node1',
      'i_agent': None,
      'open_config': {'port': 32767},
      'snmp': None,
      'system_id': None,
      'variable': None,
      'vendor': {'juniper': {'operating-system': 'junos'}}}]



### Get device facts for all the devices in HB


```python
pprint(hb.device.get_facts())
```

    [{'device-id': 'edge', 'facts': {}},
     {'device-id': 'EVO',
      'facts': {'fpc': [{'description': 'FPC-JNP10003-LOGICAL',
                         'model-number': None,
                         'name': 'FPC 1',
                         'part-number': 'BUILTIN',
                         'serial-number': 'BUILTIN',
                         'version': None}],
                'hostname': None,
                'junos-info': [{'last-reboot-reason': 'Unknown',
                                'mastership-state': 'Master',
                                'model': 'Control Board',
                                'name': 're0',
                                'status': 'OK',
                                'up-time': '0 second',
                                'version-info': {'build': None,
                                                 'major': [19, 4],
                                                 'minor': ['20190731122440-EVO_soumikd'],
                                                 'type': 'I'}}],
                'platform': 'PTX10003-160C',
                'platform-info': [{'name': 're0', 'platform': 'PTX10003-160C'}],
                'product': 'PTX',
                'release': '19.4I20190731122440-EVO_soumikd',
                'serial-number': 'xxxx'}},
     {'device-id': 'vmx',
      'facts': {'fpc': [],
                'hostname': 'R1_re0',
                'junos-info': [{'last-reboot-reason': 'Router rebooted after a '
                                                      'normal shutdown.',
                                'mastership-state': 'master',
                                'model': 'RE-VMX',
                                'name': 're0',
                                'status': 'OK',
                                'up-time': '80 days, 1 hour, 20 minutes, 9 seconds',
                                'version-info': {'build': '0',
                                                 'major': [19, 3],
                                                 'minor': ['20190421_dev_common'],
                                                 'type': 'I'}}],
                'platform': 'MX960',
                'platform-info': [{'name': 're0', 'platform': 'MX960'}],
                'product': 'MX',
                'release': '19.3-20190421_dev_common.0.84473',
                'serial-number': 'xxxx'}},
     {'device-id': 'demo',
      'facts': {'fpc': [],
                'hostname': 'R1_re0',
                'junos-info': [{'last-reboot-reason': 'Router rebooted after a '
                                                      'normal shutdown.',
                                'mastership-state': 'master',
                                'model': 'RE-VMX',
                                'name': 're0',
                                'status': 'OK',
                                'up-time': '98 days, 38 minutes, 25 seconds',
                                'version-info': {'build': '0',
                                                 'major': [19, 3],
                                                 'minor': ['20190421_dev_common'],
                                                 'type': 'I'}}],
                'platform': 'MX960',
                'platform-info': [{'name': 're0', 'platform': 'MX960'}],
                'product': 'MX',
                'release': '19.3-20190421_dev_common.0.84473',
                'serial-number': 'xxxx'}},
     {'device-id': 'vmx_db',
      'facts': {'hostname': 'riad001-g',
                'junos-info': [],
                'platform': 'MX480',
                'platform-info': [{'name': 're0', 'platform': 'MX480'}],
                'product': None,
                'release': '19.4I20190809_0730_madhus',
                'serial-number': None}},
     {'device-id': 'core_db',
      'facts': {'fpc': [{'description': 'MPC Type 2 3D',
                         'model-number': 'MX-MPC2-3D',
                         'name': 'FPC 1',
                         'part-number': '750-031089',
                         'serial-number': 'xxxx',
                         'version': 'REV 31'}],
                'hostname': 'choc-mx480-b',
                'junos-info': [{'last-reboot-reason': 'Router rebooted after a '
                                                      'normal shutdown.',
                                'mastership-state': 'master',
                                'model': 'RE-S-2000',
                                'name': 're0',
                                'status': 'OK',
                                'up-time': '5 hours, 27 minutes, 15 seconds',
                                'version-info': {'build': None,
                                                 'major': [19, 4],
                                                 'minor': ['20190809_0730_madhus'],
                                                 'type': 'I'}},
                               {'last-reboot-reason': '0x1:power cycle/failure',
                                'mastership-state': 'backup',
                                'model': 'RE-S-2000',
                                'name': 're1',
                                'status': 'OK',
                                'up-time': '14 days, 22 hours, 34 minutes, 13 '
                                           'seconds',
                                'version-info': {'build': 7,
                                                 'major': [15, 1],
                                                 'minor': ['6'],
                                                 'type': 'R'}}],
                'platform': 'MX480',
                'platform-info': [{'name': 're0', 'platform': 'MX480'},
                                  {'name': 're1', 'platform': 'MX480'}],
                'product': 'MX',
                'release': '19.4I20190809_0730_madhus',
                'serial-number': 'xxxx'}},
     {'device-id': 'node1', 'facts': {}}]


### Add device group using DevicegroupSchema and APIs provided


```python
from jnpr.healthbot import DeviceGroupSchema
```


```python
dgs = DeviceGroupSchema(device_group_name="edge", devices=['demo'])
```

### We can also set any param/attribute after creating schema object


```python
dgs.description="All devices on the edge"
```

### Now add device group using provided API


```python
print(hb.device_group.add(dgs))
```

    True


### Let see whats the plus point of using Schema

     1> Helps with any missing paramters
     2> Checks for any rule associated with given params


```python
# Error for missing mandatory parameters

dgs = DeviceGroupSchema()
```


    ---------------------------------------------------------------------------

    ValueError                                Traceback (most recent call last)

    <ipython-input-39-4d61d231fd38> in <module>
          1 # Error for missing mandatory parameters
          2 
    ----> 3 dgs = DeviceGroupSchema()
    

    ~/Coding/git.juniper.net.iceberg/healthbot-py-client/lib/jnpr/healthbot/swagger/models/device_group_schema.py in __init__(self, authentication, description, device_group_name, devices, logging, native_gpb, notification, playbooks, reports, retention_policy, variable)
         85         if description is not None:
         86             self.description = description
    ---> 87         self.device_group_name = device_group_name
         88         if devices is not None:
         89             self.devices = devices


    ~/Coding/git.juniper.net.iceberg/healthbot-py-client/lib/jnpr/healthbot/swagger/models/device_group_schema.py in device_group_name(self, device_group_name)
        168         """
        169         if device_group_name is None:
    --> 170             raise ValueError("Invalid value for `device_group_name`, must not be `None`")  # noqa: E501
        171         if device_group_name is not None and len(device_group_name) > 64:
        172             raise ValueError("Invalid value for `device_group_name`, length must be less than or equal to `64`")  # noqa: E501


    ValueError: Invalid value for `device_group_name`, must not be `None`



```python
# Error for not following rule for give parameter

dgs = DeviceGroupSchema(device_group_name="edge group")
```


    ---------------------------------------------------------------------------

    ValueError                                Traceback (most recent call last)

    <ipython-input-40-8617b5d8e365> in <module>
          1 # Error for not following rule for give parameter
          2 
    ----> 3 dgs = DeviceGroupSchema(device_group_name="edge group")
    

    ~/Coding/git.juniper.net.iceberg/healthbot-py-client/lib/jnpr/healthbot/swagger/models/device_group_schema.py in __init__(self, authentication, description, device_group_name, devices, logging, native_gpb, notification, playbooks, reports, retention_policy, variable)
         85         if description is not None:
         86             self.description = description
    ---> 87         self.device_group_name = device_group_name
         88         if devices is not None:
         89             self.devices = devices


    ~/Coding/git.juniper.net.iceberg/healthbot-py-client/lib/jnpr/healthbot/swagger/models/device_group_schema.py in device_group_name(self, device_group_name)
        172             raise ValueError("Invalid value for `device_group_name`, length must be less than or equal to `64`")  # noqa: E501
        173         if device_group_name is not None and not re.search('^[a-zA-Z][a-zA-Z0-9_-]*$', device_group_name):  # noqa: E501
    --> 174             raise ValueError("Invalid value for `device_group_name`, must be a follow pattern or equal to `/^[a-zA-Z][a-zA-Z0-9_-]*$/`")  # noqa: E501
        175 
        176         self._device_group_name = device_group_name


    ValueError: Invalid value for `device_group_name`, must be a follow pattern or equal to `/^[a-zA-Z][a-zA-Z0-9_-]*$/`



```python
# Now we are in compliance with rules

dgs = DeviceGroupSchema(device_group_name="edge")
```


```python
dgs.devices = ['demo']
```

### We can also pass all Schema params to add_ APIs, internally it will use these params to create Schema


```python
print(hb.device_group.add(device_group_name="edge", description="All devices on the edge", devices=['demo']))
hb.commit()
```

    True





    True




```python
# Get details for a given device group
hb.device_group.get('real')
```




    {'authentication': None,
     'description': None,
     'device_group_name': 'real',
     'devices': ['edge'],
     'logging': None,
     'native_gpb': None,
     'notification': {},
     'playbooks': ['phyport'],
     'reports': [],
     'retention_policy': None,
     'variable': [{'@': {'changed-seconds': 1563348601},
                   'instance-id': 'ge-1-0-0',
                   'playbook': 'phyport',
                   'rule': 'external/interface-info',
                   'variable-value': [{'name': 'interface_name',
                                       'value': 'ge-1/0/0'}]},
                  {'@': {'changed-seconds': 1563348601},
                   'instance-id': 'ge-1-0-1',
                   'playbook': 'phyport',
                   'rule': 'external/interface-info',
                   'variable-value': [{'name': 'interface_name',
                                       'value': 'ge-1/0/1'}]}]}




```python
hb.device_group.delete('edge', force=True)
```

    





    True



### Add an existing device to existing group


```python
hb.device_group.add_device_in_group('vmx', 'edge')
```




    True




```python
obj = hb.device_group.get('edge')
print (obj)
```

    {'authentication': None,
     'description': 'All devices on the edge',
     'device_group_name': 'edge',
     'devices': ['vmx', 'demo'],
     'logging': {'log-level': 'warn'},
     'native_gpb': None,
     'notification': {},
     'playbooks': [],
     'reports': [],
     'retention_policy': None,
     'variable': [{'@': {'changed-seconds': 1565668543},
                   'instance-id': 'HbEZ-instance',
                   'playbook': 'forwarding-table-summary',
                   'rule': 'protocol.routesummary/check-fib-summary'},
                  {'@': {'changed-seconds': 1565669467},
                   'instance-id': 'HbEZ-instance',
                   'playbook': 'icmp-probe',
                   'rule': 'protocol.icmp/check-icmp-statistics'}]}



```python
obj.devices
```




    ['vmx', 'demo']



### Get details of all the device groups


```python
print(hb.device_group.get())
```

    [{'authentication': None,
     'description': None,
     'device_group_name': 'real',
     'devices': ['edge'],
     'logging': None,
     'native_gpb': None,
     'notification': {},
     'playbooks': ['phyport'],
     'reports': [],
     'retention_policy': None,
     'variable': [{'@': {'changed-seconds': 1563348601},
                   'instance-id': 'ge-1-0-0',
                   'playbook': 'phyport',
                   'rule': 'external/interface-info',
                   'variable-value': [{'name': 'interface_name',
                                       'value': 'ge-1/0/0'}]},
                  {'@': {'changed-seconds': 1563348601},
                   'instance-id': 'ge-1-0-1',
                   'playbook': 'phyport',
                   'rule': 'external/interface-info',
                   'variable-value': [{'name': 'interface_name',
                                       'value': 'ge-1/0/1'}]}]}, {'authentication': None,
     'description': 'UBS Demo',
     'device_group_name': 'QFabric',
     'devices': ['node1'],
     'logging': None,
     'native_gpb': None,
     'notification': {},
     'playbooks': [],
     'reports': [],
     'retention_policy': None,
     'variable': []}, {'authentication': {'password': {'password': 'xxxx',
                                     'username': 'xxxx'}},
     'description': None,
     'device_group_name': 'EVO_CORE',
     'devices': ['EVO'],
     'logging': None,
     'native_gpb': None,
     'notification': {},
     'playbooks': [],
     'reports': [],
     'retention_policy': None,
     'variable': []}, {'authentication': {'password': {'password': 'xxxx',
                                     'username': 'xxxx'}},
     'description': None,
     'device_group_name': 'vmx_db',
     'devices': ['core_db'],
     'logging': {'log-level': 'critical'},
     'native_gpb': None,
     'notification': {},
     'playbooks': [],
     'reports': [],
     'retention_policy': None,
     'variable': []}, {'authentication': None,
     'description': 'All devices on the edge',
     'device_group_name': 'edge',
     'devices': ['vmx', 'demo'],
     'logging': {'log-level': 'warn'},
     'native_gpb': None,
     'notification': {},
     'playbooks': [],
     'reports': [],
     'retention_policy': None,
     'variable': [{'@': {'changed-seconds': 1565668543},
                   'instance-id': 'HbEZ-instance',
                   'playbook': 'forwarding-table-summary',
                   'rule': 'protocol.routesummary/check-fib-summary'},
                  {'@': {'changed-seconds': 1565669467},
                   'instance-id': 'HbEZ-instance',
                   'playbook': 'icmp-probe',
                   'rule': 'protocol.icmp/check-icmp-statistics'}]}, {'authentication': None,
     'description': 'learning',
     'device_group_name': 'Core',
     'devices': ['vmx'],
     'logging': None,
     'native_gpb': {'ports': [22000]},
     'notification': {},
     'playbooks': ['icmp-probe', 'rca-ospf-playbook'],
     'reports': [],
     'retention_policy': None,
     'variable': [{'@': {'changed-seconds': 1564722219},
                   'instance-id': 'test1',
                   'playbook': 'rca-ospf-playbook',
                   'rule': 'interface.statistics/check-host-loopback-status',
                   'variable-value': []},
                  {'@': {'changed-seconds': 1564722219},
                   'instance-id': 'test1',
                   'playbook': 'rca-ospf-playbook',
                   'rule': 'linecard.fpc/check-fpc-memory',
                   'variable-value': []},
                  {'@': {'changed-seconds': 1564722219},
                   'instance-id': 'test1',
                   'playbook': 'rca-ospf-playbook',
                   'rule': 'linecard.ospf/check-ddos-statistics',
                   'variable-value': []},
                  {'@': {'changed-seconds': 1564722219},
                   'instance-id': 'test1',
                   'playbook': 'rca-ospf-playbook',
                   'rule': 'linecard.statistics/check-center-chip-host-path',
                   'variable-value': []},
                  {'@': {'changed-seconds': 1564722219},
                   'instance-id': 'test1',
                   'playbook': 'rca-ospf-playbook',
                   'rule': 'linecard.statistics/check-cm-error-table',
                   'variable-value': []},
                  {'@': {'changed-seconds': 1564722219},
                   'instance-id': 'test1',
                   'playbook': 'rca-ospf-playbook',
                   'rule': 'linecard.statistics/check-fpc-cpu-scheduler-info',
                   'variable-value': []},
                  {'@': {'changed-seconds': 1564722219},
                   'instance-id': 'test1',
                   'playbook': 'rca-ospf-playbook',
                   'rule': 'linecard.statistics/check-fpc-threads',
                   'variable-value': []},
                  {'@': {'changed-seconds': 1564722219},
                   'instance-id': 'test1',
                   'playbook': 'rca-ospf-playbook',
                   'rule': 'linecard.statistics/check-fpc-utilization-information',
                   'variable-value': []},
                  {'@': {'changed-seconds': 1564722219},
                   'instance-id': 'test1',
                   'playbook': 'rca-ospf-playbook',
                   'rule': 'linecard.statistics/check-ithrottle',
                   'variable-value': []},
                  {'@': {'changed-seconds': 1564722219},
                   'instance-id': 'test1',
                   'playbook': 'rca-ospf-playbook',
                   'rule': 'linecard.statistics/check-ithrottle-statistics',
                   'variable-value': []},
                  {'@': {'changed-seconds': 1564722219},
                   'instance-id': 'test1',
                   'playbook': 'rca-ospf-playbook',
                   'rule': 'linecard.statistics/check-jnh-exceptions',
                   'variable-value': []},
                  {'@': {'changed-seconds': 1564722219},
                   'instance-id': 'test1',
                   'playbook': 'rca-ospf-playbook',
                   'rule': 'linecard.statistics/check-jnh-interface-statistics',
                   'variable-value': []},
                  {'@': {'changed-seconds': 1564722219},
                   'instance-id': 'test1',
                   'playbook': 'rca-ospf-playbook',
                   'rule': 'linecard.statistics/check-linecard-ethernet-statistics',
                   'variable-value': []},
                  {'@': {'changed-seconds': 1564722219},
                   'instance-id': 'test1',
                   'playbook': 'rca-ospf-playbook',
                   'rule': 'linecard.statistics/check-pci-error-counters',
                   'variable-value': []},
                  {'@': {'changed-seconds': 1564722219},
                   'instance-id': 'test1',
                   'playbook': 'rca-ospf-playbook',
                   'rule': 'linecard.statistics/check-pfe-traffic-statistics',
                   'variable-value': []},
                  {'@': {'changed-seconds': 1564722219},
                   'instance-id': 'test1',
                   'playbook': 'rca-ospf-playbook',
                   'rule': 'linecard.statistics/check-pre-classifier-dropped-packets',
                   'variable-value': []},
                  {'@': {'changed-seconds': 1564722219},
                   'instance-id': 'test1',
                   'playbook': 'rca-ospf-playbook',
                   'rule': 'linecard.statistics/check-traffic-offload-engine-status',
                   'variable-value': []},
                  {'@': {'changed-seconds': 1564722219},
                   'instance-id': 'test1',
                   'playbook': 'rca-ospf-playbook',
                   'rule': 'protocol.infra/check-task-io-drops',
                   'variable-value': []},
                  {'@': {'changed-seconds': 1564722219},
                   'instance-id': 'test1',
                   'playbook': 'rca-ospf-playbook',
                   'rule': 'protocol.infra/check-task-memory-usage',
                   'variable-value': []},
                  {'@': {'changed-seconds': 1564722219},
                   'instance-id': 'test1',
                   'playbook': 'rca-ospf-playbook',
                   'rule': 'protocol.ospf/check-ospf-forwarding-table',
                   'variable-value': []},
                  {'@': {'changed-seconds': 1564722219},
                   'instance-id': 'test1',
                   'playbook': 'rca-ospf-playbook',
                   'rule': 'protocol.ospf/check-ospf-io-statistics-information',
                   'variable-value': []},
                  {'@': {'changed-seconds': 1564722219},
                   'instance-id': 'test1',
                   'playbook': 'rca-ospf-playbook',
                   'rule': 'protocol.ospf/check-ospf-neighbor-information',
                   'variable-value': []},
                  {'@': {'changed-seconds': 1564722219},
                   'instance-id': 'test1',
                   'playbook': 'rca-ospf-playbook',
                   'rule': 'protocol.ospf/check-ospf-statistics-information',
                   'variable-value': []},
                  {'@': {'changed-seconds': 1564722219},
                   'instance-id': 'test1',
                   'playbook': 'rca-ospf-playbook',
                   'rule': 'protocol.ospf/fpc-link-stats',
                   'variable-value': []},
                  {'@': {'changed-seconds': 1564722219},
                   'instance-id': 'test1',
                   'playbook': 'rca-ospf-playbook',
                   'rule': 'protocol.ospf/pfe-ddos-policer',
                   'variable-value': []},
                  {'@': {'changed-seconds': 1564722219},
                   'instance-id': 'test1',
                   'playbook': 'rca-ospf-playbook',
                   'rule': 'system.statistics/check-routing-engine-cpu-utilization',
                   'variable-value': []},
                  {'@': {'changed-seconds': 1564722219},
                   'instance-id': 'test1',
                   'playbook': 'rca-ospf-playbook',
                   'rule': 'system.statistics/check-system-input-queues',
                   'variable-value': []},
                  {'@': {'changed-seconds': 1564722219},
                   'instance-id': 'test1',
                   'playbook': 'rca-ospf-playbook',
                   'rule': 'system.statistics/check-system-output-queues',
                   'variable-value': []},
                  {'@': {'changed-seconds': 1564722219},
                   'instance-id': 'test1',
                   'playbook': 'rca-ospf-playbook',
                   'rule': 'system.statistics/check-system-statistics-ip',
                   'variable-value': []},
                  {'@': {'changed-seconds': 1564722219},
                   'instance-id': 'test1',
                   'playbook': 'rca-ospf-playbook',
                   'rule': 'system.statistics/check-system-storage-capacity',
                   'variable-value': []},
                  {'@': {'changed-seconds': 1564722219},
                   'instance-id': 'test1',
                   'playbook': 'rca-ospf-playbook',
                   'rule': 'system.statistics/check-system-virtual-memory-information',
                   'variable-value': []},
                  {'@': {'changed-seconds': 1564722219},
                   'instance-id': 'test1',
                   'playbook': 'rca-ospf-playbook',
                   'rule': 'system.statistics/check-version',
                   'variable-value': []},
                  {'@': {'changed-seconds': 1565263889},
                   'instance-id': 'set1',
                   'playbook': 'icmp-probe',
                   'rule': 'protocol.icmp/check-icmp-statistics',
                   'variable-value': [{'name': 'host-var', 'value': '10.221.11.11'},
                                      {'name': 'count-var', 'value': '2'}]}]}]


### We can also update any given device group


```python
print(hb.device_group.get('edge'))
```

    {'authentication': None,
     'description': 'All devices on the edge',
     'device_group_name': 'edge',
     'devices': ['vmx', 'demo'],
     'logging': {'log-level': 'warn'},
     'native_gpb': None,
     'notification': {},
     'playbooks': [],
     'reports': [],
     'retention_policy': None,
     'variable': [{'@': {'changed-seconds': 1565668543},
                   'instance-id': 'HbEZ-instance',
                   'playbook': 'forwarding-table-summary',
                   'rule': 'protocol.routesummary/check-fib-summary'},
                  {'@': {'changed-seconds': 1565669467},
                   'instance-id': 'HbEZ-instance',
                   'playbook': 'icmp-probe',
                   'rule': 'protocol.icmp/check-icmp-statistics'}]}



```python
dgs = hb.device_group.get('edge')
dgs.devices.append('vmx')
hb.device_group.update(dgs)
```




    True




```python
# Check for devices list
dgs = hb.device_group.get('edge')
print(dgs)
```

    {'authentication': None,
     'description': 'All devices on the edge',
     'device_group_name': 'edge',
     'devices': ['vmx', 'demo'],
     'logging': {'log-level': 'warn'},
     'native_gpb': None,
     'notification': {},
     'playbooks': [],
     'reports': [],
     'retention_policy': None,
     'variable': [{'@': {'changed-seconds': 1565668543},
                   'instance-id': 'HbEZ-instance',
                   'playbook': 'forwarding-table-summary',
                   'rule': 'protocol.routesummary/check-fib-summary'},
                  {'@': {'changed-seconds': 1565669467},
                   'instance-id': 'HbEZ-instance',
                   'playbook': 'icmp-probe',
                   'rule': 'protocol.icmp/check-icmp-statistics'}]}



```python
dgs.devices = ['edge']
hb.device_group.update(dgs)
```




    True




```python
dgs = hb.device_group.get('edge')
print(dgs)
```

    {'authentication': None,
     'description': 'All devices on the edge',
     'device_group_name': 'edge',
     'devices': ['edge'],
     'logging': {'log-level': 'warn'},
     'native_gpb': None,
     'notification': {},
     'playbooks': [],
     'reports': [],
     'retention_policy': None,
     'variable': [{'@': {'changed-seconds': 1565668543},
                   'instance-id': 'HbEZ-instance',
                   'playbook': 'forwarding-table-summary',
                   'rule': 'protocol.routesummary/check-fib-summary'},
                  {'@': {'changed-seconds': 1565669467},
                   'instance-id': 'HbEZ-instance',
                   'playbook': 'icmp-probe',
                   'rule': 'protocol.icmp/check-icmp-statistics'}]}



```python
# can also update by passing Device Group Schema kwargs
dgs = hb.device_group.get('edge')
pprint(dgs)
from jnpr.healthbot import DevicegroupSchemaLogging
logSchema = DevicegroupSchemaLogging('warn')
hb.device_group.update(device_group_name='edge', logging=logSchema)
```

    {'authentication': None,
     'description': 'All devices on the edge',
     'device_group_name': 'edge',
     'devices': ['edge'],
     'logging': {'log-level': 'warn'},
     'native_gpb': None,
     'notification': {},
     'playbooks': [],
     'reports': [],
     'retention_policy': None,
     'variable': [{'@': {'changed-seconds': 1565668543},
                   'instance-id': 'HbEZ-instance',
                   'playbook': 'forwarding-table-summary',
                   'rule': 'protocol.routesummary/check-fib-summary'},
                  {'@': {'changed-seconds': 1565669467},
                   'instance-id': 'HbEZ-instance',
                   'playbook': 'icmp-probe',
                   'rule': 'protocol.icmp/check-icmp-statistics'}]}





    True




```python
### Delete device and device group
```


```python
hb.device_group.delete('edge')

```

    





    True




```python
hb.device.delete('demo')
```




    True




```python
# Lets commit all the changes
hb.commit()
```




    True



### Add Network Group


```python
hb.network_group.add(network_group_name="HbEZ")
```




    True




```python
print(hb.network_group.get(network_group_name="HbEZ"))
hb.network_group.delete(network_group_name="HbEZ")
```

    


    {'description': None,
     'network_group_name': 'HbEZ',
     'notification': {},
     'playbooks': [],
     'reports': [],
     'variable': None}





    True



### Add Network Group using Schema


```python
from jnpr.healthbot import NetworkGroupSchema
```


```python
ngs = NetworkGroupSchema(network_group_name="HbEZ")
```


```python
hb.network_group.add(ngs)
```




    True




```python
hb.network_group.get(network_group_name="HbEZ")
```




    {'description': None,
     'network_group_name': 'HbEZ',
     'notification': {},
     'playbooks': [],
     'reports': [],
     'variable': None}



# Use Case: Rules


```python
hb.rule.get('linecard.ospf', 'check-ddos-statistics')
```




    {'description': 'Monitors ospf related distributed denial of service '
                    'statistics',
     'field': [{'constant': {'value': '{{ddos-arrival-rate-threshold}}'},
                'description': 'This field is for ddos arive rate threshold',
                'field-name': 'ddos-arrival-rate-threshold'},
               {'constant': {'value': '{{ddos-drop-count-threshold}}'},
                'description': 'This field is for ddos drop count threshold',
                'field-name': 'ddos-drop-count-threshold'},
               {'constant': {'value': '{{ddos-drop-rate-threshold}}'},
                'description': 'This field is for ddos drop rate threshold',
                'field-name': 'ddos-drop-rate-threshold'}],
     'function': None,
     'keys': ['group-name', 'protocol-states-locale'],
     'network_rule': None,
     'rule_frequency': None,
     'rule_name': 'check-ddos-statistics',
     'rule_properties': {'catalogue': {'tier': '1'},
                         'contributor': 'juniper',
                         'helper-files': [{'file-type': 'other',
                                           'list-of-files': ['ddos-statistics.yml']}],
                         'supported-devices': {'juniper': {'operating-system': [{'os-name': 'junos',
                                                                                 'products': [{'product-name': 'ACX',
                                                                                               'releases': [{'platform': ['All'],
                                                                                                             'release-name': '15.2R1',
                                                                                                             'release-support': 'min-supported-release'}]},
                                                                                              {'product-name': 'EX',
                                                                                               'releases': [{'platform': ['All'],
                                                                                                             'release-name': '15.2R1',
                                                                                                             'release-support': 'min-supported-release'}]},
                                                                                              {'product-name': 'MX',
                                                                                               'releases': [{'platform': ['All'],
                                                                                                             'release-name': '15.2R1',
                                                                                                             'release-support': 'min-supported-release'}]},
                                                                                              {'product-name': 'PTX',
                                                                                               'releases': [{'platform': ['All'],
                                                                                                             'release-name': '15.2R1',
                                                                                                             'release-support': 'min-supported-release'}]},
                                                                                              {'product-name': 'QFX',
                                                                                               'releases': [{'platform': ['All'],
                                                                                                             'release-name': '15.2R1',
                                                                                                             'release-support': 'min-supported-release'}]},
                                                                                              {'product-name': 'SRX',
                                                                                               'releases': [{'platform': ['All'],
                                                                                                             'release-name': '15.2R1',
                                                                                                             'release-support': 'min-supported-release'}]}]}]}},
                         'supported-healthbot-version': '1.0.1',
                         'version': 2},
     'sensor': [{'description': 'Netconf rpc get-ddos-ospf-information iAgent '
                                'sensor to collect telemetry data from network '
                                'device',
                 'iAgent': {'file': 'ddos-statistics.yml',
                            'frequency': '60s',
                            'table': 'ddosStats'},
                 'sensor-name': 'ddosstats',
                 'synopsis': 'ddos statistics sensor definition'}],
     'synopsis': 'OSPF distributed denial of service statistics analyzer',
     'trigger': [{'description': 'Sets health based on DDOS packet drop rate',
                  'frequency': '60s',
                  'synopsis': 'DDOS packet drops kpi',
                  'term': [{'term-name': 'is-ddos-drops-increasing',
                            'then': {'status': {'color': 'red',
                                                'message': 'DDOS packet drops '
                                                           '($dropped-packets) '
                                                           'increasing'}},
                            'when': {'min-rate-of-increase': [{'field-name': '$dropped-packets',
                                                               'rate': '$ddos-drop-rate-threshold',
                                                               'time-range': '5m'}]}},
                           {'term-name': 'are-ddos-drops-over-threshold',
                            'then': {'status': {'color': 'yellow',
                                                'message': 'DDOS packet drops '
                                                           '($dropped-packets) '
                                                           'over threshold '
                                                           '($ddos-drop-count-threshold)'}},
                            'when': {'greater-than': [{'left-operand': '$dropped-packets',
                                                       'right-operand': '$ddos-drop-count-threshold'}]}},
                           {'term-name': 'ddos-drops-not-increasing',
                            'then': {'status': {'color': 'green'}}}],
                  'trigger-name': 'ddos-drops'},
                 {'description': 'Sets health based on DDOS packet arrival rate',
                  'frequency': '60s',
                  'synopsis': 'DDOS packet arrival kpi',
                  'term': [{'term-name': 'is-max-packet-arrival-rate-greater-than-threshold',
                            'then': {'status': {'color': 'yellow',
                                                'message': 'DDOS packet max '
                                                           'arrival rate is over '
                                                           'threshold '
                                                           '($ddos-arrival-rate-threshold)'}},
                            'when': {'greater-than-or-equal-to': [{'left-operand': '$packet-arrival-rate-max',
                                                                   'right-operand': '$ddos-arrival-rate-threshold'}]}},
                           {'term-name': 'max-packet-arrival-rate-less-than-threshold',
                            'then': {'status': {'color': 'green'}}}],
                  'trigger-name': 'ddos-packet-arrival-rate'},
                 {'description': 'Sets health based on DDOS packet drop others',
                  'frequency': '60s',
                  'synopsis': 'DDOS packet drop other kpi',
                  'term': [{'term-name': 'is-ddos-packet-dropped-others-increasing',
                            'then': {'status': {'color': 'red',
                                                'message': 'DDOS packet dropped '
                                                           'others '
                                                           '($dropped-packets-others) '
                                                           'increasing'}},
                            'when': {'min-rate-of-increase': [{'field-name': '$dropped-packets-others',
                                                               'rate': '$ddos-drop-rate-threshold',
                                                               'time-range': '5m'}]}},
                           {'term-name': 'is-ddos-packet-drop-others-over-threshold',
                            'then': {'status': {'color': 'yellow',
                                                'message': 'DDOS packet dropped '
                                                           'others '
                                                           '($dropped-packets-others) '
                                                           'over threshold '
                                                           '($ddos-drop-count-threshold)'}},
                            'when': {'greater-than': [{'left-operand': '$dropped-packets-others',
                                                       'right-operand': '$ddos-drop-count-threshold'}]}},
                           {'term-name': 'ddos-packet-drop-others-not-increasing',
                            'then': {'status': {'color': 'green'}}}],
                  'trigger-name': 'ddos-packet-dropped-others'}],
     'variable': [{'description': 'DDOS arrival rate threshold value',
                   'name': 'ddos-arrival-rate-threshold',
                   'type': 'int',
                   'value': '1000'},
                  {'description': 'DDOS drop count threshold value',
                   'name': 'ddos-drop-count-threshold',
                   'type': 'int',
                   'value': '0'},
                  {'description': 'DDOS drop rate threshold value',
                   'name': 'ddos-drop-rate-threshold',
                   'type': 'int',
                   'value': '1'}],
     'vector': None}



### Add new rule


```python
from jnpr.healthbot.modules.rules import RuleSchema
rs = RuleSchema(rule_name="hbez-fpc-heap-utilization")
```

### setting rule schema params


```python
rs.description = "HealthBot EZ example"
rs.synopsis = "Using python client for demo"
rs.sensor = [{'description': 'Monitors FPC buffer, heap and cpu utilization',
              'iAgent': {'file': 'fpc-utilization.yml',
                         'frequency': '30s',
                         'table': 'FPCCPUHEAPutilizationTable'},
              'sensor-name': 'fpccpuheaputilization'}]
```


```python
from jnpr.healthbot.swagger.models.rule_schema_field import RuleSchemaField
from jnpr.healthbot.swagger.models.rule_schema_constant import RuleSchemaConstant

rs.field = [RuleSchemaField(constant=RuleSchemaConstant(value='{{fpc-buffer-usage-threshold}}'),
                            description='This field is for buffer usage threshold',
                            field_name='linecard-buffer-usage-threshold'),
            RuleSchemaField(constant=RuleSchemaConstant(value='{{fpc-cpu-usage-threshold}}'),
                            description='This field is for linecard cpu usage threshold',
                            field_name='linecard-cpu-usage-threshold'),
            RuleSchemaField(constant=RuleSchemaConstant(value='{{fpc-heap-usage-threshold}}'),
                            description='This field is for linecard heap usage threshold',
                            field_name='linecard-heap-usage-threshold')]

rs.keys = ['slot']
```


```python
rs.variable = [{'description': 'Linecard Buffer Memory usage threshold value',
               'name': 'fpc-buffer-usage-threshold',
               'type': 'int',
               'value': '80'},
              {'description': 'Linecard CPU usage threshold value',
               'name': 'fpc-cpu-usage-threshold',
               'type': 'int',
               'value': '80'},
              {'description': 'Linecard Heap Memory usage threshold value',
               'name': 'fpc-heap-usage-threshold',
               'type': 'int',
               'value': '80'}]
```


```python
rs.trigger = [{'description': 'Sets health based on linecard buffer memory',
               'frequency': '60s',
               'synopsis': 'Linecard buffer memory kpi',
               'term': [{'term-name': 'is-buffer-memory-utilization-greater-than-threshold',
                         'then': {'status': {'color': 'red',
                                             'message': 'FPC buffer memory '
                                                        'utilization '
                                                        '($memory-buffer-utilization) '
                                                        'is over threshold '
                                                        '($linecard-buffer-usage-threshold)'}},
                         'when': {'greater-than': [{'left-operand': '$memory-buffer-utilization',
                                                    'right-operand': '$linecard-buffer-usage-threshold'}]}},
                        {'term-name': 'buffer-utilization-less-than-threshold',
                         'then': {'status': {'color': 'green'}}}],
               'trigger-name': 'fpc-buffer-memory-utilization'},
              {'description': 'Sets health based on linecard cpu utilization',
               'frequency': '60s',
               'synopsis': 'Linecard cpu utilization kpi',
               'term': [{'term-name': 'is-cpu-utilization-greater-than-80',
                         'then': {'status': {'color': 'red',
                                             'message': 'FPC CPU utilization '
                                                        '($cpu-total) is over '
                                                        'threshold '
                                                        '($linecard-cpu-usage-threshold)'}},
                         'when': {'greater-than': [{'left-operand': '$cpu-total',
                                                    'right-operand': '$linecard-cpu-usage-threshold',
                                                    'time-range': '180s'}]}},
                        {'term-name': 'cpu-utilization-less-than-threshold',
                         'then': {'status': {'color': 'green'}}}],
               'trigger-name': 'fpc-cpu-utilization'},
              {'description': 'Sets health based on linecard heap memory '
                              'utilization',
               'frequency': '60s',
               'synopsis': 'Linecard heap memory kpi',
               'term': [{'term-name': 'is-heap-memory-utilization-greater-than-threshold',
                         'then': {'status': {'color': 'red',
                                             'message': 'FPC heap memory '
                                                        'utilization '
                                                        '($memory-heap-utilization) '
                                                        'is over threshold '
                                                        '($linecard-heap-usage-threshold)'}},
                         'when': {'greater-than': [{'left-operand': '$memory-heap-utilization',
                                                    'right-operand': '$linecard-heap-usage-threshold'}]}},
                        {'term-name': 'heap-memory-utilization-less-than-threshold',
                         'then': {'status': {'color': 'green'}}}],
               'trigger-name': 'fpc-heap-memory-utilization'}]
```

### If the topic name is not present, first it will create given topic


```python
hb.rule.add('hbez', schema=rs)
```




    True




```python
# hb.rules.delete_rule(topic_name='external', rule_name="hbez-fpc-heap-utilization")
```

# Use Case: Playbooks


```python
pprint(hb.playbook.get('linecard-kpis-playbook'))
```

    {'description': 'Playbook checks linecard health i.e. cpu, memory and CM '
                    'errors',
     'playbook_name': 'linecard-kpis-playbook',
     'rules': ['linecard.cm-events/check-cm-events',
               'linecard.fpc/check-fpc-cpu',
               'linecard.fpc/check-fpc-memory'],
     'synopsis': 'Linecards key performance indicators'}



```python
from jnpr.healthbot.modules.playbooks import PlaybookSchema
```


```python
pbs = PlaybookSchema(playbook_name="HbEZ-example")
```


```python
pbs.description = "HbEZ Demo Examples"
pbs.synopsis = 'fpc status'
```


```python
pbs.rules = ['hbez/hbez-fpc-heap-utilization']
```


```python
hb.playbook.add(pbs)
```




    True




```python
hb.playbook.delete(playbook_name="HbEZ-example")
```

    





    True



# Use Case: Health


```python
pprint(hb.health.get_device_health('edge'))
```

    {'children': [{'children': [{'children': [], 'name': 'external'}],
                   'name': 'real'}],
     'color': None,
     'data': None,
     'name': 'edge',
     'timestamp': None}



```python
pprint(hb.health.get_device_group_health('real'))
```

    {'children': [{'children': [{'children': [], 'name': 'external'}],
                   'name': 'edge'}],
     'color': None,
     'data': None,
     'name': 'real',
     'timestamp': None}


# Use Case: Database
    This we might need to take it off


```python
print (hb.tsdb.query("show databases"))
```

    ResultSet({'('databases', None)': [{'name': 'health'}, {'name': '_internal'}, {'name': 'Core:vmx'}, {'name': 'real:edge'}, {'name': 'Core:demo'}, {'name': 'EVO_Core:EVO'}, {'name': 'EVO_CORE:EVO'}, {'name': 'vmx_db:vmx_db'}, {'name': 'vmx_db:core_db'}]})



```python
obj = hb.tsdb.query('select * from "protocol-eventd-host/check-host-traffic/packet-loss" limit 10', database='Core:vmx')
pprint(obj.raw)
```

    {'statement_id': 0}



```python
print(hb.version)
```

    2.0.1



```python
### Load any helper file
```


```python
hb.upload_helper_file('/Users/nitinkr/xxx/xyz.rule')

```

# Use Case: Notification


```python
from jnpr.healthbot import NotificationSchema
from jnpr.healthbot import NotificationSchemaSlack


ns = NotificationSchema(notification_name='HbEZ-notification')
ns.description = "example of adding notification via API"
nss = NotificationSchemaSlack(channel="HbEZ", url='http://testing')
ns.slack = nss
hb.settings.notification.add(ns)
```




    True




```python
print(hb.settings.notification.get())
```

    [{'description': 'example of adding notification via API',
     'http_post': None,
     'kafka_publish': None,
     'notification_name': 'HbEZ-notification',
     'slack': {'channel': 'HbEZ', 'url': 'http://testing'}}]



```python
pprint(hb.settings.notification.delete('HbEZ-notification'))
```

    


    True


# Use Case: Settings


```python
from jnpr.healthbot import RetentionPolicySchema

rps = RetentionPolicySchema(retention_policy_name='HbEZ-testing')
hb.settings.retention_policy.add(rps)
```




    True




```python
print(hb.settings.retention_policy.get())
```

    [{'duration': None, 'replication': None, 'retention_policy_name': 'HbEZ-testing'}, {'duration': None,
     'replication': None,
     'retention_policy_name': 'HbEZ-testing1'}, {'duration': None,
     'replication': None,
     'retention_policy_name': 'HbEZ-testing2'}]



```python
from jnpr.healthbot import SchedulerSchema
sc = SchedulerSchema(name='HbEZ-schedule', repeat={'every': 'week'}, start_time="2019-07-22T05:32:23Z")
hb.settings.scheduler.add(sc)

from jnpr.healthbot import DestinationSchema
ds = DestinationSchema(name='HbEZ-destination', email={'id': 'nitinkr@juniper.net'})
hb.settings.destination.add(ds)

from jnpr.healthbot import ReportSchema
rs = ReportSchema(name="HbEZ-report", destination=['HbEZ-destination'], format="html", schedule=["HbEZ-schedule"])
hb.settings.report.add(rs)
```




    True



# Use Case: PlayBook Instance


```python
from jnpr.healthbot.modules.playbooks import PlayBookInstanceBuilder

# case where we dont need to set any variable
pbb = PlayBookInstanceBuilder(hb, 'forwarding-table-summary', 'HbEZ-instance', 'Core')
pbb.apply()

#hb.commit()
```




    True



### when we need to set any rule variable for given device/group in playbook instance


```python
from jnpr.healthbot.modules.playbooks import PlayBookInstanceBuilder

pbb = PlayBookInstanceBuilder(hb, 'forwarding-table-summary', 'HbEZ-instance', 'Core')

variable = pbb.rule_variables["protocol.routesummary/check-fib-summary"]


variable.route_address_family = 'pqr'
variable.route_count_threshold = 100

# Apply variable to given device(s)
pbb.apply(device_ids=['vmx'])

#clear all the variable if you want to set it something else for group or other device(s)
pbb.clear()

variable = pbb.rule_variables["protocol.routesummary/check-fib-summary"]
variable.route_address_family = 'abc'
variable.route_count_threshold = 200

pbb.apply()

#hb.commit()
```




    True


### Configure hb charts when there is device-group present and there is a running playbook for it

```python
from jnpr.healthbot.swagger.models.hb_graphs_query import HbGraphsQuery
from jnpr.healthbot.swagger.models.hb_graphs import HbGraphs
from jnpr.healthbot import HealthBotClient

with HealthBotClient(ip, gui_username, gui_password, port=8080) as hb:

    # group_name, device_name, measurement_name, field_name are compulsory fields here
    query1 = HbGraphsQuery(group_name='dg-junos', device_name="d2", measurement_name="system.commit/commit-history",
                           transformation=None, field_name="l1-threshold", field_aggregation="mean",
                           where=[{'key': "comment", "operator": '=', "value": "new"}],
                           group_by_interval="1s", group_by_fill="fill(null)", group_by_tag_key=[])
    # Multiple queries can be present for a graph

    # graph_name, graph_type, time_range are compulsory here
    graph1 = HbGraphs(graph_name="graph1", graph_description=None, graph_type="Heatmap",
                      time_range='3h', query=[query1], y_label=None, y_max=None,
                      y_min=None, unit_type=None, decimals=None)
    # Multiple graphs can be present for a canvas 
    
    # Adding a new canvas with a single graph
    hb.charts.add_canvas(canvas_name="mycanvas", graphs=[graph1])
    hb.commit()

```




    True

        
        
# VERSIONS

Healthbot versions upto 3.2.0 are supported by `https://pypi.org/project/hbez/2.0.0/`

Healthbot/Paragon Insights 4.0.0 and above will be supported by `https://pypi.org/project/hbez/4.0.0/` and above

# LICENSE

Apache 2.0

# CONTRIBUTORS

Juniper Networks is actively contributing to and maintaining this repo. Please contact healthbot-hackers at juniper.net for any queries.

*Contributors:*

* v1.0.0: [Nitin Kumar](https://github.com/vnitinv)
* v2.0.0: [Nitin Kumar](https://github.com/vnitinv)
* v4.0.0: [Sharanya Bhat](https://github.com/sharanyabhat)
* v4.1.0: [Sharanya Bhat](https://github.com/sharanyabhat)
