| 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 number and size of each type of object in the data store. |
| 17 |
|
| 18 |
.. note:: |
| 19 |
|
| 20 |
This plugin is for Cylc developers debugging the data store. |
| 21 |
|
| 22 |
If ``matplotlib`` is installed this plugin will plot results as a PDF in |
| 23 |
the run directory when the workflow is shut down (cleanly). |
| 24 |
|
| 25 |
""" |
| 26 |
import json |
| 27 |
from pathlib import Path |
| 28 |
from time import time |
| 29 |
|
| 30 |
from cylc.flow.main_loop import (startup, shutdown, periodic) |
| 31 |
|
| 32 |
|
| 33 |
try: |
| 34 |
import matplotlib |
| 35 |
matplotlib.use('Agg') |
| 36 |
from matplotlib import pyplot as plt |
| 37 |
PLT = True |
| 38 |
except ModuleNotFoundError: |
| 39 |
PLT = False |
| 40 |
|
| 41 |
from pympler.asizeof import asizeof |
| 42 |
|
| 43 |
|
| 44 |
@startup |
| 45 |
async def init(scheduler, state): |
| 46 |
"""Construct the initial state.""" |
| 47 |
state['objects'] = {} |
| 48 |
state['size'] = {} |
| 49 |
state['times'] = [] |
| 50 |
for key, _ in _iter_data_store(scheduler.data_store_mgr): |
| 51 |
state['objects'][key] = [] |
| 52 |
state['size'][key] = [] |
| 53 |
|
| 54 |
|
| 55 |
@periodic |
| 56 |
async def log_data_store(scheduler, state): |
| 57 |
"""Count the number of objects and the data store size.""" |
| 58 |
state['times'].append(time()) |
| 59 |
for key, value in _iter_data_store(scheduler.data_store_mgr): |
| 60 |
if isinstance(value, (list, dict, set)): |
| 61 |
state['objects'][key].append( |
| 62 |
len(value) |
| 63 |
) |
| 64 |
state['size'][key].append( |
| 65 |
asizeof(value) |
| 66 |
) |
| 67 |
|
| 68 |
|
| 69 |
@shutdown |
| 70 |
async def report(scheduler, state): |
| 71 |
"""Dump data to JSON, attempt to plot results.""" |
| 72 |
_dump(state, scheduler.workflow_run_dir) |
| 73 |
_plot(state, scheduler.workflow_run_dir) |
| 74 |
|
| 75 |
|
| 76 |
def _iter_data_store(data_store_mgr): |
| 77 |
# the data store itself (for a total measurement) |
| 78 |
yield ('data_store_mgr (total)', data_store_mgr) |
| 79 |
|
| 80 |
# the top-level attributes of the data store |
| 81 |
for key in dir(data_store_mgr): |
| 82 |
if ( |
| 83 |
key != 'data' |
| 84 |
and not key.startswith('__') |
| 85 |
and isinstance( |
| 86 |
value := getattr(data_store_mgr, key), |
| 87 |
(list, dict, set) |
| 88 |
) |
| 89 |
): |
| 90 |
yield (key, value) |
| 91 |
|
| 92 |
# the individual components of the "data" attribute |
| 93 |
for datum in data_store_mgr.data.values(): |
| 94 |
for key, value in datum.items(): |
| 95 |
if key == 'workflow': |
| 96 |
yield (f'data.{key}', [value]) |
| 97 |
else: |
| 98 |
yield (f'data.{key}', value) |
| 99 |
# there should only be one workflow in the data store |
| 100 |
break |
| 101 |
|
| 102 |
|
| 103 |
def _dump(state, path): |
| 104 |
data = { |
| 105 |
'times': state['times'], |
| 106 |
'objects': state['objects'], |
| 107 |
'size': state['size'] |
| 108 |
} |
| 109 |
json.dump( |
| 110 |
data, |
| 111 |
Path(path, f'{__name__}.json').open('w+') |
| 112 |
) |
| 113 |
return True |
| 114 |
|
| 115 |
|
| 116 |
def _plot(state, path, min_size_percent=2): |
| 117 |
if ( |
| 118 |
not PLT |
| 119 |
or len(state['times']) < 2 |
| 120 |
): |
| 121 |
return False |
| 122 |
|
| 123 |
# extract snapshot times |
| 124 |
times = [tick - state['times'][0] for tick in state['times']] |
| 125 |
|
| 126 |
max_size = max( |
| 127 |
size |
| 128 |
for sizes in state['size'].values() |
| 129 |
for size in sizes |
| 130 |
) |
| 131 |
|
| 132 |
# filter attributes by the minimum size |
| 133 |
min_size_bytes = max_size * (min_size_percent / 100) |
| 134 |
filtered_keys = { |
| 135 |
key |
| 136 |
for key, sizes in state['size'].items() |
| 137 |
if ( |
| 138 |
any(size > min_size_bytes for size in sizes) |
| 139 |
or key.startswith('data.') |
| 140 |
) |
| 141 |
} |
| 142 |
|
| 143 |
# plot |
| 144 |
fig = plt.figure(figsize=(15, 8)) |
| 145 |
ax1 = fig.add_subplot(111) |
| 146 |
fig.suptitle( |
| 147 |
f'data_store_mgr data and attrs above {min_size_percent}% of largest' |
| 148 |
f' (> {int(min_size_bytes / 1000)}kb)' |
| 149 |
) |
| 150 |
|
| 151 |
# plot sizes |
| 152 |
ax1.set_xlabel('Time (s)') |
| 153 |
ax1.set_ylabel('Size (kb)') |
| 154 |
for key, sizes in state['size'].items(): |
| 155 |
if key in filtered_keys: |
| 156 |
ax1.plot(times, [x / 1000 for x in sizes], label=key) |
| 157 |
|
| 158 |
# plot # objects |
| 159 |
ax2 = ax1.twinx() |
| 160 |
ax2.set_ylabel('Objects') |
| 161 |
for key, objects in state['objects'].items(): |
| 162 |
if objects and key in filtered_keys: |
| 163 |
ax2.plot(times, objects, label=key, linestyle=':') |
| 164 |
|
| 165 |
# legends |
| 166 |
ax1.legend(loc=0) |
| 167 |
ax2.legend( |
| 168 |
(ax1.get_children()[0], ax2.get_children()[0]), |
| 169 |
('size', 'objects'), |
| 170 |
loc=0 |
| 171 |
) |
| 172 |
|
| 173 |
# start the x-axis at zero |
| 174 |
ax1.set_xlim(0, ax1.get_xlim()[1]) |
| 175 |
|
| 176 |
plt.savefig( |
| 177 |
Path(path, f'{__name__}.pdf') |
| 178 |
) |
| 179 |
return True |