ReST based network device broker

Overview



The Open API Platform for Network Devices


netpalm makes it easy to push and pull state from your apps to your network by providing multiple southbound drivers, abstraction methods and modern northbound interfaces such as open API3 and REST webhooks.

Tests NTC Slack Github Issues Github Pull Requests Github Stars Github Contributors Github Release License

Supporting netpalm

Apcela
Apcela

Because Enterprise Speed Matters
Bandwidth


Delivering the power to communicate
Support
Maybe you?

Table of Contents

What is netpalm?

Leveraging best of breed open source network components like napalm, netmiko, ncclient and requests, netpalm makes it easy to abstract from any network devices native telnet, SSH, NETCONF or RESTCONF interface into a modern model driven open api 3 interface.

Taking a platform based approach means netpalm allows you to bring your own jinja2 config, service and webhook templates, python scripts and webhooks for quick adoption into your existing devops workflows.

Built on a scalable microservice based architecture netpalm provides unparalleled scalable API access into your network.

Features

  • Speaks REST and JSON RPC northbound, then CLI over SSH or Telnet or NETCONF/RESTCONF southbound to your network devices
  • Turns any Python script into a easy to consume, asynchronous and documented API with webhook support
  • Large amount of supported network device vendors thanks to napalm, netmiko, ncclient and requests
  • Built in multi-level abstraction interface for network service lifecycle functions for create, retrieve and delete and validate
  • In band service inventory
  • Ability to write your own service models and templates using your own existing jinja2 templates
  • Well documented API with postman collection full of examples and every instance gets it own self documenting openAPI 3 UI.
  • Supports pre and post checks accross CLI devices raising exceptions and not deploying config as required
  • Multiple ways to queue jobs to devices, either pinned strict (prevent connection pooling at device)or pooled first in first out
  • Modern, container based scale out architecture supported by every component
  • Highly configurable for all aspects of the platform
  • Leverages an ecrypted Redis layer providing caching and queueing of jobs to and from devices

Concepts

Basic Concepts

netpalm acts as a ReST broker and abstraction layer for NAPALM, Netmiko, NCCLIENT or a Python Script. netpalm uses TextFSM or Jinja2 to model and transform both ingress and egress data if required.

Component Concepts

netpalm is underpinned by a container based scale out architecture for all components.

Queueing Concepts

netpalm provides domain focused queueing strategy for task execution on network equipment.

Scaling Concepts

Every netpalm container can be scaled in and out as required. Kubernetes or Swarm is reccomended for any large scale deployments.

To scale out the basic included compose deployment use the docker-compose command

docker-compose scale netpalm-controller=1 netpalm-worker-pinned=2 netpalm-worker-fifo=3

Additional Features

  • Jinja2

  • Parsers

    • TextFSM support via netmiko
    • NTC-templates for parsing/structuring device data (includes)
    • TTP Template Text Parser - Jinja2-like parsing of semi-structured CLI data
    • Napalm getters
    • Genie support via netmiko
    • Automated download and installation of TextFSM templates from http://textfsm.nornir.tech online TextFSM development tool
    • Optional dynamic rendering of Netconf XML data into JSON
  • Webhooks

    • Comes with standard REST webhook which supports data transformation via your own jinja2 template
    • Supports you to bring your own (BYO) webhook scripts
  • Scripts

    • Execute ANY python script as async via the ReST API and includes passing in of parameters
    • Supports pydantic models for data validation and documentation
  • Queueing

    • Supports a "pinned" queueing strategy where a dedicated process and queue is established for your device, tasks are sync queued and processed for that device
    • Supports a "fifo" pooled queueing strategy where a pool of workers
    • Supports on the fly changes to the async queue strategy for a device
  • Caching

    • Can cache responses from devices so that the same request doesnt have to go back to the device
    • Automated cache poisioning on config changes on devices
  • Scaling

    • Horizontal container based scale out architecture supported by each component

Examples

We could show you examples for days, but we recommend playing with the online postman collection to get a feel for what can be done. We also host a public instance where you can test netpalm via the Swagger UI.

getconfig method

netpalm also supports all arguments for the transport libs, simply pass them in as below

netpalm eg3

check response

netpalm eg4

ServiceTemplates

netpalm supports model driven service templates, these self render an OpenAPI 3 interface and provide abstraction and orchestration of tasks accross many devices using the get/setconfig or script methods.

The below example demonstrates basic SNMP state orchestration accross multiple devices for create, retrieve, delete

netpalm auto ingest

Template Development and Deployment

