Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Client SDK support instead of calling the Banyan APIs directly #47

Open
wants to merge 10 commits into
base: master
Choose a base branch
from
38 changes: 33 additions & 5 deletions banyan/api/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,10 +29,14 @@
from banyan.api.cloud_resource import CloudResourceAPI
from banyan.core.exc import BanyanError

import banyanclient
from pprint import pprint
# from banyanclient.apis.tags import customerfacingnamespace_api
from banyanclient.apis.tags import registered_service_api

JsonListOrObj = Union[List, Dict]
ProgressCallback = Callable[[str, str, int, int, List[JsonListOrObj]], None]


class BanyanApiClient:
"""
Main class for interacting with the Banyan API.
Expand All @@ -55,7 +59,8 @@ class BanyanApiClient:
:raises: :py:exc:`BanyanError` if no refresh token is provided.
"""

DEFAULT_API_URL = 'https://net.banyanops.com'
# DEFAULT_API_URL = 'https://net.banyanops.com'
DEFAULT_API_URL = 'https://dev02.console.bnntest.com'
"""
Default API server URL if none is specified and if a :envvar:`BANYAN_API_URL` environment variable
is not found.
Expand Down Expand Up @@ -136,7 +141,7 @@ def _read_config_file(self):
# noinspection PyMethodMayBeStatic
def _normalize_url(self, url: str) -> str:
if '/api' not in url:
url += '/api/v1'
url += '/api'
return url

def _create_session(self) -> requests.Session:
Expand All @@ -148,6 +153,29 @@ def _create_session(self) -> requests.Session:
requests_log.setLevel(logging.DEBUG)
requests_log.propagate = True
return http

def get_openapi_instance(self,api_version: str) -> registered_service_api.RegisteredServiceApi:
host = self._api_url
if api_version == 'v2':
host = host.replace('/api', '/api/experimental')
elif api_version == 'v1':
pass
else:
urllib3.warnings.resetwarnings()

if not self._access_token:
authorization = self.get_access_token()
configuration = banyanclient.Configuration(
host = host,access_token = authorization
)
else:
configuration = banyanclient.Configuration(
host= host,access_token = self._access_token
)
with banyanclient.ApiClient(configuration) as api_client:
# Create an instance of the API class
api_instance = registered_service_api.RegisteredServiceApi(api_client)
return api_instance

def get_access_token(self) -> str:
"""
Expand All @@ -157,14 +185,15 @@ def get_access_token(self) -> str:
:return: the new access token.
:raises: :py:exc:`BanyanError` if the refresh token is invalid.
"""
content = self._request('POST', '/refresh_token').json()
content = self._request('POST', '/v1/refresh_token').json()
self._access_token = content['Message']
return self._access_token

def _request(self, method: str, url: str, params: Dict[str, Any] = None, data: Any = None,
headers: Dict[str, str] = None, cookies: Dict[str, str] = None,
files=None, auth=None, timeout=None, allow_redirects=True, proxies=None,
hooks=None, stream=None, verify=None, cert=None, json=None) -> requests.Response:

if '://' not in url:
url = self._api_url + url
if '/v2/' in url:
Expand Down Expand Up @@ -419,7 +448,6 @@ def cloud_resources(self) -> CloudResourceAPI:

if __name__ == '__main__':
logging.basicConfig(level=logging.DEBUG)

c = BanyanApiClient(api_server_url='https://gcstage.banyanops.com',
refresh_token=os.getenv('BANYAN_REFRESH_TOKEN'), debug=True)
print(c.get_access_token())
Expand Down
37 changes: 32 additions & 5 deletions banyan/api/base.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,15 @@
from __future__ import print_function
from abc import ABC
from typing import Dict, List, Union, Iterable, Any, Callable

from banyan.core.exc import BanyanError
from banyan.model import InfoBase, BanyanApiObject, Resource, ResourceOrName

import json

import banyanclient


InfoObjectOrName = Union[InfoBase, str]


Expand All @@ -26,13 +32,34 @@ def __init__(self, client):
self._by_id: Dict[str, Resource] = dict()

def list(self, params: Dict[str, Any] = None) -> list:
list_func = self._client.api_request

service_id = ""
# default_services = False
service_name = ""
friendly_name = ""
if params:
service_id = params["ServiceID"] # str | The ID of the Service to retrieve (optional)
# default_services = params["DefaultServices"] # bool | Default services flag. (optional)
service_name = params["ServiceName"] # bool | The Name of the Service to retrieve (optional)
friendly_name = params["FriendlyName"] # str | Friendly Name of the Service. (optional)
query_params = {
'ServiceID': service_id,
# 'DefaultServices': default_services,
'ServiceName': service_name,
'FriendlyName': friendly_name,
}

try:
if self.Meta.supports_paging:
list_func = self._client.paged_request
# List services
api_instance = self._client.get_openapi_instance('v1')
response = api_instance.v1_registered_services_get(query_params=query_params,skip_deserialization=True).response
except banyanclient.ApiException as e:
print("Exception when calling CUSTOMERFACINGNAMESPACEApi->v1_registered_services_get: %s\n" % e)
except AttributeError:
pass
response_json = list(list_func('GET', self.Meta.list_uri, params=params))
pass

response_json = json.loads(response.data)
response_json = list(response_json)
data: List[Resource] = self.Meta.info_class.Schema().load(response_json, many=True)
self._build_cache(data)
return data
Expand Down
35 changes: 28 additions & 7 deletions banyan/api/service.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,12 @@
from banyan.api.base import ApiBase
from banyan.api.service import ApiBase
from banyan.model.policy import PolicyInfo, PolicyInfoOrName, PolicyAttachInfo
from banyan.model.service import ServiceInfo, Service, ServiceInfoOrName

import json

import banyanclient

class ServiceAPI(ApiBase):
class Meta:
data_class = Service
Expand All @@ -15,16 +20,32 @@ class Meta:

def enable(self, service: ServiceInfoOrName) -> str:
service = self.find(service)
json_response = self._client.api_request('POST',
'/enable_registered_service',
params={'ServiceID': service.id})
query_params = {
'ServiceID': service.id,
}
try:
api_instance = self._client.get_openapi_instance('v1')
response = api_instance.v1_enable_registered_service_post(query_params=query_params,skip_deserialization=True).response
except banyanclient.ApiException as e:
print("Exception when calling CUSTOMERFACINGNAMESPACEApi->v1_enable_registered_service_post: %s\n" % e)
except AttributeError:
pass
json_response = json.loads(response.data)
return json_response['Message']

def disable(self, service: ServiceInfoOrName) -> str:
def disable(self, service: ServiceInfoOrName) -> str:
service = self.find(service)
json_response = self._client.api_request('POST',
'/disable_registered_service',
params={'ServiceID': service.id})
query_params = {
'ServiceID': service.id,
}
try:
api_instance = self._client.get_openapi_instance('v1')
response = api_instance.v1_disable_registered_service_post(query_params=query_params,skip_deserialization=True).response
except banyanclient.ApiException as e:
print("Exception when calling CUSTOMERFACINGNAMESPACEApi->v1_disable_registered_service_post: %s\n" % e)
except AttributeError:
pass
json_response = json.loads(response.data)
return json_response['Message']

def attach(self, service: ServiceInfoOrName, policy: PolicyInfoOrName, enforcing: bool) -> PolicyAttachInfo:
Expand Down
8 changes: 7 additions & 1 deletion examples/list_services.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,10 @@
from banyan.api import BanyanApiClient
c = BanyanApiClient()
c = BanyanApiClient(api_server_url='https://dev02.console.bnntest.com',refresh_token="eyJhbGciOiJSUzI1NiIsImtpZCI6ImZjNTg5Mjg3YzQxNDkzYjI1MDAyYzM2YzQxZDZiMGI0YWFjZTgxMWMiLCJ0eXAiOiJKV1QifQ.eyJBY2Nlc3NUb2tlbiI6ImxldmVsMSIsIkF1dGgiOiJMT0NBTCIsIkVtYWlsIjoiIiwiTm9WUE4iOiJESVNBQkxFRCIsIk9yZ0lEIjoiIiwiUHJvZmlsZSI6IlJlYWRPbmx5IiwiUmVmcmVzaCI6InRydWUiLCJSZWZyZXNoRW1haWwiOiJhbmtpdC5rdW1hckBqb3Noc29mdHdhcmUuY29tIiwiVVVJRCI6IiIsIlVuaXF1ZUlEIjoiNmJkYzBjMmMtNjhjMi00MmZmLWFkMjgtNjFjMDMxZTExMWJjIiwiZXhwIjoxNjY2MTcyNjY5LCJpYXQiOjE2NjYxNzI2Njh9.i29gQ2M2jTMhqP1pNupb0MAErjJQL0GV7obwnOtiU3ZZoJ42XTnHky7J5VGpZ79AVtiqTcUE-Eie_KBQ02l_2VKquiYSG51jqyhcSHZs2FQblgm3NXNHj_1JWX_bVYTlgZi7gQFJal97IOC3mEJTg8S3VVVi8LuY1G34jKpVpqiHVPhnQXJYHzOr-HkOT-laFU5X97aTKq24zQUoxsE_-05jsJaqu2Q-tSdqtoSt8b_c3H1NPM6ydxeKWEzIHRi1hyBAAac0xHPJSn_xGbmh_pNqCuhmHzeDk5MQT7M_zW9x7rUzgTwGP8iSMGg_eFRVMIVn-0Qjkjb_JdaRjotBVg")
for service in c.services.list():
print(service.name)
# service.disable()
# if service.name == 'test-service':
# service.disable("test-service")
# c.services.disable("test-service.ankitdev02-shield.bnn")
#c.services.enable("test-service.ankitdev02-shield.bnn")

1 change: 1 addition & 0 deletions requirements-dev.txt
Original file line number Diff line number Diff line change
Expand Up @@ -11,3 +11,4 @@ flake8
pexpect
pep8
pylint
pybanyan-client