Giter VIP home page Giter VIP logo

bigrest's Introduction

Support

I am no longer supporting this project with new functionalities or bug fixes.
Version 1.7.3 is the latest and it will continue available for download.
Jason Rahm has forked the project, and you can see his work here https://github.com/f5-rahm/BIGREST.

What is BIGREST?

F5 BIG-IP and BIG-IQ devices have an API called iControl REST.
BIGREST is an SDK with multiple methods and functions that simplifies the use of the iControl REST API.

BIGIP Next and BIGIP Next Central Manager are not supported by BIGREST.

What is useful for?

If you want to automate tasks on a BIG-IP or BIG-IQ devices, one of the options is to use the iControl REST API.
If you interact with the API directly, you will have to know how the API works, including headers, tokens, etc...
Probably, you will end up scripting those tasks using a programming language, and creating some functions you normally use.

BIGREST removes that work, as it includes those functions that you normally use.
It creates a kind of abstraction layer on to of the API.

Why create another SDK?

This was one of the first questions I got when BIGREST was released.
In case you don't know, there was already an SDK (https://github.com/F5Networks/f5-common-python) before BIGREST was created.

I have used the other SDK, and I did initially wanted to support and expand it.
However, the approach that was taken in that SDK to defined every HTTP path as Python modules made it difficult to expand and support it.
For example, it just supports very few BIG-IQ functionalities.

On the other hand, BIGREST tries to be more generic as possible, and the user has to indicate the HTTP path they want to use.
This means any new HTTP path included on the next version will be automatically available on BIGREST.
Also, with this generic approach, it fully supports both BIG-IP and BIG-IQ.

BIGREST functionalities

  • Supports partition
  • Supports route domain
  • Support HTTP basic authentication
  • Support token
  • Support refresh token
  • Implements all HTTP methods used in the iControl REST API
  • Implements HTTP path /stats
  • Implements HTTP path /example
  • Implements command
  • Implements task
  • Implements transaction

Documentation

https://bigrest.readthedocs.io/

Source code

https://github.com/leonardobdes/BIGREST

Author

Name:
Leonardo Souza
LinkedIn:

Contributor

Name:
Jason Rahm
LinkedIn:

How to install?

Requires Python version 3.7 or above.

Requires requests package, install using Python pip:

pip install requests

Install BIGREST using Python pip:

pip install bigrest

How to use it?

In the following example:

192.168.1.245 IP or name of the F5 device.
admin Username to be used to connect to the device.
password Password to be used to connect to the device.

First, import the SDK:

from bigrest.bigip import BIGIP

Next, create a device object:

device = BIGIP("192.168.1.245", "admin", "password")

Lastily, load all virtual servers and print their names:

virtuals = device.load("/mgmt/tm/ltm/virtual")
for virtual in virtuals:
    print(virtual.properties["name"])
This is just a simple example to give you a first view about the SDK.
Detailed information about how to use the SDK will be provided in the next sections of this documentation.

How to get help?

If you have problems using this SDK, or to understand how the F5 iControl REST API works, use DevCentral website to get help.

How to report bugs?

Use GitHub issues to report bugs.
For any bug, please provide the following information.

BIGREST version:

Run the following command to find the version you are using.

pip show bigrest

F5 device type:

BIG-IP or BIG-IQ

F5 device version:

Run the following command to find the version you are using.

tmsh show sys version

Python code to replicate the bug.

Output generated when the bug is triggered.

How to request new functionalities?

Use GitHub issues to request new functionalities.
Use the following format in the title RFE - Title.

bigrest's People

Contributors

jasonrahm avatar leonardobdes avatar rahveetufts avatar shell2 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

bigrest's Issues

Login/auth. token retrieval takes 30 seconds with BIG-IP 15.1.6.1 Build 0.0.10 Point Release 1 => workaround

Hi,

probably more a "FYI" for anyone who is also hitting the same issue we had. For some reason BIG-IP 15.1.6.1 Build 0.0.10 Point Release 1 has some odd behaviour if one requests an authentication token and uses basic authentication to retrieve that token. It takes over 30 seconds for this request to complete! Funny part is that it works fast if one access the REST API via localhost / 127.0.0.1 (think ssh port forwarding). So I still think that this is just a bug in f5 because it worked with 14.x. (Using 1.4.0 but happens with 1.7.3 too.)

Anyway, the issue can be easily fixed by patching BIGREST: You need to edit big.py and utils/utils.py. Just search for "Required for 12.0.0, but not in 15.1.0".

