Skip to content

Commit

Permalink
feat(staticroutes): adds v2 static routes
Browse files Browse the repository at this point in the history
This commit introduces support for V2 static routes
  • Loading branch information
RomilShah committed Jul 28, 2023
1 parent 17365ab commit 9f6d02b
Show file tree
Hide file tree
Showing 11 changed files with 152 additions and 61 deletions.
18 changes: 18 additions & 0 deletions riocli/jsonschema/schemas/static_route-schema.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,10 @@ definitions:
const: StaticRoute
metadata:
"$ref": "#/definitions/metadata"
spec:
"$ref": "#/definitions/staticRouteSpec"
status:
"$ref": "#/definitions/staticRouteStatus"
required:
- apiVersion
- kind
Expand Down Expand Up @@ -47,3 +51,17 @@ definitions:
uuid:
type: string
pattern: "^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}$"
staticRouteSpec:
type: object
properties:
url:
type: string
staticRouteStatus:
type: object
properties:
status:
type: string
packageID:
type: string
deploymentID:
type: string
2 changes: 1 addition & 1 deletion riocli/static_route/__init__.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# Copyright 2021 Rapyuta Robotics
# Copyright 2023 Rapyuta Robotics
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
Expand Down
18 changes: 10 additions & 8 deletions riocli/static_route/create.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,30 +14,32 @@
import click
from click_help_colors import HelpColorsCommand

from riocli.config import new_client
from riocli.config import new_v2_client
from riocli.constants import Colors, Symbols
from riocli.utils.spinner import with_spinner


@click.command(
'create',
cls=HelpColorsCommand,
help_headers_color=Colors.YELLOW,
help_options_color=Colors.GREEN,
)
@click.argument('prefix', type=str)
@click.argument('name', type=str)
@with_spinner(text="Creating static route...")
def create_static_route(prefix: str, spinner=None) -> None:
def create_static_route(name: str, spinner=None) -> None:
"""
Creates a new static route
"""
try:
client = new_client()
route = client.create_static_route(prefix)
client = new_v2_client(with_project=True)
payload = {
"metadata": {"name": name}
}
route = client.create_static_route(payload)
spinner.text = click.style(
'Static Route created successfully for URL {}'.format(route.urlString), fg=Colors.GREEN)
'Static Route created successfully for URL {}'.format(route.spec.url), fg=Colors.GREEN)
spinner.green.ok(Symbols.SUCCESS)
except Exception as e:
spinner.text = click.style('Failed to create static route: {}'.format(e), fg=Colors.RED)
spinner.red.fail(Symbols.ERROR)
raise SystemExit(1)
raise SystemExit(1) from e
11 changes: 5 additions & 6 deletions riocli/static_route/delete.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,12 +14,11 @@
import click
from click_help_colors import HelpColorsCommand

from riocli.config import new_client
from riocli.constants import Colors, Symbols
from riocli.static_route.util import name_to_guid
from riocli.config import new_v2_client
from riocli.constants import Colors, Symbols
from riocli.utils.spinner import with_spinner


@click.command(
'delete',
cls=HelpColorsCommand,
Expand All @@ -46,12 +45,12 @@ def delete_static_route(
static_route, static_route_guid), abort=True)

try:
client = new_client()
client.delete_static_route(static_route_guid)
client = new_v2_client()
client.delete_static_route(static_route)
spinner.text = click.style(
'Static Route deleted successfully ', fg=Colors.GREEN)
spinner.green.ok(Symbols.SUCCESS)
except Exception as e:
spinner.text = click.style('Failed to delete static route: {}'.format(e), fg=Colors.RED)
spinner.red.fail(Symbols.ERROR)
raise SystemExit(1)
raise SystemExit(1) from e
24 changes: 5 additions & 19 deletions riocli/static_route/inspect.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,8 @@
# limitations under the License.
import click
from click_help_colors import HelpColorsCommand
from rapyuta_io.clients.static_route import StaticRoute