netpalm is integrated into http://textfsm.nornir.tech so you can ingest your templates with ease

netpalm auto ingest

API Docs

netpalm comes with a Postman Collection and an OpenAPI based API with a SwaggerUI located at http://localhost:9000/ after starting the container.

netpalm swagger

Caching

  • Supports the following per-request configuration (/getconfig routes only for now)

    • permit the result of this request to be cached (default: false), and permit this request to return cached data
    • hold the cache for 30 seconds (default: 300. Should not be set above redis_task_result_ttl which defaults to 500)
    • do NOT invalidate any existing cache for this request (default: false)
      {
        "cache": {
          "enabled": true,
          "ttl": 30,
          "poison": false
        }
      }
  • Supports the following global configuration:

    • Enable/Disable caching: "redis_cache_enabled": true for caching to apply it must be enabled BOTH globally and in the request itself
    • Default TTL: "redis_cache_default_timeout": 300
  • Any change to the request payload will result in a new cache key EXCEPT:

    • JSON formatting. { "x": 1, "y": 2 } == {"x":1,"y":2}
    • Dictionary ordering: {"x":1,"y":2} == {"y":2,"x"1}
    • changes to cache configuration (e.g. changing the TTL, etc)
    • fifo vs pinned queueing strategy
  • Any call to any /setconfig route for a given host:port will poison ALL cache entries for that host:port

    • Except /setconfig/dry-run of course

Configuration

Edit the config/config.json file to change any parameters

{
    "api_key": "2a84465a-cf38-46b2-9d86-b84Q7d57f288",
    "api_key_name" : "x-api-key",
    "cookie_domain" : "netpalm.local",
    "listen_port": 9000,
    "listen_ip":"0.0.0.0",
    "gunicorn_workers":3,
    "redis_task_ttl":500,
    "redis_task_timeout":500,
    "redis_server":"redis",
    "redis_port":6379,
    "redis_core_q":"process",
    "redis_fifo_q":"fifo",
    "redis_queue_store":"netpalm_queue_store",
    "pinned_process_per_node":100,
    "fifo_process_per_node":10,
    "txtfsm_index_file":"backend/plugins/ntc-templates/index",
    "txtfsm_template_server":"http://textfsm.nornir.tech",
    "custom_scripts":"backend/plugins/custom_scripts/",
    "jinja2_config_templates":"backend/plugins/jinja2_templates/",
    "jinja2_service_templates":"backend/plugins/service_templates/",
    "self_api_call_timeout":15
}

Installation

  1. Ensure you first have docker installed
sudo apt-get install docker.io
sudo apt-get install docker-compose
  1. Clone this repository
git clone https://github.com/tbotnz/netpalm.git
cd netpalm
  1. Build the container
sudo docker-compose up -d --build
  1. After the container has been built and started, you're good to go! netpalm will be available on port 9000 under your docker hosts IP.
http://$(yourdockerhost):9000

Further Reading

Contributing

We are open to contributions, before making a PR, please make sure you've read our CONTRIBUTING.md document.

You can also find us in the channel #netpalm on the networktocode Slack.