# ---
# big.py

         # I guess those two lines can be commented also but didn't test (yet).
         if self.request_token is False:
            self.session.auth = (username, password)

         ...
  
         # Required for 12.0.0, but not in 15.1.0
         self.session.auth = (self.username, self.password)  # <= comment this line
         response = None
  
# ---
# utils.py
  
      response = requests.post(
        f"https://{device}/mgmt/shared/authn/login",
        json=data, verify=False, auth=auth)
  
# =>  
  
      response = requests.post(
        f"https://{device}/mgmt/shared/authn/login",
        json=data, verify=False)

Maybe I will provide some patch sometime. But I hope that information is helpful anyway for someone.

Kind regards,
Dietmar


diff -x '*.pyc' -x '*.bak' -r REDACTED/big.py ./big.py
439c439
<         # self.session.auth = (self.username, self.password)
---
>         self.session.auth = (self.username, self.password)
diff -x '*.pyc' -x '*.bak' -r REDACTED/utils/utils.py ./utils/utils.py
57c57
<         json=data, verify=False)
---
>         json=data, verify=False, auth=auth)
88c88
<         json=data, verify=False)
---
>         json=data, verify=False, auth=auth)
[REDACTED@REDACTED bigrest]$

command doesn't work. Return "Found invalid content-type

When attempting to run device.command() i get Found invalid content-type no matter what the command is. Here is an example

>>> from pprint import pprint
>>> from bigrest.utils.utils import rest_format
>>> from f5lib import bigrest_login
>>> br = bigrest_login('myF5Device','','')[0]
>>> from bigrest.bigip import BIGIP
>>> cmd = {}
>>> cmd["command"] = "run"
>>> cmd["utilCmdArgs"] = "-c 'cat /VERSION'"
>>> pprint(cmd)
{'command': 'run', 'utilCmdArgs': "-c 'cat /VERSION'"}
>>> br.command("/mgmt/tm/util/bash", cmd)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/bigrest/big.py", line 270, in command
    obj = self.create(path, data)
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/bigrest/big.py", line 186, in create
    raise RESTAPIError(response, self.debug)
bigrest.common.exceptions.RESTAPIError:
Status:
415
Response Body:
{
    "code": 415,
    "message": "Found invalid content-type. The content-type must be application/json. The received content-type is application/octet-stream",
    "errorStack": [],
    "apiError": 1
}

I don't see any way to adjust the content-type for the command method. Any advice?

Connection timeout?

Hi,
I have seen that the connection timeout is set to default "None" which is trying connecting endless when a host is not available.
How can we set the timeout globally for BIGREST?

Thanks

ValueError: list.remove(x): x not in list

I figure we'll start with the error and everything I'm using is what you have as current :) This is the letsencrypt stuff Jason Rahm's been working on btw. But I'm thinking this issue might be w/ the BIGREST framework and potentially because I'm on F5's BIG-IP 16.1.2.1 Build 0.0.10 Point Release 1. We love how F5 changes stuff all the time ;)

File "/shared/letsencrypt/hook_script.py", line 62, in clean_challenge
vip.properties['rules'].remove('/Common/le_challenge_rule')
ValueError: list.remove(x): x not in list
ERROR: clean_challenge hook returned with non-zero exit code

I see the files created on my Apache server using "watch ls" since it creates then removes them quickly. They did happen so that's working.
The iRule fails to delete per the error and it remains on the box. I've deleted it manually and re-run various times trying various things and still no luck.
I've commented out a few sections of the hook script and it still fails but it gives some insight. I'm not going to explain that now unless ya'll ask.

The other thing I'm seeing and this is more for Jason but this might be the issue w/ the iRule deletion failure.
The tokens seem to mismatch from what's in the log in the CLI vs. the token stored in the challenge iRule.
Thoughts?
Here's a full log example below:

INFO: Using main config file /shared/letsencrypt/config

