summaryrefslogtreecommitdiff
path: root/nemesis/nemesis.py
blob: c20d68dacc8e4edc9fd7dc21663a5c6ae3248e7b (plain)
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
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
#!/usr/bin/env python3
'''
       _/      _/                                                _/
      _/_/    _/    _/_/    _/_/_/  _/_/      _/_/      _/_/_/        _/_/_/
     _/  _/  _/  _/_/_/_/  _/    _/    _/  _/_/_/_/  _/_/      _/  _/_/
    _/    _/_/  _/        _/    _/    _/  _/            _/_/  _/      _/_/
   _/      _/    _/_/_/  _/    _/    _/    _/_/_/  _/_/_/    _/  _/_/_/


Copyright 2025 bdunahu

   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.

Commentary:
Code:
'''

from collections import defaultdict
from experiment import Experiment
import argparse
import asyncio
import os
import signal
import sys
import time
import traceback
import types


class Nemesis(object):

    # the (ideal) interval between samples
    signal_interval = 0.0
    # the timestamp which the last sample was taken
    last_sample = None
    # the current experiment being run
    curr_experiment = None
    # results from previous experiments, represented as strings
    results = []
    # The duration of each performance experiment
    e_duration = None
    # The number of seconds remaining in this performance experiment.
    r_duration = None
    # A mapping of event loops to the previous running coroutine.
    prev_coro = defaultdict(lambda: None)

    # temp
    coro = None
    dilation = 1.0

    @staticmethod
    def __init__(coro, speedup, e_duration, w_time, signal_interval=0.01):
        Nemesis.signal_interval = signal_interval
        Nemesis.e_duration = e_duration
        Nemesis.r_duration = 0
        # temporary
        Nemesis.coro = coro
        Nemesis.speedup = max(speedup, 1.0)

    @staticmethod
    def start():
        Nemesis.last_sample = time.perf_counter()
        signal.signal(signal.SIGALRM,
                      Nemesis._signal_handler)
        signal.setitimer(signal.ITIMER_REAL,
                         Nemesis.signal_interval,
                         Nemesis.signal_interval)

    @staticmethod
    def stop():
        signal.setitimer(signal.ITIMER_REAL, 0)
        Nemesis._stop_experiment()
        for r in Nemesis.results:
            print()
            print(r)

    @staticmethod
    def _start_experiment():
        Nemesis.r_duration = Nemesis.e_duration
        Nemesis.prev_coro = defaultdict(lambda: None)
        Nemesis.curr_experiment = Experiment(Nemesis.coro, Nemesis.speedup)

    @staticmethod
    def _stop_experiment():
        if Nemesis.curr_experiment is not None:
            print(f'finished running {Nemesis.curr_experiment.get_coro()} with speedup {Nemesis.curr_experiment.get_speedup()}')
            Nemesis.results.append(Nemesis.curr_experiment.get_results())
            del Nemesis.curr_experiment

    @staticmethod
    def _signal_handler(sig, frame):
        curr_sample = time.perf_counter()
        passed_time = curr_sample - Nemesis.last_sample
        Nemesis.last_sample = curr_sample
        if Nemesis.curr_experiment:
            loops = Nemesis.curr_experiment.get_loops()
            exp_coro = Nemesis.curr_experiment.get_coro()
            for loop in loops:
                coro = Nemesis._get_current_coro(loop)
                prev_coro = Nemesis.prev_coro[loop]
                if not prev_coro == coro:
                    if prev_coro == exp_coro:
                        loop.ping_exit_coro()
                    elif coro == exp_coro:
                        loop.ping_enter_coro()
                    Nemesis.prev_coro[loop] = coro

                loop._update_ready(True)
                handles = Nemesis._get_waiting_handles(loop)
                Nemesis.curr_experiment.add_handles(handles, loop, passed_time)

        Nemesis.r_duration -= passed_time
        if (Nemesis.r_duration <= 0):
            Nemesis._stop_experiment()
            Nemesis._start_experiment()

    def _get_waiting_handles(loop):
        handles = []
        for handle in loop._ready:
            # no duplicates
            handle_info = Nemesis._parse_handle(handle)
            if handle_info not in handles:
                handles.append(handle_info)
        return handles

    def _parse_handle(handle):
        cb = handle._callback
        if isinstance(getattr(cb, '__self__', None), asyncio.tasks.Task):
            task = cb.__self__
            coro = task.get_coro()
            return [task.get_name(), Nemesis.get_coro_name(coro)]
        else:
            return [str(type(handle).__name__), cb.__name__]

    def _get_current_coro(loop):
        tid = loop._thread_id
        assert tid, f"{loop} is not running, yet we attempted to sample it!"

        frame = sys._current_frames().get(tid)
        fname = frame.f_code.co_filename
        while not Nemesis._should_trace(fname):
            if frame:
                frame = frame.f_back
            else:
                break
            if frame:
                fname = frame.f_code.co_filename
        if frame and frame.f_generator:
            return frame.f_generator.cr_code.co_name
        return None

    @staticmethod
    def _should_trace(filename):
        '''Returns FALSE if filename is uninteresting to the user.
        Don't depend on this. It kind of sucks.'''
        if not filename:
            return False
        if '/gnu/store' in filename:
            return False
        if '/usr/local/lib/python' in filename:
            return False
        if 'site-packages' in filename:
            return False
        if 'propcache' in filename:
            return False
        if '.pyx' in filename:
            return False
        if filename[0] == '<':
            return False
        if 'nemesis' in filename:
            return False
        return True

    def get_coro_name(coro):
        '''
        Stolen from _format_coroutine in cpython/Lib/asyncio/coroutines.py
        '''
        # Coroutines compiled with Cython sometimes don't have
        # proper __qualname__ or __name__.  While that is a bug
        # in Cython, asyncio shouldn't crash with an AttributeError
        # in its __repr__ functions.
        if hasattr(coro, '__qualname__') and coro.__qualname__:
            coro_name = coro.__qualname__
        elif hasattr(coro, '__name__') and coro.__name__:
            coro_name = coro.__name__
        else:
            # Stop masking Cython bugs, expose them in a friendly way.
            coro_name = f'<{type(coro).__name__} without __name__>'
        return f'{coro_name}()'