Comments
  • Fix netmiko driver save_config/commit

    Fix netmiko driver save_config/commit

    The problem with the current commit/save_config is that every device class in netmiko inherits BaseConnection which defines both a commit and save_config. Its up to child classes to implement these. The problem is that since its using an if/elif statement the save_config method never gets called for device that have implemented it (NXOS, IOS, etc).

    The change here just catches the exception if the netmiko device class doesn't implement commit then tries to run save_config

    These changes work fine on live devices (IOSXR, NXOS) but the pytests would fail all the time. I spent a long time on it and it seems pytest will fail when it tries to save_config. Not really sure why its failing on that but as a fix I changed the uri's to /setconfig/dry-run for the tests which bypasses these save functions. Tests pass now but just wanted to let you know.

    opened by rhwendt 8
  • ncclient j2config support

    ncclient j2config support

    This PR addresses some issues I was facing when attempting to push config using ncclient. Below is a summary of the issues I had when using this library.

    • editconfig would return Unserializable return value from redis jobs
    • lack of jinja2 templating when using ncclient

    Here is a summary of the changes I am proposing.

    • Move render_json boolean out of the args body making it an optional component. This allows me to render json from the reponses of getconfig and setconfig when using the ncclient library.
    • render_json works for both getconfig and setconfig respones in the ncclient library.
    • Made args in NcclientSetConfig model optional.
    • Made j2config in NcclientSetConfig model optional.
    • If you rendered j2config for ncclient it will add it to the kwargs['args']['config'] dict which gets passed to ncclient.
    • ncclient_drvr.ncclien:editconfig formats the response as xml
    • added a ncclient template for pytest
    • added a new method for setconfig mark for pytest test_setconfig_ncclient_j2()
    • fixed references to render_json in test files.

    Side note: Do you have issues with github actions failing randomly for no reason? I built it several times locally and they passed but when I ran the github actions they would fail on different errors each time and eventually it passed after running more than once?

    opened by rhwendt 6
  • TFSM template addtemplate route won't create a new section for a new driver

    TFSM template addtemplate route won't create a new section for a new driver

    e.g. this "completes" just fine but never shows up in "gettemplates" output. Not sure if it's just the index rewrite that's failing or what.

    {
    	"key": "",
    	"driver": "cisgo_foo",
    	"command": "show asdf events"
    }
    
    opened by wrgeorge1983 6
  • Out of process by orphan processes

    Out of process by orphan processes

    When i deploy the project on a physical machine with the pinned worker model, the network worker like "rq:worker:11.0.2.2_4a06654f-0a23-4ee3-8ae6-dceb8d2b6f54" will be orphan process when the pinned worker process down, which should be killed.

    I looked through the source code,the RQ module use the os.fork to create a sub process in fork_work_horse, if the subprocess exit after execution,that's right. However, the subprocess is pinned_worker_constructor, it also has a subprocess pinned_worker which is loop, not exit, when the pinned_worker_constructor completed, it will be exited, so the pinned_worker will be orphan process. The orphan process will be sending heartbeat message after default_worker_ttl, so the pinned worker state has only one filed "last_heartbeat".

    Out of process will be caused by the pinned worker multiple restarts. The container environment doesn't has the problem due to container only monitor the init process which will also take over the orphan process.

    wontfix 
    opened by wwolfk 5
  • adding capabilities flag for /getconfig/ncclient

    adding capabilities flag for /getconfig/ncclient

    Adding a capabilities flag to /getconfig/ncclient so we can get netconf capabilities of the target devices.

    I figured this was better than adding an entire new endpoint.

    opened by rhwendt 4
  • Auto reload of template directory

    Auto reload of template directory

    Templates are currently loaded on container creation and containers have to be re-built if the templates are edited. It would be ideal if the template directory was reloaded automatically after a certain time period or when a template has been changed.

    opened by abrown-bw 4
  • Custom scripts fail at failing

    Custom scripts fail at failing

    It seems like when a script runs into an exception, it gets caught by s_exec in netpalm/backend/plugins/calls/scriptrunner/script.py and returns the exception string to the script_exec function, which then has no way to know it failed. This makes scripts always be reported as successful. Would it be better to either remove the try/except in s_exec or maybe have it re-raise the exception or something? Am I just missing something here?

    Modified "hello_world" script to fail and raise an exception:

    def run(**kwargs):
            args = kwargs.get("kwargs")
            world = args.get("hello")
            return non_existent_world
    

    Current result:

    <...>
       "task_status": "finished",
        "task_result": {},
        "task_errors": []
      }
    

    Modified scriptrunner/script.py function:

        def s_exec(self):
            module = importlib.import_module(self.script_name)
            runscrp = getattr(module, "run")
            res = runscrp(kwargs=self.arg)
            return res
    

    Result with modified s_exec():

    <...>
        "task_status": "failed",
        "task_result": null,
        "task_errors": [
          "name 'non_existent_world' is not defined"
        ]
    
    opened by jtishey 3
  • Failed to Conect

    Failed to Conect

    I think I missed something on the install I can run a getconfig command but the task is telling me it can not connect to the device. I am connecting to a cisco 3750 using cisco_ios. I can ssh in to that unit just fine from the machine that Docker is running on...what did I miss?

    invalid 
    opened by wardjallen 3
  • WIP: Add 'interfaces' service template

    WIP: Add 'interfaces' service template

    Add interfaces service template to ease the pulling of interface details with the end goal of creating a csv which one can easily import into the Netbox bulk interface importer.

    Current idea is to start with very basics and maybe just wrap this in a little CLI which can simply output the csv which one can paste into netbox. Further enhancements could include directly calling the netbox api to add said interfaces or something like that.

    Notes

    Netbox interface importer example: https://netboxdemo.com/dcim/interfaces/import

    Login: netbox/netbox

    Fields:

    device, name, type, enabled, mac_address, mtu, description, mode 
    
    • device - device name which the interface belongs to
    • name - interface name
    • type - physical medium (SFP, 10/100, 1G, etc.)
    • enabled - boolean on/off
    • mac_address - mac address
    • mtu - mtu size
    • description - description
    • mode - 802.1Q Mode (access, tagged, tagged (all))
    opened by ndom91 3
  • Expand variable usage in Postman

    Expand variable usage in Postman

    Used environment/collection variables for: the netpalm host itself the x-api-key header device creds that were 'admin/admin' (leaving alone those for the IOS XE REST sandbox)

    Used path variables as show in screenshot for: /task/:task_id /service/:service_id

    Path variables make it a bit easier/cleaner to paste values from other commands into. I, at least, find it difficult to make certain I'm not overwriting too many characters when pasting directly into the url, etc.

    image

    NOTE: Postman seems to prefer using tab indentation. Existing "bodies" were mix of tabs/spaces, so I settled on tabs.
    This isn't too hard to re-do, wrote a short utility to make it easier in the future if needed (i.e. need to create a bunch of new endpoints w/o manually futzing w/ variable definitions, etc)

    opened by wrgeorge1983 3
  • No rollback option for a task

    No rollback option for a task

    Please add rollback option for any task. This can be solved by two ways-

    1. auto generating the delete config for service template which can be triggered when asked to rollback.
    2. A rollback api can be developed which can just copy the rollback config to current running configuration device( generated during task execution by napalm)
    enhancement 
    opened by Minal1409 3
  • Vagrant support

    Vagrant support

    This adds support to build netpalm in a vagrant vm.

    I primarily need this for issues accessing resources over a VPN connection while developing my app.

    Edit: I think this would also be useful for people that just want to spin it up quick and test as well.

    opened by rhwendt 1
  • Update netmiko_drvr.py

    Update netmiko_drvr.py

    Add the ability to pass an array to "ttp_template" key in netmiko args. It will match any given command in order with the template. If there's a command without a template, it should be put in the end of the command array, and it will get the raw data.

    Example 1, will match command with template, in order (command1 -> template1, command2 -> template2) command: [ 'command1', 'command2' ] ttp_template: [ 'template1', 'template2' ]

    Example 2, will match command with template, and command without template will return the raw data (command1 -> template1, command2 -> raw) command: [ 'command1', 'command2' ] ttp_template: [ 'template1' ]

    If command and ttp_template are a string, they will be encapsulated in an array and will be matched as before.

    opened by hanunes 4
  • Use multiple ttp templates with multiple commands

    Use multiple ttp templates with multiple commands

    At the moment it's not possible to pass an array of commands to getconfig endpoint, and match multiple ttp templates to the output, meaning that you can't effectively parse data correctly. When you try to do this, only the first command get's parsed correctly.

    Would this be too hard to implement?

    opened by hanunes 4
  • Genie not available as parser

    Genie not available as parser

    I checked the requirements.txt that genie is in the list of modules to be installed. But If I try to use it in a get Config request I get an error that it is not installed.

    "args": {
       "use_genie": "true"
      },
    
    
    
    "exception_args": [
              "\nGenie and PyATS are not installed. Please PIP install both Genie and PyATS:\npip install genie\npip install pyats\n"
            ]
    
    opened by empusas 3
  • FR: new extensibles endpoints

    FR: new extensibles endpoints

    Would certainly be nice to have a few new extensibles endpoints:

    1. Bulk upload. Reload using the /reload-extensibles endpoint once at the end of processing the payload.
    2. Delete extensibles. Bulk delete, maybe?
    opened by brobare 0
