├── MANIFEST.in ├── resources └── Presto_Workload_Analyzer.png ├── requirements.txt ├── Dockerfile ├── INSTALL.md ├── setup.py ├── analyzer ├── collect.py ├── jsonl_process.py ├── extract.py ├── output.template.html └── analyze.py ├── README.md └── COPYING /MANIFEST.in: -------------------------------------------------------------------------------- 1 | include *.md 2 | include analyzer/output.template.html 3 | include Dockerfile 4 | include requirements.txt 5 | -------------------------------------------------------------------------------- /resources/Presto_Workload_Analyzer.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/varadaio/presto-workload-analyzer/HEAD/resources/Presto_Workload_Analyzer.png -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | bokeh==2.0.1 2 | jinja2==3.0.1 3 | numpy==1.22 4 | requests==2.23.0 5 | pandas==1.2.3 6 | ipython==7.16.3 7 | matplotlib==3.7.1 8 | logbook==1.5.3 9 | tqdm==4.45.0 10 | pytest==5.4.1 11 | nested-lookup==0.2.21 12 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM python:3.8 2 | 3 | RUN apt-get update -y && apt-get install -y python3-pip python3-dev 4 | 5 | COPY ./requirements.txt /app/requirements.txt 6 | WORKDIR /app 7 | 8 | RUN pip install -r requirements.txt 9 | COPY . /app 10 | -------------------------------------------------------------------------------- /INSTALL.md: -------------------------------------------------------------------------------- 1 | # Install the Presto Workload Analyzer 2 | 3 | To install the Presto Workload Analyzer in Python virtual environments, use the commands in section 1. 4 | 5 | For Docker environments, see section 2, after the video below. 6 | 7 | ## 1. Virtual environment 8 | 9 | 10 | ### Install (using Python 3.6+) 11 | ```bash 12 | python3 -m venv .env 13 | source .env/bin/activate && pip install -U pip wheel 14 | pip install . 15 | ``` 16 | 17 | ## 2. Docker 18 | 19 | ### Install (on Ubuntu 18.04 @ EC2) 20 | ```bash 21 | $ sudo apt update && sudo apt install docker.io # install Docker CE edition 22 | $ sudo usermod -aG docker $USER && logout # to allow the user to run Docker without sudo 23 | $ docker run hello-world # make sure Docker works 24 | 25 | Hello from Docker! 26 | This message shows that your installation appears to be working correctly. 27 | 28 | ``` 29 | 30 | ### Build 31 | ```bash 32 | $ cd $ANALYZER_REPOSITORY/ 33 | $ docker build -t analyzer:latest . 34 | # lot's of output, takes ~1 minute 35 | 36 | $ docker images 37 | REPOSITORY TAG IMAGE ID CREATED SIZE 38 | analyzer latest 8d36ac887157 About a minute ago 1.35GB 39 | python 3.7 cda8c7e31f89 44 hours ago 919MB 40 | hello-world latest bf756fb1ae65 3 months ago 13.3kB 41 | ``` 42 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) 2019-2022 Varada, Inc. 2 | # This file is part of Presto Workload Analyzer. 3 | # 4 | # Presto Workload Analyzer is free software: you can redistribute it and/or modify 5 | # it under the terms of the GNU General Public License as published by 6 | # the Free Software Foundation, either version 3 of the License, or 7 | # (at your option) any later version. 8 | # 9 | # Presto Workload Analyzer is distributed in the hope that it will be useful, 10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | # GNU General Public License for more details. 13 | # 14 | # You should have received a copy of the GNU General Public License 15 | # along with Presto Workload Analyzer. If not, see . 16 | 17 | import setuptools 18 | 19 | with open("README.md", "r") as fh: 20 | long_description = fh.read() 21 | 22 | setuptools.setup( 23 | name="presto-workload-analyzer", 24 | version="0.1.0", 25 | author="VARADA", 26 | author_email="info@varada.com", 27 | description="Presto performance analyzer by VARADA", 28 | long_description=long_description, 29 | long_description_content_type="text/markdown", 30 | license="GPL-3.0-or-later", 31 | # url="TBD", 32 | packages=["analyzer"], 33 | classifiers=[ 34 | "Programming Language :: Python :: 3", 35 | "License :: OSI Approved :: GNU General Public License (GPL)", 36 | "Operating System :: OS Independent", 37 | ], 38 | python_requires=">=3.6", 39 | install_requires=open("requirements.txt").read().splitlines(), 40 | ) 41 | -------------------------------------------------------------------------------- /analyzer/collect.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | # Copyright (c) 2019-2022 Varada, Inc. 4 | # This file is part of Presto Workload Analyzer. 5 | # 6 | # Presto Workload Analyzer is free software: you can redistribute it and/or modify 7 | # it under the terms of the GNU General Public License as published by 8 | # the Free Software Foundation, either version 3 of the License, or 9 | # (at your option) any later version. 10 | # 11 | # Presto Workload Analyzer is distributed in the hope that it will be useful, 12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | # GNU General Public License for more details. 15 | # 16 | # You should have received a copy of the GNU General Public License 17 | # along with Presto Workload Analyzer. If not, see . 18 | 19 | import argparse 20 | import gzip 21 | import pathlib 22 | import sys 23 | import time 24 | import logbook 25 | import requests 26 | from requests.auth import HTTPBasicAuth 27 | 28 | logbook.StreamHandler(sys.stderr).push_application() 29 | log = logbook.Logger("collect") 30 | 31 | 32 | class Client: 33 | def __init__(self, username, password, certificate_verification, username_request_header): 34 | self._username = username 35 | self._password = password 36 | self._certificate_verification = certificate_verification 37 | self._req_headers = self.set_req_headers(username_request_header) 38 | 39 | def set_req_headers(self, request_header): 40 | if request_header: 41 | if request_header not in ('X-Trino-User', 'X-Presto-User'): 42 | log.warning( 43 | 'Got client-request-header which is not X-Trino-User or X-Presto-User, collecting JSONs might fail') 44 | return {request_header: "analyzer"} 45 | else: 46 | return {"X-Trino-User": "analyzer", 47 | "X-Presto-User": "analyzer"} 48 | 49 | def get(self, url): 50 | if all([self._username, self._password]): 51 | response = requests.get(url, self._req_headers, auth=HTTPBasicAuth( 52 | self._username, 53 | self._password), verify=self._certificate_verification) 54 | else: 55 | response = requests.get(url, headers=self._req_headers) 56 | 57 | if not response.ok: 58 | log.warn("HTTP {} {} for url: {}", response.status_code, response.reason, url) 59 | return None 60 | else: 61 | return response 62 | 63 | 64 | def str_to_bool(v): 65 | if isinstance(v, bool): 66 | return v 67 | if v.lower() in ('yes', 'true', 't', 'y', '1'): 68 | return True 69 | elif v.lower() in ('no', 'false', 'f', 'n', '0'): 70 | return False 71 | 72 | 73 | def main(): 74 | p = argparse.ArgumentParser() 75 | p.add_argument("-c", "--coordinator", default="http://localhost:8080") 76 | p.add_argument("-e", "--query-endpoint", default="/v1/query") 77 | p.add_argument("-u", "--username") 78 | p.add_argument("--username-request-header") 79 | p.add_argument("-p", "--password") 80 | p.add_argument("--certificate-verification", default=True, type=str_to_bool) 81 | p.add_argument("-o", "--output-dir", default="JSONs", type=pathlib.Path) 82 | p.add_argument("-d", "--delay", default=0.1, type=float) 83 | p.add_argument("--loop", default=False, action="store_true") 84 | p.add_argument("--loop-delay", type=float, default=1.0) 85 | args = p.parse_args() 86 | client = Client(args.username, args.password, args.certificate_verification, args.username_request_header) 87 | endpoint = "{}{}".format(args.coordinator, args.query_endpoint) 88 | args.output_dir.mkdir(parents=True, exist_ok=True) 89 | 90 | done_state = {"FINISHED", "FAILED"} 91 | while True: 92 | # Download last queries' IDs: 93 | response = client.get(endpoint) 94 | if not response: 95 | return 96 | ids = [q["queryId"] for q in response.json() if q["state"] in done_state] 97 | log.debug("Found {} queries", len(ids)) 98 | 99 | # Download new queries only: 100 | for query_id in sorted(ids): 101 | output_file = args.output_dir / (query_id + ".json.gz") # to save storage 102 | if output_file.exists(): # don't download already downloaded JSONs 103 | continue 104 | 105 | url = "{}/{}?pretty".format(endpoint, query_id) # human-readable JSON 106 | time.sleep(args.delay) # for rate-limiting 107 | log.info("Downloading {} -> {}", url, output_file) 108 | try: 109 | response = client.get(url) 110 | if not response: 111 | continue 112 | except Exception: 113 | log.exception("Failed to download {}", query_id) 114 | continue 115 | 116 | with gzip.open(output_file.open("wb"), "wb") as f: 117 | f.write(response.content) 118 | 119 | if args.loop: 120 | time.sleep(args.loop_delay) 121 | else: 122 | break 123 | 124 | 125 | if __name__ == "__main__": 126 | main() 127 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Presto Workload Analyzer 2 | 3 |

4 | Presto Workload Analyzer Logo 5 |