Processing projectbaiu.org with alternative names: www.projectbaiu.org

  • Signing domains...
  • Generating private key...
  • Generating signing request...
  • Requesting new certificate order from CA...
  • Received 2 authorizations URLs from the CA
  • Handling authorization for www.projectbaiu.org
  • Handling authorization for projectbaiu.org
  • 2 pending challenge(s)
  • Deploying challenge tokens...
  • (hook) Deploying Challenge
  • (hook) Challenge rule added to virtual.
  • (hook) Deploying Challenge
  • (hook) Challenge rule added to virtual.
  • Responding to challenge for www.projectbaiu.org authorization...
  • (hook) Invalid Challenge
  • (hook) Invalid Challenge Args: ['www.projectbaiu.org', '["type"]\t"http-01"\n["status"]\t"invalid"\n["error","type"]\t"urn:ietf:params:acme:error:unauthorized"\n["error","detail"]\t"63.226.21.50: Invalid response from http://www.projectbaiu.org/.well-known/acme-challenge/oQL3Lr39uV-G-Bp4xq54VG4OQD7sexwc1uV2DmWsXHQ: 404"\n["error","status"]\t403\n["error"]\t{"type":"urn:ietf:params:acme:error:unauthorized","detail":"63.226.21.50: Invalid response from http://www.projectbaiu.org/.well-known/acme-challenge/oQL3Lr39uV-G-Bp4xq54VG4OQD7sexwc1uV2DmWsXHQ: 404","status":403}\n["url"]\t"https://acme-staging-v02.api.letsencrypt.org/acme/chall-v3/2306706054/wc9l2A"\n["token"]\t"oQL3Lr39uV-G-Bp4xq54VG4OQD7sexwc1uV2DmWsXHQ"\n["validationRecord",0,"url"]\t"http://www.projectbaiu.org/.well-known/acme-challenge/oQL3Lr39uV-G-Bp4xq54VG4OQD7sexwc1uV2DmWsXHQ"\n["validationRecord",0,"hostname"]\t"www.projectbaiu.org"\n["validationRecord",0,"port"]\t"80"\n["validationRecord",0,"addressesResolved",0]\t"63.226.21.50"\n["validationRecord",0,"addressesResolved"]\t["63.226.21.50"]\n["validationRecord",0,"addressUsed"]\t"63.226.21.50"\n["validationRecord",0]\t{"url":"http://www.projectbaiu.org/.well-known/acme-challenge/oQL3Lr39uV-G-Bp4xq54VG4OQD7sexwc1uV2DmWsXHQ","hostname":"www.projectbaiu.org","port":"80","addressesResolved":["63.226.21.50"],"addressUsed":"63.226.21.50"}\n["validationRecord"]\t[{"url":"http://www.projectbaiu.org/.well-known/acme-challenge/oQL3Lr39uV-G-Bp4xq54VG4OQD7sexwc1uV2DmWsXHQ","hostname":"www.projectbaiu.org","port":"80","addressesResolved":["63.226.21.50"],"addressUsed":"63.226.21.50"}]\n["validated"]\t"2022-04-28T17:12:46Z"']
  • Cleaning challenge tokens...
  • (hook) Cleaning Challenge
  • (hook) Challenge rule removed from virtual.
  • (hook) Cleaning Challenge
    Traceback (most recent call last):
    File "/shared/letsencrypt/hook_script.py", line 120, in
    clean_challenge(sys.argv[2:])
    File "/shared/letsencrypt/hook_script.py", line 62, in clean_challenge
    vip.properties['rules'].remove('/Common/le_challenge_rule')
    ValueError: list.remove(x): x not in list
    ERROR: clean_challenge hook returned with non-zero exit code

Max retries exceeded with url: /mgmt/shared/echo-query (Caused by NewConnectionError('<urllib3.connection.HTTPSConnection object at 0x7f376b97a4d0>: Failed to establish a new connection: [Errno -2] Name or service not known'))

In writing a script to go through our 85 F5 instances to build an inventory with VS, pool, node, and SSL information returned, we find the iControlREST times out on occasion. Rather than have the whole script fail, we want it to continue processing as if no data was received.

I have edited big.py to encapsulate the "response = self.session.get(url, timeout=self.timeout) with a try statement, and if it fails to connect, the except sets response = ''

I have done this in the load and show definitions of big.py file. Hopefully this will be helpful to others vs writing all kinds of error handling into your main script.

BIGIP module creates a token on the F5 even when `request_token` is set to `False`

I have written a connection class using the following method:

def f5_conn(f5ip: str) -> BIGIP:
    """Function to create a connection to f5"""
    try:
        return BIGIP(device=f5ip, username=secrets["f5Username"], password=secrets["f5Password"], login_provider="tmos", request_token=False)

The above class gets invoked every time there is an API request to the F5 device.
We saw an error in our API that said:

