| 1 |
# THIS FILE IS PART OF THE CYLC WORKFLOW ENGINE. |
| 2 |
# Copyright (C) NIWA & British Crown (Met Office) & Contributors. |
| 3 |
# |
| 4 |
# This program 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 |
# This program 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 this program. If not, see <http://www.gnu.org/licenses/>. |
| 16 |
"""Log the memory usage of a running scheduler over time. |
| 17 |
|
| 18 |
.. note:: |
| 19 |
|
| 20 |
This plugin is for Cylc developers debugging cylc memory usage. |
| 21 |
|
| 22 |
For general interest memory measurement try |
| 23 |
``/usr/bin/time -v cylc play`` or ``cylc play --profile``. |
| 24 |
|
| 25 |
.. note:: |
| 26 |
|
| 27 |
Pympler associates memory with the first object which references it. |
| 28 |
|
| 29 |
In Cylc we have some objects (e.g. the configuration) which are references |
| 30 |
from multiple places. |
| 31 |
|
| 32 |
This can result in a certain amount of "jitter" in the results where |
| 33 |
pympler has swapper from associating memory with one object to another. |
| 34 |
|
| 35 |
Watch out for matching increase/decrease in reported memory in |
| 36 |
different objects. |
| 37 |
|
| 38 |
.. warning:: |
| 39 |
|
| 40 |
This plugin can slow down a workflow significantly due to the |
| 41 |
complexity of memory calculations. |
| 42 |
|
| 43 |
Set a sensible interval before running workflows. |
| 44 |
|
| 45 |
If ``matplotlib`` is installed this plugin will plot results as a PDF in |
| 46 |
the run directory when the workflow is shut down (cleanly). |
| 47 |
|
| 48 |
""" |
| 49 |
|
| 50 |
import json |
| 51 |
from pathlib import Path |
| 52 |
from time import time |
| 53 |
|
| 54 |
from cylc.flow.main_loop import (startup, shutdown, periodic) |
| 55 |
|
| 56 |
try: |
| 57 |
import matplotlib |
| 58 |
matplotlib.use('Agg') |
| 59 |
from matplotlib import pyplot as plt |
| 60 |
PLT = True |
| 61 |
except ModuleNotFoundError: |
| 62 |
PLT = False |
| 63 |
|
| 64 |
from pympler.asizeof import asized |
| 65 |
|
| 66 |
|
| 67 |
# TODO: make this configurable in the global config |
| 68 |
MIN_SIZE = 10000 |
| 69 |
|
| 70 |
|
| 71 |
@startup |
| 72 |
async def init(scheduler, state): |
| 73 |
"""Take an initial memory snapshot.""" |
| 74 |
state['data'] = [] |
| 75 |
await take_snapshot(scheduler, state) |
| 76 |
|
| 77 |
|
| 78 |
@periodic |
| 79 |
async def take_snapshot(scheduler, state): |
| 80 |
"""Take a memory snapshot""" |
| 81 |
state['data'].append(( |
| 82 |
time(), |
| 83 |
_compute_sizes(scheduler, min_size=MIN_SIZE) |
| 84 |
)) |
| 85 |
|
| 86 |
|
| 87 |
@shutdown |
| 88 |
async def report(scheduler, state): |
| 89 |
"""Take a final memory snapshot and dump the results.""" |
| 90 |
await take_snapshot(scheduler, state) |
| 91 |
_dump(state['data'], scheduler.workflow_run_dir) |
| 92 |
fields, times = _transpose(state['data']) |
| 93 |
_plot( |
| 94 |
fields, |
| 95 |
times, |
| 96 |
scheduler.workflow_run_dir, |
| 97 |
f'cylc.flow.scheduler.Scheduler attrs > {MIN_SIZE / 1000}kb' |
| 98 |
) |
| 99 |
|
| 100 |
|
| 101 |
def _compute_sizes(obj, min_size=10000): |
| 102 |
"""Return the sizes of the attributes of an object.""" |
| 103 |
size = asized(obj, detail=2) |
| 104 |
for ref in size.refs: |
| 105 |
if ref.name == '__dict__': |
| 106 |
break |
| 107 |
else: |
| 108 |
raise Exception('Cannot find __dict__ reference') |
| 109 |
|
| 110 |
return { |
| 111 |
**{ |
| 112 |
item.name.split(':')[0][4:]: item.size |
| 113 |
for item in ref.refs |
| 114 |
if item.size > min_size |
| 115 |
}, |
| 116 |
**{'total': size.size}, |
| 117 |
} |
| 118 |
|
| 119 |
|
| 120 |
def _transpose(data): |
| 121 |
"""Pivot data from snapshot to series oriented.""" |
| 122 |
all_keys = set() |
| 123 |
for _, datum in data: |
| 124 |
all_keys.update(datum.keys()) |
| 125 |
|
| 126 |
# sort keys by the size of the last checkpoint so that the fields |
| 127 |
# get plotted from largest to smallest |
| 128 |
all_keys = list(all_keys) |
| 129 |
all_keys.sort(key=lambda x: data[-1][1].get(x, 0), reverse=True) |
| 130 |
|
| 131 |
# extract data for each field, if not present |
| 132 |
fields = {} |
| 133 |
for key in all_keys: |
| 134 |
fields[key] = [ |
| 135 |
datum.get(key, -1) |
| 136 |
for _, datum in data |
| 137 |
] |
| 138 |
|
| 139 |
start_time = data[0][0] |
| 140 |
times = [ |
| 141 |
timestamp - start_time |
| 142 |
for timestamp, _ in data |
| 143 |
] |
| 144 |
|
| 145 |
return fields, times |
| 146 |
|
| 147 |
|
| 148 |
def _dump(data, path): |
| 149 |
json.dump( |
| 150 |
data, |
| 151 |
Path(path, f'{__name__}.json').open('w+') |
| 152 |
) |
| 153 |
return True |
| 154 |
|
| 155 |
|
| 156 |
def _plot(fields, times, path, title='Objects'): |
| 157 |
if ( |
| 158 |
not PLT |
| 159 |
or len(times) < 2 |
| 160 |
): |
| 161 |
return False |
| 162 |
|
| 163 |
fig, ax1 = plt.subplots(figsize=(10, 7.5)) |
| 164 |
|
| 165 |
fig.suptitle(title) |
| 166 |
ax1.set_xlabel('Time (s)') |
| 167 |
ax1.set_ylabel('Memory (kb)') |
| 168 |
|
| 169 |
lines = [ |
| 170 |
ax1.plot(times, [x / 1000 for x in sizes], label=key)[0] |
| 171 |
for key, sizes in fields.items() |
| 172 |
] |
| 173 |
|
| 174 |
ax1.legend(lines, fields, loc=0) |
| 175 |
|
| 176 |
# start both axis at 0 |
| 177 |
ax1.set_xlim(0, ax1.get_xlim()[1]) |
| 178 |
ax1.set_ylim(0, ax1.get_ylim()[1]) |
| 179 |
|
| 180 |
plt.savefig( |
| 181 |
Path(path, f'{__name__}.pdf') |
| 182 |
) |
| 183 |
return True |