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)
OpenAPI generated FastAPI server

OpenAPI generated FastAPI server This Python package is automatically generated by the OpenAPI Generator project: API version: 1.0.0 Build package: or

microbo 1 Oct 31, 2021
Python supercharged for the fastai library

Welcome to fastcore Python goodies to make your coding faster, easier, and more maintainable Python is a powerful, dynamic language. Rather than bake

fast.ai 810 Jan 06, 2023
An extension for GINO to support Starlette server.

gino-starlette Introduction An extension for GINO to support starlette server. Usage The common usage looks like this: from starlette.applications imp

GINO Community 75 Dec 08, 2022
Minimal example utilizing fastapi and celery with RabbitMQ for task queue, Redis for celery backend and flower for monitoring the celery tasks.

FastAPI with Celery Minimal example utilizing FastAPI and Celery with RabbitMQ for task queue, Redis for Celery backend and flower for monitoring the

Grega Vrbančič 371 Jan 01, 2023
First API using FastApi

First API using FastApi Made this Simple Api to store and Retrive Student Data of My College Ncc-Bim To View All the endpoits Visit /docs To Run Local

Sameer Joshi 2 Jun 21, 2022
Monitor Python applications using Spring Boot Admin

Pyctuator Monitor Python web apps using Spring Boot Admin. Pyctuator supports Flask, FastAPI, aiohttp and Tornado. Django support is planned as well.

SolarEdge Technologies 145 Dec 28, 2022
A minimalistic example of preparing a model for (synchronous) inference in production.

A minimalistic example of preparing a model for (synchronous) inference in production.

Anton Lozhkov 6 Nov 29, 2021
Lung Segmentation with fastapi

Lung Segmentation with fastapi This app uses FastAPI as backend. Usage for app.py First install required libraries by running: pip install -r requirem

Pejman Samadi 0 Sep 20, 2022
Money Transaction is a system based on the recent famous FastAPI.

moneyTransfer Overview Money Transaction is a system based on the recent famous FastAPI. techniques selection System's technique selection is as follo

2 Apr 28, 2021
Example of integrating Poetry with Docker leveraging multi-stage builds.

Poetry managed Python FastAPI application with Docker multi-stage builds This repo serves as a minimal reference on setting up docker multi-stage buil

Michael Oliver 266 Dec 27, 2022
TODO aplication made with Python's FastAPI framework and Hexagonal Architecture

FastAPI Todolist Description Todolist aplication made with Python's FastAPI framework and Hexagonal Architecture. This is a test repository for the pu

Giovanni Armane 91 Dec 31, 2022
This project is a realworld backend based on fastapi+mongodb

This project is a realworld backend based on fastapi+mongodb. It can be used as a sample backend or a sample fastapi project with mongodb.

邱承 381 Dec 29, 2022
The base to start an openapi project featuring: SQLModel, Typer, FastAPI, JWT Token Auth, Interactive Shell, Management Commands.

The base to start an openapi project featuring: SQLModel, Typer, FastAPI, JWT Token Auth, Interactive Shell, Management Commands.

Bruno Rocha 251 Jan 09, 2023
asgi-server-timing-middleware

ASGI Server-Timing middleware An ASGI middleware that wraps the excellent yappi profiler to let you measure the execution time of any function or coro

33 Dec 15, 2022
更新 2.0 版本,使用 Python WEB 高性能异步框架 FastAPI 制作的抖音无水印解析下载,采用前后端分离思想!

前言 这个是 2.0 版本,使用现在流行的前后端分离思想重构。 体验网址:https://douyin.bigdataboy.cn 更新日志 2020.05.30:使用 FastAPI 前后端分离重构 2020.05.02:已更新,正常使用 2020.04.27:抖音结构更新,已修复视频有水印。(失

64 Nov 25, 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 08, 2023
Basic FastAPI starter with GraphQL, Docker, and MongoDB configurations.

FastAPI + GraphQL Starter A python starter project using FastAPI and GraphQL. This project leverages docker for containerization and provides the scri

Cloud Bytes Collection 1 Nov 24, 2022
Recommend recipes based on what ingredients you have at home

🌱 MyChef 📦 Overview MyChef is an application that helps you decide what meal to make based on what you have at home. Simply enter in ingredients you

Logan Connolly 44 Nov 08, 2022
fastapi-crud-sync

Developing and Testing an API with FastAPI and Pytest Syncronous Example Want to use this project? Build the images and run the containers: $ docker-c

59 Dec 11, 2022
Auth for use with FastAPI

FastAPI Auth Pluggable auth for use with FastAPI Supports OAuth2 Password Flow Uses JWT access and refresh tokens 100% mypy and test coverage Supports

David Montague 95 Jan 02, 2023