Skip to content

Commit f574384

Browse files
committed
optional memray
1 parent 763b661 commit f574384

File tree

6 files changed

+72
-25
lines changed

6 files changed

+72
-25
lines changed

config.yaml.original

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -66,3 +66,8 @@ test_or_dev_project_markers:
6666
- test
6767
- dev
6868
- qa
69+
70+
# If True, the application will generate memray files downloadable with the memray_download tool.
71+
# Default false
72+
use_memray:
73+
False

main.py

Lines changed: 43 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@
2020

2121
app.wsgi_app = google.appengine.api.wrap_wsgi_app(app.wsgi_app)
2222

23-
from util.utils import init_logging, tmp_dir
23+
from util.utils import init_logging, memray_tempdir
2424

2525
# Must init logging before any library code writes logs (which would then just override our config)
2626
init_logging()
@@ -54,6 +54,7 @@
5454
is_in_test_or_dev_project,
5555
is_test_or_dev_configuration,
5656
iris_homepage_text,
57+
use_memray,
5758
)
5859
from util.utils import log_time, timing
5960

@@ -70,17 +71,15 @@
7071
logging.info(
7172
"env GAE_USE_SOCKETS_HTTPLIB is %s", os.environ.get("GAE_USE_SOCKETS_HTTPLIB")
7273
)
73-
logging.info(
74-
"env PYTHONMALLOC is %s", os.environ.get("PYTHONMALLOC")
75-
)
74+
logging.info("env PYTHONMALLOC is %s", os.environ.get("PYTHONMALLOC"))
7675

7776
PluginHolder.init()
7877

7978

8079
@app.route("/list_memray")
8180
def list_memray():
8281
s = ""
83-
for f in os.listdir(tmp_dir()):
82+
for f in os.listdir(memray_tempdir()):
8483
s += f"<a href='/memrayfiles/{f}'>{f}</a><br>\n"
8584
if not s:
8685
s = "NONE FOUND"
@@ -90,15 +89,15 @@ def list_memray():
9089
@app.route("/memrayfiles/<filename>")
9190
def memrayfiles(filename):
9291

93-
with open(f"{tmp_dir()}/{filename}", "rb") as f:
92+
with open(f"{memray_tempdir()}/{filename}", "rb") as f:
9493
content = f.read()
9594

9695
return Response(content, mimetype="application/octet-stream", status=200)
9796

9897

9998
@app.route("/")
10099
def index():
101-
with memray.Tracker(memray_filename("index")):
100+
def __index():
102101
increment_invocation_count("index")
103102
with gae_memory_logging("index"):
104103
msg = iris_homepage_text()
@@ -110,24 +109,38 @@ def index():
110109
)
111110
return Response(msg, mimetype="text/plain", status=200)
112111

112+
if use_memray():
113+
with memray.Tracker(memray_filename("index")):
114+
return __index()
115+
else:
116+
return __index()
117+
113118

114119
@app.route("/_ah/warmup")
115120
def warmup():
116-
with memray.Tracker(memray_filename("warmup")):
121+
def __warmup():
122+
117123
increment_invocation_count("warmup")
118124
with gae_memory_logging("warmup"):
119125
logging.info("warmup() called")
120126

121127
return "", 200, {}
122128

129+
if use_memray():
130+
with memray.Tracker(memray_filename("warmup")):
131+
return __warmup()
132+
else:
133+
return __warmup()
134+
123135

124136
@app.route("/schedule", methods=["GET"])
125137
@log_time
126138
def schedule():
127139
"""
128140
Send out a message per-plugin per-project to label all objects of that type and project.
129141
"""
130-
with memray.Tracker(memray_filename("schedule")):
142+
143+
def __schedule():
131144

132145
increment_invocation_count("schedule")
133146
with gae_memory_logging("schedule"):
@@ -147,6 +160,12 @@ def schedule():
147160
logging.exception("In schedule()")
148161
return "Error", 500
149162

163+
if use_memray():
164+
with memray.Tracker(memray_filename("schedule")):
165+
return __schedule()
166+
else:
167+
return __schedule()
168+
150169

151170
@lru_cache(maxsize=1)
152171
def __get_enabled_projects():
@@ -218,7 +237,7 @@ def __send_pubsub_per_projectplugin(configured_projects):
218237

219238
@app.route("/label_one", methods=["POST"])
220239
def label_one():
221-
with memray.Tracker(memray_filename("label_one")):
240+
def __label_one():
222241

223242
increment_invocation_count("label_one")
224243
with gae_memory_logging("label_one"):
@@ -275,6 +294,12 @@ def label_one():
275294
logging.exception("Error on label_one %s %s", plugins_found, project_id)
276295
return "Error", 500
277296

297+
if use_memray():
298+
with memray.Tracker(memray_filename("label_one")):
299+
return __label_one()
300+
else:
301+
return __label_one()
302+
278303

279304
def __label_one_0(data, plugin_cls: Type[Plugin]):
280305
plugin = PluginHolder.get_plugin_instance(plugin_cls)
@@ -330,7 +355,8 @@ def __extract_pubsub_content() -> Dict:
330355

