Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion declad/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@ class Config(dict):
"scanner.path",
"scanner.interval",
"scanner.location",
"scanner.quarantine_location",
"scanner.ls_command_template",
"scanner.metadata_extractor_log",
"scanner.metadata_extractor",
Expand All @@ -63,6 +64,7 @@ class Config(dict):
"scanner.filename_pattern",
"scanner.server",
"scanner.timeout",
"scanners",
"source_root_path",
"source_server",
"transfer_timeout",
Expand All @@ -83,8 +85,12 @@ def check(self, cfg ):
unknown_keys= set()
for k,v in cfg.items():
if isinstance(v,dict):
if k.startswith("scanner_"):
check_k = "scanner"
else:
check_k = k
for k2, v2 in v.items():
if not f"{k}.{k2}" in Config._valid_keys:
if not f"{check_k}.{k2}" in Config._valid_keys:
unknown_keys.add( f"{k}.{k2}" )
else:
if not k in Config._valid_keys:
Expand Down
46 changes: 34 additions & 12 deletions declad/declad.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,14 +19,26 @@ def __init__(self, config, history_db):
Logged.__init__(self, "declad")
self.Config = config
self.HistoryDB = history_db
self.MoverManager = Manager(config, self.HistoryDB)
scanner_type = config["scanner"].get("type")
if scanner_type == "local":
self.Scanner = LocalScanner(self.MoverManager, config, history_db)
elif scanner_type == "xrootd":
self.Scanner = Scanner(self.MoverManager, config)
else:
raise ValueError(f"Unknown or unspecified scanner type: {scanner_type}")
slist = config.get("scanners", [""])
scanner_names = []
for scanner_name in slist:
if scanner_name:
scanner_name= f"scanner_{scanner_name}"
else:
scanner_name = "scanner"
scanner_names.append(scanner_name)

self.MoverManager = Manager(config, self.HistoryDB, scanner_names)

self.Scanners = {}
for scanner_name in scanner_names:
scanner_type = config[scanner_name].get("type")
if scanner_type == "local":
self.Scanners[scanner_name] = LocalScanner(self.MoverManager, config, history_db, name=scanner_name)
elif scanner_type == "xrootd":
self.Scanners[scanner_name] = Scanner(self.MoverManager, config, name=scanner_name)
else:
raise ValueError(f"Unknown or unspecified scanner type: {scanner_type}")
self.Stop = False

def signal_handler(self, signum, frame):
Expand All @@ -40,7 +52,8 @@ def stop(self):

def run(self):
self.HistoryDB.start()
self.Scanner.start()
for scanner_name in self.Scanners:
self.Scanners[scanner_name].start()
self.MoverManager.start()
while not self.Stop:
self.sleep(100)
Expand All @@ -57,7 +70,7 @@ def finished_transfers(self, limit=None):
return list(self.HistoryDB.historySince(limit=limit)) # already reversed

def quarantined(self):
files, error = self.MoverManager.quarantined() # file descriptors
files, error = self.MoverManager.quarantined() # file descriptors
if files:
status_records = self.HistoryDB.latest_records_bulk([d.Name for d in files])
for d in files:
Expand All @@ -71,10 +84,19 @@ def task(self, name):
return self.MoverManager.task(name)

def ls_input(self):
return self.Scanner.ls_input()
res_files = []
res_error = None
for s in self.Scanners:
files, error = self.Scanners[s].ls_input()
res_files.extend(files)
res_error = res_error or error
return res_files, res_error

def input_location(self):
return self.Scanner.Server, self.Scanner.Location
res = []
for s in self.Scanners:
res.append((s, self.Scanners[s].Server, self.Scanners[s].Location))
return res

class ThreadMonitor(PyThread, Logged):

Expand Down
5 changes: 3 additions & 2 deletions declad/file_descriptor.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
class FileDescriptor(object):

def __init__(self, server, location, path, size):
def __init__(self, server, location, path, size, scanner_name="scanner"):
assert path.startswith(location)
self.Server = server
self.ScannerName = scanner_name
self.Location = location
if '/' in path:
self.Name = path.rsplit("/", 1)[-1]
Expand All @@ -19,7 +20,7 @@ def path(self, location):
return location + "/" + self.RelPath