from riocli.config import new_client
from riocli.config import new_v2_client
from riocli.constants import Colors
from riocli.static_route.util import name_to_guid
from riocli.utils import inspect_with_format
Expand All @@ -41,24 +40,11 @@ def inspect_static_route(
Inspect a static route
"""
try:
client = new_client()
route = client.get_static_route(static_route_guid)
data = make_static_route_inspectable(route)
inspect_with_format(data, format_type)
client = new_v2_client()
route = client.get_static_route(static_route)
inspect_with_format(route, format_type)
except Exception as e:
click.secho(str(e), fg=Colors.RED)
raise SystemExit(1)
raise SystemExit(1) from e


def make_static_route_inspectable(static_route_data: StaticRoute) -> dict:
return {
'created_at': static_route_data.CreatedAt,
'updated_at': static_route_data.UpdatedAt,
'deleted_at': static_route_data.DeletedAt,
'guid': static_route_data.guid,
'url_prefix': static_route_data.urlPrefix,
'url': static_route_data.urlString,
'creator': static_route_data.creator,
'project': static_route_data.projectGUID,
'metadata': static_route_data.metadata.__dict__,
}
20 changes: 9 additions & 11 deletions riocli/static_route/list.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,11 +17,10 @@
from click_help_colors import HelpColorsCommand
from rapyuta_io.clients.static_route import StaticRoute

from riocli.config import new_client
from riocli.config import new_v2_client
from riocli.constants import Colors
from riocli.utils import tabulate_data


@click.command(
'list',
cls=HelpColorsCommand,
Expand All @@ -33,25 +32,24 @@ def list_static_routes() -> None:
List the static routes in the selected project
"""
try:
client = new_client()
routes = client.get_all_static_routes()
client = new_v2_client(with_project=True)
routes = client.list_static_routes()
_display_routes_list(routes)
except Exception as e:
click.secho(str(e), fg=Colors.RED)
raise SystemExit(1)

raise SystemExit(1) from e

def _display_routes_list(routes: List[StaticRoute]) -> None:
headers = ['Route ID', 'Name', 'URL', 'Creator', 'CreatedAt']

data = []
for route in routes:
data.append([
route.guid,
route.urlPrefix,
route.urlString,
route.creator,
route.CreatedAt,
route.metadata.guid,
route.metadata.name,
route.spec.url,
route.metadata.creatorGUID,
route.metadata.createdAt,
])

tabulate_data(data, headers)
1 change: 0 additions & 1 deletion riocli/static_route/model.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,6 @@ def find_object(self, client: Client) -> bool:
'kind': 'staticroute',
'nameOrGUID': self.metadata.name
})

if not static_route:
return False

Expand Down
8 changes: 4 additions & 4 deletions riocli/static_route/open.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
import click
from click_help_colors import HelpColorsCommand

from riocli.config import new_client
from riocli.config import new_v2_client
from riocli.constants import Colors
from riocli.static_route.util import name_to_guid

