Skip to content

Commit

Permalink
feat: adding platform and isolation level selection.
Browse files Browse the repository at this point in the history
  • Loading branch information
John2360 committed Sep 2, 2024
1 parent 27bbc72 commit 55efba2
Show file tree
Hide file tree
Showing 6 changed files with 98 additions and 124 deletions.
5 changes: 2 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -41,14 +41,13 @@ Below is a list of the available functionality in the SDK. Using the SDK you can

Database Management:

- `create_database(database_name: str, alias: str)`: Creates a new database.
- `create_database(platform: str, alias: str)`: Creates a new database.
- `delete_database(database_name: str)`: Deletes to a database.
- `list_databases()`: Lists all databases.
- `connect_database(database_id: str)`: Connects to a database and turns into SQL connection.

Tenant Management:

- `create_tenant(tenant_name: str, alias: str, database_id: str = "")`: Creates a new tenant.
- `create_tenant(tenant_name: str, isolation_level: str, platform: str, alias: str, database_id: str = "")`: Creates a new tenant.
- `delete_tenant(tenant_name: str)`: Deletes a tenant.
- `list_tenants()`: Lists all tenants.
- `connect_tenant(tenant_name: str)`: Connects to a tenant and turns into SQL connection.
Expand Down
7 changes: 6 additions & 1 deletion examples/test.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,14 +9,19 @@
# Create a database
database_id = None
try:
database_id = fortress.create_database(alias="Client 1")
database_id = fortress.create_database(
platform="aws",
alias="Client 1",
)
except Exception as e:
print(f"Database creation failed: {e}")

# Create a tenant (if you do not provide a database_id, a new database will be created)
try:
fortress.create_tenant(
tenant_id="client1",
isolation_level="dedicated",
platform="aws",
alias="Client 1",
database_id=database_id,
)
Expand Down
155 changes: 68 additions & 87 deletions fortress_sdk_python/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,13 +34,13 @@ class ConnectionDetails:


class InternalError(Exception):
def __init__(self, message='Internal Server Error'):
def __init__(self, message="Internal Server Error"):
self.message = message
super().__init__(self.message)


class ValidationError(Exception):
def __init__(self, message='Validation Error'):
def __init__(self, message="Validation Error"):
self.message = message
super().__init__(self.message)

