mozgeckoprofiler 1.0.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,30 @@
1
+ Metadata-Version: 2.4
2
+ Name: mozgeckoprofiler
3
+ Version: 1.0.0
4
+ Summary: Library to generate and view performance data in the Firefox Profiler
5
+ Home-page: https://wiki.mozilla.org/Auto-tools/Projects/Mozbase
6
+ Author: Mozilla Automation and Tools team
7
+ Author-email: tools@lists.mozilla.org
8
+ License: MPL
9
+ Keywords: mozilla
10
+ Classifier: Programming Language :: Python
11
+ Classifier: Programming Language :: Python :: 3 :: Only
12
+ Classifier: Programming Language :: Python :: 3.8
13
+ Classifier: Programming Language :: Python :: 3.9
14
+ Classifier: Programming Language :: Python :: 3.10
15
+ Classifier: Programming Language :: Python :: 3.11
16
+ Classifier: Programming Language :: Python :: 3.12
17
+ Classifier: Programming Language :: Python :: 3.13
18
+ Classifier: License :: OSI Approved :: Mozilla Public License 2.0 (MPL 2.0)
19
+ Requires-Python: >=3.8
20
+ Dynamic: author
21
+ Dynamic: author-email
22
+ Dynamic: classifier
23
+ Dynamic: description
24
+ Dynamic: home-page
25
+ Dynamic: keywords
26
+ Dynamic: license
27
+ Dynamic: requires-python
28
+ Dynamic: summary
29
+
30
+ see https://firefox-source-docs.mozilla.org/mozbase/mozgeckoprofiler.html
@@ -0,0 +1,23 @@
1
+ # This Source Code Form is subject to the terms of the Mozilla Public
2
+ # License, v. 2.0. If a copy of the MPL was not distributed with this file,
3
+ # You can obtain one at http://mozilla.org/MPL/2.0/.
4
+
5
+ """
6
+ mozgeckoprofiler has utilities to symbolicate and load gecko profiles.
7
+ """
8
+
9
+ from .profiling import (
10
+ save_gecko_profile,
11
+ symbolicate_profile_json,
12
+ symbolicate_profiles,
13
+ )
14
+ from .symbolication import symbolicate_profile
15
+ from .viewgeckoprofile import view_gecko_profile
16
+
17
+ __all__ = [
18
+ "save_gecko_profile",
19
+ "symbolicate_profile",
20
+ "symbolicate_profile_json",
21
+ "symbolicate_profiles",
22
+ "view_gecko_profile",
23
+ ]
@@ -0,0 +1,163 @@
1
+ # This Source Code Form is subject to the terms of the Mozilla Public
2
+ # License, v. 2.0. If a copy of the MPL was not distributed with this
3
+ # file, You can obtain one at http://mozilla.org/MPL/2.0/.
4
+ import gzip
5
+ import json
6
+ import os
7
+ import shutil
8
+ import tempfile
9
+ from pathlib import Path
10
+
11
+ try:
12
+ import orjson
13
+ except ImportError:
14
+ orjson = None
15
+
16
+ from mozlog import get_proxy_logger
17
+
18
+ from .symbolication import get_extracted_symbols, symbolicate_profile
19
+
20
+ LOG = get_proxy_logger("profiler")
21
+
22
+
23
+ def save_gecko_profile(profile, filename, gzip_compress=False):
24
+ LOG.info(
25
+ f"Saving profile to {filename} {'with gzip compression' if gzip_compress else ''}"
26
+ )
27
+ if orjson is not None:
28
+ try:
29
+ data = orjson.dumps(profile)
30
+ except Exception:
31
+ data = json.dumps(profile).encode("utf-8")
32
+ else:
33
+ data = json.dumps(profile).encode("utf-8")
34
+
35
+ if gzip_compress:
36
+ with gzip.open(filename, "wb") as f:
37
+ f.write(data)
38
+ else:
39
+ with open(filename, "wb") as f:
40
+ f.write(data)
41
+
42
+
43
+ def symbolicate_profile_json(profile_path, symbol_dir=None):
44
+ """
45
+ Symbolicate a single JSON profile.
46
+ """
47
+
48
+ stat = Path(profile_path).stat()
49
+ original_atime = stat.st_atime
50
+ original_mtime = stat.st_mtime
51
+
52
+ with tempfile.TemporaryDirectory() as work_dir:
53
+ if symbol_dir is None:
54
+ symbol_dir = get_extracted_symbols(work_dir)
55
+
56
+ LOG.info("Symbolicating the performance profile...")
57
+ try:
58
+ gzipped = False
59
+ with open(profile_path, "rb") as profile_file:
60
+ # Some profile.json files may be compressed with gzip
61
+ # (ex. Mochitest / XPCshell profiles)
62
+ data = profile_file.read()
63
+ LOG.info(f"Profile file size: {len(data)} bytes")
64
+ gzip_magic_number = b"\x1f\x8b"
65
+ if data[:2] == gzip_magic_number:
66
+ gzipped = True
67
+ data = gzip.decompress(data)
68
+ LOG.info(f"Decompressed profile size: {len(data)} bytes")
69
+ else:
70
+ LOG.debug("Profile was not gzipped, treating as regular JSON")
71
+
72
+ if orjson is not None:
73
+ try:
74
+ profile = orjson.loads(data)
75
+ except Exception:
76
+ profile = json.loads(data)
77
+ else:
78
+ profile = json.loads(data)
79
+
80
+ symbolicate_profile(profile, symbol_dir)
81
+ save_gecko_profile(profile, profile_path, gzip_compress=gzipped)
82
+ except MemoryError:
83
+ LOG.error(
84
+ f"Ran out of memory while trying to symbolicate profile {profile_path}"
85
+ )
86
+ except Exception as e:
87
+ LOG.error("Encountered an exception during profile symbolication")
88
+ LOG.error(e)
89
+
90
+ # To ensure the artifact markers in resource usage profiles are accurate,
91
+ # the symbolicated profile's mod and access time should reflect
92
+ # when the artifact was created rather than when the profile was symbolicated
93
+ os.utime(profile_path, (original_atime, original_mtime))
94
+
95
+
96
+ def symbolicate_profiles(profile_dir=None, symbol_dir=None):
97
+
98
+ if "MOZ_AUTOMATION" in os.environ:
99
+ if profile_dir is None and os.environ.get("MOZ_UPLOAD_DIR"):
100
+ profile_dir = Path(os.environ.get("MOZ_UPLOAD_DIR"))
101
+
102
+ if profile_dir is None:
103
+ LOG.warning("No profile directory specified, skipping symbolication")
104
+ return
105
+
106
+ profile_files = sorted(
107
+ profile
108
+ for profile in profile_dir.glob("profile_*.json")
109
+ if "resource-usage" not in profile.name
110
+ )
111
+
112
+ with tempfile.TemporaryDirectory() as work_dir:
113
+ if symbol_dir is None:
114
+ symbol_dir = get_extracted_symbols(work_dir)
115
+ if symbol_dir is None:
116
+ LOG.warning(
117
+ "Symbols not found. Attempting to symbolication with remote symbol server."
118
+ )
119
+
120
+ with tempfile.TemporaryDirectory() as temp_dir:
121
+ for profile_file in profile_files:
122
+ stat = profile_file.stat()
123
+ unsym_size = stat.st_size
124
+ unsym_mod_time = stat.st_mtime
125
+ unsym_access_time = stat.st_atime
126
+ LOG.info(f"Symbolicating {profile_file.name} ({unsym_size} bytes)...")
127
+
128
+ try:
129
+ temp_path = Path(temp_dir) / profile_file.name
130
+ shutil.copy(profile_file, temp_path)
131
+
132
+ symbolicate_profile_json(str(temp_path), symbol_dir)
133
+
134
+ if temp_path.is_file():
135
+ sym_size = temp_path.stat().st_size
136
+ LOG.info(
137
+ f"Successfully symbolicated {profile_file.name}: "
138
+ f"{unsym_size} bytes -> {sym_size} bytes"
139
+ )
140
+ # Use shutil move if os.replace fails with
141
+ # ([Errno 18] Invalid cross-device link in CI
142
+ try:
143
+ os.replace(str(temp_path), str(profile_file))
144
+ LOG.info(
145
+ f"Successfully moved {profile_file.name} using os.replace"
146
+ )
147
+ except Exception:
148
+ shutil.move(str(temp_path), str(profile_file))
149
+ LOG.info(
150
+ f"Successfully moved {profile_file.name} using shutil.move"
151
+ )
152
+
153
+ # To ensure the artifact markers in resource usage profiles are accurate,
154
+ # the symbolicate profile's mod and access time should reflect
155
+ # when the artifact was created rather than when the profile
156
+ # was symbolicated
157
+ os.utime(profile_file, (unsym_access_time, unsym_mod_time))
158
+
159
+ except Exception as e:
160
+ LOG.warning(
161
+ f"Failed to symbolicate {profile_file.name}: {e}",
162
+ exc_info=True,
163
+ )
@@ -0,0 +1,227 @@
1
+ # This Source Code Form is subject to the terms of the Mozilla Public
2
+ # License, v. 2.0. If a copy of the MPL was not distributed with this
3
+ # file, You can obtain one at http://mozilla.org/MPL/2.0/.
4
+ import gzip
5
+ import json
6
+ import os
7
+ import platform
8
+ import signal
9
+ import subprocess
10
+ import tempfile
11
+ import time
12
+ import zipfile
13
+ from pathlib import Path
14
+ from urllib.parse import unquote
15
+
16
+ from mozlog import get_proxy_logger
17
+
18
+ try:
19
+ from mozbuild.base import MozbuildObject
20
+ except ImportError:
21
+ MozbuildObject = None
22
+
23
+ LOG = get_proxy_logger("profiler")
24
+ BREAKPAD_SYMBOL_SERVER = "https://symbols.mozilla.org/"
25
+ SYMBOL_SERVER_TIMEOUT = 60 # seconds
26
+ SAMPLY_WAIT_TIMEOUT = 60 # seconds
27
+
28
+
29
+ def get_extracted_symbols(work_dir=None):
30
+ try:
31
+ if "MOZ_AUTOMATION" in os.environ:
32
+ base_path = os.environ["MOZ_FETCHES_DIR"]
33
+ symbol_zip = Path(base_path) / "target.crashreporter-symbols.zip"
34
+ if symbol_zip.exists():
35
+ if work_dir is None:
36
+ raise ValueError(
37
+ "work_dir must be provided in MOZ_AUTOMATION environment"
38
+ )
39
+ breakpad_symbol_dir = Path(work_dir) / "breakpad_symbols"
40
+ breakpad_symbol_dir.mkdir(exist_ok=True)
41
+ with zipfile.ZipFile(symbol_zip, "r") as zipf:
42
+ zipf.extractall(breakpad_symbol_dir)
43
+ LOG.info(f"Extracted symbols to {breakpad_symbol_dir}")
44
+ return breakpad_symbol_dir
45
+ LOG.warning("Symbol directory not found.")
46
+ else:
47
+ if "MOZ_DEVELOPER_OBJ_DIR" in os.environ:
48
+ objdir_symbols = (
49
+ Path(os.environ["MOZ_DEVELOPER_OBJ_DIR"])
50
+ / "dist"
51
+ / "crashreporter-symbols"
52
+ )
53
+ if objdir_symbols.is_dir():
54
+ LOG.info(
55
+ f"Returning symbol_dir from MOZ_DEVELOPER_OBJ_DIR: {objdir_symbols}"
56
+ )
57
+ return objdir_symbols
58
+
59
+ if MozbuildObject is not None:
60
+ moz_obj = MozbuildObject.from_environment()
61
+ objdir_symbols = Path(moz_obj.distdir) / "crashreporter-symbols"
62
+ if objdir_symbols.is_dir():
63
+ LOG.info(
64
+ f"Returning symbol_dir from MozbuildObject: {objdir_symbols}"
65
+ )
66
+ return objdir_symbols
67
+
68
+ LOG.warning(
69
+ "Symbol directory not found. Try running: ./mach build and ./mach buildsymbols"
70
+ )
71
+
72
+ return None
73
+ except Exception as e:
74
+ LOG.error(f"Error extracting or finding symbols: {e}", exc_info=True)
75
+ return None
76
+
77
+
78
+ def _validate_symbolication_deps(paths_to_validate):
79
+ for dep_path in paths_to_validate:
80
+ if not dep_path.exists():
81
+ LOG.warning(f"{dep_path} does not exist.")
82
+ return False
83
+ return True
84
+
85
+
86
+ def symbolicate_profile(profile_json, symbol_dir=None):
87
+ """Symbolicate a Gecko profile in place, using samply and profiler-edit.
88
+
89
+ Args:
90
+ profile_json (dict): The profile to symbolicate, mutated in place.
91
+ symbol_dir (path): Directory of Breakpad symbols to use. When omitted,
92
+ it is looked up with get_extracted_symbols().
93
+ """
94
+
95
+ # Check if running in CI
96
+ if "MOZ_AUTOMATION" in os.environ:
97
+ base_path = os.environ["MOZ_FETCHES_DIR"]
98
+ else:
99
+ base_path = os.environ.get(
100
+ "MOZBUILD_STATE_PATH", str(Path.home() / ".mozbuild")
101
+ )
102
+
103
+ profiler_edit_path = Path(base_path, "profiler-node-tools", "profiler-edit.js")
104
+ if platform.system() == "Windows":
105
+ samply_path = Path(base_path, "samply", "samply.exe")
106
+ node_path = Path(base_path, "node", "node.exe")
107
+ else:
108
+ samply_path = Path(base_path, "samply", "samply")
109
+ node_path = Path(base_path, "node", "bin", "node")
110
+
111
+ # Check if symbolication dependencies are available
112
+ if not _validate_symbolication_deps([
113
+ profiler_edit_path,
114
+ samply_path,
115
+ node_path,
116
+ ]):
117
+ LOG.info("Symbolication dependencies not available, skipping symbolication.")
118
+ return
119
+
120
+ try:
121
+ with tempfile.TemporaryDirectory() as work_dir:
122
+ if symbol_dir is None:
123
+ symbol_dir = get_extracted_symbols(work_dir)
124
+ if symbol_dir is None:
125
+ LOG.warning(
126
+ f"Symbol directory not found. Attempting to symbolicate with {BREAKPAD_SYMBOL_SERVER}"
127
+ )
128
+
129
+ unsym_profile = Path(work_dir, "unsym_profile.json")
130
+ unsym_profile.write_text(
131
+ json.dumps(profile_json, ensure_ascii=False), encoding="utf-8"
132
+ )
133
+ sym_profile = Path(work_dir) / "sym_profile.json.gz"
134
+
135
+ # Load unsymbolicated profile with samply
136
+ samply_cmd = [
137
+ samply_path,
138
+ "load",
139
+ str(unsym_profile),
140
+ "--no-open",
141
+ ]
142
+ if symbol_dir:
143
+ samply_cmd.extend([
144
+ "--breakpad-symbol-dir",
145
+ str(symbol_dir),
146
+ ])
147
+ samply_cmd.extend([
148
+ "--breakpad-symbol-server",
149
+ BREAKPAD_SYMBOL_SERVER,
150
+ ])
151
+
152
+ LOG.info(f"Running samply command: {samply_cmd}")
153
+ samply_process = subprocess.Popen(
154
+ samply_cmd,
155
+ stdout=subprocess.PIPE,
156
+ stderr=subprocess.STDOUT,
157
+ text=True,
158
+ )
159
+
160
+ # Tail output for timeout seconds to obtain symbol server url
161
+ server_url = ""
162
+ start = time.time()
163
+ with samply_process.stdout:
164
+ for line in iter(samply_process.stdout.readline, ""):
165
+ if line.startswith("http"):
166
+ url = unquote(line)
167
+ server_url = str(url.split("symbolServer=", 1)[-1])
168
+ break
169
+ timeout = time.time() - start
170
+ if timeout > SYMBOL_SERVER_TIMEOUT:
171
+ raise TimeoutError(
172
+ f"Server timed out after exceeding {SYMBOL_SERVER_TIMEOUT} seconds. Time elapsed : {timeout} seconds."
173
+ )
174
+
175
+ profiler_edit_cmd = [
176
+ node_path,
177
+ "--max-old-space-size=8192",
178
+ str(profiler_edit_path),
179
+ "-i",
180
+ str(unsym_profile),
181
+ "-o",
182
+ str(sym_profile),
183
+ "--symbolicate-with-server",
184
+ server_url,
185
+ ]
186
+ LOG.info(f"Running profiler-edit command: {profiler_edit_cmd}")
187
+ with subprocess.Popen(
188
+ profiler_edit_cmd,
189
+ stdout=subprocess.PIPE,
190
+ stderr=subprocess.STDOUT,
191
+ text=True,
192
+ bufsize=1,
193
+ ) as profiler_edit_process:
194
+ for line in profiler_edit_process.stdout:
195
+ LOG.info(f"profiler-edit {line.strip()}")
196
+
197
+ # Terminate samply server
198
+ if platform.system() == "Windows":
199
+ samply_process.terminate()
200
+ else:
201
+ samply_process.send_signal(signal.SIGINT) # ctrl-c shutdown
202
+
203
+ samply_process.wait(timeout=SAMPLY_WAIT_TIMEOUT)
204
+
205
+ if sym_profile.exists():
206
+ # Load profile json into memory and mutate profile
207
+ is_gzipped = False
208
+ with sym_profile.open("rb") as f:
209
+ gzip_magic_number = b"\x1f\x8b"
210
+ if f.read(2) == gzip_magic_number:
211
+ is_gzipped = True
212
+
213
+ if is_gzipped:
214
+ with gzip.open(sym_profile, "rt", encoding="utf-8") as f:
215
+ sym = json.load(f)
216
+ else:
217
+ with sym_profile.open("r", encoding="utf-8") as f:
218
+ sym = json.load(f)
219
+
220
+ profile_json.clear()
221
+ profile_json.update(sym)
222
+
223
+ except Exception:
224
+ LOG.critical(
225
+ "Profile symbolication with Samply and profiler-edit failed.",
226
+ exc_info=True,
227
+ )
@@ -0,0 +1,125 @@
1
+ #!/usr/bin/env python
2
+
3
+ # This Source Code Form is subject to the terms of the Mozilla Public
4
+ # License, v. 2.0. If a copy of the MPL was not distributed with this
5
+ # file, You can obtain one at http://mozilla.org/MPL/2.0/.
6
+
7
+ import argparse
8
+ import os
9
+ import socket
10
+ import sys
11
+ import webbrowser
12
+
13
+ from mozlog import commandline, get_proxy_logger
14
+ from mozlog.commandline import add_logging_group
15
+
16
+ here = os.path.abspath(os.path.dirname(__file__))
17
+ LOG = get_proxy_logger("profiler")
18
+
19
+ from http.server import SimpleHTTPRequestHandler
20
+ from socketserver import TCPServer
21
+ from urllib.parse import quote
22
+
23
+
24
+ class ProfileServingHTTPRequestHandler(SimpleHTTPRequestHandler):
25
+ """Extends the basic SimpleHTTPRequestHandler (which serves a directory
26
+ of files) to include request headers required by profiler.firefox.com"""
27
+
28
+ def end_headers(self):
29
+ self.send_header("Access-Control-Allow-Origin", "https://profiler.firefox.com")
30
+ SimpleHTTPRequestHandler.end_headers(self)
31
+
32
+
33
+ class ViewGeckoProfile:
34
+ """Container class for ViewGeckoProfile"""
35
+
36
+ def __init__(self, gecko_profile_data_path):
37
+ self.gecko_profile_data_path = gecko_profile_data_path
38
+ self.gecko_profile_dir = os.path.dirname(gecko_profile_data_path)
39
+ self.profiler_url = "https://profiler.firefox.com/from-url/"
40
+ self.httpd = None
41
+ self.host = "127.0.0.1"
42
+ self.port = None
43
+ self.oldcwd = os.getcwd()
44
+
45
+ def setup_http_server(self):
46
+ # pick a free port
47
+ sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
48
+ sock.bind(("", 0))
49
+ self.port = sock.getsockname()[1]
50
+ sock.close()
51
+
52
+ # Temporarily change the directory to the profile directory.
53
+ os.chdir(self.gecko_profile_dir)
54
+ self.httpd = TCPServer((self.host, self.port), ProfileServingHTTPRequestHandler)
55
+
56
+ def handle_single_request(self):
57
+ self.httpd.handle_request()
58
+ # Go back to the old cwd, which some infrastructure may be relying on.
59
+ os.chdir(self.oldcwd)
60
+
61
+ def encode_url(self):
62
+ # Encode url i.e.: https://profiler.firefox.com/from-url/http...
63
+ file_url = f"http://{self.host}:{self.port}/{os.path.basename(self.gecko_profile_data_path)}"
64
+
65
+ self.profiler_url = self.profiler_url + quote(file_url, safe="")
66
+ LOG.info("Temporarily serving the profile from: %s" % file_url)
67
+
68
+ def open_profile_in_browser(self):
69
+ # Open the file in the user's preferred browser.
70
+ LOG.info("Opening the profile: %s" % self.profiler_url)
71
+ webbrowser.open_new_tab(self.profiler_url)
72
+
73
+
74
+ def create_parser(mach_interface=False):
75
+ parser = argparse.ArgumentParser()
76
+ add_arg = parser.add_argument
77
+
78
+ add_arg(
79
+ "-p",
80
+ "--profile-zip",
81
+ required=True,
82
+ dest="profile_zip",
83
+ help="path to the gecko profiles zip file to open in profiler.firefox.com",
84
+ )
85
+
86
+ add_logging_group(parser)
87
+ return parser
88
+
89
+
90
+ def verify_options(parser, args):
91
+ ctx = vars(args)
92
+
93
+ if not os.path.isfile(args.profile_zip):
94
+ parser.error("{profile_zip} does not exist!".format(**ctx))
95
+
96
+
97
+ def parse_args(argv=None):
98
+ parser = create_parser()
99
+ args = parser.parse_args(argv)
100
+ verify_options(parser, args)
101
+ return args
102
+
103
+
104
+ def view_gecko_profile(profile_path):
105
+ """
106
+ Open a gecko profile in the user's default browser. This function opens
107
+ up a special URL to profiler.firefox.com and serves up the local profile.
108
+ """
109
+ view_gecko_profile = ViewGeckoProfile(profile_path)
110
+
111
+ view_gecko_profile.setup_http_server()
112
+ view_gecko_profile.encode_url()
113
+ view_gecko_profile.open_profile_in_browser()
114
+ view_gecko_profile.handle_single_request()
115
+
116
+
117
+ def start_from_command_line():
118
+ args = parse_args(sys.argv[1:])
119
+ commandline.setup_logging("view-gecko-profile", args, {"tbpl": sys.stdout})
120
+
121
+ view_gecko_profile(args.profile_zip)
122
+
123
+
124
+ if __name__ == "__main__":
125
+ start_from_command_line()
@@ -0,0 +1,30 @@
1
+ Metadata-Version: 2.4
2
+ Name: mozgeckoprofiler
3
+ Version: 1.0.0
4
+ Summary: Library to generate and view performance data in the Firefox Profiler
5
+ Home-page: https://wiki.mozilla.org/Auto-tools/Projects/Mozbase
6
+ Author: Mozilla Automation and Tools team
7
+ Author-email: tools@lists.mozilla.org
8
+ License: MPL
9
+ Keywords: mozilla
10
+ Classifier: Programming Language :: Python
11
+ Classifier: Programming Language :: Python :: 3 :: Only
12
+ Classifier: Programming Language :: Python :: 3.8
13
+ Classifier: Programming Language :: Python :: 3.9
14
+ Classifier: Programming Language :: Python :: 3.10
15
+ Classifier: Programming Language :: Python :: 3.11
16
+ Classifier: Programming Language :: Python :: 3.12
17
+ Classifier: Programming Language :: Python :: 3.13
18
+ Classifier: License :: OSI Approved :: Mozilla Public License 2.0 (MPL 2.0)
19
+ Requires-Python: >=3.8
20
+ Dynamic: author
21
+ Dynamic: author-email
22
+ Dynamic: classifier
23
+ Dynamic: description
24
+ Dynamic: home-page
25
+ Dynamic: keywords
26
+ Dynamic: license
27
+ Dynamic: requires-python
28
+ Dynamic: summary
29
+
30
+ see https://firefox-source-docs.mozilla.org/mozbase/mozgeckoprofiler.html
@@ -0,0 +1,11 @@
1
+ setup.py
2
+ mozgeckoprofiler/__init__.py
3
+ mozgeckoprofiler/profiling.py
4
+ mozgeckoprofiler/symbolication.py
5
+ mozgeckoprofiler/viewgeckoprofile.py
6
+ mozgeckoprofiler.egg-info/PKG-INFO
7
+ mozgeckoprofiler.egg-info/SOURCES.txt
8
+ mozgeckoprofiler.egg-info/dependency_links.txt
9
+ mozgeckoprofiler.egg-info/not-zip-safe
10
+ mozgeckoprofiler.egg-info/top_level.txt
11
+ tests/test_view_gecko_profiler.py
@@ -0,0 +1 @@
1
+ mozgeckoprofiler
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,37 @@
1
+ # This Source Code Form is subject to the terms of the Mozilla Public
2
+ # License, v. 2.0. If a copy of the MPL was not distributed with this file,
3
+ # You can obtain one at http://mozilla.org/MPL/2.0/.
4
+
5
+ from setuptools import setup
6
+
7
+ PACKAGE_NAME = "mozgeckoprofiler"
8
+ PACKAGE_VERSION = "1.0.0"
9
+
10
+ setup(
11
+ name=PACKAGE_NAME,
12
+ version=PACKAGE_VERSION,
13
+ description="Library to generate and view performance data in the Firefox Profiler",
14
+ long_description="see https://firefox-source-docs.mozilla.org/mozbase/mozgeckoprofiler.html",
15
+ classifiers=[
16
+ "Programming Language :: Python",
17
+ "Programming Language :: Python :: 3 :: Only",
18
+ "Programming Language :: Python :: 3.8",
19
+ "Programming Language :: Python :: 3.9",
20
+ "Programming Language :: Python :: 3.10",
21
+ "Programming Language :: Python :: 3.11",
22
+ "Programming Language :: Python :: 3.12",
23
+ "Programming Language :: Python :: 3.13",
24
+ "License :: OSI Approved :: Mozilla Public License 2.0 (MPL 2.0)",
25
+ ],
26
+ keywords="mozilla",
27
+ author="Mozilla Automation and Tools team",
28
+ author_email="tools@lists.mozilla.org",
29
+ url="https://wiki.mozilla.org/Auto-tools/Projects/Mozbase",
30
+ license="MPL",
31
+ packages=["mozgeckoprofiler"],
32
+ include_package_data=True,
33
+ zip_safe=False,
34
+ install_requires=[],
35
+ tests_require=[],
36
+ python_requires=">=3.8",
37
+ )
@@ -0,0 +1,97 @@
1
+ #!/usr/bin/env python
2
+
3
+ import os
4
+ import re
5
+ import shutil
6
+ import tempfile
7
+ import threading
8
+ import time
9
+ import unittest
10
+ from unittest import mock
11
+ from urllib.parse import unquote
12
+
13
+ import mozunit
14
+ import requests
15
+ from mozgeckoprofiler import view_gecko_profile
16
+
17
+
18
+ def access_profiler_link(file_url, response):
19
+ """Attempts to access the profile in a loop for 5 seconds.
20
+
21
+ This is run from a separate thread.
22
+ """
23
+ timeout = 5 # seconds
24
+ start = time.time()
25
+
26
+ while time.time() - start < timeout:
27
+ # Poll the server to try and get a response.
28
+ result = requests.get(url=file_url)
29
+ if result.ok:
30
+ # Return the text back in a list.
31
+ response[0] = result.text
32
+ return
33
+ time.sleep(0.1)
34
+
35
+ response[0] = "Accessing the profiler link timed out after %s seconds" % timeout
36
+
37
+
38
+ class TestViewGeckoProfile(unittest.TestCase):
39
+ """Tests the opening local profiles in the Firefox Profiler."""
40
+
41
+ def setUp(self):
42
+ self.firefox_profiler_url = None
43
+ self.thread = None
44
+ self.response = [None]
45
+
46
+ def test_view_gecko_profile(self):
47
+ # Create a temporary fake performance profile.
48
+ temp_dir = tempfile.mkdtemp()
49
+ profile_path = os.path.join(temp_dir, "fakeprofile.json")
50
+ with open(profile_path, "w") as f:
51
+ f.write("FAKE_PROFILE")
52
+
53
+ # Mock the open_new_tab function so that we know when the view_gecko_profile
54
+ # function has done all of its work, and we can assert ressult of the
55
+ # user behavior.
56
+ def mocked_open_new_tab(firefox_profiler_url):
57
+ self.firefox_profiler_url = firefox_profiler_url
58
+ encoded_file_url = firefox_profiler_url.split("/")[-1]
59
+ decoded_file_url = unquote(encoded_file_url)
60
+ # Extract the actual file from the path.
61
+ self.thread = threading.Thread(
62
+ target=access_profiler_link, args=(decoded_file_url, self.response)
63
+ )
64
+ print("firefox_profiler_url %s" % firefox_profiler_url)
65
+ print("encoded_file_url %s" % encoded_file_url)
66
+ print("decoded_file_url %s" % decoded_file_url)
67
+ self.thread.start()
68
+
69
+ with mock.patch("webbrowser.open_new_tab", new=mocked_open_new_tab):
70
+ # Run the test
71
+ view_gecko_profile(profile_path)
72
+
73
+ self.thread.join()
74
+
75
+ # Compare the URLs, but replace the PORT value supplied, as that is dynamic.
76
+ expected_url = (
77
+ "https://profiler.firefox.com/from-url/"
78
+ "http%3A%2F%2F127.0.0.1%3A{PORT}%2Ffakeprofile.json"
79
+ )
80
+ actual_url = re.sub(r"%3A\d+%2F", "%3A{PORT}%2F", self.firefox_profiler_url)
81
+
82
+ self.assertEqual(
83
+ actual_url,
84
+ expected_url,
85
+ "The URL generated was correct for the Firefox Profiler.",
86
+ )
87
+ self.assertEqual(
88
+ self.response[0],
89
+ "FAKE_PROFILE",
90
+ "The response from the serve provided the profile contents.",
91
+ )
92
+
93
+ shutil.rmtree(temp_dir)
94
+
95
+
96
+ if __name__ == "__main__":
97
+ mozunit.main()