Expand All @@ -32,9 +32,9 @@ def open_static_route(static_route, static_route_guid) -> None:
Opens the static route in the default browser
"""
try:
client = new_client()
route = client.get_static_route(static_route_guid)
click.launch(url='https://{}'.format(route.urlString), wait=False)
client = new_v2_client()
route = client.get_static_route(static_route)
click.launch(url='https://{}'.format(route.spec.url), wait=False)
except Exception as e:
click.secho(str(e), fg=Colors.RED)
raise SystemExit(1)
22 changes: 12 additions & 10 deletions riocli/static_route/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,23 +16,23 @@

from rapyuta_io import Client

from riocli.config import new_client
from riocli.config import new_v2_client


def name_to_guid(f: typing.Callable) -> typing.Callable:
@functools.wraps(f)
def decorated(**kwargs: typing.Any):
client = new_client()
client = new_v2_client()
name = kwargs.pop('static_route')
guid = None

name = name.rsplit(".", 2)[0]
if name.startswith('staticroute-'):
guid = name
name = None

if name is None:
name = get_static_route_name(client, guid)

if guid is None:
guid = find_static_route_guid(client, name)

Expand All @@ -44,18 +44,20 @@ def decorated(**kwargs: typing.Any):


def get_static_route_name(client: Client, guid: str) -> str:
static_route = client.get_static_route(guid)
return static_route.urlPrefix.split("-")[0]


def find_static_route_guid(client: Client, name: str) -> str:
routes = client.get_all_static_routes()
routes = client.list_static_routes()
for route in routes:
if route.urlPrefix == name or route.urlString == name:
return route.guid
if route.metadata.guid == guid:
return route.metadata.name

raise StaticRouteNotFound()

def find_static_route_guid(client: Client, name: str) -> str:
static_route = client.get_static_route(name)
if not static_route:
raise StaticRouteNotFound()
return static_route.metadata.guid


class StaticRouteNotFound(Exception):
def __init__(self):
Expand Down
2 changes: 1 addition & 1 deletion riocli/utils/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -161,7 +161,7 @@ def is_pip_installation() -> bool:
return 'python' in sys.executable


def check_for_updates(current_version: str) -> tuple[bool, str]:
def check_for_updates(current_version: str) -> typing.Tuple[bool, str]:
try:
package_info = requests.get(
'https://pypi.org/pypi/rapyuta-io-cli/json').json()
Expand Down
87 changes: 87 additions & 0 deletions riocli/v2client/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -332,3 +332,90 @@ def delete_instance_binding(self, instance_name: str, binding_name: str) -> Munc
raise Exception("managedservice: {}".format(err_msg))

return munchify(data)

def list_static_routes(
self,
query: dict = None
) -> Munch:
"""
List all static routes in a project
"""
url = "{}/v2/staticroutes/".format(self._host)
headers = self._config.get_auth_header()

params = {}
params.update(query or {})

offset, result = 0, []
while True:
params.update({
"continue": offset,
"limit": 10,
})
response = RestClient(url).method(HttpMethod.GET).query_param(
params).headers(headers).execute()
data = json.loads(response.text)
if not response.ok:
err_msg = data.get('error')
raise Exception("static routes: {}".format(err_msg))
staticRoutes = data.get('items', [])
if not staticRoutes:
break
offset = data['metadata']['continue']
result.extend(staticRoutes)

return munchify(result)

def get_static_route(self, name: str) -> Munch:
"""
Get a static route by its name
"""
url = "{}/v2/staticroutes/{}/".format(self._host, name)
headers = self._config.get_auth_header()
response = RestClient(url).method(
HttpMethod.GET).headers(headers).execute()

handle_server_errors(response)

data = json.loads(response.text)
if not response.ok:
err_msg = data.get('error')
raise Exception("static routes: {}".format(err_msg))

return munchify(data)

def create_static_route(self, metadata: dict) -> Munch:
"""
Create a new static route
"""
url = "{}/v2/staticroutes/".format(self._host)
headers = self._config.get_auth_header()
response = RestClient(url).method(HttpMethod.POST).headers(
headers).execute(payload=metadata)

handle_server_errors(response)

data = json.loads(response.text)
if not response.ok:
err_msg = data.get('error')
raise Exception("static routes: {}".format(err_msg))

return munchify(data)

def delete_static_route(self, name: str) -> Munch:
"""
Delete a static route by its name
"""
url = "{}/v2/staticroutes/{}/".format(self._host, name)
headers = self._config.get_auth_header()
response = RestClient(url).method(
HttpMethod.DELETE).headers(headers).execute()

handle_server_errors(response)

data = json.loads(response.text)
if not response.ok:
err_msg = data.get('error')
raise Exception("static routes: {}".format(err_msg))

return munchify(data)

0 comments on commit 9f6d02b

Please sign in to comment.