Expand All @@ -57,218 +57,199 @@ def __init__(
self.api_key = api_key

def get_uri(self, id: str, type: str) -> ConnectionDetails:
if type != 'tenant' and type != 'database':
if type != "tenant" and type != "database":
raise ValidationError("Type must be either 'tenant' or 'database'")

endpoint = (
f'{self.base_url}/v1/organization/{self.org_id}/{type}/{id}/uri'
)
endpoint = f"{self.base_url}/v1/organization/{self.org_id}/{type}/{id}/uri"
response = requests.get(
endpoint,
headers={'Api-Key': self.api_key},
headers={"Api-Key": self.api_key},
)

json_response = response.json()
if response.status_code != 200:
if response.status_code == 400:
raise ValidationError(
json_response.get('message', 'Validation Error')
)
raise ValidationError(json_response.get("message", "Validation Error"))
if response.status_code == 500:
raise InternalError(
json_response.get('message', 'Internal Server Error')
json_response.get("message", "Internal Server Error")
)

connection_details_str = None
try:
connection_details_str = decrypt(
private_key=self.api_key,
ciphertext=json_response.get('connectionDetails', ''),
ciphertext=json_response.get("connectionDetails", ""),
)
except Exception as e:
raise InternalError(
'An error occured: Unable to decrypt connection details'
"An error occured: Unable to decrypt connection details"
)

if connection_details_str is None:
raise InternalError(
'An error occured: Unable to decrypt connection details'
"An error occured: Unable to decrypt connection details"
)

connection_details = json.loads(connection_details_str)
url = connection_details.get('url', '')
database = connection_details.get('database', '')
port = int(connection_details.get('port', 0))
username = connection_details.get('username', '')
password = connection_details.get('password', '')

if (
url == ''
or port == 0
or username == ''
or password == ''
or database == ''
):
raise InternalError('An error occured: Invalid connection details')
url = connection_details.get("url", "")
database = connection_details.get("database", "")
port = int(connection_details.get("port", 0))
username = connection_details.get("username", "")
password = connection_details.get("password", "")

if url == "" or port == 0 or username == "" or password == "" or database == "":
raise InternalError("An error occured: Invalid connection details")

return ConnectionDetails(
database_id=json_response['databaseId'],
database_id=json_response["databaseId"],
url=url,
database=database,
port=port,
username=username,
password=password,
)

def create_database(self, alias: str = '') -> str:
endpoint = f'{self.base_url}/v1/organization/{self.org_id}/database'
payload = {'alias': alias}
def create_database(self, platform: str, alias: str = "") -> str:
endpoint = f"{self.base_url}/v1/organization/{self.org_id}/database"
payload = {"platform": platform, "alias": alias}
response = requests.post(
endpoint,
headers={'Api-Key': self.api_key},
headers={"Api-Key": self.api_key},
json=payload,
)

json_response = response.json()
if response.status_code != 200:
if response.status_code == 400:
raise ValidationError(
json_response.get('message', 'Validation Error')
)
raise ValidationError(json_response.get("message", "Validation Error"))
if response.status_code == 500:
raise InternalError(
json_response.get('message', 'Internal Server Error')
json_response.get("message", "Internal Server Error")
)

return json_response['databaseId']
return json_response["databaseId"]

def delete_database(self, database_id: str):
endpoint = f'{self.base_url}/v1/organization/{self.org_id}/database/{database_id}'
endpoint = (
f"{self.base_url}/v1/organization/{self.org_id}/database/{database_id}"
)
response = requests.delete(
endpoint,
headers={'Api-Key': self.api_key},
headers={"Api-Key": self.api_key},
)

json_response = response.json()
if response.status_code != 200:
if response.status_code == 400:
raise ValidationError(
json_response.get('message', 'Validation Error')
)
raise ValidationError(json_response.get("message", "Validation Error"))
if response.status_code == 500:
raise InternalError(
json_response.get('message', 'Internal Server Error')
json_response.get("message", "Internal Server Error")
)

def list_databases(self) -> list[Database]:
endpoint = f'{self.base_url}/v1/organization/{self.org_id}/databases'
endpoint = f"{self.base_url}/v1/organization/{self.org_id}/databases"
response = requests.get(
endpoint,
headers={'Api-Key': self.api_key},
headers={"Api-Key": self.api_key},
)

json_response = response.json()
if response.status_code != 200:
if response.status_code == 400:
raise ValidationError(
json_response.get('message', 'Validation Error')
)
raise ValidationError(json_response.get("message", "Validation Error"))
else:
raise InternalError(
json_response.get('message', 'Internal Server Error')
json_response.get("message", "Internal Server Error")
)

databases = [
Database(
id=data.get('databaseId', ''),
alias=data.get('alias', ''),
size=data.get('sizeBytes', 0),
average_read_iops=data.get('averageReadIOPS', 0),
average_write_iops=data.get('averageWriteIOPS', 0),
id=data.get("databaseId", ""),
alias=data.get("alias", ""),
size=data.get("sizeBytes", 0),
average_read_iops=data.get("averageReadIOPS", 0),
average_write_iops=data.get("averageWriteIOPS", 0),
created_date=datetime.datetime.fromisoformat(
data.get('createdDate', '')
data.get("createdDate", "")
),
)
for data in json_response.get('databases', [])
for data in json_response.get("databases", [])
]

return databases

def create_tenant(
self, tenant_id: str, alias: str = '', database_id: str = ''
self,
tenant_id: str,
isolation_level: str,
platform: str,
alias: str = "",
database_id: str = "",
) -> None:
endpoint = (
f'{self.base_url}/v1/organization/{self.org_id}/tenant/{tenant_id}'
)
payload = {'alias': alias}
endpoint = f"{self.base_url}/v1/organization/{self.org_id}/tenant/{tenant_id}"
payload = {"isolation": isolation_level, "platform": platform, "alias": alias}
if database_id:
payload['databaseId'] = database_id
payload["databaseId"] = database_id

response = requests.post(
endpoint,
headers={'Api-Key': self.api_key},
headers={"Api-Key": self.api_key},
json=payload,
)

json_response = response.json()
if response.status_code != 200:
if response.status_code == 400:
raise ValidationError(
json_response.get('message', 'Validation Error')
)
raise ValidationError(json_response.get("message", "Validation Error"))
if response.status_code == 500:
raise InternalError(
json_response.get('message', 'Internal Server Error')
json_response.get("message", "Internal Server Error")
)

def delete_tenant(self, tenant_id: str) -> None:
endpoint = (
f'{self.base_url}/v1/organization/{self.org_id}/tenant/{tenant_id}'
)
endpoint = f"{self.base_url}/v1/organization/{self.org_id}/tenant/{tenant_id}"
response = requests.delete(
endpoint,
headers={'Api-Key': self.api_key},
headers={"Api-Key": self.api_key},
)

json_response = response.json()
if response.status_code != 200:
if response.status_code == 400:
raise ValidationError(
json_response.get('message', 'Validation Error')
)
raise ValidationError(json_response.get("message", "Validation Error"))
if response.status_code == 500:
raise InternalError(
json_response.get('message', 'Internal Server Error')
json_response.get("message", "Internal Server Error")
)

def list_tenants(self) -> list[Tenant]:
endpoint = f'{self.base_url}/v1/organization/{self.org_id}/tenants'
endpoint = f"{self.base_url}/v1/organization/{self.org_id}/tenants"
response = requests.get(
endpoint,
headers={'Api-Key': self.api_key},
headers={"Api-Key": self.api_key},
)

json_response = response.json()
if response.status_code != 200:
if response.status_code == 400:
raise ValidationError(
json_response.get('message', 'Validation Error')
)
raise ValidationError(json_response.get("message", "Validation Error"))
else:
raise InternalError(
json_response.get('message', 'Internal Server Error')
json_response.get("message", "Internal Server Error")
)

tenants = [
Tenant(
name=data.get('tenantId', ''),
alias=data.get('alias', ''),
database_id=data.get('databaseId', ''),
name=data.get("tenantId", ""),
alias=data.get("alias", ""),
database_id=data.get("databaseId", ""),
created_date=datetime.datetime.fromisoformat(
data.get('createdDate', '')
data.get("createdDate", "")
),
)
for data in json_response.get('tenants', [])
for data in json_response.get("tenants", [])
]

return tenants
Loading

0 comments on commit 55efba2

Please sign in to comment.