|
| 1 | +# @copyright@ |
| 2 | +# Copyright (c) 2006 - 2020 Teradata |
| 3 | +# All rights reserved. Stacki(r) v5.x stacki.com |
| 4 | +# https://github.com/Teradata/stacki/blob/master/LICENSE.txt |
| 5 | +# @copyright@ |
| 6 | + |
| 7 | +import json |
| 8 | +import subprocess |
| 9 | + |
| 10 | + |
| 11 | +class StackCommandError(Exception): |
| 12 | + """Exception raised for errors running a stack command.""" |
| 13 | + |
| 14 | + def __init__(self, message): |
| 15 | + self.message = message |
| 16 | + |
| 17 | + |
| 18 | +def run_stack_command(command, args=None): |
| 19 | + """Runs a stack command, returning StackCommandError if there is an error.""" |
| 20 | + |
| 21 | + # Create our command to run |
| 22 | + command_args = ["/opt/stack/bin/stack"] |
| 23 | + command_args.extend(command.replace(".", " ").split()) |
| 24 | + if args: |
| 25 | + command_args.extend(args) |
| 26 | + command_args.append("output-format=json") |
| 27 | + |
| 28 | + try: |
| 29 | + # Run the command, throwing a CalledProcessError if something goes wrong |
| 30 | + result = subprocess.run( |
| 31 | + command_args, capture_output=True, text=True, check=True |
| 32 | + ) |
| 33 | + except subprocess.CalledProcessError as e: |
| 34 | + # Get the first line of the stderr |
| 35 | + if e.stderr: |
| 36 | + message = e.stderr.splitlines()[0] |
| 37 | + else: |
| 38 | + message = "error - unknown" |
| 39 | + |
| 40 | + # Raise an exception for the caller |
| 41 | + raise StackCommandError(message) |
| 42 | + |
| 43 | + # Return the result as a dict |
| 44 | + try: |
| 45 | + data = json.loads(result.stdout) |
| 46 | + except json.JSONDecodeError: |
| 47 | + # Something invalid was returned, likely an empty string |
| 48 | + data = [] |
| 49 | + |
| 50 | + return data |
0 commit comments