Package: openwisp-ipam
Table of Contents:Available FeaturesProject GoalsDependenciesInstall stable versionInstall development versionInstallation for developmentRun TestsVisual Display of subnetsREST APILive documentationBrowsable web interfaceAuthenticationPaginationList of endpointsAPI ThrottlingGet Next Available IPIpAddress-Subnet List and Create ViewSubnet List/Create ViewSubnet ViewIP Address ViewExport Subnet ViewImport Subnet ViewExporting and Importing SubnetCSV file formatSetup (integrate in an existing Django project)Extending openwisp-ipam1. Initialize your custom module2. Installopenwisp-ipam3. AddEXTENDED_APPS4. Addopenwisp_utils.staticfiles.DependencyFinder5. Addopenwisp_utils.loaders.DependencyLoader6. Inherit the AppConfig class7. Create your custom models8. Add swapper configurations9. Create database migrations10. Create the admin11. Create root URL configuration12. Import the automated testsOther base classes that can be inherited and extendedContributingAvailable FeaturesIPv4 and IPv6 IP address managementIPv4 and IPv6 Subnet managementAutomatic free space display for all subnetsVisual display for a specific subnetIP request moduleREST API for CRUD operations and main featuresPossibility to search for an IP or subnetCSV Import and Export of subnets and their IPsProject Goalsprovide basic features of IP Address management as a reusable django appintegrate this module in the rest of the OpenWISP ecosystemallow standalone usage (without the rest of OpenWISP)provide ways to extended the core features in order to create derivativesDependenciesPython 3.7 or higherDjango 3.0 or higherDjango REST Framework (for the REST API)openwisp-usersswapperInstall stable versionpipinstallopenwisp-ipamInstall development versionInstall tarball:pipinstallhttps://github.com/openwisp/openwisp-ipam/tarball/masterAlternatively you can install via pip using git:pipinstall-egit+git://github.com/openwisp/openwisp-ipam#egg=openwisp-ipamInstallation for developmentInstallopenwisp-ipamfor development using following commands:gitclonehttps://github.com/openwisp/openwisp-ipam.gitcdopenwisp-ipampipinstall-e.pipinstall-rrequirements-test.txtLaunch the development sever:cdtests/./manage.pymigrate./manage.pycreatesuperuser./manage.pyrunserverYou can access the admin interface athttp://127.0.0.1:8000/admin/.Run TestsInstall test requirements:pipinstall-rrequirements-test.txtThen run the test suite:# options "--keepdb" & "--parallel" are optional but
# improve time required for running tests../runtests.py--keepdb--parallel# Run tests for the sample_appSAMPLE_APP=1./runtests.py--keepdb--parallelVisual Display of subnetsopenwisp-ipam provides a graphical representation of a subnet which shows the available free space under any subnet.REST APILive documentationA general live API documentation (following the OpenAPI specification) is available at/api/v1/docs/.Browsable web interfaceAdditionally, opening any of the endpointslisted belowdirectly in the browser will show thebrowsable API interface of Django-REST-Framework,
which makes it even easier to find out the details of each endpoint.AuthenticationSee openwisp-users:authenticating with the user token.When browsing the API via theLive documentationor theBrowsable web page, you can also use
the session authentication by logging in the django admin.PaginationAlllistendpoints support thepage_sizeparameter that allows paginating
the results in conjunction with thepageparameter.GET /api/v1/<api endpoint url>/?page_size=10
GET /api/v1/<api endpoint url>/?page_size=10&page=2List of endpointsSince the detailed explanation is contained in theLive documentationand in theBrowsable web pageof each endpoint,
here we’ll provide just a list of the available endpoints,
for further information please open the URL of the endpoint in your browser.API ThrottlingTo override the default API throttling settings, add the following to yoursettings.pyfile:REST_FRAMEWORK={'DEFAULT_THROTTLE_RATES':{'ipam':'100/hour',}}The rate descriptions used inDEFAULT_THROTTLE_RATESmay includesecond,minute,hourordayas the throttle period.Get Next Available IPA model method to fetch the next available IP address under a specific subnet. This method can also be accessed via a REST API:openwisp_ipam/base/models.pyGETReturns the next available IP address under a subnet./api/v1/ipam/subnet/<subnet_id>/get-next-available-ip/Request IPA model method to create and fetch the next available IP address record under a subnet.POSTCreates a record for next available IP address and returns JSON data of that record.POST /api/v1/ipam/subnet/<subnet_id>/request-ip/ParamDescriptiondescriptionOptional description for the IP addressResponse{"ip_address":"ip_address","subnet":"subnet_uuid","description":"optional description"}IpAddress-Subnet List and Create ViewAn api endpoint to retrieve or create IP addresses under a specific subnet.GETReturns the list of IP addresses under a particular subnet./api/v1/ipam/subnet/<subnet_id>/ip-address/POSTCreate a newIP Address./api/v1/ipam/subnet/<subnet_id>/ip-address/ParamDescriptionip_addressIPv6/IPv4 address valuesubnetSubnet UUIDdescriptionOptional description for the IP addressSubnet List/Create ViewAn api endpoint to create or retrieve the list of subnet instances.GETReturns the list ofSubnetinstances./api/v1/ipam/subnet/POSTCreate a newSubnet./api/v1/ipam/subnet/ParamDescriptionsubnetSubnet value in CIDR formatmaster_subnetMaster Subnet UUIDdescriptionOptional description for the IP addressSubnet ViewAn api endpoint for retrieving, updating or deleting a subnet instance.GETGet details of aSubnetinstance/api/v1/ipam/subnet/<subnet-id>/DELETEDelete aSubnetinstance/api/v1/ipam/subnet/<subnet-id>/PUTUpdate details of aSubnetinstance./api/v1/ipam/subnet/<subnet-id>/ParamDescriptionsubnetSubnet value in CIDR formatmaster_subnetMaster Subnet UUIDdescriptionOptional description for the IP addressIP Address ViewAn api endpoint for retrieving, updating or deleting a IP address instance.GETGet details of anIP addressinstance./api/v1/ipam/ip-address/<ip_address-id>/DELETEDelete anIP addressinstance./api/v1/ipam/ip-address/<ip_address-id>/PUTUpdate details of anIP addressinstance./api/v1/ipam/ip-address/<ip_address-id>/ParamDescriptionip_addressIPv6/IPv4 valuesubnetSubnet UUIDdescriptionOptional description for the IP addressExport Subnet ViewView to export subnet data.POST/api/v1/ipam/subnet/<subnet-id>/export/Import Subnet ViewView to import subnet data.POST/api/v1/ipam/import-subnet/Exporting and Importing SubnetOne can easily import and exportSubnetdata and it’s Ip Addresses usingopenwisp-ipam.
This works for both IPv4 and IPv6 types of networks.ExportingData can be exported via the admin interface or by using a management command. The exported data is in.csvfile format.From management command./manage.pyexport_subnet<subnetvalue>This would export the subnet if it exists on the database.From admin interfaceData can be exported from the admin interface by just clicking on the export button on the subnet’s admin change view.ImportingData can be imported via the admin interface or by using a management command.
The imported data file can be in.csvand.xlsxformat. While importing
data for ip addresses, the system checks if the subnet specified in the import file exists or not.
If the subnet does not exists it will be created while importing data.From management command./manage.pyimport_subnet--file=<filepath>From admin interfaceData can be imported from the admin interface by just clicking on the import button on the subnet view.CSV file formatFollow the following structure while creatingcsvfile to import data.Subnet Name
Subnet Value
Organization Slug