the_globals = {
    '__name__': '__main__',
    '__doc__': None,
    '__package__': None,
    '__loader__': globals()['__loader__'],
    '__spec__': None,
    '__annotations__': {},
    '__builtins__': globals()['__builtins__'],
    '__file__': None,
    '__cached__': None,
}


if __name__ == "__main__":
    # parses CLI arguments and facilitates profiler runtime.
    parser = argparse.ArgumentParser(
        usage='%(prog)s [args] -- prog'
    )

    parser.add_argument('-i', '--interval',
                        help='The minimum amount of time inbetween \
                        samples in seconds.',
                        metavar='',
                        type=float,
                        default=0.01)
    parser.add_argument('-s', '--speedup',
                        help='The amount of virtual speedup. Cannot go below one. Default is 2.0.',
                        metavar='',
                        type=float,
                        default=2.0)
    parser.add_argument('-c', '--task',
                        help='The task to virtually speedup.',
                        metavar='',
                        type=str,
                        required=True)
    parser.add_argument('-e', '--experiment-duration',
                        help='The performance experiment duration. Defaults to 4 seconds.',
                        metavar='',
                        type=float,
                        default=4)
    parser.add_argument('-w', '--warmup-time',
                        help='Amount of time to wait until the first performance experiment. Default is 0 milliseconds',
                        metavar='',
                        type=float,
                        default=0.1)
    parser.add_argument('prog',
                        type=str,
                        nargs='*',
                        help='Path to the python script and its arguments.')
    args = parser.parse_args()

    sys.argv = args.prog
    try:
        with open(args.prog[0], 'r', encoding='utf-8') as fp:
            code = compile(fp.read(), args.prog[0], "exec")
            Nemesis(args.task,
                    args.speedup,
                    args.experiment_duration,
                    args.warmup_time,
                    args.interval).start()
            exec(code, the_globals)
            Nemesis.stop()
    except Exception:
        traceback.print_exc()