This repository has been archived by the owner on Aug 24, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 114
/
__main__.py
705 lines (600 loc) · 22.2 KB
/
__main__.py
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
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
# -*- coding: utf-8 -*-
"""
profiling.__main__
~~~~~~~~~~~~~~~~~~
The command-line interface to profile a script or view profiling results.
.. sourcecode:: console
$ profiling --help
"""
from __future__ import absolute_import
from datetime import datetime
from functools import partial, wraps
import importlib
import os
try:
import cPickle as pickle
except ImportError:
import pickle
import runpy
import signal
import socket
from stat import S_ISREG, S_ISSOCK
import sys
import threading
import time
import traceback
import click
from six import exec_
from . import remote, sampling, tracing
from .__about__ import __version__
from .profiler import Profiler
from .remote.background import BackgroundProfiler
from .remote.client import FailoverProfilingClient, ProfilingClient
from .remote.select import SelectProfilingServer
from .sampling import samplers, SamplingProfiler
from .tracing import timers, TracingProfiler
from .viewer import StatisticsViewer
__all__ = ['cli', 'profile', 'view']
class ProfilingCLI(click.Group):
def __init__(self, *args, **kwargs):
super(ProfilingCLI, self).__init__(*args, **kwargs)
self.implicit_command_name = None
self.command_name_aliases = {}
def command(self, *args, **kwargs):
"""Usage::
@cli.command(implicit=True)
def main():
...
@cli.command(aliases=['ci'])
def commit():
...
"""
implicit = kwargs.pop('implicit', False)
aliases = kwargs.pop('aliases', None)
decorator = super(ProfilingCLI, self).command(*args, **kwargs)
if not implicit and aliases is None:
# customized features not used.
return decorator
def _decorator(f):
cmd = decorator(f)
if implicit:
if self.implicit_command_name is not None:
del self.commands[cmd.name]
raise RuntimeError('Implicit command already defined')
self.implicit_command_name = cmd.name
if aliases:
for alias in aliases:
self.command_name_aliases[alias] = cmd.name
return cmd
return _decorator
def get_command(self, ctx, cmd_name):
# resolve alias.
try:
cmd_name = self.command_name_aliases[cmd_name]
except KeyError:
pass
if self.implicit_command_name is None:
pass
elif cmd_name not in self.commands:
ctx.args.insert(0, self.implicit_command_name)
cmd_name = self.implicit_command_name
return super(ProfilingCLI, self).get_command(ctx, cmd_name)
@click.command('profiling', cls=ProfilingCLI)
@click.version_option(__version__)
def cli():
pass
def get_title(src_name, src_type=None):
"""Normalizes a source name as a string to be used for viewer's title."""
if src_type == 'tcp':
return '{0}:{1}'.format(*src_name)
return os.path.basename(src_name)
def make_viewer(mono=False, *loop_args, **loop_kwargs):
"""Makes a :class:`profiling.viewer.StatisticsViewer` with common options.
"""
viewer = StatisticsViewer()
viewer.use_vim_command_map()
viewer.use_game_command_map()
loop = viewer.loop(*loop_args, **loop_kwargs)
if mono:
loop.screen.set_terminal_properties(1)
return (viewer, loop)
def spawn_thread(func, *args, **kwargs):
"""Spawns a daemon thread."""
thread = threading.Thread(target=func, args=args, kwargs=kwargs)
thread.daemon = True
thread.start()
return thread
def spawn(mode, func, *args, **kwargs):
"""Spawns a thread-like object which runs the given function concurrently.
Available modes:
- `threading`
- `greenlet`
- `eventlet`
"""
if mode is None:
# 'threading' is the default mode.
mode = 'threading'
elif mode not in spawn.modes:
# validate the given mode.
raise ValueError('Invalid spawn mode: %s' % mode)
if mode == 'threading':
return spawn_thread(func, *args, **kwargs)
elif mode == 'gevent':
import gevent
return gevent.spawn(func, *args, **kwargs)
elif mode == 'eventlet':
import eventlet
return eventlet.spawn(func, *args, **kwargs)
assert False
spawn.modes = ['threading', 'gevent', 'eventlet']
#: Just returns the first argument.
noop = lambda x: x
def import_(module_name, name):
"""Imports an object by a relative module path::
Profiler = import_('.profiler', 'Profiler')
"""
module = importlib.import_module(module_name, __package__)
return getattr(module, name)
#: Makes a function which import an object by :func:`import_` lazily.
importer = lambda module_name, name: partial(import_, module_name, name)
# custom parameter types
class Class(click.ParamType):
def __init__(self, modules, base, base_name=None, postfix=True):
self.modules = modules
self.base = base
self.base_name = base_name
self.postfix = postfix
def convert(self, value, param, ctx):
if value == self.base_name:
return self.base
name = value.title()
if self.postfix:
name += self.base.__name__.title()
for mod in self.modules:
try:
cls = getattr(mod, name)
except AttributeError:
continue
if not isinstance(cls, type):
continue
elif not issubclass(cls, self.base):
continue
return cls
self.fail('%s not found' % name)
def get_metavar(self, param):
return self.base.__name__.upper()
class Script(click.File):
"""A parameter type for Python script."""
def __init__(self):
super(Script, self).__init__('rb')
def convert(self, value, param, ctx):
with super(Script, self).convert(value, param, ctx) as f:
filename = f.name
code = compile(f.read(), filename, 'exec')
globals_ = {'__file__': filename, '__name__': '__main__',
'__package__': None, '__doc__': None}
return (filename, code, globals_)
def get_metavar(self, param):
return 'PYTHON'
class Module(click.ParamType):
def convert(self, value, param, ctx):
# inspired by @htch's fork.
# https://github.com/htch/profiling/commit/4a4eb6e
try:
detail = runpy._get_module_details(value)
except ImportError as exc:
ctx.fail(str(exc))
try:
# since Python 3.4.
mod_name, mod_spec, code = detail
except ValueError:
mod_name, loader, code, filename = detail
else:
loader = mod_spec.loader
filename = mod_spec.origin
# follow runpy's behavior.
pkg_name = mod_name.rpartition('.')[0]
globals_ = sys.modules['__main__'].__dict__.copy()
globals_.update(__name__='__main__', __file__=filename,
__loader__=loader, __package__=pkg_name)
return (filename, code, globals_)
def get_metavar(self, param):
return 'PYTHON-MODULE'
class Command(click.ParamType):
def convert(self, value, param, ctx):
filename = '<string>'
code = compile(value, filename, 'exec')
globals_ = {'__name__': '__main__',
'__package__': None, '__doc__': None}
return (filename, code, globals_)
def get_metavar(self, param):
return 'PYTHON-COMMAND'
class Address(click.ParamType):
"""A parameter type for IP address."""
def convert(self, value, param, ctx):
host, port = value.split(':')
port = int(port)
return (host, port)
def get_metavar(self, param):
return 'HOST:PORT'
class ViewerSource(click.ParamType):
"""A parameter type for :class:`profiling.viewer.StatisticsViewer` source.
"""
def convert(self, value, param, ctx):
src_type = False
try:
mode = os.stat(value).st_mode
except OSError:
try:
src_name = Address().convert(value, param, ctx)
except ValueError:
pass
else:
src_type = 'tcp'
else:
src_name = value
if S_ISSOCK(mode):
src_type = 'sock'
elif S_ISREG(mode):
src_type = 'dump'
if not src_type:
raise ValueError('A dump file or a socket address required.')
return (src_type, src_name)
def get_metavar(self, param):
return 'SOURCE'
class SignalNumber(click.ParamType):
"""A parameter type for signal number."""
@staticmethod
def name_of(signum):
for name, value in signal.__dict__.items():
if signum == value:
if name.startswith('SIG') and not name.startswith('SIG_'):
return name
return str(signum)
def convert(self, value, param, ctx):
if isinstance(value, int):
return value
elif value.isdigit():
return int(value)
signame = value.upper()
if not signame.startswith('SIG'):
signame = 'SIG' + signame
if signame.startswith('SIG_'):
self.fail('Invalid signal %s' % signame)
try:
signum = getattr(signal, signame)
except AttributeError:
self.fail('Unknown signal %s' % signame)
return signum
def get_metavar(self, param):
return 'SIGNUM'
# common parameters
class Params(object):
def __init__(self, params):
self.params = params
def __call__(self, f):
for param in self.params[::-1]:
f = param(f)
return f
def __add__(self, params):
return self.__class__(self.params + params)
def profiler_options(f):
# tracing profiler options
@click.option(
'-T', '--tracing', 'import_profiler_class',
flag_value=importer('.tracing', 'TracingProfiler'),
default=True,
help='Use tracing profiler. (default)')
@click.option(
'--timer', 'timer_class',
type=Class([timers], timers.Timer, 'basic'),
help='Choose CPU timer for tracing profiler. (basic|thread|greenlet)')
# sampling profiler options
@click.option(
'-S', '--sampling', 'import_profiler_class',
flag_value=importer('.sampling', 'SamplingProfiler'),
help='Use sampling profiler.')
@click.option(
'--sampler', 'sampler_class',
type=Class([samplers], samplers.Sampler),
help='Choose frames sampler for sampling profiler. (itimer|tracing)')
@click.option(
'--sampling-interval', type=float, default=samplers.INTERVAL,
help='How often sample. (default: %.3f cpu sec)' % samplers.INTERVAL)
# etc
@click.option(
'--pickle-protocol', type=int, default=remote.PICKLE_PROTOCOL,
help='Pickle protocol to dump result.')
@wraps(f)
def wrapped(import_profiler_class, timer_class, sampler_class,
sampling_interval, **kwargs):
profiler_class = import_profiler_class()
assert issubclass(profiler_class, Profiler)
if issubclass(profiler_class, TracingProfiler):
# profiler requires timer.
timer_class = timer_class or tracing.TIMER_CLASS
timer = timer_class()
profiler_kwargs = {'timer': timer}
elif issubclass(profiler_class, SamplingProfiler):
sampler_class = sampler_class or sampling.SAMPLER_CLASS
sampler = sampler_class(sampling_interval)
profiler_kwargs = {'sampler': sampler}
else:
profiler_kwargs = {}
profiler_factory = partial(profiler_class, **profiler_kwargs)
return f(profiler_factory=profiler_factory, **kwargs)
return wrapped
def profiler_arguments(f):
@click.argument('argv', nargs=-1)
@click.option('-m', 'module', type=Module(),
help='Run library module as a script.')
@click.option('-c', 'command', type=Command(),
help='Program passed in as string.')
@wraps(f)
def wrapped(argv, module, command, **kwargs):
if module is not None and command is not None:
raise click.UsageError('Option -m and -c are exclusive')
script = module or command
if script is None:
# -m and -c not passed.
try:
script_filename, argv = argv[0], argv[1:]
except IndexError:
raise click.UsageError('Script not specified')
script = Script().convert(script_filename, None, None)
kwargs.update(script=script, argv=argv)
return f(**kwargs)
return wrapped
viewer_options = Params([
click.option('--mono', is_flag=True, help='Disable coloring.'),
])
onetime_profiler_options = Params([
click.option(
'-d', '--dump', 'dump_filename', type=click.Path(writable=True),
help='Profiling result dump filename.'),
])
live_profiler_options = Params([
click.option(
'-i', '--interval', type=float, default=remote.INTERVAL,
help='How often update result. (default: %.0f sec)' % remote.INTERVAL),
click.option(
'--spawn', type=click.Choice(spawn.modes),
callback=lambda c, p, v: partial(spawn, v),
help='How to spawn profiler server in background.'),
click.option(
'--signum', type=SignalNumber(),
default=BackgroundProfiler.signum,
help=(
'For communication between server and application. (default: %s)' %
SignalNumber.name_of(BackgroundProfiler.signum)
))
])
# sub-commands
def __profile__(filename, code, globals_, profiler_factory,
pickle_protocol=remote.PICKLE_PROTOCOL, dump_filename=None,
mono=False):
frame = sys._getframe()
profiler = profiler_factory(top_frames=[frame], top_codes=[code])
profiler.start()
try:
exec_(code, globals_)
except:
# don't profile print_exc().
profiler.stop()
traceback.print_exc()
else:
profiler.stop()
# discard this __profile__ function from the result.
profiler.stats.discard_child(frame.f_code)
if dump_filename is None:
stats, cpu_time, wall_time = profiler.result()
viewer, loop = make_viewer(mono)
viewer.set_profiler_class(profiler.__class__)
viewer.set_result(stats, cpu_time, wall_time, get_title(filename))
viewer.activate()
try:
loop.run()
except KeyboardInterrupt:
pass
else:
result = profiler.result()
with open(dump_filename, 'wb') as f:
pickle.dump((profiler.__class__, result), f, pickle_protocol)
click.echo('To view statistics:')
click.echo(' $ profiling view ', nl=False)
click.secho(dump_filename, underline=True)
class ProfilingCommand(click.Command):
def collect_usage_pieces(self, ctx):
"""Prepend "[--]" before "[ARGV]..."."""
pieces = super(ProfilingCommand, self).collect_usage_pieces(ctx)
assert pieces[-1] == '[ARGV]...'
pieces.insert(-1, 'SCRIPT')
pieces.insert(-1, '[--]')
return pieces
@cli.command(implicit=True, cls=ProfilingCommand)
@profiler_arguments
@profiler_options
@onetime_profiler_options
@viewer_options
def profile(script, argv, profiler_factory,
pickle_protocol, dump_filename, mono):
"""Profile a Python script."""
filename, code, globals_ = script
sys.argv[:] = [filename] + list(argv)
__profile__(filename, code, globals_, profiler_factory,
pickle_protocol=pickle_protocol, dump_filename=dump_filename,
mono=mono)
@cli.command('live-profile', aliases=['live'], cls=ProfilingCommand)
@profiler_arguments
@profiler_options
@live_profiler_options
@viewer_options
def live_profile(script, argv, profiler_factory, interval, spawn, signum,
pickle_protocol, mono):
"""Profile a Python script continuously."""
filename, code, globals_ = script
sys.argv[:] = [filename] + list(argv)
parent_sock, child_sock = socket.socketpair()
stderr_r_fd, stderr_w_fd = os.pipe()
pid = os.fork()
if pid:
# parent
os.close(stderr_w_fd)
viewer, loop = make_viewer(mono)
# loop.screen._term_output_file = open(os.devnull, 'w')
title = get_title(filename)
client = ProfilingClient(viewer, loop.event_loop, parent_sock, title)
client.start()
try:
loop.run()
except KeyboardInterrupt:
os.kill(pid, signal.SIGINT)
except:
# unexpected profiler error.
os.kill(pid, signal.SIGTERM)
raise
finally:
parent_sock.close()
# get exit code of child.
w_pid, status = os.waitpid(pid, os.WNOHANG)
if w_pid == 0:
os.kill(pid, signal.SIGTERM)
exit_code = os.WEXITSTATUS(status)
# print stderr of child.
with os.fdopen(stderr_r_fd, 'r') as f:
child_stderr = f.read()
if child_stderr:
sys.stdout.flush()
sys.stderr.write(child_stderr)
# exit with exit code of child.
sys.exit(exit_code)
else:
# child
os.close(stderr_r_fd)
# mute stdin, stdout.
devnull = os.open(os.devnull, os.O_RDWR)
for f in [sys.stdin, sys.stdout]:
os.dup2(devnull, f.fileno())
# redirect stderr to parent.
os.dup2(stderr_w_fd, sys.stderr.fileno())
frame = sys._getframe()
profiler = profiler_factory(top_frames=[frame], top_codes=[code])
profiler_trigger = BackgroundProfiler(profiler, signum)
profiler_trigger.prepare()
server_args = (interval, noop, pickle_protocol)
server = SelectProfilingServer(None, profiler_trigger, *server_args)
server.clients.add(child_sock)
spawn(server.connected, child_sock)
try:
exec_(code, globals_)
finally:
os.close(stderr_w_fd)
child_sock.shutdown(socket.SHUT_WR)
@cli.command('remote-profile', aliases=['remote'], cls=ProfilingCommand)
@profiler_arguments
@profiler_options
@live_profiler_options
@click.option('-b', '--bind', 'addr', type=Address(), default='127.0.0.1:8912',
help='IP address to serve profiling results.')
@click.option('-v', '--verbose', is_flag=True,
help='Print profiling server logs.')
def remote_profile(script, argv, profiler_factory, interval, spawn, signum,
pickle_protocol, addr, verbose):
"""Launch a server to profile continuously. The default address is
127.0.0.1:8912.
"""
filename, code, globals_ = script
sys.argv[:] = [filename] + list(argv)
# create listener.
listener = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
listener.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
listener.bind(addr)
listener.listen(1)
# be verbose or quiet.
if verbose:
log = lambda x: click.echo(click.style('> ', fg='cyan') + x)
bound_addr = listener.getsockname()
log('Listening on {0}:{1} for profiling...'.format(*bound_addr))
else:
log = noop
# start profiling server.
frame = sys._getframe()
profiler = profiler_factory(top_frames=[frame], top_codes=[code])
profiler_trigger = BackgroundProfiler(profiler, signum)
profiler_trigger.prepare()
server_args = (interval, log, pickle_protocol)
server = SelectProfilingServer(listener, profiler_trigger, *server_args)
spawn(server.serve_forever)
# exec the script.
try:
exec_(code, globals_)
except KeyboardInterrupt:
pass
@cli.command()
@click.argument('src', type=ViewerSource())
@viewer_options
def view(src, mono):
"""Inspect statistics by TUI view."""
src_type, src_name = src
title = get_title(src_name, src_type)
viewer, loop = make_viewer(mono)
if src_type == 'dump':
time = datetime.fromtimestamp(os.path.getmtime(src_name))
with open(src_name, 'rb') as f:
profiler_class, (stats, cpu_time, wall_time) = pickle.load(f)
viewer.set_profiler_class(profiler_class)
viewer.set_result(stats, cpu_time, wall_time, title, time)
viewer.activate()
elif src_type in ('tcp', 'sock'):
family = {'tcp': socket.AF_INET, 'sock': socket.AF_UNIX}[src_type]
client = FailoverProfilingClient(viewer, loop.event_loop,
src_name, family, title=title)
client.start()
try:
loop.run()
except KeyboardInterrupt:
pass
@cli.command('timeit-profile', aliases=['timeit'])
@click.argument('stmt', metavar='STATEMENT', default='pass')
@click.option('-n', '--number', type=int,
help='How many times to execute the statement.')
@click.option('-r', '--repeat', type=int, default=3,
help='How many times to repeat the timer.')
@click.option('-s', '--setup', default='pass',
help='Statement to be executed once initially.')
@click.option('-t', '--time', help='Ignored.')
@click.option('-c', '--clock', help='Ignored.')
@click.option('-v', '--verbose', help='Ignored.')
@profiler_options
@onetime_profiler_options
@viewer_options
def timeit_profile(stmt, number, repeat, setup,
profiler_factory, pickle_protocol, dump_filename, mono,
**_ignored):
"""Profile a Python statement like timeit."""
del _ignored
sys.path.insert(0, os.curdir)
globals_ = {}
exec_(setup, globals_)
if number is None:
# determine number so that 0.2 <= total time < 2.0 like timeit.
dummy_profiler = profiler_factory()
dummy_profiler.start()
for x in range(1, 10):
number = 10 ** x
t = time.time()
for y in range(number):
exec_(stmt, globals_)
if time.time() - t >= 0.2:
break
dummy_profiler.stop()
del dummy_profiler
code = compile('for _ in range(%d): %s' % (number, stmt),
'STATEMENT', 'exec')
__profile__(stmt, code, globals_, profiler_factory,
pickle_protocol=pickle_protocol, dump_filename=dump_filename,
mono=mono)
# Deprecated.
main = cli
if __name__ == '__main__':
cli(prog_name='python -m profiling')