Releases(v0.2.6)
Owner
null
Backend, modern REST API for obtaining match and odds data crawled from multiple sites. Using FastAPI, MongoDB as database, Motor as async MongoDB client, Scrapy as crawler and Docker.

Introduction Apiestas is a project composed of a backend powered by the awesome framework FastAPI and a crawler powered by Scrapy. This project has fo

Fran Lozano 54 Dec 13, 2022
signal-cli-rest-api is a wrapper around signal-cli and allows you to interact with it through http requests

signal-cli-rest-api signal-cli-rest-api is a wrapper around signal-cli and allows you to interact with it through http requests. Features register/ver

Sebastian Noel Lübke 31 Dec 9, 2022
Publish Xarray Datasets via a REST API.

Xpublish Publish Xarray Datasets via a REST API. Serverside: Publish a Xarray Dataset through a rest API ds.rest.serve(host="0.0.0.0", port=9000) Clie

xarray-contrib 106 Jan 6, 2023
REST API with FastAPI and SQLite3.

REST API with FastAPI and SQLite3

Luis Quiñones Requelme 2 Mar 14, 2022
A Prometheus Python client library for asyncio-based applications

aioprometheus aioprometheus is a Prometheus Python client library for asyncio-based applications. It provides metrics collection and serving capabilit

