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)
An image validator using FastAPI.

fast_api_image_validator An image validator using FastAPI.

Kevin Zehnder 7 Jan 06, 2022
Analytics service that is part of iter8. Robust analytics and control to unleash cloud-native continuous experimentation.

iter8-analytics iter8 enables statistically robust continuous experimentation of microservices in your CI/CD pipelines. For in-depth information about

16 Oct 14, 2021
Generate FastAPI projects for high performance applications

Generate FastAPI projects for high performance applications. Based on MVC architectural pattern, WSGI + ASGI. Includes tests, pipeline, base utilities, Helm chart, and script for bootstrapping local

Radosław Szamszur 274 Jan 08, 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
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
sample web application built with FastAPI + uvicorn

SPARKY Sample web application built with FastAPI & Python 3.8 shows simple Flask-like structure with a Bootstrap template index.html also has a backgr

mrx 21 Jan 03, 2022
Install multiple versions of r2 and its plugins via Pip on any system!

r2env This repository contains the tool available via pip to install and manage multiple versions of radare2 and its plugins. r2-tools doesn't conflic

radare org 18 Oct 11, 2022
基于Pytorch的脚手架项目,Celery+FastAPI+Gunicorn+Nginx+Supervisor实现服务部署,支持Docker发布

cookiecutter-pytorch-fastapi 基于Pytorch的 脚手架项目 按规范添加推理函数即可实现Celery+FastAPI+Gunicorn+Nginx+Supervisor+Docker的快速部署 Requirements Python = 3.6 with pip in

17 Dec 23, 2022
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
[rewrite 중] 코로나바이러스감염증-19(COVID-19)의 국내/국외 발생 동향 조회 API | Coronavirus Infectious Disease-19 (COVID-19) outbreak trend inquiry API

COVID-19API 코로나 바이러스 감염증-19(COVID-19, SARS-CoV-2)의 국내/외 발생 동향 조회 API Corona Virus Infectious Disease-19 (COVID-19, SARS-CoV-2) outbreak trend inquiry

Euiseo Cha 28 Oct 29, 2022
Deploy an inference API on AWS (EC2) using FastAPI Docker and Github Actions

Deploy an inference API on AWS (EC2) using FastAPI Docker and Github Actions To learn more about this project: medium blog post The goal of this proje

Ahmed BESBES 60 Dec 17, 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
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
A Nepali Dictionary API made using FastAPI.

Nepali Dictionary API A Nepali dictionary api created using Fast API and inspired from https://github.com/nirooj56/Nepdict. You can say this is just t

Nishant Sapkota 4 Mar 18, 2022
Piccolo Admin provides a simple yet powerful admin interface on top of Piccolo tables

Piccolo Admin Piccolo Admin provides a simple yet powerful admin interface on top of Piccolo tables - allowing you to easily add / edit / filter your

188 Jan 09, 2023
Web Version of avatarify to democratize even further

Web-avatarify for image animations This is the code base for this website and its backend. This aims to bring technology closer to everyone, just by a

Carlos Andrés Álvarez Restrepo 66 Nov 09, 2022
Mnist API server w/ FastAPI

Mnist API server w/ FastAPI

Jinwoo Park (Curt) 8 Feb 08, 2022
Online Repo Browser

MSYS2 Web Interface A simple web interface for browsing the MSYS2 repos. Rebuild CSS/JS (optional): cd frontend npm install npm run build Run for Dev

MSYS2 64 Dec 30, 2022
🤪 FastAPI + Vue构建的Mall项目后台管理

Mall项目后台管理 前段时间学习Vue写了一个移动端项目 https://www.charmcode.cn/app/mall/home 然后教程到此就结束了, 我就总感觉少点什么,计划自己着手写一套后台管理。 相关项目 移动端Mall项目源码(Vue构建): https://github.com/

王小右 131 Jan 01, 2023
Example of using FastAPI and MongoDB database.

FastAPI Todo Application Example of using FastAPI and MangoDB database. 💡 Prerequisites Python ⚙️ Build & Run The first thing to do is to clone the r

Bobynets Ivan 1 Oct 29, 2021