├── tests ├── __init.py__ ├── config.php └── test_phpipam_client.py ├── phpipam_pyclient ├── __init__.py ├── version.py ├── config.json └── phpipam_pyclient.py ├── Dockerfile.phpipam ├── images └── phpipampyclient.png ├── requirements-dev.txt ├── config.json ├── docs ├── index.rst ├── installation.rst ├── Makefile ├── intro.rst ├── configuration.rst ├── conf.py └── usage.rst ├── tox.ini ├── docker-compose.yml ├── CHANGELOG.md ├── setup.py ├── .gitlab-ci.yml ├── README.md └── LICENSE /tests/__init.py__: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /phpipam_pyclient/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /Dockerfile.phpipam: -------------------------------------------------------------------------------- 1 | FROM pierrecdn/phpipam:1.4 2 | 3 | COPY tests/config.php /var/www/html/config.php 4 | -------------------------------------------------------------------------------- /images/phpipampyclient.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/viniarck/phpipam-pyclient/HEAD/images/phpipampyclient.png -------------------------------------------------------------------------------- /requirements-dev.txt: -------------------------------------------------------------------------------- 1 | pytest 2 | pytest-cov 3 | tox 4 | sphinx 5 | sphinx-autobuild 6 | sphinx_rtd_theme 7 | responses 8 | -------------------------------------------------------------------------------- /phpipam_pyclient/version.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | """version.""" 4 | 5 | __version__ = '1.2.1' 6 | -------------------------------------------------------------------------------- /config.json: -------------------------------------------------------------------------------- 1 | { 2 | "base_url":"http://localhost/api", 3 | "api_name":"testing", 4 | "user":"admin", 5 | "passwd":"my-secret-pw" 6 | } 7 | -------------------------------------------------------------------------------- /phpipam_pyclient/config.json: -------------------------------------------------------------------------------- 1 | { 2 | "base_url":"http://localhost/api", 3 | "api_name":"testing", 4 | "user":"admin", 5 | "passwd":"my-secret-pw" 6 | } 7 | -------------------------------------------------------------------------------- /docs/index.rst: -------------------------------------------------------------------------------- 1 | phpipam-pyclient 2 | ================ 3 | 4 | .. toctree:: 5 | :maxdepth: 2 6 | 7 | intro.rst 8 | installation.rst 9 | configuration.rst 10 | usage.rst 11 | -------------------------------------------------------------------------------- /tox.ini: -------------------------------------------------------------------------------- 1 | [tox] 2 | envlist = py36,py37,py38 3 | skipsdist = True 4 | usedevelop = True 5 | [testenv] 6 | deps= 7 | -r{toxinidir}/requirements-dev.txt 8 | commands=python -m pytest tests/test_phpipam_client.py 9 | -------------------------------------------------------------------------------- /docs/installation.rst: -------------------------------------------------------------------------------- 1 | Installation 2 | ============ 3 | 4 | via Github 5 | ---------- 6 | 7 | 1 - Git clone 8 | 9 | :: 10 | 11 | git clone https://github.com/viniarck/phpipam-pyclient.git 12 | cd phpipam-pyclient 13 | 14 | 2 - Install Python requirements dependencies, either via user install or virtualenv: 15 | 16 | 2.1 - pip user install: 17 | 18 | :: 19 | 20 | pip install -e . 21 | 22 | 2\.1 - or virtualenv: 23 | 24 | :: 25 | 26 | virtualenv -p python3.6 .venv 27 | source .venv/bin/activate 28 | pip install -e . 29 | -------------------------------------------------------------------------------- /docker-compose.yml: -------------------------------------------------------------------------------- 1 | version: '2' 2 | 3 | services: 4 | mysql: 5 | image: mysql:5.6 6 | environment: 7 | - MYSQL_ROOT_PASSWORD=my-secret-pw 8 | ports: 9 | - "3306:3306" 10 | ipam: 11 | depends_on: 12 | - mysql 13 | image: pierrecdn/local_phpipam:1.4 14 | build: 15 | context: . 16 | dockerfile: ./Dockerfile.phpipam 17 | environment: 18 | - MYSQL_ENV_MYSQL_ROOT_PASSWORD=my-secret-pw 19 | - MYSQL_ENV_MYSQL_PASSWORD=my-secret-pw 20 | - MYSQL_ENV_MYSQL_HOST=mysql 21 | - MYSQL_ENV_MYSQL_USER=root 22 | ports: 23 | - "80:80" 24 | -------------------------------------------------------------------------------- /docs/Makefile: -------------------------------------------------------------------------------- 1 | # Minimal makefile for Sphinx documentation 2 | # 3 | 4 | # You can set these variables from the command line. 5 | SPHINXOPTS = 6 | SPHINXBUILD = python -msphinx 7 | SPHINXPROJ = phpipam-pyclient 8 | SOURCEDIR = . 9 | BUILDDIR = _build 10 | 11 | # Put it first so that "make" without argument is like "make help". 12 | help: 13 | @$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) 14 | 15 | .PHONY: help Makefile 16 | 17 | # Catch-all target: route all unknown targets to Sphinx using the new 18 | # "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS). 19 | %: Makefile 20 | @$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | ## v0.1.1 4 | 5 | - The setup.py now specifies an executable for this package, so after installing, `phpipam-pyclient` executable will be available in your PATH. 6 | - `PHPIPAM_PYCLIENT_CFG_FILE` environment variable can be used to allow users to specify where the configuration file resides dynamically. It takes higher precedence than the `config.json` file that resides in the application directory. 7 | - The `PHPIpamClient` class now allows optional variables to either auto load the configuration file and open the TCP connection. If you set these flags to false you're expected to call `self.load_config()` and `self.auth_session()`. 8 | 9 | ### New commands 10 | 11 | ``` 12 | phpipam-pyclient version 13 | ``` 14 | -------------------------------------------------------------------------------- /docs/intro.rst: -------------------------------------------------------------------------------- 1 | Introduction 2 | ============ 3 | 4 | phpipam-pyclient is a REST-client CLI tool to interface with PHPIpam REST API. phpipam-pyclient leverages python fire and requests under the hood, some high level functions have been implementend to allow the user to quickly query certain information about the devices on PHPIpam. In addition, you can use this library to build your Ansible inventory by filtering a field/column of the devices on PHPIpam. 5 | 6 | Testing 7 | ------- 8 | 9 | Integration tests are implemented with pytest validating both Python2.7 and Python3.5 on a docker-based environment, in two stages: 10 | 11 | - installation: validates a installation from strach with selenium. 12 | - client-server API: validates this phpipam-pyclient with the phpipam REST API. 13 | 14 | The following versions of PHPIpam are being tested on GitLab CI: 15 | 16 | - 1.3.2 17 | - 1.3.1 18 | - 1.3 19 | -------------------------------------------------------------------------------- /docs/configuration.rst: -------------------------------------------------------------------------------- 1 | Configuration 2 | ============= 3 | 4 | In order to connect to PHPIpam REST API you have to edit the ``phpipam_pyclient/config.json`` file, which by default comes with the following configuration: 5 | 6 | :: 7 | 8 | { 9 | "base_url":"http://ipam/api", 10 | "api_name":"testing", 11 | "user":"admin", 12 | "passwd":"my-secret-pw" 13 | } 14 | 15 | 16 | - ``base_url``: This is the url of PHPIpam API ``http(s):///api``, make sure to adjust either http or https and the hostname of the PHPIpam server accordingly. 17 | - ``api_name``: The name of the API you have enabled on PHPIpam settings. 18 | - ``user``: username that will be authenticated on PHPIpam 19 | - ``passwd``: user's password 20 | 21 | Optionally, if you don't want to specify another location for the `config.json` file, you can set the environment variable `PHPIPAM_PYCLIENT_CFG_FILE` which has higher precedence. 22 | 23 | .. note:: 24 | 25 | When you enable API either choose ssl if you have https enabled or leave it as None for http. I haven't tested the crypto option. 26 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | from setuptools import setup 2 | from phpipam_pyclient.version import __version__ 3 | desc = 'REST-client and CLI tool to interface with phpipam REST API' 4 | 5 | setup( 6 | name='phipam-pyclient', 7 | version=__version__, 8 | description=desc, 9 | author='Vinicius Arcanjo', 10 | author_email='viniarck@gmail.com', 11 | keywords='phpipam client rest-client', 12 | url='http://github.com/viniarck/phpipam-pyclient', 13 | packages=['phpipam_pyclient'], 14 | license='Apache', 15 | install_requires=['requests>=2.19.1', 'fire>=0.1.3'], 16 | classifiers=[ 17 | 'Topic :: Utilities', 18 | 'Programming Language :: Python', 19 | 'Programming Language :: Python :: 3', 20 | 'Programming Language :: Python :: 3.4', 21 | 'Programming Language :: Python :: 3.5', 22 | 'Programming Language :: Python :: 3.6', 23 | 'Programming Language :: Python :: 3.7', 24 | 'Programming Language :: Python :: 3.8', 25 | 'Operating System :: POSIX :: Linux', 26 | 'Operating System :: MacOS', 27 | ], 28 | entry_points=''' 29 | [console_scripts] 30 | phpipam-pyclient=phpipam_pyclient.phpipam_pyclient:main 31 | ''', 32 | zip_safe=False, 33 | ) 34 | -------------------------------------------------------------------------------- /.gitlab-ci.yml: -------------------------------------------------------------------------------- 1 | image: docker:latest 2 | 3 | services: 4 | - docker:dind 5 | 6 | variables: 7 | DOCKER_DRIVER: overlay2 8 | 9 | stages: 10 | - lint_tests 11 | - integration_tests 12 | 13 | lint_tests: 14 | image: registry.gitlab.com/viniarck/phpipam-pyclient:dev 15 | stage: lint_tests 16 | script: 17 | # find all py files excluding hidden files 18 | - find . -type f | grep -v '/\.' | xargs ls | egrep ".py$" | xargs pylama 19 | 20 | .integration_tests: &integration_def 21 | stage: integration_tests 22 | before_script: 23 | - apk add --no-cache py-pip 24 | - pip install docker-compose==1.23.2 25 | after_script: 26 | - docker ps 27 | - sleep 10 28 | - docker ps 29 | - docker exec phpipampyclient_phpipam_pyclient_1 /bin/bash -c 'python3 -m pytest tests/test_phpipam_installation.py -v' 30 | - docker exec phpipampyclient_phpipam_pyclient_1 /bin/bash -c 'python3 -m pytest tests/test_phpipam_client.py -v' 31 | - docker exec phpipampyclient_phpipam_pyclient_1 /bin/bash -c 'tox' 32 | 33 | test_phpipam_latest: 34 | <<: *integration_def 35 | script: 36 | - docker-compose -p phpipampyclient up -d 37 | 38 | test_phpipam_1.3.1: 39 | <<: *integration_def 40 | script: 41 | - docker-compose -p phpipampyclient -f docker-compose-1.3.1.yml up -d 42 | 43 | test_phpipam_1.3: 44 | <<: *integration_def 45 | script: 46 | - docker-compose -p phpipampyclient -f docker-compose-1.3.yml up -d 47 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![pipeline status](https://gitlab.com/viniarck/phpipam-pyclient/badges/master/pipeline.svg)](https://gitlab.com/viniarck/phpipam-pyclient/commits/master) [![Documentation Status](https://readthedocs.org/projects/phpipam-pyclient/badge/?version=latest)](http://phpipam-pyclient.readthedocs.io/en/latest/?badge=latest) 2 | 3 | ## phpipam-pyclient 4 | 5 | ![logo](./images/phpipampyclient.png) 6 | 7 | phpipam-pyclient is a REST-client CLI tool to interface with [phpipam](https://github.com/phpipam/phpipam) REST API. phpipam-pyclient leverages python fire and requests under the hood, some high level functions have been implemented to allow the user to quickly query certain information about the devices on phpipam. In addition, you can use this library to build your Ansible inventory by filtering a field/column of the devices on phpipam. 8 | 9 | ## Installation 10 | 11 | Currently, the only supported installation is directly via checking the code from GitHub. After completing the installation, you have to configure the parameters to authenticate your user on phpipam in the ``phpipam_pyclient/config.json`` file. You can find more information, examples and usage on [ReadTheDocs](http://phpipam-pyclient.readthedocs.io/). 12 | 13 | ### via GitHub 14 | 15 | ``` 16 | git clone https://github.com/viniarck/phpipam-pyclient.git 17 | cd phpipam-pyclient 18 | virtualenv -p python3 .venv 19 | source .venv/bin/activate 20 | pip install -e . 21 | ``` 22 | 23 | ## Changelog 24 | 25 | [CHANGELOG.md](./CHANGELOG.md) 26 | -------------------------------------------------------------------------------- /docs/conf.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | import sphinx_rtd_theme 3 | # 4 | # phpipam-pyclient documentation build configuration file, created by 5 | # sphinx-quickstart on Tue Dec 26 13:23:47 2017. 6 | # 7 | # This file is execfile()d with the current directory set to its 8 | # containing dir. 9 | # 10 | # Note that not all possible configuration values are present in this 11 | # autogenerated file. 12 | # 13 | # All configuration values have a default; values that are commented out 14 | # serve to show the default. 15 | 16 | # If extensions (or modules to document with autodoc) are in another directory, 17 | # add these directories to sys.path here. If the directory is relative to the 18 | # documentation root, use os.path.abspath to make it absolute, like shown here. 19 | # 20 | # import os 21 | # import sys 22 | # sys.path.insert(0, os.path.abspath('.')) 23 | 24 | 25 | # -- General configuration ------------------------------------------------ 26 | 27 | # If your documentation needs a minimal Sphinx version, state it here. 28 | # 29 | # needs_sphinx = '1.0' 30 | 31 | # Add any Sphinx extension module names here, as strings. They can be 32 | # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom 33 | # ones. 34 | extensions = [] 35 | 36 | # Add any paths that contain templates here, relative to this directory. 37 | templates_path = ['_templates'] 38 | 39 | # The suffix(es) of source filenames. 40 | # You can specify multiple suffix as a list of string: 41 | # 42 | # source_suffix = ['.rst', '.md'] 43 | source_suffix = '.rst' 44 | 45 | # The master toctree document. 46 | master_doc = 'index' 47 | 48 | # General information about the project. 49 | project = u'phpipam-pyclient' 50 | copyright = u'2018, Vinicius Arcanjo' 51 | author = u'Vinicius Arcanjo' 52 | 53 | # The version info for the project you're documenting, acts as replacement for 54 | # |version| and |release|, also used in various other places throughout the 55 | # built documents. 56 | # 57 | # The short X.Y version. 58 | version = u'0.1' 59 | # The full version, including alpha/beta/rc tags. 60 | release = u'0.1' 61 | 62 | # The language for content autogenerated by Sphinx. Refer to documentation 63 | # for a list of supported languages. 64 | # 65 | # This is also used if you do content translation via gettext catalogs. 66 | # Usually you set "language" from the command line for these cases. 67 | language = None 68 | 69 | # List of patterns, relative to source directory, that match files and 70 | # directories to ignore when looking for source files. 71 | # This patterns also effect to html_static_path and html_extra_path 72 | exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store'] 73 | 74 | # The name of the Pygments (syntax highlighting) style to use. 75 | pygments_style = 'sphinx' 76 | 77 | # If true, `todo` and `todoList` produce output, else they produce nothing. 78 | todo_include_todos = False 79 | 80 | 81 | # -- Options for HTML output ---------------------------------------------- 82 | 83 | # The theme to use for HTML and HTML Help pages. See the documentation for 84 | # a list of builtin themes. 85 | # 86 | # html_theme = 'alabaster' 87 | html_theme = "sphinx_rtd_theme" 88 | 89 | html_theme_path = [sphinx_rtd_theme.get_html_theme_path()] 90 | 91 | # Theme options are theme-specific and customize the look and feel of a theme 92 | # further. For a list of options available for each theme, see the 93 | # documentation. 94 | # 95 | # html_theme_options = {} 96 | 97 | # Add any paths that contain custom static files (such as style sheets) here, 98 | # relative to this directory. They are copied after the builtin static files, 99 | # so a file named "default.css" will overwrite the builtin "default.css". 100 | html_static_path = ['_static'] 101 | 102 | 103 | # -- Options for HTMLHelp output ------------------------------------------ 104 | 105 | # Output file base name for HTML help builder. 106 | htmlhelp_basename = 'phpipam-pyclientdoc' 107 | 108 | 109 | # -- Options for LaTeX output --------------------------------------------- 110 | 111 | latex_elements = { 112 | # The paper size ('letterpaper' or 'a4paper'). 113 | # 114 | # 'papersize': 'letterpaper', 115 | 116 | # The font size ('10pt', '11pt' or '12pt'). 117 | # 118 | # 'pointsize': '10pt', 119 | 120 | # Additional stuff for the LaTeX preamble. 121 | # 122 | # 'preamble': '', 123 | 124 | # Latex figure (float) alignment 125 | # 126 | # 'figure_align': 'htbp', 127 | } 128 | 129 | # Grouping the document tree into LaTeX files. List of tuples 130 | # (source start file, target name, title, 131 | # author, documentclass [howto, manual, or own class]). 132 | latex_documents = [ 133 | (master_doc, 'phpipam-pyclient.tex', u'phpipam-pyclient Documentation', 134 | u'Vinicius Arcanjo', 'manual'), 135 | ] 136 | 137 | 138 | # -- Options for manual page output --------------------------------------- 139 | 140 | # One entry per manual page. List of tuples 141 | # (source start file, name, description, authors, manual section). 142 | man_pages = [ 143 | (master_doc, 'phpipam-pyclient', u'phpipam-pyclient Documentation', 144 | [author], 1) 145 | ] 146 | 147 | 148 | # -- Options for Texinfo output ------------------------------------------- 149 | 150 | # Grouping the document tree into Texinfo files. List of tuples 151 | # (source start file, target name, title, author, 152 | # dir menu entry, description, category) 153 | texinfo_documents = [ 154 | (master_doc, 'phpipam-pyclient', u'phpipam-pyclient Documentation', 155 | author, 'phpipam-pyclient', 'One line description of project.', 156 | 'Miscellaneous'), 157 | ] 158 | -------------------------------------------------------------------------------- /tests/config.php: -------------------------------------------------------------------------------- 1 | /index.php 146 | ******************************/ 147 | $private_subpages = array(); 148 | 149 | 150 | /** 151 | * Google MAPs API key for locations to display map 152 | * 153 | * Obtain key: Go to your Google Console (https://console.developers.google.com) and enable "Google Maps JavaScript API" 154 | * from overview tab, so go to Credentials tab and make an API key for your project. 155 | ******************************/ 156 | $gmaps_api_key = getenv("GMAPS_API_KEY") ?: ""; 157 | $gmaps_api_geocode_key = getenv("GMAPS_API_GEOCODE_KEY") ?: ""; 158 | 159 | /** 160 | * proxy connection details 161 | ******************************/ 162 | $proxy_enabled = false; // Enable/Disable usage of the Proxy server 163 | $proxy_server = 'myproxy.something.com'; // Proxy server FQDN or IP 164 | $proxy_port = '8080'; // Proxy server port 165 | $proxy_user = 'USERNAME'; // Proxy Username 166 | $proxy_pass = 'PASSWORD'; // Proxy Password 167 | $proxy_use_auth = false; // Enable/Disable Proxy authentication 168 | 169 | /** 170 | * General tweaks 171 | ******************************/ 172 | $config['logo_width'] = 220; // logo width 173 | $config['requests_public'] = true; // Show IP request module on login page 174 | $config['split_ip_custom_fields'] = false; // Show custom fields in separate table when editing IP address 175 | 176 | /** 177 | * PHP CLI binary for scanning and network discovery. 178 | * 179 | * The default behaviour is to use the system wide default php version symlinked to php in PHP_BINDIR (/usr/bin/php). 180 | * If multiple php versions are present; overide selection with $php_cli_binary. 181 | */ 182 | // $php_cli_binary = '/usr/bin/php7.1'; 183 | $db['webhost'] = '%'; 184 | -------------------------------------------------------------------------------- /docs/usage.rst: -------------------------------------------------------------------------------- 1 | Usage 2 | ===== 3 | 4 | phpipam-client leverages python fire to implement the CLI, you can start by checking what options are available: 5 | 6 | .. note:: 7 | 8 | Before you use this client, the PHPIpam server has to be up and running, since it's going to connect to it. 9 | 10 | .. code:: shell 11 | 12 | root@c0630eda943f:/app# phpipam-pyclient 13 | Type: PHPIpamClient 14 | String form: 15 | Docstring: PHPIPam Python API Client 16 | 17 | Usage: phpipam-pyclient - 18 | phpipam-pyclient - add-device 19 | phpipam-pyclient - ansible-inv-endpoint-field 20 | phpipam-pyclient - auth-session 21 | phpipam-pyclient - list-device-fields 22 | phpipam-pyclient - list-devices 23 | phpipam-pyclient - load-config 24 | phpipam-pyclient - version 25 | 26 | Since I don't have any devices yet, let me start off by checking the arguments of the add-device function: 27 | 28 | - input: 29 | 30 | .. code:: shell 31 | 32 | phpipam-pyclient - add-device -- --help 33 | 34 | - output: 35 | 36 | .. code:: shell 37 | 38 | root@c0630eda943f:/app# phpipam-pyclient - add-device -- --help 39 | Type: method 40 | String form: > 41 | File: phpipam_pyclient.py 42 | Line: 125 43 | Docstring: Adds device to PHPIpam given a dictionary that represents a device 44 | i.e., it should have these keys at least 45 | 'ip', 'hostname', 'description' 46 | 47 | :device: dictionary that represents a device 48 | :Returns: REST post status code 49 | 50 | Usage: phpipam-pyclient - add-device [DEVICE] 51 | phpipam-pyclient - add-device [--device DEVICE] 52 | 53 | Let's add three devices on PHPIPam: 54 | 55 | - input: 56 | 57 | .. code:: shell 58 | 59 | phpipam-pyclient add-device --device '{hostname:"server1",ip:"1.2.3.4",description:"backend"}' 60 | phpipam-pyclient add-device --device '{hostname:"server2",ip:"1.2.3.5",description:"backend"}' 61 | phpipam-pyclient add-device --device '{hostname:"server3",ip:"1.2.3.6",description:"frontend"}' 62 | 63 | - output 64 | 65 | Note all REST calls returned 201 (OK) status code: 66 | 67 | .. code:: shell 68 | 69 | root@c0630eda943f:/app/phpipam_pyclient# phpipam-pyclient add-device --device '{hostname:"server1",ip:"1.2.3.4",description:"backend"}' 70 | 201 71 | root@c0630eda943f:/app/phpipam_pyclient# phpipam-pyclient add-device --device '{hostname:"server2",ip:"1.2.3.5",description:"backend"}' 72 | 201 73 | root@c0630eda943f:/app/phpipam_pyclient# phpipam-pyclient add-device --device '{hostname:"server3",ip:"1.2.3.6",description:"frontend"}' 74 | 201 75 | root@c0630eda943f:/app/phpipam_pyclient# 76 | 77 | Now, let's list all devices on PHPIPam: 78 | 79 | - input: 80 | 81 | .. code:: shell 82 | 83 | phpipam-pyclient list-devices 84 | 85 | - output: 86 | 87 | .. code:: shell 88 | 89 | root@c0630eda943f:/app/phpipam_pyclient# phpipam-pyclient list-devices 90 | {"sections": "1;2", "snmp_v3_priv_protocol": "none", "snmp_queries": null, "hostname": "server1", "snmp_port": "161", "rack_size": null, "id": "1", "location": null, "snmp_v3_priv_pass": null, "description": "backend", "snmp_v3_auth_pass": null, "ip": "1.2.3.4", "editDate": null, "snmp_v3_ctx_name": null, "snmp_timeout": "500", "snmp_v3_auth_protocol": "none", "rack_start": null,"snmp_v3_ctx_engine_id": null, "rack": null, "type": "0", "snmp_version": "0", "snmp_community": null, "snmp_v3_sec_level": "none"} 91 | {"sections": "1;2", "snmp_v3_priv_protocol": "none", "snmp_queries": null, "hostname": "server2", "snmp_port": "161", "rack_size": null, "id": "2", "location": null, "snmp_v3_priv_pass": null, "description": "backend", "snmp_v3_auth_pass": null, "ip": "1.2.3.5", "editDate": null, "snmp_v3_ctx_name": null, "snmp_timeout": "500", "snmp_v3_auth_protocol": "none", "rack_start": null,"snmp_v3_ctx_engine_id": null, "rack": null, "type": "0", "snmp_version": "0", "snmp_community": null, "snmp_v3_sec_level": "none"} 92 | {"sections": "1;2", "snmp_v3_priv_protocol": "none", "snmp_queries": null, "hostname": "server3", "snmp_port": "161", "rack_size": null, "id": "3", "location": null, "snmp_v3_priv_pass": null, "description": "frontend", "snmp_v3_auth_pass": null, "ip": "1.2.3.6", "editDate": null, "snmp_v3_ctx_name": null, "snmp_timeout": "500", "snmp_v3_auth_protocol": "none", "rack_start": null,"snmp_v3_ctx_engine_id": null, "rack": null, "type": "0", "snmp_version": "0", "snmp_community": null, "snmp_v3_sec_level": "none"} 93 | 94 | Sweet! What if I wanted to export these devices as an Ansible inventory? It can group Ansible servers by their description, for example: 95 | 96 | - input: 97 | 98 | .. code:: shell 99 | 100 | phpipam-pyclient ansible-inv-endpoint-field devices/ "description" 101 | 102 | .. note:: 103 | 104 | Essentially, this command queries the devices/ endpoint and it'll group all hostnames according to their description, you could group by any other attribute if you wanted. 105 | 106 | .. code:: shell 107 | 108 | root@c0630eda943f:/app/phpipam_pyclient# phpipam-pyclient ansible-inv-endpoint-field devices/ "description" 109 | [frontend] 110 | server3 111 | 112 | [backend] 113 | server1 114 | server2 115 | 116 | 117 | From this point forward, Ansible all the way to do whatever you need. But, what if you wanted to check all the other available fields what you could filter? If you had custom fields they would show up here too. 118 | 119 | - input: 120 | 121 | .. code:: shell 122 | 123 | phpipam-pyclient list-device-fields 124 | 125 | - output: 126 | 127 | .. code:: shell 128 | 129 | root@c0630eda943f:/app/phpipam_pyclient# phpipam-pyclient list-device-fields 130 | Type: dict_keys 131 | String form: dict_keys(['rack_size', 'snmp_v3_priv_pass', 'snmp_community', 'snmp_v3_priv_protocol', 'sections', 'snmp_v3_ctx_name', 'snmp_v3_sec_level', 'editDate', 'rack_start', 'hostname', 'snmp_version', 'snmp_queries', 'snmp_v3_auth_pass', 'snmp_timeout', 'id', 'rack', 'description', 'location', 'snmp_v3_ctx_engine_id', 'ip', 'snmp_v3_auth_protocol', 'type', 'snmp_port']) 132 | Length: 23 133 | 134 | Usage: phpipam_pyclient.py list-device-fields 135 | phpipam_pyclient.py list-device-fields isdisjoint 136 | root@c0630eda943f:/app/phpipam_pyclient# 137 | 138 | 139 | New Features 140 | ------------ 141 | 142 | On version 1.0.0, released in Dec 2021, new filtering and Ansible grouping capabilities have been added: 143 | 144 | Use and combine multiple filters (as a logic ``and`` operator) to filter based on any field that they have, for instance, let's say you wanted to filter if 'ip' fields contains the string '1.2.3' and also the 'description' is equal to 'backend'. These filter options are also available in the ``ansible_inv_endpoint_field`` command, here's it's being used on the ``list_devices`` command: 145 | 146 | .. code:: shell 147 | 148 | phpipam-pyclient list_devices --fields="['hostname', 'ip', 'description']" --filters="[{'type': 'contains', 'value': '1.2.3', 'field': 'ip'},{'type': 'eq', 'field': 'description', 'value': 'backend'}]" 149 | 150 | {"hostname": "server1", "ip": "1.2.3.4", "description": "backend"} 151 | {"hostname": "server2", "ip": "1.2.3.5", "description": "backend"} 152 | 153 | 154 | If you need numerical comparisons, you can use the filter type as ``ge, gt, le, gt`` which respectively means greater than or equal, greater than, less than or equal, greater than. Another feature that was added was the support for adding Ansible default variables when generating the inventory, for instance, let's say you want to use these filters, group them by their ``description``, but also, for any hosts that have the ``description`` as ``frontend`` you want to set the ``ansible_port`` as 2222, and ``ansible_user`` as ``some_user``: 155 | 156 | .. code:: shell 157 | 158 | phpipam-pyclient ansible_inv_endpoint_field devices/ description --filters="[{'type': 'contains', 'value': '1', 'field': 'ip'}]" --ansible_kwargs="{'frontend': {'ansible_port': 2222, ' ansible_user': 'some_user'}}" 159 | 160 | [backend] 161 | server1 162 | server2 163 | 164 | [frontend] 165 | server3 ansible_port=2222 ansible_user=some_user 166 | 167 | 168 | On top of that, if you also only want to include certain Ansible groups you can leverage the ``--include_groups`` option, notice that compared to the previous example, only the ``frontend`` group, that was grouped by their description is in the generated output: 169 | 170 | 171 | .. code:: shell 172 | 173 | phpipam-pyclient ansible_inv_endpoint_field devices/ description --filters="[{'type': 'contains', 'value': '1', 'field': 'ip'}]" --ansible_kwargs="{'frontend': {'ansible_port': 2222, 'ansible_user': 'some_user'}}" --include_groups="['frontend']" 174 | 175 | [frontend] 176 | server3 ansible_port=2222 ansible_user=some_user 177 | -------------------------------------------------------------------------------- /tests/test_phpipam_client.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | """ 4 | test phpipamclient module 5 | """ 6 | 7 | import pytest 8 | import responses 9 | from phpipam_pyclient.phpipam_pyclient import PHPIpamClient 10 | 11 | 12 | class TestPhpIpamClient(object): 13 | """Class to test PHPIpam Client module""" 14 | 15 | @pytest.fixture(scope="module") 16 | def get_client(self): 17 | """PHPIpam client module fixture""" 18 | return PHPIpamClient(init_auth=False) 19 | 20 | @pytest.fixture 21 | def devices_data(self): 22 | devices = list() 23 | 24 | # test data 25 | devices.append( 26 | { 27 | "hostname": "dev1", 28 | "ip": "1.2.3.4", 29 | "description": "Ubuntu", 30 | "device_type": "server", 31 | "rack_size": 1, 32 | "rack_power": "a", 33 | "id": 1, 34 | } 35 | ) 36 | devices.append( 37 | { 38 | "hostname": "dev2", 39 | "ip": "4.3.2.1", 40 | "description": "Ubuntu", 41 | "device_type": "server", 42 | "rack_size": 2, 43 | "rack_power": 10, 44 | "id": 2, 45 | } 46 | ) 47 | devices.append( 48 | { 49 | "hostname": "dev3", 50 | "ip": "1.2.3.4", 51 | "description": None, 52 | "device_type": "server", 53 | "id": 3, 54 | } 55 | ) 56 | 57 | return devices 58 | 59 | @responses.activate 60 | def test_auth(self, get_client): 61 | """Test authentication""" 62 | token_res = {"token": "some_token"} 63 | responses.add( 64 | responses.POST, 65 | "http://localhost/api/testing/user/", 66 | json={"data": token_res}, 67 | ) 68 | client = get_client 69 | req = client.auth_session() 70 | assert req.status_code == 200 71 | assert client._token == token_res 72 | 73 | def test_version(self, get_client): 74 | """Test version""" 75 | client = get_client 76 | assert client.version() 77 | 78 | @responses.activate 79 | def test_add_device(self, get_client, devices_data): 80 | """Test add devices""" 81 | responses.add( 82 | responses.POST, 83 | "http://localhost/api/testing/devices/1/", 84 | json={}, 85 | status=201, 86 | ) 87 | for device in devices_data: 88 | req = get_client.add_device(device=device) 89 | assert req == 201 90 | 91 | @responses.activate 92 | def test_list_devices(self, get_client, devices_data): 93 | """Test get all devices""" 94 | responses.add( 95 | responses.GET, 96 | "http://localhost/api/testing/devices/", 97 | json={"data": devices_data}, 98 | ) 99 | 100 | client = get_client 101 | resp = client.list_devices() 102 | # in case devices had been already added (in production or whatever) 103 | assert len(resp) >= len(devices_data) 104 | 105 | @responses.activate 106 | def test_list_devices_fields(self, get_client, devices_data): 107 | """Test get all devices with fields selection""" 108 | responses.add( 109 | responses.GET, 110 | "http://localhost/api/testing/devices/", 111 | json={"data": devices_data}, 112 | ) 113 | 114 | client = get_client 115 | fields = ["hostname"] 116 | resp = client.list_devices(fields=fields) 117 | for dev in resp: 118 | assert list(dev.keys()) == fields 119 | 120 | @responses.activate 121 | def test_list_devices_filter_eq_contains(self, get_client, devices_data): 122 | """Test get all devices filter eq and contains""" 123 | responses.add( 124 | responses.GET, 125 | "http://localhost/api/testing/devices/", 126 | json={"data": devices_data}, 127 | ) 128 | 129 | client = get_client 130 | filters = [ 131 | {"type": "contains", "field": "description", "value": "Ubu"}, 132 | {"type": "eq", "field": "device_type", "value": "server"}, 133 | ] 134 | resp = client.list_devices(filters=filters) 135 | for dev in resp: 136 | assert "Ubu" in dev["description"] and dev["device_type"] == "server" 137 | 138 | filters = [ 139 | {"type": "contains", "field": "description", "value": "not_found"}, 140 | ] 141 | resp = client.list_devices(filters=filters) 142 | assert not resp 143 | 144 | @responses.activate 145 | def test_list_devices_filter_le(self, get_client, devices_data): 146 | """Test get all devices filter le""" 147 | responses.add( 148 | responses.GET, 149 | "http://localhost/api/testing/devices/", 150 | json={"data": devices_data}, 151 | ) 152 | 153 | client = get_client 154 | filters = [ 155 | {"type": "le", "field": "rack_size", "value": "3"}, 156 | ] 157 | resp = client.list_devices(filters=filters) 158 | assert resp 159 | for dev in resp: 160 | assert dev["rack_size"] <= 3 161 | 162 | @responses.activate 163 | def test_list_devices_filter_lt(self, get_client, devices_data): 164 | """Test get all devices filter numeric""" 165 | responses.add( 166 | responses.GET, 167 | "http://localhost/api/testing/devices/", 168 | json={"data": devices_data}, 169 | ) 170 | 171 | client = get_client 172 | filters = [ 173 | {"type": "lt", "field": "rack_size", "value": "2"}, 174 | ] 175 | resp = client.list_devices(filters=filters) 176 | assert resp 177 | for dev in resp: 178 | assert dev["rack_size"] < 2 179 | 180 | @responses.activate 181 | def test_list_devices_filter_gt(self, get_client, devices_data): 182 | """Test get all devices filter gt""" 183 | responses.add( 184 | responses.GET, 185 | "http://localhost/api/testing/devices/", 186 | json={"data": devices_data}, 187 | ) 188 | 189 | client = get_client 190 | filters = [ 191 | {"type": "gt", "field": "rack_size", "value": "1"}, 192 | ] 193 | resp = client.list_devices(filters=filters) 194 | assert resp 195 | for dev in resp: 196 | assert dev["rack_size"] > 1 197 | 198 | @responses.activate 199 | def test_list_devices_filter_ge(self, get_client, devices_data): 200 | """Test get all devices filter ge""" 201 | responses.add( 202 | responses.GET, 203 | "http://localhost/api/testing/devices/", 204 | json={"data": devices_data}, 205 | ) 206 | 207 | client = get_client 208 | filters = [ 209 | {"type": "ge", "field": "rack_size", "value": "1"}, 210 | ] 211 | resp = client.list_devices(filters=filters) 212 | assert resp 213 | for dev in resp: 214 | assert dev["rack_size"] >= 1 215 | 216 | @responses.activate 217 | def test_list_device_fields(self, get_client, devices_data): 218 | """Test listing all available fields of devices""" 219 | responses.add( 220 | responses.GET, 221 | "http://localhost/api/testing/devices/", 222 | json={"data": devices_data}, 223 | ) 224 | 225 | client = get_client 226 | assert len(client.list_device_fields()) >= 1 227 | 228 | @responses.activate 229 | def test_ansible_inv_devices_desc(self, get_client, devices_data): 230 | """Test listing unique key values from an endpoint""" 231 | responses.add( 232 | responses.GET, 233 | "http://localhost/api/testing/devices/", 234 | json={"data": devices_data}, 235 | ) 236 | 237 | client = get_client 238 | assert client.ansible_inv_endpoint_field("devices/", "description") 239 | 240 | @responses.activate 241 | def test_remove_added_devices(self, get_client, devices_data): 242 | """Test removing added devices in devices data""" 243 | responses.add( 244 | responses.GET, 245 | "http://localhost/api/testing/devices/", 246 | json={"data": devices_data}, 247 | ) 248 | for i in range(1, 4): 249 | responses.add( 250 | responses.DELETE, f"http://localhost/api/testing/devices/{i}/", json={} 251 | ) 252 | 253 | client = get_client 254 | devs = client.list_devices() 255 | for dev in devs: 256 | for ddata in devices_data: 257 | if dev["hostname"] == ddata["hostname"]: 258 | req = get_client._delete_device(dev["id"]) 259 | assert req.status_code == 200 260 | 261 | @responses.activate 262 | def test_list_devices_filter_ge_float_cast(self, get_client, devices_data): 263 | """Test get all devices filter ge with float cast""" 264 | responses.add( 265 | responses.GET, 266 | "http://localhost/api/testing/devices/", 267 | json={"data": devices_data}, 268 | ) 269 | 270 | client = get_client 271 | filters = [ 272 | {"type": "ge", "field": "rack_power", "value": "1"}, 273 | ] 274 | resp = client.list_devices(filters=filters) 275 | assert resp 276 | for dev in resp: 277 | if "rack_size" in dev: 278 | assert dev["rack_size"] >= 1 279 | -------------------------------------------------------------------------------- /phpipam_pyclient/phpipam_pyclient.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | """ 4 | PHPIpam Python API Client 5 | """ 6 | 7 | import fire 8 | import json 9 | import warnings 10 | import requests 11 | import os 12 | import sys 13 | from collections import defaultdict 14 | from phpipam_pyclient.version import __version__ 15 | 16 | DISABLE_SSL_WARNINGS = True 17 | if DISABLE_SSL_WARNINGS: 18 | warnings.filterwarnings("ignore") 19 | 20 | 21 | class PHPIpamClient(object): 22 | """PHPIPam Python API Client""" 23 | 24 | def __init__(self, cfg_file="config.json", init_auth=True): 25 | """PHPIpam Python client 26 | This class is meant to be used with Google's fire in order to also 27 | be used in a CLI exploring style. 28 | """ 29 | try: 30 | self.load_config(cfg_file=cfg_file) 31 | self._token = None 32 | self._session = None 33 | self._verify = False 34 | if init_auth: 35 | self.auth_session() 36 | except FileNotFoundError as e: 37 | print(str(e)) 38 | except json.JSONDecodeError as e: 39 | print(str(e)) 40 | sys.exit(1) 41 | except requests.exceptions.RequestException as e: 42 | print(str(e)) 43 | print("\nHave you configured your config.json file yet? ") 44 | sys.exit(1) 45 | 46 | def load_config(self, cfg_file="config.json"): 47 | """Load configuration file specified in config.json 48 | 49 | If the PHPIPAM_PYCLIENT_CFG_FILE environment variable 50 | exists, it takes higher precedence. 51 | 52 | :cfg_file: configuration file 53 | 54 | """ 55 | file_path = os.environ.get("PHPIPAM_PYCLIENT_CFG_FILE") 56 | if not file_path: 57 | file_path = os.path.join( 58 | os.path.abspath(os.path.dirname(__file__)), cfg_file 59 | ) 60 | with open(file_path) as json_file: 61 | data = json.load(json_file) 62 | self._base_url = data["base_url"] 63 | self._api_name = data["api_name"] 64 | self._auth_url = "{0}/{1}/user/".format(self._base_url, self._api_name) 65 | self._api_url = "{0}/{1}".format(self._base_url, self._api_name) 66 | self._user = data["user"] 67 | self._passwd = data["passwd"] 68 | 69 | def _build_url(self, endpoint: str): 70 | """Build url""" 71 | return f"{self._api_url}/{endpoint}" 72 | 73 | def auth_session(self): 74 | """Authenticate on PHPIpam API""" 75 | req = requests.post( 76 | self._auth_url, auth=(self._user, self._passwd), verify=self._verify 77 | ) 78 | if req.status_code != 200: 79 | raise requests.exceptions.RequestException( 80 | "Authentication failed on {0}".format(self._auth_url) 81 | ) 82 | self._token = {"token": req.json()["data"]["token"]} 83 | return req 84 | 85 | def list_device_fields(self): 86 | """List all devices' available fields/columns""" 87 | req = requests.get( 88 | self._build_url("devices/"), headers=self._token, verify=self._verify 89 | ) 90 | req.raise_for_status() 91 | data = req.json()["data"] 92 | for device in data: 93 | return list(device.keys()) 94 | return [] 95 | 96 | def _validate_ansible_kwargs(self, dict_value): 97 | if not isinstance(dict_value, dict): 98 | raise ValueError( 99 | f"ansible_kwargs is supposed to be a dict. got {dict_value}" 100 | ) 101 | for key in dict_value.keys(): 102 | if not isinstance(dict_value[key], dict): 103 | raise ValueError(f"ansible_kwargs key '{key}' is supposed to be a dict") 104 | return dict_value 105 | 106 | def ansible_inv_endpoint_field( 107 | self, endpoint, group_field, include_groups=[], filters=[], ansible_kwargs={} 108 | ): 109 | """Group devices based on a unique field value and outputs 110 | Ansible inventory 111 | 112 | :endpoint: endpoint to be filtered, e.g., devices/ 113 | :group_field: field to be filtered as a group, e.g., "description", 114 | :include_groups: ansible groups to be included, if empty, includes all 115 | :filters: filter objects to filter each host field with an expression and value 116 | :ansible_kwargs: ansible kwargs to be set based on a group name as default values 117 | :Returns: str formated as Ansible inventory 118 | 119 | Example: 120 | - endpoint=devices/ 121 | - group_field=description 122 | - include_groups=["backend"] 123 | - filters=[{"type": "contains", "field": "hostname", "value": "light"}] 124 | - ansible_kwargs={"backend": {"ansible_port": "2222"}} 125 | """ 126 | try: 127 | self._validate_ansible_kwargs(ansible_kwargs) 128 | except ValueError as e: 129 | print(str(e)) 130 | sys.exit(1) 131 | 132 | req = requests.get( 133 | self._build_url(endpoint), headers=self._token, verify=self._verify 134 | ) 135 | req.raise_for_status() 136 | data = req.json().get("data") 137 | if not data: 138 | return None 139 | 140 | device_list = data 141 | for filter_obj in filters: 142 | try: 143 | device_list = self._apply_filter(filter_obj, device_list) 144 | except ValueError as e: 145 | print(str(e)) 146 | sys.exit(1) 147 | 148 | dev = defaultdict(list) 149 | for device in device_list: 150 | if not device.get(group_field): 151 | continue 152 | if include_groups and device.get(group_field) not in include_groups: 153 | continue 154 | dev[device.get(group_field)].append(device.get("hostname")) 155 | 156 | res = str() 157 | for key, value in dev.items(): 158 | res = res + "[{0}]\n".format(key) 159 | for host in value: 160 | if key not in ansible_kwargs: 161 | res = res + "{0}\n".format(host) 162 | else: 163 | args = [f"{k}={v}" for k, v in ansible_kwargs[key].items()] 164 | res = res + "{0} {1}\n".format(host, " ".join(args)) 165 | res = res + "\n" 166 | return res 167 | 168 | def _delete_device(self, id): 169 | """Delete a device given a database id""" 170 | url = "{0}/{1}".format(self._api_url, "devices/{0}/".format(id)) 171 | return requests.delete(url, headers=self._token, verify=self._verify) 172 | 173 | def add_device(self, device=None): 174 | """Add device to PHPIpam given a dictionary that represents a device 175 | i.e., it should have these keys at least 176 | 'ip', 'hostname', 'description' 177 | 178 | :device: dictionary that represents a device 179 | :Returns: REST post status code 180 | 181 | """ 182 | if isinstance(device, str): 183 | device = json.loads(device) 184 | url = f"{self._api_url}/devices/1/" 185 | return requests.post( 186 | url, headers=self._token, verify=self._verify, data=device 187 | ).status_code 188 | 189 | def _apply_filter(self, filter_obj, collection): 190 | """Apply a filter to a collection""" 191 | if not collection: 192 | return collection 193 | 194 | if not isinstance(filter_obj, dict): 195 | raise ValueError(f"filter {filter_obj} must be a dictionary") 196 | if any( 197 | ( 198 | "type" not in filter_obj, 199 | "field" not in filter_obj, 200 | "value" not in filter_obj, 201 | ) 202 | ): 203 | raise ValueError( 204 | f"filter must have 'type', 'field' and 'value' keys. obj: {filter_obj}" 205 | ) 206 | 207 | def float_cast(value) -> float: 208 | try: 209 | return float(value) 210 | except (ValueError, TypeError): 211 | return 0 212 | 213 | filter_value = filter_obj["value"] 214 | filter_field = filter_obj["field"] 215 | filter_types = { 216 | "contains": lambda x: filter_value in str(x.get(filter_field)), 217 | "eq": lambda x: filter_value == str(x.get(filter_field)), 218 | "ge": lambda x: float(filter_value) <= float_cast(x.get(filter_field)), 219 | "gt": lambda x: float(filter_value) < float_cast(x.get(filter_field)), 220 | "le": lambda x: float(filter_value) >= float_cast(x.get(filter_field)), 221 | "lt": lambda x: float(filter_value) > float_cast(x.get(filter_field)), 222 | } 223 | if filter_obj["type"] not in filter_types: 224 | raise ValueError( 225 | f"invalid filter type, it must be of one these values: {list(filter_types.keys())}" 226 | ) 227 | 228 | return list( 229 | filter( 230 | filter_types[filter_obj["type"]], 231 | [elem for elem in collection if filter_obj["field"] in elem], 232 | ) 233 | ) 234 | 235 | def list_devices(self, fields=None, filters=[]): 236 | """List all devices and filter for specific fields 237 | 238 | :fields: optional field attributes to be included, includes all by default 239 | :filters: filter objects to filter each field with an expression and value 240 | 241 | Example: 242 | - fields=["ip", "hostname", "vendor"] 243 | - filters=[{"type": "contains", "field": "hostname", "value": "light"}] 244 | 245 | """ 246 | if not isinstance(fields, list): 247 | fields = [] 248 | 249 | req = requests.get( 250 | self._build_url("devices/"), headers=self._token, verify=self._verify 251 | ) 252 | req.raise_for_status() 253 | 254 | data = req.json().get("data") 255 | if not data: 256 | return [] 257 | 258 | device_list = [] 259 | for device in data: 260 | if not fields: 261 | device_list.append(device) 262 | continue 263 | 264 | dev = {} 265 | for field in fields: 266 | dev[field] = device.get(field) 267 | if dev: 268 | device_list.append(dev) 269 | 270 | try: 271 | for filter_obj in filters: 272 | device_list = self._apply_filter(filter_obj, device_list) 273 | return device_list 274 | except ValueError as e: 275 | print(str(e)) 276 | sys.exit(1) 277 | 278 | def version(self): 279 | """Get phpipam-pyclient version.""" 280 | return __version__ 281 | 282 | 283 | def main(): 284 | fire.Fire(PHPIpamClient) 285 | 286 | 287 | if __name__ == "__main__": 288 | main() 289 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright 2018 Vinicius da Silva Arcanjo 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | --------------------------------------------------------------------------------