Skip to content

Commit

Permalink
feat(device): updates device delete command to delete multiple devices
Browse files Browse the repository at this point in the history
This commit updates device delete command that enables users
to conveniently delete existing devices by providing device
name or regex that can delete multiple devices

Usage: python -m rio device delete [OPTIONS] [DEVICE_NAME_OR_REGEX]

  Deletes one more devices

Options:
  -f, --force, --silent  Skip confirmation
  -a, --delete-all       Deletes all devices
  -w, --workers INTEGER  number of parallel workers while running delete device command. defaults to 10.
  --help                 Show this message and exit.
  • Loading branch information
RomilShah committed Aug 8, 2023
1 parent de7289c commit 096b885
Showing 1 changed file with 115 additions and 29 deletions.
144 changes: 115 additions & 29 deletions riocli/device/delete.py
Original file line number Diff line number Diff line change
@@ -1,23 +1,31 @@
# Copyright 2023 Rapyuta Robotics
#
# Licensed under the Apache License, Version 2.0 (the "License");
# 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,
# 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.
from concurrent.futures import ThreadPoolExecutor
import functools
import re
from queue import Queue
from typing import List

import click
from click_help_colors import HelpColorsCommand
from requests import Response
from rapyuta_io.clients.device import Device
from yaspin.api import Yaspin

from rapyuta_io import Client
from riocli.config import new_client
from riocli.constants import Colors, Symbols
from riocli.device.util import name_to_guid
from riocli.constants import Symbols, Colors
from riocli.utils import tabulate_data
from riocli.utils.spinner import with_spinner


Expand All @@ -27,41 +35,119 @@
help_headers_color=Colors.YELLOW,
help_options_color=Colors.GREEN,
)
@click.option('--force', '-f', 'force', is_flag=True, help='Skip confirmation')
@click.argument('device-name', type=str)
@name_to_guid
@click.option('--force', '-f', '--silent', is_flag=True, default=False,
help='Skip confirmation')
@click.option('--delete-all', '-a', is_flag=True, default=False,
help='deletes all devices')
@click.option('--workers', '-w',
help='number of parallel workers while running delete devices '
'command. defaults to 10.', type=int, default=10)
@click.argument('device-name-or-regex', type=str, default='')
@with_spinner(text='Deleting device...')
def delete_device(device_name: str, device_guid: str, force: bool, spinner=None):
def delete_device(
force: bool,
delete_all: bool,
workers: int,
device_name_or_regex: str,
spinner: Yaspin = None,
) -> None:
"""
Deletes a device
Deletes one more devices
"""
with spinner.hidden():
if not force:
click.confirm(
'Deleting device {} ({})'.format(
device_name, device_guid), abort=True)
client = new_client()
if not (device_name_or_regex or delete_all):
spinner.text = 'Nothing to delete'
spinner.green.ok(Symbols.SUCCESS)
return

try:
client = new_client(with_project=True)
handle_device_delete_error(client.delete_device(device_id=device_guid))
spinner.text = click.style('Device deleted successfully', fg=Colors.GREEN)
spinner.green.ok(Symbols.SUCCESS)
devices = fetch_devices(
client, device_name_or_regex, delete_all)
except Exception as e:
spinner.text = click.style('Failed to delete device: {}'.format(e), fg=Colors.RED)
spinner.text = click.style(
'Failed to delete device(s): {}'.format(e), Colors.RED)
spinner.red.fail(Symbols.ERROR)
raise SystemExit(1) from e


def handle_device_delete_error(response: Response):
if response.status_code < 400:
if not devices:
spinner.text = 'No devices to delete'
spinner.ok(Symbols.SUCCESS)
return

data = response.json()
headers = ['Name', 'Device ID', 'Status']
data = [[d.name, d.uuid, d.status] for d in devices]

with spinner.hidden():
tabulate_data(data, headers)

spinner.write('')

if not force:
with spinner.hidden():
click.confirm('Do you want to delete above device(s)?',
default=True, abort=True)
spinner.write('')

try:
result = Queue()
func = functools.partial(_delete_deivce, client, result)
with ThreadPoolExecutor(max_workers=workers) as executor:
executor.map(func, devices)

error = data.get('response', {}).get('error')
result = sorted(list(result.queue), key=lambda x: x[0])

if 'deployments' in error:
msg = 'Device has running deployments. Please de-provision them before deleting the device.'
raise Exception(msg)
data, fg, statuses = [], Colors.GREEN, []
for name, status in result:
fg = Colors.GREEN if status else Colors.RED
icon = Symbols.SUCCESS if status else Symbols.ERROR
statuses.append(status)
data.append([
click.style(name, fg),
click.style(icon, fg)
])

raise Exception(error)
with spinner.hidden():
tabulate_data(data, headers=['Name', 'Status'])

icon = Symbols.SUCCESS if all(statuses) else Symbols.WARNING
fg = Colors.GREEN if all(statuses) else Colors.YELLOW
text = 'successfully' if all(statuses) else 'partially'

spinner.write('')
spinner.text = click.style(
'Devices(s) deleted {}.'.format(text), fg)
spinner.ok(click.style(icon, fg))
except Exception as e:
spinner.text = click.style(
'Failed to delete device(s): {}'.format(e), Colors.RED)
spinner.red.fail(Symbols.ERROR)
raise SystemExit(1) from e


def fetch_devices(
client: Client,
device_name_or_regex: str,
delete_all: bool,
) -> List[Device]:
devices = client.get_all_devices()
result = []
for device in devices:
if (delete_all or device.name == device_name_or_regex or
(device_name_or_regex not in device.name and
re.search(device_name_or_regex, device.name)) or
device_name_or_regex == device.uuid):
result.append(device)

return result


def _delete_deivce(
client: Client,
result: Queue,
device: Device,
) -> None:
try:
client.delete_device(device.uuid)
result.put((device['name'], True))
except Exception:
result.put((device['name'], False))

0 comments on commit 096b885

Please sign in to comment.