"user xxxx-xxxx-xxxx-xxxx-xxxxxxxx has reached maximum active login tokens"

So, I decided to delete all tokens using a DELETE call to the /mgmt/shared/authz/tokens endpoint and then making sure request_token was set to False

Once I made a simple GET call to the device, I notice the device is still issuing tokens for that user.

Change load to return the object instead of list of objects

Refactor the load method in bigip.py so that only collections return a list. This will allow the behaviors on load to be consistent:

# Collection
pools = br.load('/mgmt/tm/ltm/pool')
for p in pools:
    for k, v in iter(p.properties.items()):
        print(k, v)

# Named Object
pool = br.load('/mgmt/tm/ltm/pool/testpool')
for k, v in iter(pool.properties.items()):
    print(k, v)

Currently, you have to manipulate the pool on load or in the loop like this:

pool = br.load('/mgmt/tm/ltm/pool/testpool')[0]
for k, v in iter(pool.properties.items()):
    print(k, v)
## OR ##
pool = br.load('/mgmt/tm/ltm/pool/testpool')
for k, v in iter(pool[0].properties.items()):
...     print(k, v)

RESTAPIError on connect, /mgmt/shared/echo-query is not guaranteed to exist

BIGREST Version: 1.4.0
BIG-IP Version: 14.1.4.6 Build 0.0.8

To replicate bug, simply try to create an instance of the BIGIP class
bigip = BIGIP(hostname, username, password)

stack trace:

_connect, big.py:491
__init__, big.py:91
__init__, bigip.py:40

The issue is line 491. During _connect(), BIGIP tries to GET on f"https://{self.device}/mgmt/shared/echo-query"
In my version of BIG-IP, this URL does not exist. My response status code is 401, so BIGIP will raise RESTAPIError on line 493.

The solution is simple (at least for me). Just get rid of the mgmt/shared/echo-query from the URL. Use this URL instead:
f"https://{self.device}/

This returns a 200 status, so everything works.

My change is here:
https://github.com/rahvee/BIGREST/commit/f535bfaec341741f90bd0c90cd21f60ebad628a3

This change works for me. I don't have the ability to test on any other system (different versions of Big-IP, IQ), so I didn't submit it as a pull request for you.

RFE - Explain what bigrest does

Hi, what does this actually provide? I know it provides some things that apparently make it easier to work with both BIGIP and BIGIQ but more examples are needed. The reason behind its creation.... to provide a unified REST API to BIG-IP products perhaps?

Unable to make a connection to BIG-IQ

Hello - I tried to make a connection to our new BIG-IQ. I get the error below. admin user account has the following roles: Administrator Role, F5 Device Trust User and Device Manager.

>>> bq = BIGIQ("10.14.49.94","admin","xZxZxZxZx",session_verify=False)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/appviewx/apineda/venv/lib/python3.8/site-packages/bigrest/big.py", line 96, in __init__
    self._connect()
  File "/home/appviewx/apineda/venv/lib/python3.8/site-packages/bigrest/big.py", line 499, in _connect
    raise RESTAPIError(response, self.debug)
bigrest.common.exceptions.RESTAPIError: 
Status:
401
Response Body:
<html>
<head><title>401 Authorization Required</title></head>
<body>
<center><h1>401 Authorization Required</h1></center>
<hr><center>webd</center>
</body>
</html>

BIGREST returns errors on successful calls

BIGREST seems to consider only the 200 code as a successful request. Should be updated to include the other successful codes (201, 202, etc).

if response.status_code != 200:

Example:

Traceback (most recent call last):
  File "XXXX.py", line 52, in <module>
    create = device.create(f'/mgmt/tm/asm/policies/{rest_format(policyId)}/whitelist-ips', whitelist_settings)
  File "/home/nick/.local/lib/python3.8/site-packages/bigrest/big.py", line 184, in create
    raise RESTAPIError(response, self.debug)
bigrest.common.exceptions.RESTAPIError: 
Status:
201
Response Body:
{
    "ignoreIpReputation": true,
    "blockRequests": "never",
    "ignoreAnomalies": false,
    "neverLogRequests": true,
 …
}

Enhance debug functionality

Add ability to see curl format of every request sent as a list item in a debug attribute, whether or not there is an error.

Requires no change to the debug='file' submission, but will take that and:

  • Set debug attribute to True
  • Set debug_file attribute to the filename
  • Append all requests as curl formatted commands to debug_output list attribute
  • Still allow for debug file to be created on errors

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.