Passed
Push — master ( ccf839...2e3794 )
by Plexxi
02:27
created

monkey_patch_pkg_resources()   A

Complexity

Conditions 1

Size

Total Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
dl 0
loc 7
rs 9.4285
c 1
b 0
f 0
1
# Licensed to the StackStorm, Inc ('StackStorm') under one or more
2
# contributor license agreements.  See the NOTICE file distributed with
3
# this work for additional information regarding copyright ownership.
4
# The ASF licenses this file to You under the Apache License, Version 2.0
5
# (the "License"); you may not use this file except in compliance with
6
# the License.  You may obtain a copy of the License at
7
#
8
#     http://www.apache.org/licenses/LICENSE-2.0
9
#
10
# Unless required by applicable law or agreed to in writing, software
11
# distributed under the License is distributed on an "AS IS" BASIS,
12
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
# See the License for the specific language governing permissions and
14
#
15
16
"""
17
Module for performing eventlet and other monkey patching.
18
"""
19
20
from __future__ import absolute_import
21
22
import sys
23
24
__all__ = [
25
    'monkey_patch',
26
    'monkey_patch_pkg_resources'
27
]
28
29
USE_DEBUGGER_FLAG = '--use-debugger'
30
PARENT_ARGS_FLAG = '--parent-args='
31
32
33
def monkey_patch():
34
    """
35
    Function which performs eventlet monkey patching and also takes into account "--use-debugger"
36
    argument in the command line arguments.
37
38
    If this argument is found, no monkey patching is performed for the thread module. This allows
39
    user to use remote debuggers.
40
    """
41
    import eventlet
42
43
    patch_thread = not is_use_debugger_flag_provided()
44
    eventlet.monkey_patch(os=True, select=True, socket=True, thread=patch_thread, time=True)
45
46
47
def monkey_patch_pkg_resources():
48
    # Note: This is a work-around for a very slow "pkg_resources" import.
49
    # pkg_resources is used by cryptography which is used by eventlet and importing pkg_resources
50
    # adds ~500-600ms to the import time of any script which uses that code :/
51
    # See https://github.com/pypa/setuptools/issues/510 for details
52
    import entrypoints
53
    sys.modules['pkg_resources'] = entrypoints
54
55
56
def is_use_debugger_flag_provided():
57
    # 1. Check sys.argv directly
58
    if USE_DEBUGGER_FLAG in sys.argv:
59
        return True
60
61
    # 2. Check "parent-args" arguments. This is used for spawned processes such as sensors and
62
    # Python runner actions
63
64
    for arg in sys.argv:
65
        if arg.startswith(PARENT_ARGS_FLAG) and USE_DEBUGGER_FLAG in arg:
66
            return True
67
68
    return False
69