# -*- coding: utf-8 -*-# vim: tabstop=4 shiftwidth=4 softtabstop=4## Copyright (C) 2015-2023 GEM Foundation## OpenQuake is free software: you can redistribute it and/or modify it# under the terms of the GNU Affero General Public License as published# by the Free Software Foundation, either version 3 of the License, or# (at your option) any later version.## OpenQuake is distributed in the hope that it will be useful,# but WITHOUT ANY WARRANTY; without even the implied warranty of# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the# GNU Affero General Public License for more details.## You should have received a copy of the GNU Affero General Public License# along with OpenQuake. If not, see <http://www.gnu.org/licenses/>.importosimportreimportgetpassfromopenquake.baselib.generalimporthumansizefromopenquake.commonlibimportlogs,datastoredatadir=datastore.get_datadir()
[docs]defpurge_one(calc_id,user,force):""" Remove one calculation ID from the database and remove its datastore """logs.dbcmd('del_calc',calc_id,user,False,force)f1=os.path.join(datadir,'calc_%s.hdf5'%calc_id)f2=os.path.join(datadir,'calc_%s_tmp.hdf5'%calc_id)forfin[f1,f2]:ifos.path.exists(f):# not removed yetos.remove(f)print('Removed %s'%f)
# used in the reset command
[docs]defpurge_all(user=None):""" Remove all calculations of the given user """user=userorgetpass.getuser()ifos.path.exists(datadir):forfnameinos.listdir(datadir):iffname.endswith('.pik'):os.remove(os.path.join(datadir,fname))mo=re.match(r'calc_(\d+)(_tmp)?\.hdf5',fname)ifmoisnotNone:calc_id=int(mo.group(1))purge_one(calc_id,user,force=True)
[docs]defpurge(status,days,force):""" Remove calculations of the given status older than days """rows=logs.dbcmd(f'SELECT id, ds_calc_dir || ".hdf5" FROM job 'f'WHERE status IN (?X)'f"AND start_time < datetime('now', '-{days}')",status)todelete=[]totsize=0forcalc_id,fnameinrows:ifos.path.exists(fname)andos.access(fname,os.W_OK):todelete.append(fname)totsize+=os.path.getsize(fname)tname=fname.replace('.hdf5','_tmp.hdf5')ifos.path.exists(tname)andos.access(tname,os.W_OK):todelete.append(tname)totsize+=os.path.getsize(tname)size=humansize(totsize)forfnameintodelete:print(fname)ifforce:os.remove(fname)print('Processed %d HDF5 files, %s'%(len(todelete),size))
[docs]defmain(what,force=False):""" Remove calculations from the file system. If you want to remove everything, use oq reset. """ifwhat=='failed':purge(['failed'],'1 days',force)returnelifwhat=='old':purge('complete failed deleted'.split(),'30 days',force)returncalc_id=int(what)ifcalc_id<0:try:calc_id=logs.get_calc_ids(datadir)[calc_id]exceptIndexError:print('Calculation %d not found'%calc_id)returnpurge_one(calc_id,getpass.getuser(),force)
main.what='a calculation ID or the string "failed"'main.force='ignore dependent calculations'