def __str__(self):
return "%s:%s:%s(%s)" % (self.Server, self.Location, self.RelPath, self.Size)
return "<FileDescriptor>%s:%s:%s//%s(%s)" % (self.Server, self.Location, self.RelPath, self.Name, self.Size)

__repr__ = __str__

16 changes: 7 additions & 9 deletions declad/local_scanner.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,11 +15,12 @@ class LocalScanner(PyThread, Logged):
# -rw-r--r-- 1 ivm3 ivm3 1228 Mar 22 16:52 /home/ivm3/token
DefaultParseRE = r"(?P<type>[a-z-])\S+\s+\d+\s+\S+\s+\S+\s+(?P<size>\d+)\s+\S+\s+\d+\s+\S+\s+(?P<path>\S+)$"

def __init__(self, receiver, config, historydb = None):
PyThread.__init__(self, daemon=True, name="Scanner")
Logged.__init__(self, f"Scanner")
def __init__(self, receiver, config, historydb = None, name="scanner"):
PyThread.__init__(self, daemon=True, name=name)
Logged.__init__(self, name)
self.ScannerName = name
self.Receiver = receiver
scan_config = config["scanner"]
scan_config = config[name]
self.Historydb = historydb
self.Interval = scan_config.get("interval", self.DefaultInterval)
self.Location = scan_config["location"]
Expand Down Expand Up @@ -62,7 +63,7 @@ def do_ls(self, location, timeout=None):
size = int(m["size"])
if size == 0:
self.debug("Zero file size in:\n ", l)
files.append(FileDescriptor(self.Server, location, path, size))
files.append(FileDescriptor(self.Server, location, path, size, scanner_name=self.ScannerName))
elif t == "d":
dirs.append(path)
else:
Expand Down Expand Up @@ -135,10 +136,7 @@ def run(self):
self.log("found %d data files" % (len(data_files),))

if out_files:
#self.debug("sending files:")
#for fn, desc in out_files.items():
# self.debug(desc.Path, fn)
self.Receiver.add_files(out_files)
self.Receiver.add_files(out_files, scanner_name=self.ScannerName)

if self.MetadataExtractor:
# if we have a metadata extractor defined, look for files that have been here
Expand Down
88 changes: 47 additions & 41 deletions declad/mover.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
raise AttributeError("Unable to import 'custom', did you forget to symlink experiment.py as __init__.py?")

import re
import os
from pythreader import PyThread, synchronized, Primitive, Task, TaskQueue
from tools import runCommand
import json, hashlib, traceback, time, os, pprint, textwrap
Expand All @@ -29,23 +30,24 @@ class MoverTask(Task, Logged):
last_created_rucio_dataset = None
last_created_metacat_dataset = None

def __init__(self, config, filedesc):
def __init__(self, config, filedesc, scanner_name="scanner"):
Task.__init__(self, filedesc)
Logged.__init__(self, name=f"MoverTask[{filedesc.Name}]")

self.ScannerName = scanner_name
self.FileDesc = filedesc
self.Config = config
self.MetaSuffix = config.get("meta_suffix", ".json")
self.RucioConfig = config.get("rucio", {})
self.Activity = self.RucioConfig.get("activity", "")
self.SAMConfig = config.get("samweb", {})
self.QuarantineLocation = config.get("quarantine_location")
self.SourceServer = config["source_server"]
self.SourceServer = config[scanner_name].get("server",None) or config.get("source_server",None)
self.DestServer = config.get("destination_server") or self.SourceServer
self.TransferProto = config.get("transfer_proto","root")

# source and destination paths in xrootd namespace
self.SrcRootPath = config["source_root_path"]
self.SrcRootPath = config[scanner_name].get("path",None) or config.get("source_root_path",None)
self.DstRootPath = config["destination_root_path"]

self.TransferTimeout = config.get("transfer_timeout", 120)
Expand Down Expand Up @@ -103,21 +105,15 @@ def destination_rel_path(self, scope, desc, metadata):
return '%s/%s/%s/%s' % (scope, hstr[0:2], hstr[2:4], name)