ip_address,description
<ip-address>,<optional-description>
<ip-address>,<optional-description>
<ip-address>,<optional-description>Setup (integrate in an existing Django project)Thesettings.pyof your project should contain the following:INSTALLED_APPS=[# openwisp2 modules'openwisp_users','openwisp_ipam',# admin'django.contrib.admin',# rest framework'rest_framework','drf_yasg',]AUTH_USER_MODEL='openwisp_users.User'Add the URLs to your mainurls.py:fromdjango.contribimportadminfromdjango.urlsimportinclude,pathfromopenwisp_users.api.urlsimportget_api_urlsasget_users_api_urlsurlpatterns=[# admin URLspath('admin/',admin.site.urls),# IPAM APIpath('',include('openwisp_ipam.urls')),# OpenAPI docspath('api/v1/',include('openwisp_utils.api.urls')),# Bearer Authentication API URLpath('api/v1/',include((get_users_api_urls(),'users'),namespace='users')),]Then run:./manage.pymigrateExtending openwisp-ipamOne of the core values of the OpenWISP project isSoftware Reusability,
for this reasonopenwisp-ipamprovides a set of base classes
which can be imported, extended and reused to create derivative apps.In order to implement your custom version ofopenwisp-ipam,
you need to perform the steps described in this section.When in doubt, the code in thetest projectand
thesample appwill serve you as source of truth:
just replicate and adapt that code to get a basic derivative ofopenwisp-ipamworking.If you want to add new users fields, please follow thetutorial to extend the
openwisp-users.
As an example, we have extendedopenwisp-userstosample_usersapp and
added a fieldsocial_security_numberin thesample_users/models.py.Premise: if you plan on using a customized version of this module,
we suggest to start with it since the beginning, because migrating your data
from the default module to your extended version may be time consuming.1. Initialize your custom moduleThe first thing you need to do is to create a new django app which will
contain your custom version ofopenwisp-ipam.A django app is nothing more than apython package(a directory of python scripts), in the following examples we’ll call this django appmyipam, but you can name it how you want:django-admin startapp myipamKeep in mind that the command mentioned above must be called from a directory
which is available in yourPYTHON_PATHso that you can then import the result into your project.Now you need to addmyipamtoINSTALLED_APPSin yoursettings.py,
ensuring also thatopenwisp_ipamhas been removed:INSTALLED_APPS=[# ... other apps ...'openwisp_utils.admin_theme',# all-auth'django.contrib.sites','allauth','allauth.account','allauth.socialaccount',# openwisp2 modules'openwisp_users',# 'myipam',   <-- replace without your app-name here# admin'django.contrib.admin',# rest framework'rest_framework',# Other dependencies'reversion',]For more information about how to work with django projects and django apps,
please refer to thedjango documentation.2. Installopenwisp-ipamInstall (and add to the requirement of your project) openwisp-ipam:pip install openwisp-ipam3. AddEXTENDED_APPSAdd the following to yoursettings.py:EXTENDED_APPS=('openwisp_ipam',)4. Addopenwisp_utils.staticfiles.DependencyFinderAddopenwisp_utils.staticfiles.DependencyFindertoSTATICFILES_FINDERSin yoursettings.py:STATICFILES_FINDERS=['django.contrib.staticfiles.finders.FileSystemFinder','django.contrib.staticfiles.finders.AppDirectoriesFinder','openwisp_utils.staticfiles.DependencyFinder',]5. Addopenwisp_utils.loaders.DependencyLoaderAddopenwisp_utils.loaders.DependencyLoadertoTEMPLATESin yoursettings.py, but ensure it comes beforedjango.template.loaders.app_directories.Loader:TEMPLATES=[{'BACKEND':'django.template.backends.django.DjangoTemplates','OPTIONS':{'loaders':['django.template.loaders.filesystem.Loader','openwisp_utils.loaders.DependencyLoader','django.template.loaders.app_directories.Loader',],'context_processors':['django.template.context_processors.debug','django.template.context_processors.request','django.contrib.auth.context_processors.auth','django.contrib.messages.context_processors.messages',],},}]6. Inherit the AppConfig classPlease refer to the following files in the sample app of the test project:sample_ipam/__init__.py.sample_ipam/apps.py.You have to replicate and adapt that code in your project.For more information regarding the concept ofAppConfigplease refer to
the“Applications” section in the django documentation.7. Create your custom modelsFor the purpose of showing an example, we added a simple “details” field to themodels of the sample app in the test project.You can add fields in a similar way in yourmodels.pyfile.Note: for doubts regarding how to use, extend or develop models please refer to
the“Models” section in the django documentation.8. Add swapper configurationsOnce you have created the models, add the following to yoursettings.py:# Setting models for swapper moduleOPENWISP_IPAM_IPADDRESS_MODEL='myipam.IpAddress'OPENWISP_IPAM_SUBNET_MODEL='myipam.Subnet'Substitutemyipamwith the name you chose in step 1.9. Create database migrationsCreate and apply database migrations:./manage.py makemigrations
./manage.py migrateFor more information, refer to the“Migrations” section in the django documentation.10. Create the adminRefer to theadmin.py file of the sample app.To introduce changes to the admin, you can do it in two main ways which are described below.Note: for more information regarding how the django admin works, or how it can be customized,
please refer to“The django admin site” section in the django documentation.1. Monkey patchingIf the changes you need to add are relatively small, you can resort to monkey patching.For example:fromopenwisp_ipam.adminimportIpAddressAdmin,SubnetAdminSubnetAdmin.app_label='sample_ipam'2. Inheriting admin classesIf you need to introduce significant changes and/or you don’t want to resort to
monkey patching, you can proceed as follows:fromdjango.contribimportadminfromopenwisp_ipam.adminimport(IpAddressAdminasBaseIpAddressAdmin,SubnetAdminasBaseSubnetAdmin,)fromswapperimportload_modelIpAddress=load_model('openwisp_ipam','IpAddress')Subnet=load_model('openwisp_ipam','Subnet')admin.site.unregister(IpAddress)admin.site.unregister(Subnet)@admin.register(IpAddress)classIpAddressAdmin(BaseIpAddressAdmin):# add your changes here@admin.register(Subnet)classSubnetAdmin(BaseSubnetAdmin):app_label='myipam'# add your changes hereSubstitutemyipamwith the name you chose in step 1.11. Create root URL configurationfrom.sample_ipamimportviewsasapi_viewsfromopenwisp_ipam.urlsimportget_urlsurlpatterns=[# ... other urls in your project ...# openwisp-ipam urls# path('', include(get_urls(api_views))) <-- Use only when changing API views (dicussed below)path('',include('openwisp_ipam.urls')),]For more information about URL configuration in django, please refer to the“URL dispatcher” section in the django documentation.12. Import the automated testsWhen developing a custom application based on this module, it’s a good
idea to import and run the base tests too, so that you can be sure the changes
you’re introducing are not breaking some of the existing features ofopenwisp-ipam.In case you need to add breaking changes, you can overwrite the tests defined
in the base classes to test your own behavior.See thetests of the sample appto find out how to do this.You can then run tests with:# the --parallel flag is optional
./manage.py test --parallel myipamSubstitutemyipamwith the name you chose in step 1.For more information about automated tests in django, please refer to“Testing in Django”.Other base classes that can be inherited and extendedThe following steps are not required and are intended for more advanced customization.1. Extending the API ViewsThe API view classes can be extended into other django applications as well. Note
that it is not required for extending openwisp-ipam to your app and this change
is required only if you plan to make changes to the API views.Create a view file as done inviews.py.For more information about django views, please refer to theviews section in the django documentation.ContributingPlease refer to theOpenWISP contributing guidelines.Support channels|Issue Tracker|License