null 132 Dec 28, 2022
FastAPI Admin Dashboard based on FastAPI and Tortoise ORM.

FastAPI ADMIN 中文文档 Introduction FastAPI-Admin is a admin dashboard based on fastapi and tortoise-orm. FastAPI-Admin provide crud feature out-of-the-bo

long2ice 1.6k Dec 31, 2022
JSON-RPC server based on fastapi

Description JSON-RPC server based on fastapi: https://fastapi.tiangolo.com Motivation Autogenerated OpenAPI and Swagger (thanks to fastapi) for JSON-R

null 199 Dec 30, 2022
The template for building scalable web APIs based on FastAPI, Tortoise ORM and other.

FastAPI and Tortoise ORM. Powerful but simple template for web APIs w/ FastAPI (as web framework) and Tortoise-ORM (for working via database without h

prostomarkeloff 95 Jan 8, 2023
a lightweight web framework based on fastapi

start-fastapi Version 2021, based on FastAPI, an easy-to-use web app developed upon Starlette Framework Version 2020 中文文档 Requirements python 3.6+ (fo

HiKari 71 Dec 30, 2022
A Jupyter server based on FastAPI (Experimental)

jupyverse is experimental and should not be used in place of jupyter-server, which is the official Jupyter server.

Jupyter Server 122 Dec 27, 2022
A simple docker-compose app for orchestrating a fastapi application, a celery queue with rabbitmq(broker) and redis(backend)

fastapi - celery - rabbitmq - redis -> Docker A simple docker-compose app for orchestrating a fastapi application, a celery queue with rabbitmq(broker

Kartheekasasanka Kaipa 83 Dec 19, 2022
A script that publishes power usage data of iDrac enabled servers to an MQTT broker for integration into automation and power monitoring systems

iDracPowerMonitorMQTT This script publishes iDrac power draw data for iDrac 6 enabled servers to an MQTT broker. This can be used to integrate the pow

Lucas Zanchetta 10 Oct 6, 2022
Lightweight asyncio compatible utilities for consuming broker messages.

A simple asyncio compatible consumer for handling amqp messages.

Mehdi Kamani 3 Apr 10, 2022
A facial recognition device is a device that takes an image or a video of a human face and compares it to another image faces in a database.

A facial recognition device is a device that takes an image or a video of a human face and compares it to another image faces in a database. The structure, shape and proportions of the faces are compared during the face recognition steps.

Pavankumar Khot 4 Mar 19, 2022
User-related REST API based on the awesome Django REST Framework

Django REST Registration User registration REST API, based on Django REST Framework. Documentation Full documentation for the project is available at

Andrzej Pragacz 399 Jan 3, 2023
AI-based, context-driven network device ranking

Batea A batea is a large shallow pan of wood or iron traditionally used by gold prospectors for washing sand and gravel to recover gold nuggets. Batea

Secureworks Taegis VDR 269 Nov 26, 2022
Run your jupyter notebooks as a REST API endpoint. This isn't a jupyter server but rather just a way to run your notebooks as a REST API Endpoint.

Jupter Notebook REST API Run your jupyter notebooks as a REST API endpoint. This isn't a jupyter server but rather just a way to run your notebooks as

Invictify 54 Nov 4, 2022
RESTler is the first stateful REST API fuzzing tool for automatically testing cloud services through their REST APIs and finding security and reliability bugs in these services.

RESTler is the first stateful REST API fuzzing tool for automatically testing cloud services through their REST APIs and finding security and reliability bugs in these services.

Microsoft 1.8k Jan 4, 2023
Django-rest-auth provides a set of REST API endpoints for Authentication and Registration

This app makes it extremely easy to build Django powered SPA's (Single Page App) or Mobile apps exposing all registration and authentication related functionality as CBV's (Class Base View) and REST (JSON)

Tivix 2.4k Dec 29, 2022
Atualizando o projeto APIs REST Django REST 2.0

APIs REST Django REST 3.0-KevinSoffa Atualização do projeto APIs REST Django REST 2.0-Kevin Soffa Melhorando e adicionando funcionalidades O que já fo

Kevin Soffa 2 Dec 13, 2022