Skip to content

Commit

Permalink
chore: moved login to hwildevice command
Browse files Browse the repository at this point in the history
  • Loading branch information
rrkumarshikhar committed Jun 10, 2024
1 parent 055597f commit adc91e9
Show file tree
Hide file tree
Showing 8 changed files with 117 additions and 87 deletions.
19 changes: 0 additions & 19 deletions riocli/auth/login.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@
select_organization,
select_project,
validate_and_set_token,
validate_and_set_hwil_token
)
from riocli.constants import Colors, Symbols
from riocli.utils.context import get_root_context
Expand Down Expand Up @@ -47,10 +46,6 @@
help='Make login interactive')
@click.option('--auth-token', type=str, default=None,
help="Login with auth token only")
@click.option('--hwil-user', type=str,
help="Username of rapyuta.io virtual devices account")
@click.option('--hwil-password', type=str,
help="Password of the rapyuta.io virtual devices account")
@click.pass_context
def login(
ctx: click.Context,
Expand All @@ -60,8 +55,6 @@ def login(
project: str,
interactive: bool,
auth_token: str,
hwil_user: str,
hwil_password: str,
) -> None:
"""
Log into your rapyuta.io account using the CLI. This is required to
Expand All @@ -79,8 +72,6 @@ def login(
if interactive:
email = email or click.prompt('Email')
password = password or click.prompt('Password', hide_input=True)
hwil_user = hwil_user or click.prompt('HwilUser')
hwil_password = hwil_password or click.prompt('HwilPassword')

if not email:
click.secho('email not specified')
Expand All @@ -90,16 +81,6 @@ def login(
click.secho('password not specified')
raise SystemExit(1)

if hwil_user and not hwil_password:
click.secho('hwil password not specified')

if hwil_password and not hwil_user:
click.secho('hwil user not specified')

if hwil_user and hwil_password:
if not validate_and_set_hwil_token(ctx, hwil_user, hwil_password):
raise SystemExit(1)

ctx.obj.data['email_id'] = email
ctx.obj.data['password'] = password
ctx.obj.data['auth_token'] = get_token(email, password)
Expand Down
30 changes: 0 additions & 30 deletions riocli/auth/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,13 +18,11 @@
from rapyuta_io.clients.rip_client import AuthTokenLevel
from rapyuta_io.utils import UnauthorizedError

from riocli.hwilclient import Client as HwilClient
from riocli.config import Configuration
from riocli.constants import Colors, Symbols
from riocli.project.util import find_project_guid, find_organization_guid
from riocli.utils.selector import show_selection
from riocli.utils.spinner import with_spinner
from base64 import b64encode

TOKEN_LEVELS = {
0: AuthTokenLevel.LOW,
Expand Down Expand Up @@ -115,34 +113,6 @@ def select_project(

click.secho(confirmation, fg=Colors.GREEN)

@with_spinner(text='Validating hwil credentials...')
def validate_and_set_hwil_token(
ctx: click.Context,
username: str,
password: str,
spinner=None
) -> bool:
"""Validates an auth token."""
if 'environment' in ctx.obj.data:
os.environ['RIO_CONFIG'] = ctx.obj.filepath

token = b64encode(f"{username}:{password}".encode('utf-8')).decode("ascii")
client = HwilClient(auth_token=token)

try:
client.list_devices()
ctx.obj.data['hwil_auth_token'] = token
spinner.ok(Symbols.INFO)
return True
except UnauthorizedError:
spinner.text = click.style("incorrect credentials for hwil", fg=Colors.RED)
spinner.red.fail(Symbols.ERROR)
return False
except Exception as e:
spinner.text = click.style(str(e), fg=Colors.RED)
spinner.red.fail(Symbols.ERROR)
return False


@with_spinner(text='Fetching token...')
def get_token(
Expand Down
4 changes: 3 additions & 1 deletion riocli/hwil/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
from riocli.hwil.list import list_devices
from riocli.hwil.delete import delete_device
from riocli.hwil.inspect import inspect_device
from riocli.hwil.login import login


@click.group(
Expand All @@ -33,7 +34,8 @@ def hwildevice():
pass


hwildevice.add_command(login)
hwildevice.add_command(create_device)
hwildevice.add_command(list_devices)
hwildevice.add_command(delete_device)
hwildevice.add_command(inspect_device)
hwildevice.add_command(inspect_device)
21 changes: 4 additions & 17 deletions riocli/hwil/create.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,14 +12,12 @@
# See the License for the specific language governing permissions and
# limitations under the License.
import time
import typing
import click
from click_spinner import spinner
from click_help_colors import HelpColorsCommand
from riocli.constants import Colors
from rapyuta_io.utils import ConflictError
from rapyuta_io.clients.device import DevicePythonVersion, Device, DeviceStatus
from riocli.utils import tabulate_data
from riocli.device.util import find_device_guid
from riocli.hwil.util import name_to_id

Expand All @@ -28,7 +26,6 @@
from rapyuta_io import Client as v1Client



@click.command('create',
cls=HelpColorsCommand,
help_headers_color=Colors.YELLOW,
Expand All @@ -51,14 +48,14 @@ def create_device(
"""
Create a new virtual device on the cloud
"""
client = new_client()
hwil_client = new_hwil_client()
try:
client = new_client()
hwil_client = new_hwil_client()
with spinner():
try:
hwil_client.create_device(device_name, arch, os, codename)
click.secho('HWIL Device created successfully!', fg='green')
except ConflictError as c:
except ConflictError:
click.secho('HWIL Device {} already exists in cluster!'.format(device_name), fg='green')

if onboard:
Expand All @@ -72,7 +69,7 @@ def create_device(
_onboard_hwil_device(hwil_client=hwil_client, client=client, device_name=device_name,
onboard_command=onboard_command,
device_uuid=device.uuid)
except ConflictError as c:
except ConflictError:
click.secho('Device {} already exists in rapyuta.io!'.format(device_name), fg='green')
device = client.get_device(device_id=find_device_guid(client, device_name))
if device.is_online() or device.status == DeviceStatus.INITIALIZING:
Expand Down Expand Up @@ -105,13 +102,3 @@ def _onboard_hwil_device(hwil_client: Client, client: v1Client, device_name: str
except Exception as e:
click.secho(str(e), fg='red')
raise SystemExit(1)


def _display_device_list(devices: typing.List[dict], show_header: bool = True) -> None:
headers = []
if show_header:
headers = ('Device ID', 'Name', 'Status')

data = [[d.uuid, d.name, d.status] for d in devices]

tabulate_data(data, headers)
36 changes: 19 additions & 17 deletions riocli/hwil/delete.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,31 +23,33 @@
'delete',
cls=HelpColorsCommand,
)
@click.argument('device-name', type=str, default="")
@click.option('--deboard', 'deboard', is_flag=True, type=bool, default=False)
# @click.argument('device-name', type=str, default="")
@click.argument('device-names', type=str, nargs=-1)
@click.option('--offboard', 'offboard', is_flag=True, type=bool, default=False)
def delete_device(
device_name: str,
deboard: bool,
device_names: tuple,
offboard: bool,
) -> None:
"""
delete a virtual device on the cloud
"""
client = new_client()
hwil_client = new_hwil_client()
try:
client = new_client()
hwil_client = new_hwil_client()
with spinner():
try:
hwil_client.delete_device(find_device_id(hwil_client, device_name))
click.secho('HWIL Device deleted successfully!', fg='green')
except DeviceNotFound as d:
click.secho('HWIL Device already deleted!', fg='green')

if deboard:
for device_name in device_names:
try:
client.delete_device(device_id=find_device_guid(client, device_name))
click.secho('Rapyuta.io Device deleted successfully in rapyuta.io!', fg='green')
except DeviceNotFound as d:
click.secho('Rapyuta.io Device already deleted!', fg='green')
hwil_client.delete_device(find_device_id(hwil_client, device_name))
click.secho('HWIL Device {device_name} deleted successfully!', fg='green')
except DeviceNotFound:
click.secho('HWIL Device {device_name} already deleted!', fg='green')

if offboard:
try:
client.delete_device(device_id=find_device_guid(client, device_name))
click.secho('Rapyuta.io Device {device_name} deleted successfully in rapyuta.io!', fg='green')
except DeviceNotFound:
click.secho('Rapyuta.io Device {device_name} already deleted!', fg='green')
except Exception as e:
click.secho(str(e), fg='red')
raise SystemExit(1)
3 changes: 2 additions & 1 deletion riocli/hwil/list.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
from riocli.constants import Colors
from riocli.utils import tabulate_data


@click.command(
'list',
cls=HelpColorsCommand,
Expand Down Expand Up @@ -46,4 +47,4 @@ def _display_device_list(devices: typing.List[dict], show_header: bool = True) -

data = [[d.id, d.name, d.status, d.static_ip, d.ip_address] for d in devices]

tabulate_data(data, headers)
tabulate_data(data, headers)
89 changes: 89 additions & 0 deletions riocli/hwil/login.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
# Copyright 2024 Rapyuta Robotics
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import os
import click
from riocli.hwilclient import Client as HwilClient
from click_help_colors import HelpColorsCommand
from riocli.constants import Colors, Symbols
from riocli.utils.context import get_root_context
from base64 import b64encode
from rapyuta_io.utils import UnauthorizedError
from riocli.utils.spinner import with_spinner

HWIL_LOGIN_SUCCESS = click.style('{} Successfully logged into HWIL!'.format(Symbols.SUCCESS), fg=Colors.GREEN)


@click.command(
'login',
cls=HelpColorsCommand,
help_headers_color=Colors.YELLOW,
help_options_color=Colors.GREEN,
)
@click.option('--hwil-user', required=True, help='Username for HWIL login')
@click.option('--hwil-password', required=True, help='Password for HWIL login')
@click.pass_context
def login(
ctx: click.Context,
hwil_user: str,
hwil_password: str,
) -> None:
"""Log in to HWIL."""

ctx = get_root_context(ctx)
try:
if hwil_user and not hwil_password:
click.secho('hwil password not specified')

if hwil_password and not hwil_user:
click.secho('hwil user not specified')

if hwil_user and hwil_password:
if not validate_and_set_hwil_token(ctx, hwil_user, hwil_password):
raise SystemExit(1)
except Exception as e:
click.echo(f"Login failed: {e}")

ctx.obj.save()

click.echo(HWIL_LOGIN_SUCCESS)


@with_spinner(text='Validating hwil credentials...')
def validate_and_set_hwil_token(
ctx: click.Context,
username: str,
password: str,
spinner=None
) -> bool:
"""Validates an auth token."""
if 'environment' in ctx.obj.data:
os.environ['RIO_CONFIG'] = ctx.obj.filepath

token = b64encode(f"{username}:{password}".encode('utf-8')).decode("ascii")
client = HwilClient(auth_token=token)

try:
client.list_devices()
ctx.obj.data['hwil_auth_token'] = token
spinner.ok(Symbols.INFO)
return True
except UnauthorizedError:
spinner.text = click.style("incorrect credentials for hwil", fg=Colors.RED)
spinner.red.fail(Symbols.ERROR)
return False
except Exception as e:
spinner.text = click.style(str(e), fg=Colors.RED)
spinner.red.fail(Symbols.ERROR)
return False
2 changes: 0 additions & 2 deletions riocli/hwil/util.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import functools
import re
import typing
import click
from riocli.constants import Colors
Expand Down Expand Up @@ -55,4 +54,3 @@ def find_device_id(client: Client, name: str) -> str:
return device.id

raise DeviceNotFound(message="Hwil Device not found")

0 comments on commit adc91e9

Please sign in to comment.