Skip to content

Commit e5f28e2

Browse files
authored
cleanup runcommand cli (Azure#3748)
* cleanup runcommand cli * fix nolonger existing import
1 parent 4587331 commit e5f28e2

File tree

7 files changed

+0
-997
lines changed

7 files changed

+0
-997
lines changed

src/aks-preview/azext_aks_preview/_format.py

Lines changed: 0 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -10,21 +10,6 @@
1010
from jmespath import functions
1111

1212

13-
def aks_run_command_result_format(cmdResult):
14-
result = OrderedDict()
15-
if cmdResult['provisioningState'] == "Succeeded":
16-
result['exit code'] = cmdResult['exitCode']
17-
result['logs'] = cmdResult['logs']
18-
return result
19-
if cmdResult['provisioningState'] == "Failed":
20-
result['provisioning state'] = cmdResult['provisioningState']
21-
result['reason'] = cmdResult['reason']
22-
return result
23-
result['provisioning state'] = cmdResult['provisioningState']
24-
result['started At'] = cmdResult['startedAt']
25-
return result
26-
27-
2813
def aks_agentpool_show_table_format(result):
2914
"""Format an agent pool as summary results for display with "-o table"."""
3015
return [_aks_agentpool_table_format(result)]

src/aks-preview/azext_aks_preview/_help.py

Lines changed: 0 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -667,32 +667,6 @@
667667
short-summary: Display diagnostic results for the Kubernetes cluster after kollect is done.
668668
"""
669669

670-
helps['aks command'] = """
671-
type: group
672-
short-summary: see detail usage in 'az aks command invoke', 'az aks command result'.
673-
"""
674-
675-
helps['aks command invoke'] = """
676-
type: command
677-
short-summary: run a shell command (with kubectl, helm) on your aks cluster, support attaching files as well.
678-
parameters:
679-
- name: --command -c
680-
type: string
681-
short-summary: command or shell script you want run.
682-
- name: --file -f
683-
type: string
684-
short-summary: files will be used by the command, use '.' to attach the current folder.
685-
"""
686-
687-
helps['aks command result'] = """
688-
type: command
689-
short-summary: fetch result from previously triggered 'aks command invoke'.
690-
parameters:
691-
- name: --command-id -i
692-
type: string
693-
short-summary: commandId returned from 'aks command invoke'.
694-
"""
695-
696670
helps['aks maintenanceconfiguration'] = """
697671
type: group
698672
short-summary: Commands to manage maintenance configurations in managed Kubernetes cluster.

src/aks-preview/azext_aks_preview/_params.py

Lines changed: 0 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -196,13 +196,6 @@ def load_arguments(self, _):
196196
with self.argument_context('aks nodepool') as c:
197197
c.argument('cluster_name', type=str, help='The cluster name.')
198198

199-
with self.argument_context('aks command invoke') as c:
200-
c.argument('command_string', type=str, options_list=["--command", "-c"], help='the command to run')
201-
c.argument('command_files', options_list=["--file", "-f"], required=False, action="append", help='attach any files the command may use, or use \'.\' to upload the current folder.')
202-
203-
with self.argument_context('aks command result') as c:
204-
c.argument('command_id', type=str, options_list=["--command-id", "-i"], help='the command ID from "aks command invoke"')
205-
206199
for scope in ['aks nodepool add']:
207200
with self.argument_context(scope) as c:
208201
c.argument('nodepool_name', type=str, options_list=['--name', '-n'], validator=validate_nodepool_name, help='The node pool name.')

src/aks-preview/azext_aks_preview/commands.py

Lines changed: 0 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,6 @@
1616
from ._format import aks_upgrades_table_format
1717
from ._format import aks_pod_identities_table_format
1818
from ._format import aks_pod_identity_exceptions_table_format
19-
from ._format import aks_run_command_result_format
2019

2120

2221
def load_command_table(self, _):
@@ -78,12 +77,6 @@ def load_command_table(self, _):
7877
g.custom_command('get-versions', 'aks_get_versions',
7978
table_transformer=aks_versions_table_format)
8079

81-
with self.command_group('aks command', managed_clusters_sdk, client_factory=cf_managed_clusters) as g:
82-
g.custom_command('invoke', 'aks_runcommand', supports_no_wait=True,
83-
table_transformer=aks_run_command_result_format)
84-
g.custom_command('result', 'aks_command_result',
85-
supports_no_wait=False, table_transformer=aks_run_command_result_format)
86-
8780
# AKS maintenance configuration commands
8881
with self.command_group('aks maintenanceconfiguration', maintenance_configuration_sdk, client_factory=cf_maintenance_configurations) as g:
8982
g.custom_command('list', 'aks_maintenanceconfiguration_list')

src/aks-preview/azext_aks_preview/custom.py

Lines changed: 0 additions & 110 deletions
Original file line numberDiff line numberDiff line change
@@ -83,7 +83,6 @@
8383
ManagedClusterPodIdentity,
8484
ManagedClusterPodIdentityException,
8585
UserAssignedIdentity,
86-
RunCommandRequest,
8786
ComponentsQit0EtSchemasManagedclusterpropertiesPropertiesIdentityprofileAdditionalproperties)
8887
from ._client_factory import cf_resource_groups
8988
from ._client_factory import get_auth_management_client
@@ -2294,115 +2293,6 @@ def aks_upgrade(cmd, # pylint: disable=unused-argument, too-many-return-state
22942293
return sdk_no_wait(no_wait, client.begin_create_or_update, resource_group_name, name, instance, headers=headers)
22952294

22962295

2297-
def aks_runcommand(cmd, client, resource_group_name, name, command_string="", command_files=None):
2298-
colorama.init()
2299-
2300-
mc = client.get(resource_group_name, name)
2301-
2302-
if not command_string:
2303-
raise CLIError('Command cannot be empty.')
2304-
2305-
request_payload = RunCommandRequest(command=command_string)
2306-
request_payload.context = _get_command_context(command_files)
2307-
if mc.aad_profile is not None and mc.aad_profile.managed:
2308-
request_payload.cluster_token = _get_dataplane_aad_token(
2309-
cmd.cli_ctx, "6dae42f8-4368-4678-94ff-3960e28e3630")
2310-
2311-
commandResultFuture = client.begin_run_command(
2312-
resource_group_name, name, request_payload, polling_interval=5, retry_total=0)
2313-
2314-
return _print_command_result(cmd.cli_ctx, commandResultFuture.result(300))
2315-
2316-
2317-
def aks_command_result(cmd, client, resource_group_name, name, command_id=""):
2318-
if not command_id:
2319-
raise CLIError('CommandID cannot be empty.')
2320-
2321-
commandResult = client.get_command_result(
2322-
resource_group_name, name, command_id)
2323-
return _print_command_result(cmd.cli_ctx, commandResult)
2324-
2325-
2326-
def _print_command_result(cli_ctx, commandResult):
2327-
# cli_ctx.data['safe_params'] contains list of parameter name user typed in, without value.
2328-
# cli core also use this calculate ParameterSetName header for all http request from cli.
2329-
if cli_ctx.data['safe_params'] is None or "-o" in cli_ctx.data['safe_params'] or "--output" in cli_ctx.data['safe_params']:
2330-
# user specified output format, honor their choice, return object to render pipeline
2331-
return commandResult
2332-
else:
2333-
# user didn't specified any format, we can customize the print for best experience
2334-
if commandResult.provisioning_state == "Succeeded":
2335-
# succeed, print exitcode, and logs
2336-
print(f"{colorama.Fore.GREEN}command started at {commandResult.started_at}, finished at {commandResult.finished_at}, with exitcode={commandResult.exit_code}{colorama.Style.RESET_ALL}")
2337-
print(commandResult.logs)
2338-
return
2339-
2340-
if commandResult.provisioning_state == "Failed":
2341-
# failed, print reason in error
2342-
print(
2343-
f"{colorama.Fore.RED}command failed with reason: {commandResult.reason}{colorama.Style.RESET_ALL}")
2344-
return
2345-
2346-
# *-ing state
2347-
print(f"{colorama.Fore.BLUE}command is in : {commandResult.provisioning_state} state{colorama.Style.RESET_ALL}")
2348-
return None
2349-
2350-
2351-
def _get_command_context(command_files):
2352-
if not command_files:
2353-
return ""
2354-
2355-
filesToAttach = {}
2356-
# . means to attach current folder, cannot combine more files. (at least for now)
2357-
if len(command_files) == 1 and command_files[0] == ".":
2358-
# current folder
2359-
cwd = os.getcwd()
2360-
for filefolder, _, files in os.walk(cwd):
2361-
for file in files:
2362-
# retain folder structure
2363-
rel = os.path.relpath(filefolder, cwd)
2364-
filesToAttach[os.path.join(
2365-
filefolder, file)] = os.path.join(rel, file)
2366-
else:
2367-
for file in command_files:
2368-
if file == ".":
2369-
raise CLIError(
2370-
". is used to attach current folder, not expecting other attachements.")
2371-
if os.path.isfile(file):
2372-
# for individual attached file, flatten them to same folder
2373-
filesToAttach[file] = os.path.basename(file)
2374-
else:
2375-
raise CLIError(f"{file} is not valid file, or not accessable.")
2376-
2377-
if len(filesToAttach) < 1:
2378-
logger.debug("no files to attach!")
2379-
return ""
2380-
2381-
zipStream = io.BytesIO()
2382-
zipFile = zipfile.ZipFile(zipStream, "w")
2383-
for _, (osfile, zipEntry) in enumerate(filesToAttach.items()):
2384-
zipFile.write(osfile, zipEntry)
2385-
# zipFile.printdir() // use this to debug
2386-
zipFile.close()
2387-
2388-
return str(base64.encodebytes(zipStream.getbuffer()), "utf-8")
2389-
2390-
2391-
def _get_dataplane_aad_token(cli_ctx, serverAppId):
2392-
# this function is mostly copied from keyvault cli
2393-
import adal
2394-
try:
2395-
return Profile(cli_ctx=cli_ctx).get_raw_token(resource=serverAppId)[0][2].get('accessToken')
2396-
except adal.AdalError as err:
2397-
# pylint: disable=no-member
2398-
if (hasattr(err, 'error_response') and
2399-
('error_description' in err.error_response) and
2400-
('AADSTS70008:' in err.error_response['error_description'])):
2401-
raise CLIError(
2402-
"Credentials have expired due to inactivity. Please run 'az login'")
2403-
raise CLIError(err)
2404-
2405-
24062296
def _upgrade_single_nodepool_image_version(no_wait, client, resource_group_name, cluster_name, nodepool_name):
24072297
return sdk_no_wait(no_wait, client.begin_upgrade_node_image_version, resource_group_name, cluster_name, nodepool_name)
24082298

0 commit comments

Comments
 (0)