def get_file_size(self, server, path):
if self.TransferProto == 'root':
scanner = XRootDScanner(server, self.Config["scanner"])
return scanner.getFileSize(path)
elif self.TransferProto == 'https':
stat_command = f"gfal-stat https://{server}/{path}"
self.log(f"Running {stat_command}")
status, out = runCommand(stat_command, self.TransferTimeout, self.debug)
lines = [x.strip() for x in out.split("\n")]
for line in lines:
self.log(f"stat line: {line}")
if line.find("Size:") >= 0:
fields = re.split(r"\s+", line)
self.log(f"found size {fields[1]}")
return int(fields[1])
return None
# gfal-stat works for everything, file://... root://.. https://... so just use it
stat_command = f"unset PYTHONHOME PYTHONPATH LD_LIBRARY_PATH GFAL_PLUGIN_DIR GFAL_CONFIG_DIR; gfal-stat {self.TransferProto}://{server}{path}"
self.log(f"Running {stat_command}")
status, out = runCommand(stat_command, self.TransferTimeout, self.debug)
lines = [x.strip() for x in out.split("\n")]
for line in lines:
if line.find("Size:") >= 0:
fields = re.split(r"\s+", line)
return int(fields[1])

def run(self):
# import a template_tags() routine if present, otherwise nothing local..
Expand Down Expand Up @@ -313,7 +309,7 @@ def template_tags(metadata):
return self.failed(f"Can not get file size at the destination: {e}")

if dest_size != file_size:
return self.failed("Transferred file has wrong size")
return self.failed(f"Transferred file has wrong size {dest_size} vs {file_size}")
else:
self.log("data file already exists at the destination and has correct size. Not overwriting")

Expand Down Expand Up @@ -533,8 +529,8 @@ def template_tags(metadata):

do_remove_sources = self.Config.get("remove_sources", True)

rmcommand = self.Config["delete_command_template"] \
.replace("$server", self.SourceServer) \
rmcommand = self.Config["delete_command_template"] \
.replace("$server", self.SourceServer) \
.replace("$path", meta_path)
if do_remove_sources:
ret, output = runCommand(rmcommand, self.TransferTimeout, self.debug)
Expand All @@ -543,8 +539,8 @@ def template_tags(metadata):
else:
self.debug("would remove source metadata:", rmcommand)

rmcommand = self.Config["delete_command_template"] \
.replace("$server", self.SourceServer) \
rmcommand = self.Config["delete_command_template"] \
.replace("$server", self.SourceServer) \
.replace("$path", src_data_path)
if do_remove_sources:
ret, output = runCommand(rmcommand, self.TransferTimeout, self.debug)
Expand All @@ -560,7 +556,7 @@ def template_tags(metadata):
def donewith(self, src_data_path):
""" tell system buffer cache we"re done with file """

if self.Config["scanner"].get("type") == "local":
if self.Config[self.ScannerName].get("type") == "local":
self.log(f"calling fadvise w/ dontneed for {src_data_path}")
try:
with open(src_data_path) as pf:
Expand Down Expand Up @@ -593,11 +589,13 @@ def quarantine(self, reason = None):
src_path = self.FileDesc.path(self.SrcRootPath)
# tell buffer cache to drop this file
self.donewith(src_path)
if self.QuarantineLocation:
sname = self.FileDesc.ScannerName
qlocation = self.Config[sname].get("quarantine_location","") or self.Config.get("quarantine_location","")
if qlocation:

# quarantine the metadata file
meta_path = src_path + self.MetaSuffix
qmeta_path = self.QuarantineLocation + "/" + self.FileDesc.Name + self.MetaSuffix
qmeta_path = qlocation + "/" + self.FileDesc.Name + self.MetaSuffix
if self.FileDesc.Server is None:
cmd = "mv %s %s" % (
meta_path, qmeta_path
Expand All @@ -613,7 +611,7 @@ def quarantine(self, reason = None):

# quarantine the data file
path = src_path
qpath = self.QuarantineLocation + "/" + self.FileDesc.Name
qpath = qlocation + "/" + self.FileDesc.Name
if self.FileDesc.Server is None:
cmd = "mv %s %s" % (
path, qpath
Expand All @@ -636,9 +634,10 @@ class Manager(PyThread, Logged):

DEFAULT_LOW_WATER_MARK = 5

def __init__(self, config, history_db):
def __init__(self, config, history_db, scanner_list=["scanner"]):
PyThread.__init__(self, name="Mover")
Logged.__init__(self, name="Mover")
self.ScannerList = scanner_list
self.Config = config
capacity = None # config.get("queue_capacity") possible deadlock otherwise
max_movers = config.get("max_movers", 10)
Expand All @@ -648,7 +647,7 @@ def __init__(self, config, history_db):
self.TaskKeepInterval = int(config.get("keep_interval", 24*3600))
self.LowWaterMark = config.get("low_water_mark", self.DEFAULT_LOW_WATER_MARK)
self.HistoryDB = history_db
self.NextRetry = {} # name -> t
self.NextRetry = {} # name -> t
self.RecentTasks = {} # name -> task
self.Stop = False

Expand All @@ -660,16 +659,21 @@ def stop(self):
self.wakeup()

def quarantined(self):
qlocation = self.Config.get("quarantine_location")
if not qlocation:
return [], "Quarantine not configured"
scanner = XRootDScanner(self.Config["source_server"], self.Config["scanner"])
error = None
files = []
try: files = scanner.scan(qlocation) # returns file descriptors
except Exception as e:
error = str(e)
return files or [], error
errorsum = ""
for sname in self.ScannerList:
qlocation = self.Config[sname].get("quarantine_location","") or self.Config.get("quarantine_location","")
if not qlocation:
errorsum += f"Quarantine not configured in {sname} "
continue

scanner = XRootDScanner(self.Config[sname].get("server","localhost"), self.Config[sname], name=sname)
try:
files.extend(scanner.scan(qlocation))
except Exception as e:
errorsum = errorsum + f"Exception on {sname}: {str(e)}"

return files, errorsum

@synchronized
def recent_tasks(self):
Expand All @@ -684,7 +688,7 @@ def low_water(self):
return len(self.TaskQueue) < self.LowWaterMark

@synchronized
def add_files(self, files_dict):
def add_files(self, files_dict, scanner_name=""):
#
# WARNING: this can cause a deadlock of the queue capacity is limited
#
Expand All @@ -701,7 +705,9 @@ def add_files(self, files_dict):
for name, filedesc in files_dict.items():
name = filedesc.Name
if name not in in_progress and name not in self.NextRetry:
task = MoverTask(self.Config, filedesc) # retry the file: create new task with new FileDesc to reflect fresh scan results
# retry the file: create new task with new FileDesc
# to reflect fresh scan results
task = MoverTask(self.Config, filedesc,scanner_name=scanner_name)
task.KeepUntil = now + self.TaskKeepInterval
self.RecentTasks[name] = task
self.NextRetry[name] = now + self.RetryCooldown
Expand Down
13 changes: 7 additions & 6 deletions declad/scanner.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,14 +10,15 @@ class Scanner(PyThread, Logged):
MetaSuffix = ".json"
DefaultInterval = 300

def __init__(self, receiver, config):
PyThread.__init__(self, daemon=True, name="Scanner")
Logged.__init__(self, f"Scanner")
def __init__(self, receiver, config, name="scanner"):
PyThread.__init__(self, daemon=True, name=name)
Logged.__init__(self, name)
self.ScannerName = name
self.Receiver = receiver
scan_config = config["scanner"]
scan_config = config[name]
self.Interval = scan_config.get("interval", self.DefaultInterval)
self.Server, self.Location = scan_config["server"], scan_config["location"]
self.XScanner = XRootDScanner(self.Server, scan_config)
self.XScanner = XRootDScanner(self.Server, scan_config, name=name)
patterns = scan_config.get("filename_patterns") or scan_config.get("filename_pattern")
if not patterns:
raise ValueError("Filename patterns (filename_patterns) not found in the config file")
Expand Down Expand Up @@ -82,7 +83,7 @@ def run(self):
#self.debug("sending files:")
#for fn, desc in out_files.items():
# self.debug(desc.Path, fn)
self.Receiver.add_files(out_files)
self.Receiver.add_files(out_files, scanner_name=self.ScannerName)

if not self.Stop:
self.sleep(self.Interval)
Loading