6 | 7 | The Workload Analyzer collects Presto® and Trino workload statistics, and analyzes them. The analysis provides improved visibility into your analytical workloads, and enables query optimization - to enhance cluster performance. 8 | 9 | The Presto® Workload Analyzer collects, and stores, [QueryInfo](https://github.com/trinodb/trino/blob/master/core/trino-main/src/main/java/io/trino/execution/QueryInfo.java) JSONs for queries executed while it is running, and any historical queries held in the Presto® Coordinator memory. 10 | 11 | The collection process has negligible compute-costs, and does not impact cluster query execution in any way. 12 | Ensure that sufficient disk space is available in your working directory. Typically, a compressed JSON file size will be 50kb - 200kb. 13 | 14 | ## **Table of contents** 15 | - [Features](#Features) 16 | - [Supported Versions of Presto](#Supported-Versions-of-Presto) 17 | - [Installation](#Installation) 18 | - [Usage](#Usage) 19 | - [Screencasts](#Screencasts) 20 | - [Advanced Features](#Advanced-Features) 21 | - [Notes](#Notes) 22 | 23 | ## Features 24 | * Continuously collects and stores [QueryInfo](https://github.com/trinodb/trino/blob/master/core/trino-main/src/main/java/io/trino/execution/QueryInfo.java) JSONs, in the background without impacting query performance. 25 | * Summarizes key query metrics to a summary.jsonl file. 26 | * Generates an analysis [report](https://varada.io/wa-sample-report/): 27 | * Query detail- query peak memory, input data read by query, and joins distribution. 28 | * Table activity- wall time utilization, and input bytes read, by table scans. 29 | * Presto® Operators- wall time usage, and input bytes read, by operator. 30 | 31 | ## Supported Versions of Presto 32 | The Workload Analyzer supports the following versions: 33 | 1. Trino (FKA PrestoSQL)- 402 and older. 34 | 2. PrestoDB- 0.245.1 and older. 35 | 3. Starburst Enterprise- 402e and older. 36 | 4. Dataproc- 1.5.x and older. 37 | 38 | Although the Workload Analyzer may run with newer versions of Presto®, these scenarios have not been tested. 39 | 40 | ## Installation 41 | For installation, see [here](INSTALL.md). 42 | 43 | ## Usage 44 | #### Local machine/ Remote machine 45 | First, go to the `analyzer` directory, where the Workload Analyzer Python code can be found. 46 | ```bash 47 | cd analyzer/ 48 | ``` 49 | To collect statistics from your cluster, run the following script for a period that will provide a representative sample of your workload. 50 | ```bash 51 | ./collect.py -c http://:8080 --username-request-header "X-Trino-User" -o ./JSONs/ --loop 52 | ``` 53 | Notes: 54 | 1. In most cases, this period will be between 5 and 15 days, with longer durations providing more significant analysis. 55 | 2. The above command will continue running until stopped by the user (Ctrl+C). 56 | 57 | To analyze the downloaded JSONs directory (e.g. `./JSONs/`) and generate a zipped HTML report, execute the following command: 58 | ```bash 59 | ./extract.py -i ./JSONs/ && ./analyze.py -i ./JSONs/summary.jsonl.gz -o ./output.zip 60 | ``` 61 | 62 | #### Docker 63 | 64 | To collect statistics from your cluster, run the following script for a period that will provide a representative sample of your workload. 65 | ```bash 66 | $ mkdir JSONs/ 67 | $ docker run -v $PWD/JSONs/:/app/JSONs analyzer ./analyzer/collect.py -c http://$PRESTO_COORDINATOR:8080 --username-request-header "X-Trino-User" -o JSONs/ --loop 68 | ``` 69 | To analyze the downloaded JSONs directory (e.g. `./JSONs/`), and generate a zipped HTML report, execute the following commands: 70 | ```bash 71 | $ docker run -v $PWD/JSONs/:/app/JSONs analyzer ./analyzer/extract.py -i JSONs/ 72 | $ docker run -v $PWD/JSONs/:/app/JSONs analyzer ./analyzer/analyze.py -i JSONs/summary.jsonl.gz -o JSONs/output.zip 73 | ``` 74 | Notes: 75 | 1. In most cases, this period will be between 5 and 15 days, with longer durations providing more significant analysis. 76 | 2. The above command will continue running until stopped by the user (Ctrl+C). 77 | 78 | 79 | 80 | ## Screencasts 81 | 82 | See the following screencasts for usage examples: 83 | 84 | 85 | 86 | #### Collection 87 | 88 | [![asciicast](https://asciinema.org/a/AmMKV9jFT5bpNJQfbt8D6qKMy.svg)](https://asciinema.org/a/AmMKV9jFT5bpNJQfbt8D6qKMy) 89 | 90 | #### Analysis 91 | 92 | [![asciicast](https://asciinema.org/a/1AqxvxYtoIPjzjFEMGeU1p7yR.svg)](https://asciinema.org/a/1AqxvxYtoIPjzjFEMGeU1p7yR) 93 | 94 | ## Advanced Features 95 | 96 | - In exceptional circumstances, it may be desirable to do one or more of the following: 97 | 1. Obfuscate the schema names 98 | 2. Remove the SQL queries from the summary file 99 | 3. Analyze queries for a specific schema (joins with other schemas are included) 100 | 101 | 102 | To enable these requirements, the `./jsonl_process.py` script may be executed, after the `./extract.py` script, but before the `./analyze.py` script. 103 | 104 | In the example below, only queries from the `transactions` schema are kept, and the SQL queries are removed from the new summary file: 105 | ```bash 106 | ./jsonl_process.py -i ./JSONs/summary.jsonl.gz -o ./processed_summary.jsonl.gz --filter-schema transactions --remove-query 107 | ``` 108 | 109 | In the following example, all the schema names are obfuscated: 110 | ```bash 111 | ./jsonl_process.py -i ./JSONs/summary.jsonl.gz -o ./processed_summary.jsonl.gz --rename-schemas 112 | ``` 113 | 114 | In the following example, all the partition and user names are obfuscated: 115 | ```bash 116 | ./jsonl_process.py -i ./JSONs/summary.jsonl.gz -o ./processed_summary.jsonl.gz --rename-partitions --rename-user 117 | ``` 118 | 119 | After the `./jsonl_process.py` script has been executed, to generate a report based on the new summary file, run: 120 | ```bash 121 | ./analyze.py -i ./processed_summary.jsonl.gz -o ./output.zip 122 | ``` 123 | - To create a high-contrast report, use the `--high-contrast-mode` parameter, for example: 124 | ```bash 125 | ./analyze.py --high-contrast-mode -i ./JSONs/summary.jsonl.gz -o ./output.zip 126 | ``` 127 | 128 | 129 | ## Notes 130 | 131 | Presto® is a trademark of The Linux Foundation. 132 | -------------------------------------------------------------------------------- /analyzer/jsonl_process.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | # Copyright (c) 2019-2022 Varada, Inc. 4 | # This file is part of Presto Workload Analyzer. 5 | # 6 | # Presto Workload Analyzer is free software: you can redistribute it and/or modify 7 | # it under the terms of the GNU General Public License as published by 8 | # the Free Software Foundation, either version 3 of the License, or 9 | # (at your option) any later version. 10 | # 11 | # Presto Workload Analyzer is distributed in the hope that it will be useful, 12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | # GNU General Public License for more details. 15 | # 16 | # You should have received a copy of the GNU General Public License 17 | # along with Presto Workload Analyzer. If not, see . 18 | 19 | 20 | import argparse 21 | import ast 22 | import gzip 23 | import json 24 | import logbook 25 | import pathlib 26 | import sys 27 | from copy import deepcopy 28 | from tqdm import tqdm 29 | import itertools 30 | import nested_lookup as nl 31 | from pprint import pformat 32 | 33 | logbook.StreamHandler(sys.stderr).push_application() 34 | log = logbook.Logger("json") 35 | 36 | 37 | def filter_line(stat, filter_dict, or_and=True, include_absent=True): 38 | """ 39 | stat - dict which represents JSONL line 40 | filter_dict - simple dict to use for filtering 41 | or_and - True for OR logic else AND 42 | include_absent - if True and filter finds nothing return True 43 | 44 | returns True if line has entry from filter_dict 45 | Currently support simple keys and values 46 | """ 47 | found = [filter_dict[k] in nl.nested_lookup(k, stat) for k in filter_dict] 48 | num_exist = [nl.get_occurrence_of_key(stat, k) for k in filter_dict] 49 | 50 | return (include_absent and sum(num_exist) == 0) or (or_and and any(found)) or (not or_and and all(found)) 51 | 52 | 53 | class NameObfuscator: 54 | def __init__(self, prefix): 55 | self.__prefix = prefix 56 | self.__name_map = dict() 57 | 58 | def __call__(self, old_name): 59 | if old_name != '': 60 | return self.__name_map.setdefault(old_name, self.__prefix + str(len(self.__name_map))) 61 | return '' 62 | 63 | def __str__(self): 64 | return pformat(self.__name_map) 65 | 66 | 67 | class ListObfuscator(NameObfuscator): 68 | def __call__(self, old_list): 69 | print(old_list) 70 | if isinstance(old_list, str): # str due to nested_lookup behavior 71 | old_list = ast.literal_eval(old_list) 72 | 73 | if not isinstance(old_list, list): 74 | raise Exception(f"List obfuscator got incompatible type {type(old_list)}") 75 | 76 | return [super(ListObfuscator, self).__call__(old_name) for old_name in old_list] 77 | 78 | 79 | def process_line(stat, obfuscator_dict): 80 | """ 81 | obfuscator_dict - dict with structure {key: callback_function} 82 | """ 83 | new_stat = deepcopy(stat) 84 | for k in obfuscator_dict: 85 | nl.nested_alter(new_stat, k, callback_function=obfuscator_dict[k], conversion_function=str, in_place=True) 86 | return new_stat 87 | 88 | 89 | def main(): 90 | p = argparse.ArgumentParser() 91 | p.add_argument( 92 | "-i", 93 | "--input-file", 94 | type=pathlib.Path, 95 | help="Path to the extracted JSONL file (the output of extract.py)" 96 | ) 97 | p.add_argument( 98 | "-o", 99 | "--output-file", 100 | type=pathlib.Path, 101 | default="./processed_summary.jsonl.gz", 102 | help="Path to the resulting zipped JSONL file", 103 | ) 104 | 105 | p.add_argument("-l", "--limit", type=int) 106 | p.add_argument("--fail-on-error", action="store_true", default=False) 107 | p.add_argument("-q", "--quiet", action="store_true", default=False) 108 | # filter parameters 109 | p.add_argument("--filter-schema", type=str, help="Save queries for this schema only") 110 | # obfuscation parameters 111 | p.add_argument("--remove-query", action="store_true", default=False) 112 | p.add_argument("--rename-schemas", action="store_true", default=False) 113 | p.add_argument("--rename-catalogs", action="store_true", default=False) 114 | p.add_argument("--remove-locations", action="store_true", default=False) 115 | p.add_argument("--rename-user", action="store_true", default=False) 116 | p.add_argument("--rename-partitions", action="store_true", default=False) 117 | args = p.parse_args() 118 | 119 | if not args.input_file: 120 | p.error("Input filename missing") 121 | 122 | # prepare obfuscators 123 | obfuscator_dict = dict() 124 | if args.remove_query: 125 | obfuscator_dict["query"] = lambda x: '' 126 | # In case of EXPLAIN remove the query details as well (TODO: would also remove VALUES) 127 | obfuscator_dict["rows"] = lambda x: '' 128 | 129 | if args.rename_schemas: 130 | schema_obfuscator = NameObfuscator('schema') 131 | obfuscator_dict["schema"] = schema_obfuscator 132 | obfuscator_dict["schemaName"] = schema_obfuscator 133 | 134 | if args.rename_catalogs: 135 | catalog_obfuscator = NameObfuscator('catalog') 136 | obfuscator_dict["catalogName"] = catalog_obfuscator 137 | 138 | if args.remove_locations: 139 | obfuscator_dict["location"] = lambda x: '' 140 | obfuscator_dict["targetPath"] = lambda x: '' 141 | obfuscator_dict["writePath"] = lambda x: '' 142 | 143 | if args.rename_user: 144 | user_obfuscator = NameObfuscator('user') 145 | obfuscator_dict["user"] = user_obfuscator 146 | obfuscator_dict["principal"] = user_obfuscator 147 | 148 | if args.rename_partitions: 149 | partitions_obfuscator = ListObfuscator('partition') 150 | obfuscator_dict["partitionIds"] = partitions_obfuscator 151 | 152 | obfuscate = len(obfuscator_dict) > 0 153 | 154 | log.info( 155 | "loading {} = {:.3f} MB", args.input_file, args.input_file.stat().st_size / 1e6 156 | ) 157 | if args.input_file.name.endswith(".gz"): 158 | lines = gzip.open(args.input_file.open("rb"), "rt") 159 | else: 160 | lines = args.input_file.open("rt") 161 | 162 | if args.limit: 163 | lines = itertools.islice(lines, args.limit) 164 | 165 | lines = list(lines) 166 | compressed_file = args.output_file 167 | if args.output_file.suffix != ".gz": 168 | compressed_file = compressed_file + '.gz' 169 | with gzip.open(str(compressed_file), "wt") as output: 170 | for line in tqdm(lines, unit="lines", disable=args.quiet): 171 | try: 172 | s = json.loads(line) 173 | if args.filter_schema and not filter_line(s, {"schema": args.filter_schema, "schemaName": args.filter_schema}): 174 | continue 175 | 176 | if obfuscate: 177 | json.dump(process_line(s, obfuscator_dict), output) 178 | else: 179 | json.dump(s, output) 180 | output.write("\n") 181 | except Exception: 182 | log.exception("failed to process {}", line) 183 | if args.fail_on_error: 184 | raise 185 | if not args.quiet: 186 | log.info("{} processing done", len(lines)) 187 | if args.rename_schemas: 188 | log.info("Schemas translation table:\n{}", schema_obfuscator) 189 | if args.rename_catalogs: 190 | log.info("Catalogs translation table:\n{}", catalog_obfuscator) 191 | if args.rename_user: 192 | log.info("Users translation table:\n{}", user_obfuscator) 193 | if args.rename_partitions: 194 | log.info("Partitions translation table:\n{}", partitions_obfuscator) 195 | 196 | 197 | if __name__ == "__main__": 198 | main() 199 | -------------------------------------------------------------------------------- /analyzer/extract.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | # Copyright (c) 2019-2022 Varada, Inc. 4 | # This file is part of Presto Workload Analyzer. 5 | # 6 | # Presto Workload Analyzer is free software: you can redistribute it and/or modify 7 | # it under the terms of the GNU General Public License as published by 8 | # the Free Software Foundation, either version 3 of the License, or 9 | # (at your option) any later version. 10 | # 11 | # Presto Workload Analyzer is distributed in the hope that it will be useful, 12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | # GNU General Public License for more details. 15 | # 16 | # You should have received a copy of the GNU General Public License 17 | # along with Presto Workload Analyzer. If not, see . 18 | 19 | import argparse 20 | import gzip 21 | import json 22 | import logbook 23 | import pathlib 24 | import sys 25 | import tqdm 26 | 27 | logbook.StreamHandler(sys.stderr).push_application() 28 | log = logbook.Logger("extract") 29 | 30 | TIME_UNITS = [ 31 | ("ns", 1e-9), 32 | ("ms", 1e-3), 33 | ("us", 1e-6), 34 | ("s", 1), 35 | ("m", 60), 36 | ("h", 60 * 60), 37 | ("d", 60 * 60 * 24), 38 | ] 39 | 40 | SIZE_UNITS = [ 41 | ("TB", 1024 * 1024 * 1024 * 1024), 42 | ("GB", 1024 * 1024 * 1024), 43 | ("MB", 1024 * 1024), 44 | ("kB", 1024), 45 | ("B", 1), 46 | ] 47 | 48 | 49 | def parse_units(s, units): 50 | if s is None: 51 | return None 52 | for suffix, factor in units: 53 | if s.endswith(suffix): 54 | return float(s[: -len(suffix)]) * factor 55 | return float(s) 56 | 57 | 58 | def parse_size(s): 59 | return parse_units(s, SIZE_UNITS) 60 | 61 | 62 | def parse_time(s): 63 | return parse_units(s, TIME_UNITS) 64 | 65 | 66 | def get_operators(summaries): 67 | for s in summaries: 68 | try: 69 | yield dict( 70 | node_id=s["planNodeId"], 71 | type=s["operatorType"], 72 | input_size=parse_size(s.get("rawInputDataSize") or s.get("inputDataSize")) 73 | or parse_size(s["inputDataSize"]), 74 | output_size=parse_size(s["outputDataSize"]), 75 | network_size=parse_size(s.get("internalNetworkInputDataSize")), 76 | input_rows=s.get("rawInputPositions", 0) or s.get("inputPositions", 0), 77 | output_rows=s["outputPositions"], 78 | network_rows=s.get("internalNetworkInputPositions"), 79 | peak_mem=parse_size(s.get("peakTotalMemoryReservation")) if 'peakTotalMemoryReservation' in s else 0, 80 | input_cpu=parse_time(s["addInputCpu"]), 81 | output_cpu=parse_time(s["getOutputCpu"]), 82 | finish_cpu=parse_time(s["finishCpu"]), 83 | input_wall=parse_time(s["addInputWall"]), 84 | output_wall=parse_time(s["getOutputWall"]), 85 | finish_wall=parse_time(s["finishWall"]), 86 | blocked_wall=parse_time(s["blockedWall"]) 87 | # TODO: wait time 88 | ) 89 | except KeyError: 90 | log.exception("missing key for {}", s) 91 | raise 92 | 93 | 94 | def iter_plans(stage): 95 | p = stage.get("plan") 96 | if p: 97 | yield {k: p[k] for k in ["id", "root"]} 98 | for substage in stage["subStages"]: 99 | yield from iter_plans(substage) 100 | 101 | 102 | def build_tasks_in_substages(stage): 103 | substages = [] 104 | for sub in stage.get('subStages', []): 105 | sub_stage_tasks = [] 106 | for task in sub.get('tasks', []): 107 | task_stats = {} 108 | for k in ['totalScheduledTime', 'totalCpuTime', 'totalBlockedTime']: 109 | task_stats[k] = parse_time(task.get('stats', {}).get(k)) 110 | task_status = {} 111 | for k in ['taskId', 'state', 'self']: 112 | task_status[k] = task.get('taskStatus', {}).get(k) 113 | task_data = dict( 114 | taskStatus=task_status, 115 | stats=task_stats) 116 | sub_stage_tasks.append(task_data) 117 | substages.append(dict( 118 | tasks=sub_stage_tasks, 119 | subStages=build_tasks_in_substages(sub))) 120 | return substages 121 | 122 | 123 | def summary(j: dict): 124 | session = j["session"] 125 | stats = j["queryStats"] 126 | 127 | if session.get('catalogProperties', {}).get('varada', {}).get('internal_query', '') == 'true': 128 | # varada internal query - skip it 129 | return None 130 | 131 | fragments = None 132 | substages = None 133 | stage = j.get("outputStage") 134 | if stage: 135 | fragments = list(iter_plans(stage)) 136 | substages = build_tasks_in_substages(stage) 137 | 138 | try: 139 | return dict( 140 | query=j["query"], 141 | query_id=j["queryId"], 142 | user=session["user"], 143 | state=j["state"], 144 | error_code=j.get("errorCode"), 145 | update=j.get("updateType"), 146 | elapsed_time=parse_time(stats["elapsedTime"]), 147 | cpu_time=parse_time(stats["totalCpuTime"]), 148 | scheduled_time=parse_time(stats["totalScheduledTime"]), 149 | blocked_time=parse_time(stats["totalBlockedTime"]), 150 | input_size=( 151 | parse_size(stats["rawInputDataSize"]) 152 | or parse_size(stats.get("inputDataSize")) 153 | or 0 154 | ), 155 | output_size=parse_size(stats["outputDataSize"]), 156 | network_size=parse_size(stats.get("internalNetworkInputDataSize")), 157 | input_rows=stats["rawInputPositions"], 158 | output_rows=stats["outputPositions"], 159 | network_rows=stats.get("internalNetworkInputPositions"), 160 | peak_mem=parse_size(stats["peakTotalMemoryReservation"]), 161 | written_size=parse_size(stats.get("rawWrittenDataSize")), 162 | operators=list(get_operators(stats["operatorSummaries"])), 163 | inputs=j["inputs"], 164 | output=j.get("output"), 165 | fragments=fragments, 166 | substages=substages 167 | ) 168 | except KeyError: 169 | log.warning("missing key for {}", stats) 170 | 171 | 172 | def main(): 173 | p = argparse.ArgumentParser() 174 | p.add_argument("-i", "--input-dir", type=pathlib.Path) 175 | p.add_argument("-l", "--limit", type=int) 176 | p.add_argument("-q", "--quiet", action="store_true", default=False) 177 | args = p.parse_args() 178 | 179 | paths = [ 180 | p for pattern in ["*.json", "*.json.gz"] for p in args.input_dir.glob(pattern) 181 | ] 182 | log.info("{} JSONs found at {}", len(paths), args.input_dir.absolute()) 183 | paths = sorted(paths) 184 | if args.limit is not None: 185 | paths = paths[: args.limit] 186 | 187 | items = [(p, p.stat().st_size) for p in paths] 188 | total_size = sum(i[1] for i in items) 189 | compressed_file = args.input_dir / "summary.jsonl.gz" 190 | with gzip.open(str(compressed_file), "wt") as output: 191 | with tqdm.tqdm(total=total_size, unit="B", unit_scale=True, disable=args.quiet) as pbar: 192 | for path, size in items: 193 | input_file = ( 194 | gzip.open(str(path), "rt") 195 | if path.name.endswith(".gz") 196 | else path.open("rt") 197 | ) 198 | with input_file as f: 199 | try: 200 | s = summary(json.load(f)) 201 | if s: 202 | json.dump(s, output) 203 | output.write("\n") 204 | except ValueError: 205 | log.info('Got a non-valid JSON file, discarding this JSON file') 206 | pbar.update(size) 207 | 208 | log.info( 209 | "Extracted {} JSONs into {} ({:.3f} MB in GZipped JSONL format)", 210 | len(paths), 211 | output.name, 212 | compressed_file.stat().st_size / 1e6, 213 | ) 214 | 215 | 216 | if __name__ == "__main__": 217 | main() 218 | -------------------------------------------------------------------------------- /analyzer/output.template.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | VARADA Workload Analysis Report 23 | 26 | 27 | 28 | 29 | 118 | 119 | 120 | 121 | 122 | 125 | 126 | 490 | 518 |
519 | Query Id copied to clipboard 520 |
521 |
522 | 523 |
524 | 525 | 528 | 530 | 531 | 532 | 533 | 546 | 547 | 548 |
549 | 550 | 551 |
552 |
553 | Rendering... 554 |
555 |
556 |
557 |
558 |
559 |
560 | 561 | 713 |
714 | 715 | 716 | -------------------------------------------------------------------------------- /COPYING: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . -------------------------------------------------------------------------------- /analyzer/analyze.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | # Copyright (c) 2019-2022 Varada, Inc. 4 | # This file is part of Presto Workload Analyzer. 5 | # 6 | # Presto Workload Analyzer is free software: you can redistribute it and/or modify 7 | # it under the terms of the GNU General Public License as published by 8 | # the Free Software Foundation, either version 3 of the License, or 9 | # (at your option) any later version. 10 | # 11 | # Presto Workload Analyzer is distributed in the hope that it will be useful, 12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | # GNU General Public License for more details. 15 | # 16 | # You should have received a copy of the GNU General Public License 17 | # along with Presto Workload Analyzer. If not, see . 18 | 19 | 20 | import argparse 21 | import collections 22 | import datetime 23 | import gzip 24 | import itertools 25 | import json 26 | import logbook 27 | import numpy 28 | import pathlib 29 | import re 30 | import sys 31 | import zipfile 32 | from tqdm import tqdm 33 | from inspect import signature 34 | 35 | logbook.StreamHandler(sys.stderr).push_application() 36 | log = logbook.Logger("analyze") 37 | 38 | from bokeh.embed import json_item 39 | from bokeh.models import ColumnDataSource, TapTool, Span, Slope, ranges, LabelSet 40 | from bokeh.models.callbacks import CustomJS 41 | from bokeh.palettes import Category20c, Category10, Colorblind 42 | from bokeh.plotting import figure, output_file, save 43 | 44 | 45 | def groupby(keys, values, reducer): 46 | result = collections.defaultdict(list) 47 | for k, v in zip(keys, values): 48 | result[k].append(v) 49 | result = [(k, reducer(vs)) for k, vs in result.items()] 50 | result.sort() 51 | return result 52 | 53 | 54 | _ANALYZERS = [] 55 | 56 | 57 | def run(func): 58 | _ANALYZERS.append(func) 59 | return func 60 | 61 | 62 | def query_datetime(query_id): 63 | return datetime.datetime.strptime(query_id[:15], "%Y%m%d_%H%M%S") 64 | 65 | 66 | def trunc_hour(dt): 67 | return datetime.datetime(dt.year, dt.month, dt.day, dt.hour) 68 | 69 | 70 | def trunc_date(dt): 71 | return datetime.datetime(dt.year, dt.month, dt.day) 72 | 73 | 74 | TOOLS = "tap,pan,wheel_zoom,box_zoom,save,reset" 75 | TOOLS_SIMPLE = "save,reset" 76 | 77 | COPY_JS = """ 78 | const values = source.data['copy_on_tap']; 79 | copyToClipboard(values[source.selected.indices[0]]); 80 | """ # copyToClipboard() is defined in output.template.html 81 | 82 | 83 | @run 84 | def scheduled_by_date(stats): 85 | """ 86 | Shows cluster scheduled time by date, useful for high-level trend analysis. 87 | """ 88 | scheduled_cores = [s["scheduled_time"] / (60 * 60 * 24) for s in stats] 89 | date = [query_datetime(s["query_id"]) for s in stats] 90 | date = [trunc_date(d) for d in date] 91 | date, scheduled_cores = zip(*groupby(date, scheduled_cores, sum)) 92 | p = figure( 93 | title="Scheduled time by date", 94 | x_axis_label="Date", 95 | y_axis_label="Average scheduled cores", 96 | x_axis_type="datetime", 97 | sizing_mode="scale_width" 98 | ) 99 | p.vbar(x=date, top=scheduled_cores, width=24 * 3600e3) 100 | return p 101 | 102 | 103 | def add_constant_line(p, dim, value, line_color='black', 104 | line_dash='dashed', line_width=2): 105 | constant_line_value = value 106 | constant_line = Span(location=constant_line_value, 107 | dimension=dim, line_color=line_color, 108 | line_dash=line_dash, line_width=line_width) 109 | p.add_layout(constant_line) 110 | 111 | 112 | @run 113 | def scheduled_by_hour(stats): 114 | """ 115 | Shows cluster scheduled time by the hour, useful for low-level trend analysis. 116 | """ 117 | scheduled_cores = [s["scheduled_time"] / (60 * 60) for s in stats] 118 | date = [query_datetime(s["query_id"]) for s in stats] 119 | date = [trunc_hour(d) for d in date] 120 | 121 | date, scheduled_cores = zip(*groupby(date, scheduled_cores, sum)) 122 | p = figure( 123 | title="Scheduled time by hour", 124 | x_axis_label="Time", 125 | y_axis_label="Average scheduled cores", 126 | x_axis_type="datetime", 127 | sizing_mode="scale_width", 128 | ) 129 | p.vbar(x=date, top=scheduled_cores, width=3600e3) 130 | return p 131 | 132 | 133 | @run 134 | def input_by_date(stats): 135 | """ 136 | Shows cluster input bytes read by date, useful for high-level trend analysis. 137 | """ 138 | input_size = [s["input_size"] / (1e12) for s in stats] 139 | date = [query_datetime(s["query_id"]) for s in stats] 140 | date = [trunc_date(d) for d in date] 141 | 142 | date, input_size_by_date = zip(*groupby(date, input_size, sum)) 143 | p = figure( 144 | title="Input data read by date", 145 | x_axis_label="Date", 146 | y_axis_label="Input [TB]", 147 | x_axis_type="datetime", 148 | sizing_mode="scale_width", 149 | ) 150 | p.vbar(x=date, top=input_size_by_date, width=24 * 3600e3) 151 | return p 152 | 153 | 154 | @run 155 | def input_by_hour(stats): 156 | """ 157 | Shows cluster input bytes read by the hour, useful for low-level trend analysis. 158 | """ 159 | input_size = [s["input_size"] / (1e12) for s in stats] 160 | date = [query_datetime(s["query_id"]) for s in stats] 161 | date = [trunc_hour(d) for d in date] 162 | 163 | date, input_size_by_date = zip(*groupby(date, input_size, sum)) 164 | p = figure( 165 | title="Input data read by hour", 166 | x_axis_label="Time", 167 | y_axis_label="Input [TB]", 168 | x_axis_type="datetime", 169 | sizing_mode="scale_width", 170 | ) 171 | p.vbar(x=date, top=input_size_by_date, width=3600e3) 172 | return p 173 | 174 | 175 | @run 176 | def queries_by_date(stats): 177 | """ 178 | Shows the number of queries running on the cluster by date, useful for high-level trend analysis. 179 | """ 180 | ids = [s["query_id"] for s in stats] 181 | date = [query_datetime(s["query_id"]) for s in stats] 182 | date = [trunc_date(d) for d in date] 183 | 184 | date, queries_by_date = zip(*groupby(date, [1] * len(date), sum)) 185 | p = figure( 186 | title="Number of queries ran by date", 187 | x_axis_label="Date", 188 | y_axis_label="Number of queries", 189 | x_axis_type="datetime", 190 | sizing_mode="scale_width", 191 | ) 192 | p.vbar(x=date, top=queries_by_date, width=24 * 3600e3) 193 | return p 194 | 195 | 196 | @run 197 | def queries_by_hour(stats): 198 | """ 199 | Shows the number of queries running on the cluster by hour, useful for low-level trend analysis. 200 | """ 201 | ids = [s["query_id"] for s in stats] 202 | date = [query_datetime(s["query_id"]) for s in stats] 203 | date = [trunc_hour(d) for d in date] 204 | 205 | date, queries_by_date = zip(*groupby(date, [1] * len(date), sum)) 206 | p = figure( 207 | title="Number of queries ran by hour", 208 | x_axis_label="Time", 209 | y_axis_label="Number of queries", 210 | x_axis_type="datetime", 211 | sizing_mode="scale_width", 212 | ) 213 | p.vbar(x=date, top=queries_by_date, width=3600e3) 214 | return p 215 | 216 | 217 | @run 218 | def peak_mem_by_query(stats): 219 | """ 220 | Shows the peak memory used by each query as a function of time. 221 | Allow quick analysis of memory utilization patterns by different queries. 222 | 223 | Optimization Tip - Queries above the dashed black line use more than 10GB of memory and investigation is recommended. 224 | """ 225 | peak_mem = [s["peak_mem"] for s in stats] 226 | query_ids = [s["query_id"] for s in stats] 227 | date = [query_datetime(query_id) for query_id in query_ids] 228 | p = figure( 229 | title="Peak memory used by queries", 230 | x_axis_label="Time", 231 | x_axis_type="datetime", 232 | y_axis_label="Query peak memory [B]", 233 | y_axis_type="log", 234 | sizing_mode="scale_width", 235 | tools=TOOLS, 236 | ) 237 | p.yaxis.ticker = [1, 1e3, 1e6, 1e9, 1e10, 1e12] 238 | 239 | source = ColumnDataSource(dict(peak_mem=peak_mem, date=date, copy_on_tap=query_ids)) 240 | p.select(type=TapTool).callback = CustomJS(args=dict(source=source), code=COPY_JS) 241 | p.circle("date", "peak_mem", source=source, alpha=0.5) 242 | add_constant_line(p, 'width', 1e10) 243 | return p 244 | 245 | 246 | @run 247 | def input_size_by_query(stats): 248 | """ 249 | Shows the input bytes read by each query as a function of time. 250 | Allow quick analysis of input patterns by different queries. 251 | 252 | Optimization Tip - Queries above the dashed black line read more than 1TB of data. 253 | Consider using indexing/partitioning to reduce the amount of data being read and make sure predicates are being pushed-down. 254 | 255 | """ 256 | input_size = [s["input_size"] for s in stats] 257 | query_ids = [s["query_id"] for s in stats] 258 | date = [query_datetime(query_id) for query_id in query_ids] 259 | p = figure( 260 | title="Input data read by queries", 261 | x_axis_label="Time", 262 | x_axis_type="datetime", 263 | y_axis_label="Input data read [B]", 264 | y_axis_type="log", 265 | sizing_mode="scale_width", 266 | tools=TOOLS, 267 | ) 268 | p.yaxis.ticker = [1, 1e3, 1e6, 1e9, 1e12] 269 | 270 | source = ColumnDataSource(dict(input_size=input_size, date=date, copy_on_tap=query_ids)) 271 | p.select(type=TapTool).callback = CustomJS(args=dict(source=source), code=COPY_JS) 272 | p.circle("date", "input_size", source=source, alpha=0.5) 273 | add_constant_line(p, 'width', 1e12) 274 | return p 275 | 276 | 277 | @run 278 | def elapsed_time_by_query(stats): 279 | """ 280 | Shows the elapsed time of each query as a function of the query execution time. 281 | Allows quick analysis of client-side latency by different queries. 282 | 283 | Optimization Tip - Queries above the dashed black line take more than 5 minutes, consider optimizing them. 284 | """ 285 | elapsed_time = [s["elapsed_time"] for s in stats] 286 | query_ids = [s["query_id"] for s in stats] 287 | date = [query_datetime(query_id) for query_id in query_ids] 288 | p = figure( 289 | title="Elapsed time by queries", 290 | x_axis_label="Time", 291 | x_axis_type="datetime", 292 | y_axis_label="Elapsed time [s]", 293 | y_axis_type="log", 294 | sizing_mode="scale_width", 295 | tools=TOOLS, 296 | ) 297 | p.yaxis.ticker = [1e-3, 1, 1e3, 1e6] 298 | source = ColumnDataSource(dict(elapsed_time=elapsed_time, date=date, copy_on_tap=query_ids)) 299 | p.select(type=TapTool).callback = CustomJS(args=dict(source=source), code=COPY_JS) 300 | p.circle("date", "elapsed_time", source=source, alpha=0.5) 301 | add_constant_line(p, 'width', 300) 302 | return p 303 | 304 | 305 | @run 306 | def queries_by_user(stats): 307 | """ 308 | The fraction of queries executed by each user. 309 | Can be used to understand which users are responsible for the bulk of the queries running on the cluster. 310 | """ 311 | users = [s["user"] for s in stats] 312 | 313 | items = groupby(users, [1] * len(users), sum) 314 | items.sort(key=lambda i: i[1], reverse=True) 315 | users, queries_by_user = zip(*items) 316 | return pie_chart( 317 | keys=users, values=queries_by_user, title="Number of queries by user" 318 | ) 319 | 320 | 321 | @run 322 | def scheduled_by_user(stats): 323 | """ 324 | The fraction of scheduled time by user. 325 | Can be used to understand which users are responsible for most of the scheduled time of queries running on the cluster. 326 | """ 327 | scheduled_days = [s["scheduled_time"] / (60 * 60 * 24) for s in stats] 328 | users = [s["user"] for s in stats] 329 | 330 | items = groupby(users, scheduled_days, sum) 331 | items.sort(key=lambda i: i[1], reverse=True) 332 | users, scheduled_days_per_user = zip(*items) 333 | return pie_chart( 334 | keys=users, values=scheduled_days_per_user, title="Scheduled time by user" 335 | ) 336 | 337 | 338 | @run 339 | def scheduled_by_update(stats): 340 | """ 341 | The fraction of scheduled time by query type (e.g. INSERT, SELECT, CREATE TABLE). 342 | Can be used to understand which query type uses the most scheduled time on the cluster. 343 | """ 344 | scheduled_days = [s["scheduled_time"] / (60 * 60 * 24) for s in stats] 345 | update = [(s["update"] or "SELECT") for s in stats] 346 | 347 | items = groupby(update, scheduled_days, sum) 348 | items.sort(key=lambda i: i[1], reverse=True) 349 | update, scheduled_time_per_update = zip(*items) 350 | return pie_chart( 351 | keys=update, 352 | values=scheduled_time_per_update, 353 | title="Scheduled time by query type", 354 | ) 355 | 356 | 357 | @run 358 | def input_by_user(stats): 359 | """ 360 | The fraction of input bytes read by each user. 361 | Can be used to understand which users are responsible for the most I/O utilization on the cluster. 362 | """ 363 | input_size = [s["input_size"] / 1e12 for s in stats] 364 | users = [s["user"] for s in stats] 365 | 366 | items = groupby(users, input_size, sum) 367 | items.sort(key=lambda i: i[1], reverse=True) 368 | users, input_size_per_user = zip(*items) 369 | return pie_chart( 370 | keys=users, values=input_size_per_user, title="Input data read by user" 371 | ) 372 | 373 | 374 | @run 375 | def output_vs_input(stats): 376 | """ 377 | Shows the queries using a scatter plot of the input bytes read (x coordinate) and output bytes written (y coordinate). 378 | Can be useful for detecting "ETL-like" jobs (reading and writing a lot of data), and separating them from more 379 | "interactive-like" jobs (which usually result in much less data being read). 380 | """ 381 | source = ColumnDataSource(dict( 382 | input_size=[s["input_size"] for s in stats], 383 | output_size=[s["output_size"] for s in stats], 384 | copy_on_tap=[s["query_id"] for s in stats] 385 | )) 386 | p = figure( 387 | title="Output size vs input size", 388 | x_axis_label="Input size [B]", 389 | y_axis_label="Output size [B]", 390 | x_axis_type="log", 391 | y_axis_type="log", 392 | sizing_mode="scale_width", 393 | tools=TOOLS, 394 | ) 395 | p.xaxis.ticker = [1, 1e3, 1e6, 1e9, 1e12] 396 | p.yaxis.ticker = [1, 1e3, 1e6, 1e9, 1e12] 397 | p.select(type=TapTool).callback = CustomJS(args=dict(source=source), code=COPY_JS) 398 | p.circle("input_size", "output_size", source=source) 399 | return p 400 | 401 | 402 | @run 403 | def scheduled_vs_input(stats): 404 | """ 405 | Shows the queries using a scatter plot of the input bytes read (x coordinate) and scheduled time used (y coordinate). 406 | Can be useful for detecting queries that read a lot of data, and require significant scheduled time. 407 | """ 408 | source = ColumnDataSource(dict( 409 | input_size=[s["input_size"] for s in stats], 410 | scheduled_time=[s["scheduled_time"] for s in stats], 411 | copy_on_tap=[s["query_id"] for s in stats] 412 | )) 413 | p = figure( 414 | title="Scheduled time vs input size", 415 | x_axis_label="Input size [B]", 416 | y_axis_label="Scheduled time", 417 | x_axis_type="log", 418 | y_axis_type="log", 419 | sizing_mode="scale_width", 420 | tools=TOOLS, 421 | ) 422 | p.xaxis.ticker = [1, 1e3, 1e6, 1e9, 1e12] 423 | yticks = [1e-3, 1, 60, 60 * 60, 24 * 60 * 60] 424 | p.yaxis.ticker = yticks 425 | p.yaxis.major_label_overrides = dict(zip(yticks, ["1ms", "1s", "1m", "1h", "1d"])) 426 | p.select(type=TapTool).callback = CustomJS(args=dict(source=source), code=COPY_JS) 427 | p.circle("input_size", "scheduled_time", source=source) 428 | return p 429 | 430 | 431 | @run 432 | def elapsed_vs_input(stats): 433 | """ 434 | Shows the queries using a scatter plot of the input bytes read (x coordinate) and their client-side duration (y coordinate). 435 | Can be useful for detecting queries that read a lot of data and have significant user latency. 436 | """ 437 | source = ColumnDataSource(dict( 438 | input_size=[s["input_size"] for s in stats], 439 | elapsed_time=[s["elapsed_time"] for s in stats], 440 | copy_on_tap=[s["query_id"] for s in stats] 441 | )) 442 | p = figure( 443 | title="Elapsed time vs input size", 444 | x_axis_label="Input size [B]", 445 | y_axis_label="Elapsed time", 446 | x_axis_type="log", 447 | y_axis_type="log", 448 | sizing_mode="scale_width", 449 | tools=TOOLS, 450 | ) 451 | p.xaxis.ticker = [1, 1e3, 1e6, 1e9, 1e12] 452 | yticks = [1e-3, 1, 60, 60 * 60, 24 * 60 * 60] 453 | p.yaxis.ticker = yticks 454 | p.yaxis.major_label_overrides = dict(zip(yticks, ["1ms", "1s", "1m", "1h", "1d"])) 455 | p.select(type=TapTool).callback = CustomJS(args=dict(source=source), code=COPY_JS) 456 | p.circle("input_size", "elapsed_time", source=source) 457 | return p 458 | 459 | 460 | def pie_chart(keys, values, title, top=20): 461 | values = numpy.array(values) 462 | sum_values = values.sum() 463 | if not sum_values: 464 | return 465 | percent = 100 * values / sum_values 466 | relevant = (percent > 0.1) & (numpy.arange(len(keys)) < top - 1) 467 | 468 | keys = [t for r, t in zip(relevant, keys) if r] 469 | if numpy.any(~relevant): 470 | keys.append("All the rest") 471 | values = numpy.concatenate((values[relevant], [values[~relevant].sum()])) 472 | percent = 100 * values / values.sum() 473 | 474 | # make sure percent.sum() == 100% 475 | percent = percent.round(2) 476 | percent[-1] += (100 - percent.sum()) 477 | 478 | angle = 2 * numpy.pi * numpy.concatenate(([0], percent.cumsum() / percent.sum())) 479 | 480 | p = figure( 481 | title=title, 482 | width=800, 483 | tooltips="@labels", 484 | tools="hover", 485 | toolbar_location=None, 486 | x_range=(-2, 1), 487 | sizing_mode="scale_width", 488 | ) 489 | k = max(3, len(keys)) 490 | color = Category20c[k][: len(keys)] 491 | data = ColumnDataSource( 492 | dict( 493 | start=angle[:-1], 494 | end=angle[1:], 495 | keys=keys, 496 | color=color, 497 | percent=percent, 498 | labels=["{} {:.2f}%".format(shorten(k), p) for k, p in zip(keys, percent)], 499 | ) 500 | ) 501 | p.wedge( 502 | x=-1, 503 | y=0, 504 | radius=0.8, 505 | start_angle="start", 506 | end_angle="end", 507 | fill_color="color", 508 | line_color="white", 509 | legend_field="labels", 510 | source=data, 511 | ) 512 | p.axis.axis_label = None 513 | p.axis.visible = False 514 | p.grid.grid_line_color = None 515 | return p 516 | 517 | 518 | def shorten(s): 519 | if len(s) > 30: 520 | s = s[:30] + "..." 521 | return s 522 | 523 | 524 | @run 525 | def operator_wall(stats, top=20): 526 | """ 527 | The fraction of wall time usage (CPU and waiting) by each Presto operator. 528 | Can be used to understand the amount of wall time used by each part of the query processing - e.g. scan/join/aggreggation. 529 | """ 530 | operators = [op for s in stats for op in s["operators"]] 531 | types = [op["type"].replace("Operator", "") for op in operators] 532 | selectivity = [ 533 | op["output_rows"] / op["input_rows"] for op in operators if op["input_rows"] 534 | ] 535 | wall = [ 536 | op["input_wall"] + op["output_wall"] + op["finish_wall"] for op in operators 537 | ] 538 | items = groupby(types, wall, sum) 539 | items.sort(key=lambda item: item[1], reverse=True) 540 | types, total_wall = zip(*items) 541 | return pie_chart( 542 | keys=types, values=total_wall, title="Wall time usage by operator type" 543 | ) 544 | 545 | 546 | def scan_operators(operators): 547 | for op in operators: 548 | if "Scan" in op["type"]: 549 | yield op 550 | 551 | 552 | def scanfilter_operators(operators): 553 | for op in operators: 554 | if "ScanFilter" in op["type"]: 555 | yield op 556 | 557 | 558 | def last_element(iterator): 559 | for element in iterator: 560 | pass 561 | return element 562 | 563 | 564 | def parse_table_name(scan_node): 565 | table = scan_node["table"] 566 | handle = table["connectorHandle"] 567 | schema_table_name = handle.get("schemaTableName") 568 | if schema_table_name: 569 | schema_name = schema_table_name["schema"] 570 | table_name = schema_table_name["table"] 571 | else: 572 | schema_name = handle.get("schemaName") # may be missing 573 | table_name = handle.get("tableName") or handle.get("table") 574 | if table_name is None and handle.get("id",None): 575 | # MemoryTableHandle doesn't contain its name in PrestoSQL 306+ 576 | table_name = "{}:{}".format(handle["@type"], handle["id"]) 577 | if isinstance(table_name, dict): # JMX may contain schema information here 578 | schema_name = table_name["schema"] 579 | table_name = table_name["table"] 580 | 581 | connector_id = table.get("connectorId") or table.get("catalogHandle",None) or table.get("catalogName",None) 582 | values = [connector_id, schema_name, table_name] 583 | values = [v for v in values if v is not None] 584 | return ".".join(values) 585 | 586 | 587 | @run 588 | def wall_by_table_scan(stats): 589 | """ 590 | The fraction of wall time used to scan the top K tables. 591 | Useful for detecting the tables scanned the most. 592 | """ 593 | tables = [] 594 | wall = [] 595 | for s in stats: 596 | node_map = {node["id"]: node for node in nodes_from_stats(s)} 597 | for op in scan_operators(s["operators"]): 598 | node_id = op["node_id"] 599 | node = node_map[node_id] 600 | scan_node = last_element( 601 | iter_nodes(node) 602 | ) # DFS to get the "lowest" table scan node 603 | try: 604 | table_name = parse_table_name(scan_node) 605 | except KeyError as e: 606 | log.error("node: {}", scan_node) 607 | raise 608 | tables.append(table_name) 609 | wall.append(op["input_wall"] + op["output_wall"] + op["finish_wall"]) 610 | 611 | if not tables: 612 | return 613 | 614 | items = groupby(tables, wall, sum) 615 | items.sort(key=lambda item: item[1], reverse=True) 616 | tables, total_wall = zip(*items) 617 | return pie_chart( 618 | keys=tables, values=total_wall, title="Wall time utilization by table scan" 619 | ) 620 | 621 | 622 | def wall_by_selectivity_bins(stats, bins=10, max_selectivity=1, title="Wall time of table scans by selectivity bins"): 623 | selectivity = [] 624 | wall = [] 625 | for s in stats: 626 | node_map = {node["id"]: node for node in nodes_from_stats(s)} 627 | for op in scan_operators(s["operators"]): 628 | node_id = op["node_id"] 629 | node = node_map[node_id] 630 | if op["input_rows"]: 631 | wall.append(op["input_wall"] + op["output_wall"] + op["finish_wall"]) 632 | selectivity.append(op["output_rows"] / op["input_rows"]) 633 | 634 | if not selectivity: 635 | return 636 | 637 | bin_step = 1. / bins 638 | 639 | wall = numpy.array(wall) 640 | selectivity_bins = numpy.abs(numpy.round(numpy.array(selectivity) - bin_step / 2, 1)) 641 | 642 | # each bin should be represented 643 | wall = numpy.append(wall, numpy.zeros(bins)) 644 | selectivity_bins = numpy.append(selectivity_bins, numpy.arange(0, max_selectivity, bin_step)) 645 | 646 | # convert bin to string for representation 647 | selectivity_bins = numpy.array([ 648 | '%0.2f' % x if x <= max_selectivity + 1e-9 else "Above" for x in selectivity_bins]) 649 | # convert total_wall to percentage for representation 650 | wall = wall / wall.sum() * 100 651 | 652 | items = groupby(selectivity_bins, wall, sum) 653 | items.sort(key=lambda item: item[0]) 654 | selectivity_bins, total_wall = zip(*items) 655 | 656 | tooltips = ['Selectivity %0.2f-%0.2f: %0.2f%% of wall time' % (float(x), float(x) + bin_step, y) for (x, y) in 657 | zip(selectivity_bins, total_wall) if x != 'Above'] 658 | if 'Above' == selectivity_bins[-1]: 659 | tooltips.append('Selectivity above %0.2f: %0.2f%% of wall time' % (float(selectivity_bins[-2]), total_wall[-1])) 660 | 661 | source = ColumnDataSource(dict( 662 | x=selectivity_bins, 663 | top=total_wall, 664 | text=['%0.1f%%' % x for x in total_wall], 665 | tooltips=tooltips)) 666 | 667 | p = figure( 668 | width=800, 669 | title=title, 670 | x_axis_label="Selectivity Bin", 671 | y_axis_label="Wall time (%)", 672 | sizing_mode="scale_width", 673 | x_range=selectivity_bins, 674 | y_range=(0, 100), 675 | tools=TOOLS_SIMPLE, 676 | tooltips='@tooltips') 677 | 678 | labels = LabelSet(x='x', y='top', text='text', level='glyph', 679 | x_offset=-800 / len(selectivity_bins) / 4, y_offset=5, source=source, render_mode='canvas', 680 | text_font_size="10pt") 681 | 682 | p.vbar(source=source, x='x', top='top', width=1, line_width=1, line_color='black') 683 | 684 | p.add_layout(labels) 685 | 686 | return p 687 | 688 | 689 | @run 690 | def wall_by_selectivity_10(stats): 691 | """ 692 | The scan wall time percentage for each selectivity bin - 0.1 sized bins. Selectivity is defined as output_rows / input_rows, so the bin for 0.20 would mean selecting between 20% to 30% of the data. 693 | Useful for detecting whether predicate pushdown is effecient. If most scans are not very selective (selectivity above 0.8, up to a full scan which is selectivity 1) then predicate pushdown is effecient and the filtering is taken care of at the data source and not by Presto. 694 | """ 695 | return wall_by_selectivity_bins(stats) 696 | 697 | 698 | @run 699 | def wall_by_selectivity_100_first_20(stats): 700 | """ 701 | The scan wall time percentage for each selectivity bin - with focus on the most selective queries with small 0.01 bins. Selectivity is defined as output_rows / input_rows, so the bin for 0.02 would mean selecting between 2% to 3% of the data. 702 | Useful for understading predicate pushdown effeciency in high selectivity cases. 703 | """ 704 | return wall_by_selectivity_bins(stats, bins=100, max_selectivity=0.2, 705 | title="Wall time of table scans by selectivity bins (very selective)") 706 | 707 | 708 | def _get_colors(colorblind=False): 709 | return Colorblind[8] if colorblind else Category10[10] 710 | 711 | 712 | def _get_size(colorblind=False): 713 | return 8 if colorblind else 4 714 | 715 | 716 | @run 717 | def filter_selectivity_1(stats): 718 | """ 719 | Shows the selectivity of filter operators, which is the fraction of rows left after filtering is over. 720 | It plots the output number of rows as a function of the input number of rows, so non-selective filters will be near the y=x line, and highly selective filters will be significantly below it. 721 | Such highly selective filters are excellent candidates for predicate push-down, enabled by Varada Inline Indexing. 722 | """ 723 | 724 | data = {} 725 | for s in stats: 726 | for op in s["operators"]: 727 | if "Filter" in op["type"]: 728 | data.setdefault("input_rows", []).append(op["input_rows"]) 729 | data.setdefault("output_rows", []).append(op["output_rows"]) 730 | data.setdefault("copy_on_tap", []).append(s["query_id"]) 731 | 732 | source = ColumnDataSource(data) 733 | p = figure( 734 | title="Input and output rows for filtering operators", 735 | x_axis_label="Number of input rows", 736 | x_axis_type="log", 737 | y_axis_label="Number of output rows", 738 | y_axis_type="log", 739 | sizing_mode="scale_width", 740 | tools=TOOLS, 741 | ) 742 | p.circle(x="input_rows", y="output_rows", alpha=0.5, source=source) 743 | p.select(type=TapTool).callback = CustomJS(args=dict(source=source), code=COPY_JS) 744 | return p 745 | 746 | 747 | @run 748 | def walltime_vs_selectivity(stats, topK=5, colorblind=False): 749 | """ 750 | Plots the wall time of Scan and Filter operators that were applied on the top K tables, as a function of the operator's selectivity. 751 | The top K tables are the tables with the highest amount of wall time spent on performing Scan and Filter operations. 752 | Useful for detecting tables in which Scan operations can be improved using partitioning/indexing. 753 | 754 | Optimization Tip - Queries to the left of the dashed black line are selective queries, and can benefit significantly from predicate push-down and partitioning/indexing. 755 | 756 | """ 757 | tables = [] 758 | wall = [] 759 | selectivity = [] 760 | query_ids = [] 761 | for s in stats: 762 | node_map = {node["id"]: node for node in nodes_from_stats(s)} 763 | for op in scanfilter_operators(s["operators"]): 764 | node_id = op["node_id"] 765 | node = node_map[node_id] 766 | scan_node = last_element( 767 | iter_nodes(node) 768 | ) # DFS to get the "lowest" table scan node 769 | try: 770 | table_name = parse_table_name(scan_node) 771 | except KeyError as e: 772 | log.error("node: {}", scan_node) 773 | raise 774 | if op["input_rows"]: 775 | tables.append(table_name) 776 | wall.append(op["input_wall"] + op["output_wall"] + op["finish_wall"]) 777 | selectivity.append(op["output_rows"] / op["input_rows"]) 778 | query_ids.append(s["query_id"]) 779 | 780 | if not tables: 781 | return 782 | 783 | tables = numpy.array(tables) 784 | wall = numpy.array(wall) 785 | selectivity = numpy.array(selectivity) 786 | query_ids = numpy.array(query_ids) 787 | 788 | items = groupby(tables, wall, sum) 789 | items.sort(key=lambda item: item[1], reverse=True) 790 | top_tables, total_wall = zip(*items) 791 | 792 | p = figure( 793 | width=800, 794 | title="Wall time vs Selectivity", 795 | x_axis_label="Selectivity", 796 | y_axis_label="Elapsed wall time", 797 | x_axis_type="log", 798 | y_axis_type="log", 799 | sizing_mode="scale_width", 800 | tools=TOOLS, 801 | ) 802 | p.xaxis.ticker = [10 ** (-p) for p in range(9)] 803 | yticks = [1e-3, 1, 60, 60 * 60, 24 * 60 * 60] 804 | p.yaxis.ticker = yticks 805 | p.yaxis.major_label_overrides = dict(zip(yticks, ["1ms", "1s", "1m", "1h", "1d"])) 806 | 807 | shape_size = _get_size(colorblind) 808 | top_tables = set(top_tables[:topK]) 809 | 810 | I = numpy.array([(t in top_tables) for t in tables], dtype=bool) 811 | selectivity = selectivity[I] 812 | elapsed_time = wall[I] 813 | tables = tables[I] 814 | query_ids = query_ids[I] 815 | 816 | markers = ["circle", "diamond", "square", "triangle", "cross", "asterisk"] 817 | markers = itertools.cycle(markers) 818 | markers = itertools.islice(markers, len(top_tables)) 819 | markers_map = dict(zip(top_tables, markers)) 820 | markers = [markers_map[t] for t in tables] 821 | 822 | colors = _get_colors(colorblind) 823 | colors = itertools.cycle(colors) 824 | colors_map = dict(zip(top_tables, colors)) 825 | colors = [colors_map[t] for t in tables] 826 | 827 | source = ColumnDataSource( 828 | dict(selectivity=selectivity, elapsed_time=elapsed_time, table_name=tables, colors=colors, markers=markers, 829 | copy_on_tap=query_ids)) 830 | p.scatter("selectivity", "elapsed_time", legend_group="table_name", color="colors", marker="markers", source=source, 831 | size=shape_size) 832 | p.select(type=TapTool).callback = CustomJS(args=dict(source=source), code=COPY_JS) 833 | add_constant_line(p, 'height', 1e-2) 834 | return p 835 | 836 | 837 | @run 838 | def inputrows_vs_selectivity(stats, topK=5, colorblind=False): 839 | """ 840 | Shows the number of input rows that were scanned and filtered from the top K tables. 841 | The top K tables are chosen by the fraction of wall time needed for Scan and Filter operations. 842 | Useful for detecting the tables where scanning can be improved by partitioning/indexing. 843 | 844 | Optimization Tip - Queries to the left of the dashed black line are selective queries, and can benefit significantly from predicate push-down and partitioning/indexing. 845 | """ 846 | tables = [] 847 | wall = [] 848 | input_rows = [] 849 | selectivity = [] 850 | query_ids = [] 851 | for s in stats: 852 | node_map = {node["id"]: node for node in nodes_from_stats(s)} 853 | for op in scanfilter_operators(s["operators"]): 854 | node_id = op["node_id"] 855 | node = node_map[node_id] 856 | scan_node = last_element( 857 | iter_nodes(node) 858 | ) # DFS to get the "lowest" table scan node 859 | try: 860 | table_name = parse_table_name(scan_node) 861 | except KeyError as e: 862 | log.error("node: {}", scan_node) 863 | raise 864 | if op["input_rows"]: 865 | tables.append(table_name) 866 | wall.append(op["input_wall"] + op["output_wall"] + op["finish_wall"]) 867 | input_rows.append(op["input_rows"]) 868 | selectivity.append(op["output_rows"] / op["input_rows"]) 869 | query_ids.append(s["query_id"]) 870 | 871 | if not tables: 872 | return 873 | 874 | tables = numpy.array(tables) 875 | input_rows = numpy.array(input_rows) 876 | selectivity = numpy.array(selectivity) 877 | query_ids = numpy.array(query_ids) 878 | 879 | items = groupby(tables, wall, sum) 880 | items.sort(key=lambda item: item[1], reverse=True) 881 | top_tables, total_wall = zip(*items) 882 | 883 | p = figure( 884 | width=800, 885 | title="Input rows vs Selectivity", 886 | x_axis_label="Selectivity", 887 | y_axis_label="Input rows", 888 | x_axis_type="log", 889 | y_axis_type="log", 890 | sizing_mode="scale_width", 891 | tools=TOOLS, 892 | ) 893 | p.xaxis.ticker = [10 ** (-p) for p in range(9)] 894 | p.yaxis.ticker = [10 ** p for p in range(9)] 895 | 896 | shape_size = _get_size(colorblind) 897 | top_tables = set(top_tables[:topK]) 898 | 899 | I = numpy.array([(t in top_tables) for t in tables], dtype=bool) 900 | selectivity = selectivity[I] 901 | input_rows = input_rows[I] 902 | tables = tables[I] 903 | query_ids = query_ids[I] 904 | 905 | markers = ["circle", "diamond", "square", "triangle", "cross", "asterisk"] 906 | markers = itertools.cycle(markers) 907 | markers = itertools.islice(markers, len(top_tables)) 908 | markers_map = dict(zip(top_tables, markers)) 909 | markers = [markers_map[t] for t in tables] 910 | 911 | colors = _get_colors(colorblind) 912 | colors = itertools.cycle(colors) 913 | colors_map = dict(zip(top_tables, colors)) 914 | colors = [colors_map[t] for t in tables] 915 | 916 | source = ColumnDataSource( 917 | dict(selectivity=selectivity, input_rows=input_rows, table_name=tables, colors=colors, markers=markers, 918 | copy_on_tap=query_ids)) 919 | p.scatter("selectivity", "input_rows", legend_group="table_name", color="colors", marker="markers", source=source, 920 | size=shape_size) 921 | p.select(type=TapTool).callback = CustomJS(args=dict(source=source), code=COPY_JS) 922 | add_constant_line(p, 'height', 1e-2) 923 | return p 924 | 925 | 926 | @run 927 | def input_size_by_table_scan(stats, topK=20): 928 | """ 929 | The fraction of bytes read while scanning the top K tables. 930 | Useful for detecting the tables that are scanned the most. 931 | """ 932 | tables = [] 933 | input_size = [] 934 | for s in stats: 935 | node_map = {node["id"]: node for node in nodes_from_stats(s)} 936 | for op in scan_operators(s["operators"]): 937 | node_id = op["node_id"] 938 | node = node_map[node_id] 939 | scan_node = last_element( 940 | iter_nodes(node) 941 | ) # DFS to get the "lowest" table scan node 942 | try: 943 | table_name = parse_table_name(scan_node) 944 | except KeyError as e: 945 | log.error("node: {}", scan_node) 946 | raise 947 | tables.append(table_name) 948 | input_size.append(op["input_size"]) 949 | 950 | if not tables: 951 | return 952 | 953 | items = groupby(tables, input_size, sum) 954 | items.sort(key=lambda item: item[1], reverse=True) 955 | tables, input_size = zip(*items) 956 | return pie_chart( 957 | keys=tables, values=input_size, title="Input bytes read by table scan" 958 | ) 959 | 960 | 961 | @run 962 | def operator_input(stats): 963 | """ 964 | The fraction of bytes read by each Presto operator. 965 | Can be used to understand the percentage of bytes read by each part of the query processing - e.g. scan/join/aggreggation. 966 | """ 967 | operators = [op for s in stats for op in s["operators"]] 968 | types = [op["type"] for op in operators] 969 | input_size = [op["input_size"] for op in operators] 970 | items = groupby(types, input_size, sum) 971 | items.sort(key=lambda item: item[1], reverse=True) 972 | types, input_size = zip(*items) 973 | return pie_chart( 974 | keys=types, values=input_size, title="Input bytes read by operator" 975 | ) 976 | 977 | 978 | @run 979 | def operator_rows(stats): 980 | """ 981 | The fraction of rows read by each Presto operator. 982 | Can be used to understand the percentage of rows read by each part of the query processing - e.g. scan/join/aggreggation. 983 | """ 984 | operators = [op for s in stats for op in s["operators"]] 985 | types = [op["type"] for op in operators] 986 | input_rows = [op["input_rows"] for op in operators] 987 | items = groupby(types, input_rows, sum) 988 | items.sort(key=lambda item: item[1], reverse=True) 989 | types, input_rows = zip(*items) 990 | return pie_chart(keys=types, values=input_rows, title="Rows read by operator") 991 | 992 | 993 | def nodes_from_stats(s): 994 | fragments = s["fragments"] or [] 995 | nodes_iterators = (iter_nodes(fragment["root"]) for fragment in fragments) 996 | return itertools.chain.from_iterable(nodes_iterators) 997 | 998 | 999 | def get_node_type(node): 1000 | node_type = node["@type"] 1001 | match = re.search(r"\.(\w+)Node$", node_type) 1002 | if match: # convert PrestoDB to PrestoSQL naming 1003 | node_type = match.group(1) 1004 | return node_type.lower() 1005 | 1006 | 1007 | def iter_nodes(node): 1008 | yield node 1009 | node_type = get_node_type(node) 1010 | 1011 | if node_type == "exchange": 1012 | children = node["sources"] 1013 | elif node_type == "join": 1014 | children = [node["left"], node["right"]] 1015 | elif node_type in {"remotesource", "tablescan", "metadatadelete", "values", "tabledelete", "refreshmaterializedview"}: 1016 | children = [] 1017 | else: 1018 | try: 1019 | children = [node["source"]] 1020 | except KeyError: 1021 | log.error("no 'source' at {}", node) 1022 | raise 1023 | 1024 | for child in children: 1025 | yield from iter_nodes(child) 1026 | 1027 | 1028 | def group_operators_by_nodes(operators): 1029 | operators_map = {} 1030 | for op in operators: 1031 | try: 1032 | node_id = op["node_id"] 1033 | except KeyError: 1034 | log.error("Missing node ID from {}", op) 1035 | raise 1036 | operators_map.setdefault(node_id, []).append(op) 1037 | return operators_map 1038 | 1039 | 1040 | def iter_joins(stats): 1041 | for s in stats: 1042 | if not s["operators"]: 1043 | continue # usually it's a DDL or a "... LIMIT 0" query. 1044 | operators_map = group_operators_by_nodes(s["operators"]) 1045 | for node in nodes_from_stats(s): 1046 | node_type = get_node_type(node) 1047 | if node_type.endswith("join"): # join & semijoin 1048 | try: 1049 | join_ops = operators_map[node["id"]] 1050 | except KeyError: 1051 | log.error("{}: {} id={} has no matching operator: {!r}", s["query_id"], node_type, node["id"], 1052 | s["query"]) 1053 | continue 1054 | 1055 | join_ops = {op["type"]: op for op in join_ops} 1056 | if node_type == "join": 1057 | if node["criteria"] or node["type"] != "INNER": 1058 | keys = ("LookupJoinOperator", "HashBuilderOperator") 1059 | else: # i.e full-join 1060 | keys = ("NestedLoopJoinOperator", "NestedLoopBuildOperator") 1061 | elif node_type == "semijoin": 1062 | keys = ("HashSemiJoinOperator", "SetBuilderOperator") 1063 | else: 1064 | raise ValueError( 1065 | "{}: unsupported join type: {}".format(s["query_id"], node) 1066 | ) 1067 | 1068 | try: 1069 | probe = join_ops[keys[0]] 1070 | build = join_ops[keys[1]] 1071 | except KeyError: 1072 | log.error( 1073 | "missing keys {} in {}, node: {}", 1074 | keys, 1075 | join_ops, 1076 | json.dumps(node, indent=4), 1077 | ) 1078 | raise 1079 | 1080 | yield s, node, probe, build 1081 | 1082 | 1083 | @run 1084 | def joins_sides(stats, colorblind=False): 1085 | """ 1086 | Shows the join distribution using a scatter plot. 1087 | Each join operator is shown by a dot. The x coordinate is the data read from the 1088 | right-side table, and the y coordinate is the data read from the left-side table. 1089 | Replicated joins are shown in a different color than Partitioned joins. 1090 | For optimal performance, keep the right-side smaller than the left-side (the points should be above the y=x line). Replicated joins should be used as long as the right-side table is not too large, to prevent out-of-memory errors. 1091 | If you are using CBO, ensure the correct statistics are estimated for all tables being joined using ANALYZE command. 1092 | 1093 | Optimization Tips - 1094 | 1. Queries to the left of the black dashed line and above the orange dashed line should all use the REPLICATED join distribution type. 1095 | 2. Queries to the right of the orange dashed line perform joins with an incorrect table order. Ensure statistics are used, or rewrite the queries to flip the table sides, to boost performance and save cluster resources. 1096 | 1097 | """ 1098 | joins = list(iter_joins(stats)) 1099 | if not joins: 1100 | return 1101 | 1102 | p = figure( 1103 | title="Joins distribution", 1104 | x_axis_label="Right-side data read [bytes]", 1105 | x_axis_type="log", 1106 | y_axis_label="Left-side data read [bytes]", 1107 | y_axis_type="log", 1108 | sizing_mode="scale_width", 1109 | tools=TOOLS, 1110 | ) 1111 | 1112 | data = {} 1113 | for stat, node, probe, build in joins: 1114 | data.setdefault("x", []).append(build["input_size"]) # right-side 1115 | data.setdefault("y", []).append(probe["input_size"]) # left-side 1116 | data.setdefault("dist", []).append(node["distributionType"]) 1117 | data.setdefault("copy_on_tap", []).append(stat["query_id"]) 1118 | 1119 | shape_size = _get_size(colorblind) 1120 | color_map = {"PARTITIONED": "red", "REPLICATED": "blue"} 1121 | marker_map = {"PARTITIONED": "circle", "REPLICATED": "square"} 1122 | 1123 | data["color"] = [color_map[d] for d in data["dist"]] 1124 | data["marker"] = [marker_map[d] for d in data["dist"]] 1125 | source = ColumnDataSource(data) 1126 | p.scatter("x", "y", marker="marker", color="color", legend_group="dist", alpha=0.5, size=shape_size, source=source) 1127 | p.select(type=TapTool).callback = CustomJS(args=dict(source=source), code=COPY_JS) 1128 | p.legend.title = "Join distribution" 1129 | p.xaxis.ticker = [1, 1e3, 1e6, 1e9, 1e12] 1130 | p.yaxis.ticker = [1, 1e3, 1e6, 1e9, 1e12] 1131 | add_constant_line(p, 'height', 1e6) 1132 | slope = Slope(gradient=1, y_intercept=0, 1133 | line_color='orange', line_dash='dashed', line_width=2) 1134 | 1135 | p.add_layout(slope) 1136 | return p 1137 | 1138 | 1139 | @run 1140 | def joins_selectivity(stats): 1141 | """ 1142 | Show the joins' selectivity, using a scatter plot. 1143 | Each join operator is illustrated by a dot, whose distance below the y=x 1144 | line indicates how much it will benefit from Dynamic Filtering. 1145 | Joins on y=x line are non-selective, since they require all their input rows to be processed. 1146 | """ 1147 | joins = list(iter_joins(stats)) 1148 | if not joins: 1149 | return 1150 | 1151 | p = figure( 1152 | title="Joins selectivity", 1153 | x_axis_label="Input rows = max(left, right)", 1154 | x_axis_type="log", 1155 | y_axis_label="Output rows", 1156 | y_axis_type="log", 1157 | sizing_mode="scale_width", 1158 | tools=TOOLS, 1159 | ) 1160 | 1161 | data = [] 1162 | for stat, node, probe, build in joins: 1163 | x = max(probe["input_rows"], build["input_rows"]) 1164 | y = probe["output_rows"] 1165 | data.append((x, y, stat["query_id"])) 1166 | x, y, query_ids = zip(*data) 1167 | source = ColumnDataSource(dict(x=x, y=y, copy_on_tap=query_ids)) 1168 | 1169 | p.circle("x", "y", source=source, color="green", alpha=0.5) 1170 | p.select(type=TapTool).callback = CustomJS(args=dict(source=source), code=COPY_JS) 1171 | 1172 | p.xaxis.ticker = [1, 1e3, 1e6, 1e9, 1e12] 1173 | p.yaxis.ticker = [1, 1e3, 1e6, 1e9, 1e12] 1174 | return p 1175 | 1176 | 1177 | def collect_metrics(stats): 1178 | cpu_days = sum(s["cpu_time"] for s in stats) / (60 * 60 * 24) 1179 | scheduled_days = sum(s["scheduled_time"] for s in stats) / (60 * 60 * 24) 1180 | input_rows = sum(s["input_rows"] for s in stats) 1181 | input_TB = sum(s["input_size"] for s in stats) / 1e12 1182 | dates = (query_datetime(s["query_id"]) for s in stats) 1183 | n_days = len(set(trunc_date(d) for d in dates)) 1184 | n_users = len(set(s["user"] for s in stats)) 1185 | return { 1186 | "days": n_days, 1187 | "cpu_days": cpu_days, 1188 | "scheduled_days": scheduled_days, 1189 | "queries": len(stats), 1190 | "input_rows": input_rows, 1191 | "input_TB": input_TB, 1192 | "users": n_users, 1193 | } 1194 | 1195 | 1196 | def main(): 1197 | p = argparse.ArgumentParser() 1198 | p.add_argument( 1199 | "-i", 1200 | "--input-file", 1201 | type=pathlib.Path, 1202 | help="Path to the extracted JSONL file (the output of extract.py)", 1203 | ) 1204 | p.add_argument( 1205 | "-o", 1206 | "--output-file", 1207 | type=pathlib.Path, 1208 | default="./output.zip", 1209 | help="Path to the resulting zipped HTML report", 1210 | ) 1211 | p.add_argument("-l", "--limit", type=int) 1212 | p.add_argument("--filter", type=str) 1213 | p.add_argument("--fail-on-error", action="store_true", default=False) 1214 | p.add_argument("--high-contrast-mode", action="store_true", default=False) 1215 | p.add_argument("-q", "--quiet", action="store_true", default=False) 1216 | args = p.parse_args() 1217 | 1218 | log.info( 1219 | "loading {} = {:.3f} MB", args.input_file, args.input_file.stat().st_size / 1e6 1220 | ) 1221 | if args.input_file.name.endswith(".gz"): 1222 | lines = gzip.open(args.input_file.open("rb"), "rt") 1223 | else: 1224 | lines = args.input_file.open("rt") 1225 | 1226 | if args.limit: 1227 | lines = itertools.islice(lines, args.limit) 1228 | 1229 | lines = list(lines) 1230 | stats = [] 1231 | for line in tqdm(lines, unit="files", disable=args.quiet): 1232 | s = json.loads(line) 1233 | if s["state"] == "FAILED": 1234 | continue 1235 | stats.append(s) 1236 | log.info("{} queries loaded", len(stats)) 1237 | 1238 | metrics = collect_metrics(stats) 1239 | charts = [] 1240 | scripts = [] 1241 | for func in tqdm(_ANALYZERS, unit="graphs", disable=args.quiet): 1242 | graph_id = func.__name__ 1243 | if args.filter is None or args.filter == func.__name__: 1244 | try: 1245 | if 'colorblind' in signature(func).parameters: 1246 | p = func(stats, colorblind=args.high_contrast_mode) 1247 | else: 1248 | p = func(stats) 1249 | 1250 | if p is None: 1251 | log.warn("not enough data for {}", graph_id) 1252 | continue 1253 | item = json_item(model=p, target=graph_id) 1254 | item["doc"]["roots"]["references"].sort(key=lambda r: (r["type"], r["id"])) 1255 | 1256 | item = json.dumps({"doc": item["doc"]}) 1257 | scripts.append( 1258 | '\n'.format( 1259 | graph_id, item 1260 | ) 1261 | ) 1262 | charts.append( 1263 | { 1264 | "title": p.title.text or graph_id, 1265 | "description": func.__doc__.strip(), 1266 | "id": graph_id, 1267 | } 1268 | ) 1269 | except Exception: 1270 | log.exception("failed to generate {}", graph_id) 1271 | if args.fail_on_error: 1272 | raise 1273 | 1274 | scripts.append( 1275 | "".format( 1276 | json.dumps({"metrics": metrics, "charts": charts}, indent=4) 1277 | ) 1278 | ) 1279 | 1280 | template = pathlib.Path(__file__).parent / "output.template.html" 1281 | placeholder = "" 1282 | output = template.open().read().replace(placeholder, "\n".join(scripts)) 1283 | log.info("report is written to {}", args.output_file) 1284 | suffix = args.output_file.suffix 1285 | if suffix == ".zip": 1286 | with zipfile.ZipFile(args.output_file, "w") as f: 1287 | f.writestr("output.html", data=output, compress_type=zipfile.ZIP_DEFLATED) 1288 | elif suffix == ".html": 1289 | with open(args.output_file, "w") as f: 1290 | f.write(output) 1291 | else: 1292 | raise ValueError("Unsupport output file extension: {}".format(args.output_file)) 1293 | 1294 | 1295 | if __name__ == "__main__": 1296 | main() 1297 | --------------------------------------------------------------------------------