File: event_utils.py

package info (click to toggle)
python-openstacksdk 4.4.0-5
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 13,352 kB
  • sloc: python: 122,960; sh: 153; makefile: 23
file content (117 lines) | stat: -rw-r--r-- 3,871 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
# Copyright 2015 Red Hat Inc.
#
# 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, 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.

import collections
import time

from openstack.cloud import meta
from openstack import exceptions


# TODO(stephenfin): Convert to use real resources
def get_events(cloud, stack_id, event_args, marker=None, limit=None):
    # TODO(mordred) FIX THIS ONCE assert_calls CAN HANDLE QUERY STRINGS
    params = collections.OrderedDict()
    for k in sorted(event_args.keys()):
        params[k] = event_args[k]

    if marker:
        event_args['marker'] = marker
    if limit:
        event_args['limit'] = limit

    response = cloud.orchestration.get(
        f'/stacks/{stack_id}/events',
        params=params,
    )
    exceptions.raise_from_response(response)

    # Show which stack the event comes from (for nested events)
    events = meta.get_and_munchify('events', response.json())
    for e in events:
        e['stack_name'] = stack_id.split("/")[0]
    return events


def poll_for_events(
    cloud, stack_name, action=None, poll_period=5, marker=None
):
    """Continuously poll events and logs for performed action on stack."""

    def stop_check_action(a):
        stop_status = (f'{action}_FAILED', f'{action}_COMPLETE')
        return a in stop_status

    def stop_check_no_action(a):
        return a.endswith('_COMPLETE') or a.endswith('_FAILED')

    if action:
        stop_check = stop_check_action
    else:
        stop_check = stop_check_no_action

    no_event_polls = 0
    msg_template = "\n Stack %(name)s %(status)s \n"

    def is_stack_event(event):
        if (
            event.get('resource_name', '') != stack_name
            and event.get('physical_resource_id', '') != stack_name
        ):
            return False

        phys_id = event.get('physical_resource_id', '')
        links = {
            link.get('rel'): link.get('href')
            for link in event.get('links', [])
        }
        stack_id = links.get('stack', phys_id).rsplit('/', 1)[-1]
        return stack_id == phys_id

    while True:
        events = get_events(
            cloud,
            stack_id=stack_name,
            event_args={'sort_dir': 'asc', 'marker': marker},
        )

        if len(events) == 0:
            no_event_polls += 1
        else:
            no_event_polls = 0
            # set marker to last event that was received.
            marker = getattr(events[-1], 'id', None)

            for event in events:
                # check if stack event was also received
                if is_stack_event(event):
                    stack_status = getattr(event, 'resource_status', '')
                    msg = msg_template % dict(
                        name=stack_name, status=stack_status
                    )
                    if stop_check(stack_status):
                        return stack_status, msg

        if no_event_polls >= 2:
            # after 2 polls with no events, fall back to a stack get
            stack = cloud.get_stack(stack_name, resolve_outputs=False)
            if stack:
                stack_status = stack['stack_status']
                msg = msg_template % dict(name=stack_name, status=stack_status)
                if stop_check(stack_status):
                    return stack_status, msg
                # go back to event polling again
                no_event_polls = 0

        time.sleep(poll_period)