Debian Codegraph @

heatclient/osc/v1/event.py

raw symbols SCIP
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 # Copyright 2015 IBM Corp.
14
15 import logging
16 import time
17
18 from cliff.formatters import base
19 from osc_lib.command import command
20 from osc_lib import utils
21
22 from heatclient._i18n import _
23 from heatclient.common import event_utils
24 from heatclient.common import utils as heat_utils
25 from heatclient import exc
26 from heatclient.osc.v1 import common
27
28
29 class ShowEvent(command.ShowOne):
30 """Show event details."""
31
32 log = logging.getLogger(__name__ + '.ShowEvent')
33
34 def get_parser(self, prog_name):
35 parser = super().get_parser(prog_name)
36 parser.add_argument(
37 'stack',
38 metavar='<stack>',
39 help=_('Name or ID of stack to show events for')
40 )
41 parser.add_argument(
42 'resource',
43 metavar='<resource>',
44 help=_('Name of the resource event belongs to')
45 )
46 parser.add_argument(
47 'event',
48 metavar='<event>',
49 help=_('ID of event to display details for')
50 )
51
52 return parser
53
54 def take_action(self, parsed_args):
55 self.log.debug('take_action(%s)', parsed_args)
56
57 client = self.app.client_manager.orchestration
58
59 fields = {
60 'stack_id': parsed_args.stack,
61 'resource_name': parsed_args.resource,
62 'event_id': parsed_args.event
63 }
64
65 try:
66 client.stacks.get(parsed_args.stack)
67 client.resources.get(parsed_args.stack, parsed_args.resource)
68 event = client.events.get(**fields)
69 except exc.HTTPNotFound as ex:
70 raise exc.CommandError(str(ex))
71
72 formatters = {
73 'links': common.LinkColumn,
74 'resource_properties': common.JsonColumn
75 }
76
77 columns = []
78 for key in event.to_dict():
79 columns.append(key)
80
81 return columns, utils.get_item_properties(event, columns,
82 formatters=formatters)
83
84
85 class ListEvent(command.Lister):
86 """List events."""
87
88 log = logging.getLogger(__name__ + '.ListEvent')
89
90 @property
91 def formatter_default(self):
92 return 'log'
93
94 @property
95 def formatter_namespace(self):
96 return 'heatclient.event.formatter.list'
97
98 def get_parser(self, prog_name):
99 parser = super().get_parser(prog_name)
100 parser.add_argument(
101 'stack',
102 metavar='<stack>',
103 help=_('Name or ID of stack to show events for')
104 )
105 parser.add_argument(
106 '--resource',
107 metavar='<resource>',
108 help=_('Name of resource to show events for. Note: this cannot '
109 'be specified with --nested-depth')
110 )
111 parser.add_argument(
112 '--filter',
113 metavar='<key=value>',
114 action='append',
115 help=_('Filter parameters to apply on returned events')
116 )
117 parser.add_argument(
118 '--limit',
119 metavar='<limit>',
120 type=int,
121 help=_('Limit the number of events returned')
122 )
123 parser.add_argument(
124 '--marker',
125 metavar='<id>',
126 help=_('Only return events that appear after the given ID')
127 )
128 parser.add_argument(
129 '--nested-depth',
130 metavar='<depth>',
131 type=int,
132 help=_('Depth of nested stacks from which to display events. '
133 'Note: this cannot be specified with --resource')
134 )
135 parser.add_argument(
136 '--sort',
137 metavar='<key>[:<direction>]',
138 action='append',
139 help=_('Sort output by selected keys and directions (asc or desc) '
140 '(default: asc). Specify multiple times to sort on '
141 'multiple keys. Sort key can be: '
142 '"event_time" (default), "resource_name", "links", '
143 '"logical_resource_id", "resource_status", '
144 '"resource_status_reason", "physical_resource_id", or '
145 '"id". You can leave the key empty and specify ":desc" '
146 'for sorting by reverse time.')
147 )
148 parser.add_argument(
149 '--follow',
150 action='store_true',
151 help=_('Print events until process is halted')
152 )
153 return parser
154
155 def take_action(self, parsed_args):
156 self.log.debug('take_action(%s)', parsed_args)
157
158 client = self.app.client_manager.orchestration
159
160 columns = ['id', 'resource_status', 'resource_status_reason',
161 'event_time', 'physical_resource_id']
162
163 kwargs = {
164 'resource_name': parsed_args.resource,
165 'filters': heat_utils.format_parameters(parsed_args.filter),
166 'sort_dir': 'asc'
167 }
168
169 if parsed_args.resource and parsed_args.nested_depth:
170 msg = _('--nested-depth cannot be specified with --resource')
171 raise exc.CommandError(msg)
172
173 if parsed_args.nested_depth:
174 columns.append('stack_name')
175 nested_depth = parsed_args.nested_depth
176 else:
177 nested_depth = 0
178
179 if parsed_args.sort:
180 sorts = []
181 sort_keys = []
182 for sort in parsed_args.sort:
183 if sort.startswith(":"):
184 sorts.append(":".join(["event_time", sort.lstrip(":")]))
185 else:
186 sorts.append(sort)
187 sort_keys.append(sort.split(":")[0])
188 kwargs['sort_keys'] = sort_keys
189
190 if ":" in parsed_args.sort[0]:
191 kwargs['sort_dir'] = parsed_args.sort[0].split(":")[1]
192
193 if parsed_args.follow:
194 if parsed_args.formatter != 'log':
195 msg = _('--follow can only be specified with --format log')
196 raise exc.CommandError(msg)
197
198 marker = parsed_args.marker
199 try:
200 event_log_context = heat_utils.EventLogContext()
201 while True:
202 events = event_utils.get_events(
203 client,
204 stack_id=parsed_args.stack,
205 event_args=kwargs,
206 nested_depth=nested_depth,
207 marker=marker)
208 if events:
209 marker = getattr(events[-1], 'id', None)
210 events_log = heat_utils.event_log_formatter(
211 events, event_log_context)
212 self.app.stdout.write(events_log)
213 self.app.stdout.write('\n')
214 time.sleep(5)
215 # this loop never exits
216 except (KeyboardInterrupt, EOFError): # ctrl-c, ctrl-d
217 return [], []
218
219 events = event_utils.get_events(
220 client, stack_id=parsed_args.stack, event_args=kwargs,
221 nested_depth=nested_depth, marker=parsed_args.marker,
222 limit=parsed_args.limit)
223
224 if parsed_args.sort:
225 events = utils.sort_items(events, ','.join(sorts))
226
227 if parsed_args.formatter == 'log':
228 return [], events
229
230 if len(events):
231 if hasattr(events[0], 'resource_name'):
232 columns.insert(0, 'resource_name')
233 columns.append('logical_resource_id')
234 else:
235 columns.insert(0, 'logical_resource_id')
236
237 return (
238 columns,
239 (utils.get_item_properties(s, columns) for s in events)
240 )
241
242
243 class LogFormatter(base.ListFormatter):
244 """A formatter which prints event objects in a log style"""
245
246 def add_argument_group(self, parser):
247 pass
248
249 def emit_list(self, column_names, data, stdout, parsed_args):
250 stdout.write(heat_utils.event_log_formatter(data))
251 stdout.write('\n')