331356
@app.route("/do_label", methods=["POST"])
332357
def do_label():
333-
with memray.Tracker(memray_filename("do_label")):
358+
def __do_label():
359+
334360
increment_invocation_count("do_label")
335361
with gae_memory_logging("do_label"):
336362

@@ -373,6 +399,12 @@ def do_label():
373399
)
374400
return "Error", 500
375401

402+
if use_memray():
403+
with memray.Tracker(memray_filename("do_label")):
404+
return __do_label()
405+
else:
406+
return __do_label()
407+
376408

377409
def __check_pubsub_verification_token():
378410
"""Token verifying that only PubSub accesses PubSub push endpoints"""

util/config_utils.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
import re
44
import sys
55
import typing
6+
from collections import defaultdict
67

78
import yaml
89

@@ -107,6 +108,10 @@ def is_test_or_dev_configuration():
107108
return get_config()["config_file"] != "config.yaml"
108109

109110

111+
def use_memray():
112+
return get_config().get("use_memray")
113+
114+
110115
def is_in_test_or_dev_project(project_id):
111116
markers = get_config().get("test_or_dev_project_markers", [])
112117
for marker in markers:

util/gcp_utils.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@
1212

1313
from util import localdev_config, utils
1414
from util.detect_gae import detect_gae
15-
from util.utils import timed_lru_cache, log_time, dict_to_camelcase, tmp_dir
15+
from util.utils import timed_lru_cache, log_time, dict_to_camelcase, memray_tempdir
1616

1717
__invocation_count = Counter()
1818

@@ -240,7 +240,7 @@ def memray_filename(sample_loc):
240240
mem = ""
241241
global global_counter
242242
global_counter += 1
243-
ret = f"{tmp_dir()}/{__inst_id}_{__isonow_for_filename()}.{global_counter}_{sample_loc}{mem}.bin"
243+
ret = f"{memray_tempdir()}/{__inst_id}_{__isonow_for_filename()}.{global_counter}_{sample_loc}{mem}.bin"
244244
return ret
245245

246246

util/memray_download.py

Lines changed: 13 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,8 @@
1313

1414

1515
def download(base, path):
16-
if base.endswith("/") and path.startswith("/"): path=path[1:]
16+
if base.endswith("/") and path.startswith("/"):
17+
path = path[1:]
1718
url = base + path
1819
try:
1920

@@ -46,10 +47,10 @@ def download_list_and_bins(base):
4647
html = download_txt(base, "list_memray")
4748
parser = ExtractHrefs()
4849
parser.feed(html)
49-
existing_bin=[Path(p).stem for p in Path(dir_with_bin()).iterdir()]
50+
existing_bin = [Path(p).stem for p in Path(dir_with_bin()).iterdir()]
5051
for path in parser.paths:
5152
bin_pth = Path(path)
52-
exist= bin_pth.stem in existing_bin
53+
exist = bin_pth.stem in existing_bin
5354

5455
if not exist:
5556
bin_content = download(base, path)
@@ -70,7 +71,9 @@ def generate_flamegraphs():
7071
mkdirs(dir_with_html_leaks())
7172
mkdirs(dir_with_html_basic())
7273

73-
binfiles = list(filter(lambda filename: filename.endswith(".bin"), os.listdir(dir_with_bin())))
74+
binfiles = list(
75+
filter(lambda filename: filename.endswith(".bin"), os.listdir(dir_with_bin()))
76+
)
7477
print(len(binfiles), "bin files in", dir_with_bin())
7578

7679
for f in binfiles:
@@ -79,7 +82,11 @@ def generate_flamegraphs():
7982
binfn = f"{dir_with_bin()}/{f}"
8083
sz = os.path.getsize(binfn)
8184
if sz > 1000:
82-
convert_bin_to_one_html(binfn, stem_for_html, False, )
85+
convert_bin_to_one_html(
86+
binfn,
87+
stem_for_html,
88+
False,
89+
)
8390
convert_bin_to_one_html(binfn, stem_for_html, True)
8491

8592
count_html = sum(1 for _ in Path(dir_with_html_basic()).iterdir())
@@ -124,8 +131,7 @@ def main():
124131
base = sys.argv[1] if len(sys.argv) > 1 else "http://localhost:8000"
125132
if not base.endswith("/"):
126133
base += "/"
127-
MINUTES = 60
128-
while time.time() - start < 10 * MINUTES:
134+
while time.time() - start < 10 * 60:
129135
try:
130136
download_and_convert(base)
131137
except HTTPError as e:

util/utils.py

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -254,12 +254,11 @@ def run_command(command_s):
254254
return output.strip("\n")
255255

256256

257-
def tmp_dir() -> str:
258-
subdir = "memray"
259-
ret = f"/tmp/{subdir}"
257+
def memray_tempdir() -> str:
258+
ret = f"/tmp/memray"
260259
mkdirs(ret)
261260
return ret
262261

263262

264-
def mkdirs(ret):
265-
pathlib.Path(ret).mkdir(parents=True, exist_ok=True)
263+
def mkdirs(dir_):
264+
pathlib.Path(dir_).mkdir(parents=True, exist_ok=True)

0 commit comments

Comments
 (0)