|
| 1 | +# Licensed under the Apache License, Version 2.0 (the "License"); you may |
| 2 | +# not use this file except in compliance with the License. You may obtain |
| 3 | +# a copy of the License at |
| 4 | +# |
| 5 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 6 | +# |
| 7 | +# Unless required by applicable law or agreed to in writing, software |
| 8 | +# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT |
| 9 | +# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the |
| 10 | +# License for the specific language governing permissions and limitations |
| 11 | +# under the License. |
| 12 | + |
| 13 | +""" |
| 14 | +Example Action Command |
| 15 | +
|
| 16 | +Invoke an action method on a resource. |
| 17 | +
|
| 18 | +A session will be provided to the action if needed. The action itself |
| 19 | +must be identified by the 'action' key. Arguments to the action may be |
| 20 | +provided through an 'action_args' dictionary. |
| 21 | +
|
| 22 | +For examples: |
| 23 | + python -m examples.action openstack/telemetry/v2/alarm.py \ |
| 24 | + --data '{"alarm_id": "33109eea-24dd-45ff-93f7-82292d1dd38c", |
| 25 | + "action": "change_state", |
| 26 | + "action_args": {"next_state": "insufficient data"}' |
| 27 | +
|
| 28 | + python -m examples.action openstack/compute/v2/server.py \ |
| 29 | + --data '{"id": "a1369557-748f-429c-bd3e-fc385aacaec7", |
| 30 | + "action": "reboot", |
| 31 | + "action_args": {"reboot_type": "SOFT"}}' |
| 32 | +""" |
| 33 | + |
| 34 | +import inspect |
| 35 | +import sys |
| 36 | + |
| 37 | +from examples import common |
| 38 | +from examples import session |
| 39 | + |
| 40 | + |
| 41 | +def filter_args(method, params): |
| 42 | + expected_args = inspect.getargspec(method).args |
| 43 | + accepted_args = ([a for a in expected_args if a != 'self']) |
| 44 | + filtered_args = {desired: params[desired] for desired in accepted_args} |
| 45 | + return filtered_args |
| 46 | + |
| 47 | + |
| 48 | +def invoke_method(target, method_name, params): |
| 49 | + action = getattr(target, method_name) |
| 50 | + filtered_args = filter_args(action, params) |
| 51 | + reply = action(**filtered_args) |
| 52 | + return reply |
| 53 | + |
| 54 | + |
| 55 | +def run_action(options): |
| 56 | + sess = session.make_session(options) |
| 57 | + cls = common.find_resource_cls(options) |
| 58 | + data = common.get_data_option(options) |
| 59 | + |
| 60 | + action = data.pop('action') |
| 61 | + if 'action_args' in data: |
| 62 | + args = data.pop('action_args') |
| 63 | + else: |
| 64 | + args = {} |
| 65 | + args.update(session=sess) |
| 66 | + |
| 67 | + obj = cls.new(**data) |
| 68 | + reply = invoke_method(obj, action, args) |
| 69 | + print(str(reply)) |
| 70 | + return |
| 71 | + |
| 72 | + |
| 73 | +if __name__ == "__main__": |
| 74 | + opts = common.setup() |
| 75 | + sys.exit(common.main(opts, run_action)) |
0 commit comments