| 1 | package EAI::Wrap 1.921; | ||
| 2 | |||
| 3 | 2 | ▶ | use strict; use feature 'unicode_strings'; use warnings; |
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
Subroutine
BEGIN: called CC=1 SCAR=0.0
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||
| 4 | 2 | ▶ | use Exporter qw(import); use Data::Dumper qw(Dumper); use File::Copy qw(copy move); use Cwd qw(chdir); use Archive::Extract (); use Carp qw(confess longmess); |
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
Subroutine
BEGIN: called CC=1 SCAR=0.0
Subroutine
BEGIN: called CC=1 SCAR=0.0
Subroutine
BEGIN: called CC=1 SCAR=0.0
Subroutine
BEGIN: called CC=1 SCAR=0.0
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||
| 5 | # we make $EAI::Common::common/config/execute/loads/optload/opt an alias for $EAI::Wrap::common/config/execute/loads/optload/opt so that the user can set it without knowing anything about the Common package! | ||
| 6 | our %common;our %config;our @loads;our %execute;our @optload;our %opt; | ||
| 7 | |||
| 8 | 2 | ▶ | BEGIN { |
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||
| 9 | 2 | *EAI::Common::common = \%common; | |
| 10 | 2 | *EAI::Common::config = \%config; | |
| 11 | 2 | *EAI::Common::execute = \%execute; | |
| 12 | 2 | *EAI::Common::loads = \@loads; | |
| 13 | 2 | *EAI::Common::optload = \@optload; | |
| 14 | 2 | *EAI::Common::opt = \%opt; | |
| 15 | }; | ||
| 16 | 0 | ▶ | use EAI::Common; use EAI::DateUtil; use EAI::DB; use EAI::File; use EAI::FTP; |
|
Subroutine
BEGIN: called CC=1 SCAR=0.1
Subroutine
BEGIN: called CC=1 SCAR=0.1
Subroutine
BEGIN: called CC=1 SCAR=0.1
| |||
| 17 | |||
| 18 | # first structures and functions from this module, then from DateUtil, DB, File, FTP, Common; last useful external functions | ||
| 19 | our @EXPORT = qw(%common %config %execute @loads @optload %opt removeFilesinFolderOlderX openDBConn openFTPConn redoFiles getLocalFiles getFilesFromFTP getFiles checkFiles extractArchives getAdditionalDBData readFileData dumpDataIntoDB markProcessed writeFileFromDB writeFileFromMemory putFileInLocalDir markUploadForHistoryDelete uploadFileToFTP uploadFileCMD uploadFile processingEnd processingPause processingContinues standardLoop moveFilesToHistory deleteFiles | ||
| 20 | monthsToInt intToMonths addLocaleMonths get_curdate get_curdatetime get_curdate_dot formatDate formatDateFromYYYYMMDD get_curdate_dash get_curdate_gen get_curdate_dash_plus_X_years get_curtime get_curtime_HHMM get_lastdateYYYYMMDD get_lastdateDDMMYYYY is_first_day_of_month is_last_day_of_month get_last_day_of_month weekday is_weekend is_holiday is_easter addCalendar first_week first_weekYYYYMMDD last_week last_weekYYYYMMDD convertDate convertDateFromMMM convertDateToMMM convertToDDMMYYYY addDays addDaysHol addMonths subtractDays subtractDaysHol convertcomma convertToThousendDecimal get_dateseries parseFromDDMMYYYY parseFromYYYYMMDD convertEpochToYYYYMMDD convertJulianToYYYYMMDD make_time formatTime get_curtime_epochs localtime timelocal_modern skipOnDate | ||
| 21 | newDBH beginWork commit rollback readFromDB readFromDBHash doInDB storeInDB deleteFromDB updateInDB getConn setConn | ||
| 22 | readText readExcel readXML writeText writeExcel | ||
| 23 | removeFilesOlderX fetchFiles putFile moveTempFile archiveFiles removeFiles login getHandle setHandle | ||
| 24 | readConfigFile getSensInfo setupConfigMerge getOptions setupEAIWrap setErrSubject dumpFlat extractConfigs checkHash checkParam setupLogging checkStartingCond sendGeneralMail | ||
| 25 | get_logger Dumper); | ||
| 26 | |||
| 27 | # initialize module, reading all config files and setting basic execution variables | ||
| 28 | sub INIT { | ||
| 29 | # read site config, additional configs and sensitive config in alphabetical order (allowing precedence) | ||
| 30 | STDOUT->autoflush(1); | ||
| 31 | $EAI_WRAP_CONFIG_PATH = ($ENV{EAI_WRAP_CONFIG_PATH} ? $ENV{EAI_WRAP_CONFIG_PATH} : ""); | ||
| 32 | $EAI_WRAP_SENS_CONFIG_PATH = ($ENV{EAI_WRAP_SENS_CONFIG_PATH} ? $ENV{EAI_WRAP_SENS_CONFIG_PATH} : ""); | ||
| 33 | $EAI_WRAP_CONFIG_PATH =~ s/\\/\//g; | ||
| 34 | $EAI_WRAP_SENS_CONFIG_PATH =~ s/\\/\//g; | ||
| 35 | print STDOUT "EAI_WRAP_CONFIG_PATH: ".($EAI_WRAP_CONFIG_PATH ? $EAI_WRAP_CONFIG_PATH : "not set").", EAI_WRAP_SENS_CONFIG_PATH: ".($EAI_WRAP_SENS_CONFIG_PATH ? $EAI_WRAP_SENS_CONFIG_PATH : "not set")."\n"; | ||
| 36 | readConfigs(); | ||
| 37 | |||
| 38 | $execute{homedir} = File::Basename::dirname(File::Spec->rel2abs((caller(0))[1])); # folder, where the main script is being executed. | ||
| 39 | $execute{scriptname} = File::Basename::fileparse((caller(0))[1]); | ||
| 40 | my ($homedirnode) = ($execute{homedir} =~ /^.*[\\\/](.*?)$/); | ||
| 41 | $execute{envraw} = $config{folderEnvironmentMapping}{$homedirnode}; | ||
| 42 | my $modulepath = File::Basename::dirname(File::Spec->rel2abs(__FILE__)); # get this module's folder as additional folderEnvironmentMapping. | ||
| 43 | $execute{envraw} = $config{folderEnvironmentMapping}{$modulepath} if !$execute{envraw}; # if nothing found check if modulepath is configured to get envraw from there... | ||
| 44 | $execute{envraw} = "" if !$execute{envraw}; # prevent uninitialized warning | ||
| 45 | print STDOUT "\$execute{homedir}: $execute{homedir}, \$execute{scriptname}: $execute{scriptname}, \$homedirnode: $homedirnode, \$modulepath: $modulepath, \$execute{envraw}: $execute{envraw}\n"; | ||
| 46 | if ($execute{envraw}) { | ||
| 47 | $execute{env} = $execute{envraw}; | ||
| 48 | readConfigs($execute{envraw}); # read configs again for different environment | ||
| 49 | } else { | ||
| 50 | # if not configured, use default mapping (usually ''=>"Prod" for production) | ||
| 51 | $execute{env} = $config{folderEnvironmentMapping}{''}; | ||
| 52 | } | ||
| 53 | |||
| 54 | EAI::Common::getOptions(); # getOptions before logging setup as centralLogHandling depends on interactive options passed. Also need options to be present for executeOnInit | ||
| 55 | doExecuteOnInit(); | ||
| 56 | $execute{failcount}=0; | ||
| 57 | EAI::Common::setupLogging(); | ||
| 58 | EAI::Common::setErrSubject("starting process"); | ||
| 59 | } | ||
| 60 | |||
| 61 | # read configs from EAI_WRAP_CONFIG_PATH/site.config, EAI_WRAP_CONFIG_PATH/additional/*.config (if existing) and EAI_WRAP_SENS_CONFIG_PATH/*.config (if existing) | ||
| 62 | # if argument envraw given, read EAI_WRAP_CONFIG_PATH/envraw/site.config, and additionally to above EAI_WRAP_CONFIG_PATH/envraw/additional/*.config (if existing) and EAI_WRAP_SENS_CONFIG_PATH/envraw/*.config (if existing), because config is set new by reading EAI_WRAP_CONFIG_PATH/envraw/site.config | ||
| 63 | sub readConfigs (;$) { | ||
| 64 | my $envraw = ($_[0] ? $_[0]."/" : ""); | ||
| 65 | EAI::Common::readConfigFile("$EAI_WRAP_CONFIG_PATH/${envraw}site.config") if -e "$EAI_WRAP_CONFIG_PATH/${envraw}site.config"; | ||
| 66 | EAI::Common::readConfigFile($_) for sort glob qq{"$EAI_WRAP_CONFIG_PATH/additional/*.config"}; | ||
| 67 | EAI::Common::readConfigFile($_) for sort glob qq{"$EAI_WRAP_SENS_CONFIG_PATH/*.config"}; | ||
| 68 | if ($envraw) { | ||
| 69 | EAI::Common::readConfigFile($_) for sort glob qq{"$EAI_WRAP_CONFIG_PATH/${envraw}additional/*.config"}; | ||
| 70 | EAI::Common::readConfigFile($_) for sort glob qq{"$EAI_WRAP_SENS_CONFIG_PATH/${envraw}*.config"}; | ||
| 71 | } | ||
| 72 | } | ||
| 73 | |||
| 74 | sub doExecuteOnInit () { | ||
| 75 | if ($config{executeOnInit}) { | ||
| 76 | print STDOUT "doing executeOnInit\n"; | ||
| 77 | if (ref($config{executeOnInit}) eq "CODE") { | ||
| 78 | eval {$config{executeOnInit}->()}; | ||
| 79 | } else { | ||
| 80 | eval $config{executeOnInit}; | ||
| 81 | } | ||
| 82 | confess("Error parsing config{executeOnInit} ".(ref($config{executeOnInit}) eq "CODE" ? "defined sub" : "'".$config{executeOnInit}."'").": $@") if $@; | ||
| 83 | } | ||
| 84 | } | ||
| 85 | |||
| 86 | # open a DB connection | ||
| 87 | sub openDBConn ($;$) { | ||
| 88 | my ($arg, $enforceConn) = @_; | ||
| 89 | my $logger = get_logger(); | ||
| 90 | my ($DB,$process) = EAI::Common::extractConfigs("opening DB connection",$arg,"DB","process"); | ||
| 91 | # only for set prefix, take username and password from $config{sensitive}{$DB->{prefix}} | ||
| 92 | if ($DB->{prefix}) { | ||
| 93 | $logger->debug("getting sensitive Info for user and pwd from $DB->{prefix}"); | ||
| 94 | $DB->{user} = EAI::Common::getSensInfo($DB->{prefix},"user"); | ||
| 95 | $DB->{pwd} = EAI::Common::getSensInfo($DB->{prefix},"pwd"); | ||
| 96 | } | ||
| 97 | my ($DSNeval, $newDSN); | ||
| 98 | $DSNeval = $DB->{DSN}; | ||
| 99 | if ($enforceConn) { | ||
| 100 | $logger->info("enforced DB reconnect"); | ||
| 101 | # close connection to reopen when enforced connect | ||
| 102 | $EAI::DB::DSN = ""; | ||
| 103 | } else { | ||
| 104 | if ($process->{successfullyDone} and $process->{successfullyDone} =~ /\QopenDBConn$DSNeval/ and $execute{retryBecauseOfError}) { | ||
| 105 | $logger->debug("don't connect to DB because of \$process->{successfullyDone} = openDBConn$DSNeval and \$execute{retryBecauseOfError} being set"); | ||
| 106 | return 1; | ||
| 107 | } | ||
| 108 | } | ||
| 109 | unless ($DSNeval) { | ||
| 110 | $logger->error("no DSN available in \$DB->{DSN}".longmess()); | ||
| 111 | $process->{hadErrors} = 1; | ||
| 112 | return 0; | ||
| 113 | } | ||
| 114 | (!$DB->{user} and $DSNeval =~ /\$DB->\{user\}/) and do { | ||
| 115 | $logger->error("specified DSN ('".$DSNeval."') contains \$DB->{user}, which is neither set in \$DB->{user} nor in \$config{sensitive}{".$DB->{prefix}."}{user} !".longmess()); | ||
| 116 | $process->{hadErrors} = 1; | ||
| 117 | return 0; | ||
| 118 | }; | ||
| 119 | $newDSN = eval qq{"$DSNeval"}; | ||
| 120 | if (!$newDSN) { | ||
| 121 | $logger->error("error parsing \$DB->{DSN}(".$DSNeval."), couldn't interpolate all values:".$@.longmess()); | ||
| 122 | $process->{hadErrors} = 1; | ||
| 123 | return 0; | ||
| 124 | } | ||
| 125 | EAI::DB::newDBH($DB,$newDSN) or do { | ||
| 126 | $logger->error("couldn't open database connection for $newDSN".longmess()); | ||
| 127 | $process->{hadErrors} = 1; | ||
| 128 | return 0; # false means error in connection and signal to die... | ||
| 129 | }; | ||
| 130 | $process->{successfullyDone}.="openDBConn".$DSNeval; | ||
| 131 | return 1; | ||
| 132 | } | ||
| 133 | |||
| 134 | # open a FTP connection | ||
| 135 | sub openFTPConn ($;$$) { | ||
| 136 | my ($arg, $enforceConn, $enforceConnForRedo) = @_; | ||
| 137 | my $logger = get_logger(); | ||
| 138 | my ($FTP,$process) = EAI::Common::extractConfigs("opening FTP connection",$arg,"FTP","process"); | ||
| 139 | my $hostname = $FTP->{remoteHost}; | ||
| 140 | $hostname = $FTP->{remoteHost}{$execute{env}} if ref($FTP->{remoteHost}) eq "HASH"; | ||
| 141 | if ($enforceConn and !$common{task}{redoFile}) { | ||
| 142 | $logger->info("enforced FTP connect"); | ||
| 143 | } else { | ||
| 144 | if ($common{task}{redoFile} and !$enforceConnForRedo) { | ||
| 145 | $logger->debug("don't connect to FTP because of redoFile being set"); | ||
| 146 | # don't connect if redo from local file | ||
| 147 | return 1; | ||
| 148 | } else { | ||
| 149 | $logger->info("enforced FTP connect for Redo"); | ||
| 150 | } | ||
| 151 | } | ||
| 152 | # only for set prefix, take username, password, hostkey and privKey from $config{sensitive}{$FTP->{prefix}} (directly or via environment hash) | ||
| 153 | if ($FTP->{prefix}) { | ||
| 154 | $FTP->{user} = EAI::Common::getSensInfo($FTP->{prefix},"user"); | ||
| 155 | $FTP->{pwd} = EAI::Common::getSensInfo($FTP->{prefix},"pwd"); | ||
| 156 | $FTP->{hostkey} = EAI::Common::getSensInfo($FTP->{prefix},"hostkey"); | ||
| 157 | $FTP->{hostkey2} = EAI::Common::getSensInfo($FTP->{prefix},"hostkey2"); | ||
| 158 | $FTP->{privKey} = EAI::Common::getSensInfo($FTP->{prefix},"privKey"); | ||
| 159 | } | ||
| 160 | (!$FTP->{user}) and do { | ||
| 161 | $logger->error("ftp user neither set in \$FTP->{user} nor in \$config{sensitive}{".$FTP->{prefix}."}{user} !".longmess()); | ||
| 162 | $process->{hadErrors} = 1; | ||
| 163 | return 0; | ||
| 164 | }; | ||
| 165 | no warnings 'uninitialized'; | ||
| 166 | $logger->debug("\$FTP->{user}:$FTP->{user}, \$FTP->{privKey}:$FTP->{privKey}, \$FTP->{hostkey}:$FTP->{hostkey}"); | ||
| 167 | EAI::FTP::login($FTP,$hostname,$enforceConn) or do { | ||
| 168 | $logger->error("couldn't open ftp connection for $hostname".longmess()); | ||
| 169 | $process->{hadErrors} = 1; | ||
| 170 | return 0; # false means error in connection and signal to die... | ||
| 171 | }; | ||
| 172 | $process->{successfullyDone}.="openFTPConn".$hostname; | ||
| 173 | return 1; | ||
| 174 | } | ||
| 175 | |||
| 176 | # remove all files in FTP server folders that are older than a given day/month/year | ||
| 177 | sub removeFilesinFolderOlderX ($) { | ||
| 178 | my ($arg) = @_; | ||
| 179 | my $logger = get_logger(); | ||
| 180 | my ($FTP,$process) = EAI::Common::extractConfigs("Cleaning of Archive folders",$arg,"FTP","process"); | ||
| 181 | return 1 if $process->{successfullyDone} and $process->{successfullyDone} =~ /removeFilesOlderX/ and $execute{retryBecauseOfError}; | ||
| 182 | if (EAI::FTP::removeFilesOlderX($FTP)) { | ||
| 183 | $process->{successfullyDone}.="removeFilesOlderX"; | ||
| 184 | return 1; | ||
| 185 | } else { | ||
| 186 | return 0; | ||
| 187 | } | ||
| 188 | } | ||
| 189 | |||
| 190 | # redo file from redo directory if specified (used in getLocalFile and getFileFromFTP) | ||
| 191 | sub redoFiles ($) { | ||
| 192 | my ($arg) = @_; | ||
| 193 | my $logger = get_logger(); | ||
| 194 | return unless $common{task}{redoFile}; | ||
| 195 | my ($File,$process) = EAI::Common::extractConfigs("setting/renaming redo files",$arg,"File","process"); | ||
| 196 | my $redoDir = $execute{redoDir}; | ||
| 197 | # file extension for local redo | ||
| 198 | my ($barename,$ext) = $File->{filename} =~ /(.*)\.(.*?)$/; # get file bare name and extension from filename | ||
| 199 | if (!$ext) { | ||
| 200 | $ext = $File->{extension}; # if no dots in filename (e.g. because of glob) -> no file extension retrievable -> take from here | ||
| 201 | } | ||
| 202 | if (!$ext) { | ||
| 203 | $logger->error("redoFile set, no file extension for renaming redo files! should be either retrievable in filename as .<ext> or be set separately in File=>extension".longmess()); | ||
| 204 | return 0; | ||
| 205 | } | ||
| 206 | $logger->info("redoFile set, redoing files in ".$redoDir.", looking for files with extension ".$ext); | ||
| 207 | if ($File->{filename} =~ /\*/) { | ||
| 208 | $barename = $File->{filename}; | ||
| 209 | $barename =~ s/\*.*$//g; # remove glob pattern and quote dots to allow matching with redo file | ||
| 210 | } | ||
| 211 | if (chdir($redoDir)) { | ||
| 212 | my $globPattern = $barename."*".($ext ? ".$ext" : ""); # extend glob with .$ext only if defined | ||
| 213 | $logger->debug("checking against glob pattern ".$globPattern); | ||
| 214 | for my $redofile (glob qq{"$globPattern"}) { #qq{}, um Ergebnis des interpolierten $globPattern in hochkomma einzuschliessen, weil glob leerzeichen als trennzeichen interpretiert und dann pfade/files mit leerzeichen geglobbed werden. | ||
| 215 | $logger->debug("found candidate file $redofile in $redoDir"); | ||
| 216 | my $redoTimestampPatternPart = $common{task}{redoTimestampPatternPart}; | ||
| 217 | if (!$redoTimestampPatternPart) { | ||
| 218 | $redoTimestampPatternPart = '[\d_]'; # sensible default, but warn... | ||
| 219 | $logger->warn('missing $common{task}{redoTimestampPatternPart}, set to [\d_]'.longmess()); | ||
| 220 | } | ||
| 221 | # check against barename with additional timestamp pattern (e.g. numbers and _) and \.$ext only if defined | ||
| 222 | # anything after barename (and before ".$ext" if extension defined) is regarded as a timestamp | ||
| 223 | my $regexCheck = ($ext ? qr/${barename}.*\.$ext/ : qr/${barename}.*/); | ||
| 224 | $logger->debug("checking candidate against regex $regexCheck"); | ||
| 225 | if ($redofile =~ $regexCheck) { | ||
| 226 | $logger->info("file $redofile available for redo, matched regex $barename.*"); | ||
| 227 | # only rename if not prohibited and not a glob, else just push into retrievedFiles | ||
| 228 | if (!$File->{avoidRenameForRedo} and $File->{filename} !~ /\*/) { | ||
| 229 | rename $redofile, "$barename.$ext" or $logger->error("error renaming file $redofile to $barename.$ext : $!".longmess()); | ||
| 230 | push @{$process->{retrievedFiles}}, "$barename.$ext"; | ||
| 231 | } else { | ||
| 232 | push @{$process->{retrievedFiles}}, $redofile; | ||
| 233 | } | ||
| 234 | } | ||
| 235 | } | ||
| 236 | } else { | ||
| 237 | $logger->error("couldn't change into redo folder ".$redoDir.longmess()); | ||
| 238 | return 0; | ||
| 239 | } | ||
| 240 | chdir($execute{homedir}); | ||
| 241 | return checkFiles($arg); | ||
| 242 | } | ||
| 243 | |||
| 244 | # get local file(s) from source into homedir | ||
| 245 | sub getLocalFiles ($) { | ||
| 246 | my ($arg) = @_; | ||
| 247 | my $logger = get_logger(); | ||
| 248 | my ($File,$process) = EAI::Common::extractConfigs("Getting local files",$arg,"File","process"); | ||
| 249 | return 1 if $process->{successfullyDone} and $process->{successfullyDone} =~ /getLocalFiles/ and $execute{retryBecauseOfError}; | ||
| 250 | @{$process->{retrievedFiles}} = (); # reset last retrieved | ||
| 251 | if ($File->{localFilesystemPath}) { | ||
| 252 | my $localFilesystemPath = $File->{localFilesystemPath}; | ||
| 253 | $localFilesystemPath.="/" if $localFilesystemPath !~ /^.*\/$/; | ||
| 254 | if ($common{task}{redoFile}) { | ||
| 255 | return redoFiles($arg); | ||
| 256 | } else { | ||
| 257 | my @multipleFiles; | ||
| 258 | if ($File->{filename} =~ /\*/) { # if there is a glob character then copy multiple files ! | ||
| 259 | if (chdir($localFilesystemPath)) { | ||
| 260 | @multipleFiles = glob qq{"$File->{filename}"}; | ||
| 261 | chdir($execute{homedir}); | ||
| 262 | } else { | ||
| 263 | $logger->error("couldn't change into folder ".$localFilesystemPath.longmess()); | ||
| 264 | $process->{hadErrors} = 1; | ||
| 265 | return 0; | ||
| 266 | } | ||
| 267 | } else { | ||
| 268 | # no glob char -> single file | ||
| 269 | push @multipleFiles, $File->{filename}; | ||
| 270 | } | ||
| 271 | push @{$process->{retrievedFiles}}, @multipleFiles; | ||
| 272 | for my $localfile (@multipleFiles) { | ||
| 273 | unless ($File->{localFilesystemPath} eq ".") { | ||
| 274 | $logger->info("copying local file: ".$localFilesystemPath.$localfile." to ".$execute{homedir}); | ||
| 275 | copy ($localFilesystemPath.$localfile, ".") or do { | ||
| 276 | $logger->error("couldn't copy ".$localFilesystemPath.$localfile.": $!".longmess()); | ||
| 277 | @{$process->{retrievedFiles}} = (); | ||
| 278 | $process->{hadErrors} = 1; | ||
| 279 | return 0; | ||
| 280 | }; | ||
| 281 | } else { | ||
| 282 | $logger->info("taking local file: ".$localfile." from current folder (".$execute{homedir}.")"); | ||
| 283 | } | ||
| 284 | } | ||
| 285 | } | ||
| 286 | } else { | ||
| 287 | $logger->error("no \$File->{localFilesystemPath} parameter given".longmess()); | ||
| 288 | $process->{hadErrors} = 1; | ||
| 289 | return 0; | ||
| 290 | } | ||
| 291 | $process->{successfullyDone}.="getLocalFiles"; | ||
| 292 | return checkFiles($arg); | ||
| 293 | } | ||
| 294 | |||
| 295 | # get file/s (can also be a glob for multiple files) from FTP into homedir | ||
| 296 | sub getFilesFromFTP ($;$$) { | ||
| 297 | my ($arg,$maxTimeout,$waitTime) = @_; | ||
| 298 | my $logger = get_logger(); | ||
| 299 | my ($FTP,$File,$process) = EAI::Common::extractConfigs("Getting files from ftp",$arg,"FTP","File","process"); | ||
| 300 | return 1 if $process->{successfullyDone} and $process->{successfullyDone} =~ /getFilesFromFTP/ and $execute{retryBecauseOfError}; | ||
| 301 | @{$process->{retrievedFiles}} = (); # reset last retrieved, but this is also necessary to create the retrievedFiles hash entry for passing back the list from getFiles | ||
| 302 | if (defined($FTP->{remoteDir})) { | ||
| 303 | if ($common{task}{redoFile}) { | ||
| 304 | return redoFiles($arg); | ||
| 305 | } else { | ||
| 306 | if ($File->{filename}) { | ||
| 307 | if ($maxTimeout) { | ||
| 308 | my $timer = 0; | ||
| 309 | $waitTime = 10 if !$waitTime; # wait for 10 sec if not given or 0 | ||
| 310 | do { | ||
| 311 | unless (EAI::FTP::fetchFiles($FTP,{firstRunSuccess=>$execute{firstRunSuccess},homedir=>$execute{homedir},fileToRetrieve=>$File->{filename},fileToRetrieveOptional=>1,retrievedFiles=>$process->{retrievedFiles}})) { | ||
| 312 | processingPause($waitTime); | ||
| 313 | $timer += $waitTime; | ||
| 314 | } else { | ||
| 315 | $timer = 0; | ||
| 316 | } | ||
| 317 | } until ($timer == 0 or $timer >= $maxTimeout); # timer = 0: success, else timed out. | ||
| 318 | # issue warning or error depending on optionality | ||
| 319 | if ($File->{optional} or $execute{firstRunSuccess}) { | ||
| 320 | $logger->warn("EAI::FTP::fetchFiles not successful".longmess()) if $timer >= $maxTimeout; | ||
| 321 | } else { | ||
| 322 | $logger->error("EAI::FTP::fetchFiles not successful".longmess()) if $timer >= $maxTimeout; | ||
| 323 | } | ||
| 324 | } else { | ||
| 325 | unless (EAI::FTP::fetchFiles($FTP,{firstRunSuccess=>$execute{firstRunSuccess},homedir=>$execute{homedir},fileToRetrieve=>$File->{filename},fileToRetrieveOptional=>$File->{optional},retrievedFiles=>$process->{retrievedFiles}})) { | ||
| 326 | $logger->warn("EAI::FTP::fetchFiles not successful".longmess()); | ||
| 327 | } | ||
| 328 | } | ||
| 329 | } else { | ||
| 330 | $logger->error("no \$File->{filename} given, can't get it from FTP".longmess()); | ||
| 331 | $process->{hadErrors} = 1; | ||
| 332 | return 0; | ||
| 333 | } | ||
| 334 | } | ||
| 335 | } else { | ||
| 336 | $logger->error("no \$FTP->{remoteDir} parameter defined".longmess()); | ||
| 337 | $process->{hadErrors} = 1; | ||
| 338 | return 0; | ||
| 339 | } | ||
| 340 | if (checkFiles($arg)) { | ||
| 341 | $process->{successfullyDone}.="getFilesFromFTP"; | ||
| 342 | return 1; | ||
| 343 | } else { | ||
| 344 | return 0; | ||
| 345 | } | ||
| 346 | } | ||
| 347 | |||
| 348 | # general procedure to get files from FTP or locally | ||
| 349 | sub getFiles ($) { | ||
| 350 | my ($arg) = @_; | ||
| 351 | my $logger = get_logger(); | ||
| 352 | my ($FTP,$File,$process) = EAI::Common::extractConfigs("",$arg,"FTP","File","process"); | ||
| 353 | if ($File->{localFilesystemPath}) { | ||
| 354 | return getLocalFiles($arg); | ||
| 355 | } else { | ||
| 356 | return getFilesFromFTP($arg); | ||
| 357 | } | ||
| 358 | } | ||
| 359 | |||
| 360 | # check files for continuation of processing and extract archives if needed | ||
| 361 | sub checkFiles ($) { | ||
| 362 | my ($arg) = @_; | ||
| 363 | my $logger = get_logger(); | ||
| 364 | my ($File,$process) = EAI::Common::extractConfigs("checking for existence of files",$arg,"File","process"); | ||
| 365 | my $redoDir = ($common{task}{redoFile} ? $execute{redoDir}."/" : ""); | ||
| 366 | my $fileDoesntExist = 0; | ||
| 367 | if ($process->{retrievedFiles} and @{$process->{retrievedFiles}} >= 1) { | ||
| 368 | for my $singleFilename (@{$process->{retrievedFiles}}) { | ||
| 369 | $logger->debug("checking file: ".$redoDir.$singleFilename); | ||
| 370 | open (CHECKFILE, "<".$redoDir.$singleFilename) or $fileDoesntExist=1; | ||
| 371 | close CHECKFILE; | ||
| 372 | } | ||
| 373 | } else { | ||
| 374 | $fileDoesntExist=1; | ||
| 375 | } | ||
| 376 | if ($fileDoesntExist) { | ||
| 377 | # exceptions from error message and return false for not continuing with readFile/whatever | ||
| 378 | if ($File->{optional} or ($execute{firstRunSuccess} and $common{task}{plannedUntil}) or $common{task}{redoFile}) { | ||
| 379 | if ($execute{firstRunSuccess} and $common{task}{plannedUntil}) { | ||
| 380 | $logger->warn("file ".$File->{filename}." missing with planned execution until ".$common{task}{plannedUntil}." and first run successful, skipping".longmess()); | ||
| 381 | } elsif ($File->{optional}) { | ||
| 382 | $logger->warn("file ".$File->{filename}." missing being marked as optional, skipping".longmess()); | ||
| 383 | } elsif ($common{task}{redoFile}) { | ||
| 384 | $logger->warn("file ".$File->{filename}." missing being retried, skipping".longmess()); | ||
| 385 | } | ||
| 386 | } else { | ||
| 387 | if (!$process->{retrievedFiles} or @{$process->{retrievedFiles}} == 0) { | ||
| 388 | $logger->error("file ".$File->{filename}." was not retrieved (maybe no successful call done to getFilesFromFTP or getLocalFiles ?)".longmess()); | ||
| 389 | } else { | ||
| 390 | $logger->error("file ".$File->{filename}." doesn't exist and is not marked as optional!".longmess()); | ||
| 391 | } | ||
| 392 | $process->{hadErrors} = 1; | ||
| 393 | } | ||
| 394 | $logger->info("checking file failed"); | ||
| 395 | return 0; | ||
| 396 | } | ||
| 397 | # extract from files if needed | ||
| 398 | if ($File->{extract}) { | ||
| 399 | if (@{$process->{retrievedFiles}} == 1) { | ||
| 400 | $logger->info("file to be extracted exists, now extracting archive"); | ||
| 401 | return extractArchives($arg); | ||
| 402 | } else { | ||
| 403 | $logger->error("multiple files returned (probably glob passed as filename), extracting not supported in this case".longmess()); | ||
| 404 | $process->{hadErrors} = 1; | ||
| 405 | return 0; | ||
| 406 | } | ||
| 407 | } | ||
| 408 | # add the files retrieved | ||
| 409 | if ($process->{retrievedFiles} and @{$process->{retrievedFiles}} > 0) { | ||
| 410 | push @{$process->{filenames}}, @{$process->{retrievedFiles}}; | ||
| 411 | $logger->info("files checked: @{$process->{filenames}}"); | ||
| 412 | return 1; | ||
| 413 | } else { | ||
| 414 | $logger->error("no files retrieved for checking".longmess()); | ||
| 415 | return 0; | ||
| 416 | } | ||
| 417 | } | ||
| 418 | |||
| 419 | # extract files from archive | ||
| 420 | sub extractArchives ($) { | ||
| 421 | my ($arg) = @_; | ||
| 422 | my $logger = get_logger(); | ||
| 423 | my ($process) = EAI::Common::extractConfigs("extracting archives",$arg,"process"); | ||
| 424 | return 1 if $process->{successfullyDone} and $process->{successfullyDone} =~ /extractArchives/ and $execute{retryBecauseOfError}; | ||
| 425 | my $redoDir = ($common{task}{redoFile} ? $execute{redoDir}."/" : ""); | ||
| 426 | if ($process->{retrievedFiles}) { | ||
| 427 | my $filename = $process->{retrievedFiles}[0]; # only one file expected. | ||
| 428 | if (! -e $redoDir.$filename) { | ||
| 429 | $logger->error($redoDir.$filename." doesn't exist for extraction".longmess()); | ||
| 430 | $process->{hadErrors} = 1; | ||
| 431 | return 0; | ||
| 432 | } | ||
| 433 | $logger->info("extracting file(s) from archive package: $redoDir$filename"); | ||
| 434 | local $SIG{__WARN__} = sub { $logger->error("opening archive: ".$_[0].longmess()); }; # capturing warnings... | ||
| 435 | my $ae; | ||
| 436 | eval { | ||
| 437 | $ae = Archive::Extract->new(archive => $redoDir.$filename); | ||
| 438 | }; | ||
| 439 | unless ($ae) { | ||
| 440 | $process->{hadErrors} = 1; | ||
| 441 | return 0; | ||
| 442 | } | ||
| 443 | if (!$ae->extract(to => ($redoDir ? $redoDir : "."))) { | ||
| 444 | $logger->error("extracting files: ".$ae->error().longmess()); | ||
| 445 | $process->{hadErrors} = 1; | ||
| 446 | return 0; | ||
| 447 | } | ||
| 448 | $logger->info("extracted files: @{$ae->files}"); | ||
| 449 | push @{$process->{filenames}}, @{$ae->files}; | ||
| 450 | push @{$process->{archivefilenames}}, $filename; # archive itself needs to be removed/historized | ||
| 451 | # reset retrievedFiles to get rid of fetched archives (not to be processed further) | ||
| 452 | @{$process->{retrievedFiles}} = (); | ||
| 453 | } else { | ||
| 454 | $logger->error("no files available to extract..".longmess()); | ||
| 455 | $process->{hadErrors} = 1; | ||
| 456 | return 0; | ||
| 457 | } | ||
| 458 | $process->{successfullyDone}.="extractArchives"; | ||
| 459 | return 1; | ||
| 460 | } | ||
| 461 | |||
| 462 | # get additional data from DB, optionally give ref to hash in argument $refToDataHash for returning data there (otherwise data is returned in $process->{additionalLookupData}) | ||
| 463 | sub getAdditionalDBData ($;$) { | ||
| 464 | my ($arg,$refToDataHash) = @_; | ||
| 465 | my $logger = get_logger(); | ||
| 466 | my ($DB,$process) = EAI::Common::extractConfigs("Getting additional data from DB",$arg,"DB","process"); | ||
| 467 | return 1 if $process->{successfullyDone} and $process->{successfullyDone} =~ /getAdditionalDBData/ and $execute{retryBecauseOfError}; | ||
| 468 | # reset additionalLookupData to avoid strange errors in retrying run. Also needed to pass data back as reference | ||
| 469 | %{$process->{additionalLookupData}} = (); | ||
| 470 | if ($refToDataHash and ref($refToDataHash) ne "HASH") { | ||
| 471 | $logger->error("passed second argument \$refToDataHash is not a ref to a hash".longmess()); | ||
| 472 | return 0; | ||
| 473 | } | ||
| 474 | return 0 if !checkParam($DB,"additionalLookup"); | ||
| 475 | return 0 if !checkParam($DB,"additionalLookupKeys"); | ||
| 476 | # additional lookup needed (e.g. used in addtlProcessing), if optional $refToDataHash given pass data into that? | ||
| 477 | my $readSuccess = EAI::DB::readFromDBHash({query => $DB->{additionalLookup}, keyfields=> $DB->{additionalLookupKeys}}, ($refToDataHash ? \%{$refToDataHash} : \%{$process->{additionalLookupData}})); | ||
| 478 | $process->{successfullyDone}.="getAdditionalDBData" if $readSuccess; | ||
| 479 | return $readSuccess; | ||
| 480 | } | ||
| 481 | |||
| 482 | # read data from file | ||
| 483 | sub readFileData ($) { | ||
| 484 | my ($arg) = @_; | ||
| 485 | my $logger = get_logger(); | ||
| 486 | my ($File,$process) = EAI::Common::extractConfigs("reading file data",$arg,"File","process"); | ||
| 487 | my $redoDir = $execute{redoDir}."/" if $common{task}{redoFile}; | ||
| 488 | return 1 if $process->{successfullyDone} and $process->{successfullyDone} =~ /readFileData/ and $execute{retryBecauseOfError}; | ||
| 489 | my $readSuccess; | ||
| 490 | @{$process->{data}} = (); # reset data in case of error retries having erroneous data | ||
| 491 | if ($File->{format_xlformat}) { | ||
| 492 | $readSuccess = EAI::File::readExcel($File, \@{$process->{data}}, $process->{filenames}, $redoDir, $process->{countPercent}); | ||
| 493 | } elsif ($File->{format_XML}) { | ||
| 494 | $readSuccess = EAI::File::readXML($File, \@{$process->{data}}, $process->{filenames}, $redoDir); | ||
| 495 | } else { | ||
| 496 | $readSuccess = EAI::File::readText($File, \@{$process->{data}}, $process->{filenames}, $redoDir, $process->{countPercent}); | ||
| 497 | } | ||
| 498 | $process->{successfullyDone}.="readFileData" if $readSuccess; | ||
| 499 | return $readSuccess; # return error when reading files with readFile/readExcel/readXML | ||
| 500 | } | ||
| 501 | |||
| 502 | # store data into Database | ||
| 503 | sub dumpDataIntoDB ($) { | ||
| 504 | my ($arg) = @_; | ||
| 505 | my $logger = get_logger(); | ||
| 506 | my ($DB,$File,$process) = EAI::Common::extractConfigs("storing data to DB",$arg,"DB","File","process"); | ||
| 507 | return 1 if $process->{successfullyDone} and $process->{successfullyDone} =~ /dumpDataIntoDB/ and $execute{retryBecauseOfError}; | ||
| 508 | return 0 if !checkParam($DB,"tablename"); | ||
| 509 | our $hadDBErrors = 0; | ||
| 510 | if ($process->{data} and @{$process->{data}}) { # data supplied? | ||
| 511 | if ($DB->{noDumpIntoDB}) { | ||
| 512 | $logger->info("skip dumping of ".$File->{filename}." into DB"); | ||
| 513 | } else { | ||
| 514 | my $table = $DB->{tablename}; | ||
| 515 | # Transaction begin | ||
| 516 | unless ($DB->{noDBTransaction}) { | ||
| 517 | EAI::DB::beginWork() or do { | ||
| 518 | $logger->error ("couldn't start DB transaction".longmess()); | ||
| 519 | $hadDBErrors=1; | ||
| 520 | }; | ||
| 521 | } | ||
| 522 | # store data, tables are deleted if explicitly marked | ||
| 523 | if ($DB->{dontKeepContent}) { | ||
| 524 | $logger->info("removing all data from Table $table ..."); | ||
| 525 | EAI::DB::doInDB({doString => "delete from $table"}); | ||
| 526 | } | ||
| 527 | $logger->info("dumping data to table $table"); | ||
| 528 | if (! EAI::DB::storeInDB($DB, $process->{data},$process->{countPercent})) { | ||
| 529 | $logger->error("error storing DB data.. ".longmess()); | ||
| 530 | $hadDBErrors=1; | ||
| 531 | } | ||
| 532 | # post processing (Perl code) for config, where postDumpProcessing is defined | ||
| 533 | if ($DB->{postDumpProcessing}) { | ||
| 534 | evalCustomCode($DB->{postDumpProcessing},"postDumpProcessing",\$hadDBErrors); | ||
| 535 | } | ||
| 536 | # post processing (execute in DB!) for all configs, where postDumpExecs conditions and referred execs (DB scripts, that should be executed) are defined | ||
| 537 | if (!$hadDBErrors and $DB->{postDumpExecs}) { | ||
| 538 | $logger->info("starting postDumpExecs ... "); | ||
| 539 | for my $postDumpExec (@{$DB->{postDumpExecs}}) { | ||
| 540 | $logger->info("checking postDumpExec condition: ".$postDumpExec->{condition}); | ||
| 541 | my $dopostdumpexec; | ||
| 542 | if (ref($config{executeOnInit}) eq "CODE") { | ||
| 543 | eval {$dopostdumpexec = eval $postDumpExec->{condition}->();}; | ||
| 544 | } else { | ||
| 545 | $dopostdumpexec = eval $postDumpExec->{condition}; | ||
| 546 | } | ||
| 547 | if ($@) { | ||
| 548 | $logger->error("error parsing postDumpExec condition: ".(ref($postDumpExec->{condition}) eq "CODE" ? "defined sub" : "'".$postDumpExec->{condition}."'").": $@".longmess()); | ||
| 549 | $hadDBErrors = 1; | ||
| 550 | last; | ||
| 551 | } | ||
| 552 | if ($dopostdumpexec) { | ||
| 553 | for my $preexec (@{$postDumpExec->{execs}}) { | ||
| 554 | if ($preexec) { # only if defined (there could be an interpolation of perl variables, if these are contained in $exec. This is for setting $selectedDate in postDumpProcessing. | ||
| 555 | $logger->debug("pre eval execute: $preexec"); | ||
| 556 | # eval qq{"$preexec"} doesn't evaluate $preexec but the quoted string (to enforce interpolation where needed) | ||
| 557 | my $exec = eval qq{"$preexec"} if $preexec =~ /$/; # only interpolate if perl scalars are contained | ||
| 558 | if ($@) { | ||
| 559 | $logger->error("error evaluating '".$preexec."': $@".longmess()); | ||
| 560 | } else { | ||
| 561 | $logger->info("post execute: $exec"); | ||
| 562 | if (!EAI::DB::doInDB({doString => $exec})) { | ||
| 563 | $logger->error("error executing postDumpExec: '".$exec."' .. ".longmess()); | ||
| 564 | $hadDBErrors=1; | ||
| 565 | last; | ||
| 566 | } | ||
| 567 | } | ||
| 568 | } | ||
| 569 | } | ||
| 570 | } | ||
| 571 | } | ||
| 572 | $logger->info("postDumpExecs finished"); | ||
| 573 | } | ||
| 574 | if (!$hadDBErrors) { | ||
| 575 | # Transaction: commit of DB changes | ||
| 576 | unless ($DB->{noDBTransaction}) { | ||
| 577 | $logger->debug("committing data"); | ||
| 578 | if (EAI::DB::commit()) { | ||
| 579 | $logger->info("data stored into table $table successfully"); | ||
| 580 | } else { | ||
| 581 | $logger->error("error when committing".longmess()); | ||
| 582 | $hadDBErrors = 1; | ||
| 583 | }; | ||
| 584 | } | ||
| 585 | } else { # error dumping to DB or during pre/postDumpExecs | ||
| 586 | unless ($DB->{noDBTransaction}) { | ||
| 587 | $logger->info("Rollback because of error when storing into database"); | ||
| 588 | EAI::DB::rollback() or $logger->error("error with rollback ...".longmess()); | ||
| 589 | } | ||
| 590 | $logger->error("error storing data into database".longmess()); | ||
| 591 | $hadDBErrors = 1; | ||
| 592 | } | ||
| 593 | } | ||
| 594 | } else { | ||
| 595 | if ($File->{emptyOK}) { | ||
| 596 | $logger->warn("received empty data, will be ignored as \$File{emptyOK}=1".longmess()); | ||
| 597 | } else { | ||
| 598 | my @filesdone = @{$process->{filenames}} if $process->{filenames}; | ||
| 599 | $logger->error("error as none of the following files contained any data: @filesdone".longmess()); | ||
| 600 | $hadDBErrors = 1; | ||
| 601 | } | ||
| 602 | } | ||
| 603 | $process->{successfullyDone}.="dumpDataIntoDB" if !$hadDBErrors; | ||
| 604 | $process->{hadErrors} = $hadDBErrors if $hadDBErrors; | ||
| 605 | return !$hadDBErrors; | ||
| 606 | } | ||
| 607 | |||
| 608 | # evaluate custom code contained either in string or ref to sub | ||
| 609 | sub evalCustomCode ($$;$) { | ||
| 610 | my ($customCode,$processingName,$hadDBErrorsRef) = @_; | ||
| 611 | my $logger = get_logger(); | ||
| 612 | $logger->info("starting $processingName"); | ||
| 613 | if (ref($customCode) eq "CODE") { | ||
| 614 | eval {$customCode->()}; | ||
| 615 | } else { | ||
| 616 | my $hadDBErrors; | ||
| 617 | eval $customCode; | ||
| 618 | $$hadDBErrorsRef = $hadDBErrors; | ||
| 619 | } | ||
| 620 | $logger->error("eval of $processingName ".(ref($customCode) eq "CODE" ? "defined sub" : "'".$customCode."'")." returned error:$@".longmess()) if $@; | ||
| 621 | } | ||
| 622 | |||
| 623 | |||
| 624 | # mark files as being processed depending on whether there were errors, also decide on removal/archiving of downloaded files | ||
| 625 | sub markProcessed ($) { | ||
| 626 | my ($arg) = @_; | ||
| 627 | my $logger = get_logger(); | ||
| 628 | my ($File,$process) = EAI::Common::extractConfigs("marking processed",$arg,"File","process"); | ||
| 629 | # this is important for the archival/deletion on the FTP Server! | ||
| 630 | if ($File->{emptyOK} || !$process->{hadErrors}) { | ||
| 631 | for (@{$process->{filenames}}) { | ||
| 632 | $process->{filesProcessed}{$_} = 1; | ||
| 633 | $logger->info("filesProcessed: $_"); | ||
| 634 | } | ||
| 635 | } else { | ||
| 636 | $process->{hadErrors} = 1; | ||
| 637 | } | ||
| 638 | # mark to be removed or be moved to history | ||
| 639 | if ($File->{dontKeepHistory}) { | ||
| 640 | push @{$execute{filesToDelete}}, @{$process->{filenames}} if $process->{filenames}; | ||
| 641 | push @{$execute{filesToDelete}}, @{$process->{archivefilenames}} if $process->{archivefilenames}; | ||
| 642 | } else { | ||
| 643 | push @{$execute{filesToMoveinHistory}}, @{$process->{filenames}} if $process->{filenames}; | ||
| 644 | push @{$execute{filesToMoveinHistory}}, @{$process->{archivefilenames}} if $process->{archivefilenames}; | ||
| 645 | } | ||
| 646 | } | ||
| 647 | |||
| 648 | # create Data-files from Database | ||
| 649 | sub writeFileFromDB ($) { | ||
| 650 | my ($arg) = @_; | ||
| 651 | my $logger = get_logger(); | ||
| 652 | my ($DB,$File,$process) = EAI::Common::extractConfigs("creating/writing file from DB",$arg,"DB","File","process"); | ||
| 653 | return 1 if $process->{successfullyDone} and $process->{successfullyDone} =~ /writeFileFromDB/ and $execute{retryBecauseOfError}; | ||
| 654 | |||
| 655 | # get data from database, including column names (passed by ref) | ||
| 656 | @{$DB->{columnnames}} = (); # reset columnnames to pass data back as reference | ||
| 657 | @{$process->{data}} = (); # reset data to pass data back as reference | ||
| 658 | EAI::DB::readFromDB($DB,\@{$process->{data}}) or do { | ||
| 659 | $logger->error("couldn' read from DB".longmess()); | ||
| 660 | $process->{hadErrors} = 1; | ||
| 661 | return 0; | ||
| 662 | }; | ||
| 663 | # pass column information from database, if not explicitly set | ||
| 664 | $File->{columns} = $DB->{columnnames} if !$File->{columns}; | ||
| 665 | $logger->warn("no data retrieved from database for file ".$File->{filename}.", query: ".$DB->{query}.longmess()) if ($process->{data} and @{$process->{data}} == 0); | ||
| 666 | # prepare for all configs, where postReadProcessing is defined | ||
| 667 | if ($DB->{postReadProcessing}) { | ||
| 668 | evalCustomCode($DB->{postReadProcessing},"postReadProcessing"); | ||
| 669 | } | ||
| 670 | my $writeSuccess; | ||
| 671 | if ($File->{format_xlformat}) { | ||
| 672 | $writeSuccess = EAI::File::writeExcel($File,\@{$process->{data}},$process->{countPercent}); | ||
| 673 | } else { | ||
| 674 | $writeSuccess = EAI::File::writeText($File,\@{$process->{data}},$process->{countPercent}); | ||
| 675 | } | ||
| 676 | $process->{successfullyDone}.="writeFileFromDB" if $writeSuccess; | ||
| 677 | $process->{hadErrors} = 1 unless $writeSuccess; | ||
| 678 | return $writeSuccess; | ||
| 679 | } | ||
| 680 | |||
| 681 | # create Data-files from Memory | ||
| 682 | sub writeFileFromMemory ($$) { | ||
| 683 | my ($arg, $data) = @_; | ||
| 684 | my $logger = get_logger(); | ||
| 685 | my ($File,$process) = EAI::Common::extractConfigs("creating/writing file from Memory",$arg,"File","process"); | ||
| 686 | return 1 if $process->{successfullyDone} and $process->{successfullyDone} =~ /writeFileFromMem/ and $execute{retryBecauseOfError}; | ||
| 687 | $logger->warn("no columns given for file ".$File->{filename}.longmess()) if !$File->{columns}; | ||
| 688 | $logger->warn("no data available for writing".longmess()) if !$data or ($data and @{$data} == 0); | ||
| 689 | my $writeSuccess; | ||
| 690 | if ($File->{format_xlformat}) { | ||
| 691 | $writeSuccess = EAI::File::writeExcel($File,$data,$process->{countPercent}); | ||
| 692 | } else { | ||
| 693 | $writeSuccess = EAI::File::writeText($File,$data,$process->{countPercent}); | ||
| 694 | } | ||
| 695 | $process->{successfullyDone}.="writeFileFromMem" if $writeSuccess; | ||
| 696 | $process->{hadErrors} = 1 unless $writeSuccess; | ||
| 697 | return $writeSuccess; | ||
| 698 | } | ||
| 699 | |||
| 700 | # put files into local folder if required | ||
| 701 | sub putFileInLocalDir ($) { | ||
| 702 | my ($arg) = @_; | ||
| 703 | my $logger = get_logger(); | ||
| 704 | my ($File,$process) = EAI::Common::extractConfigs("putting file into local folder",$arg,"File","process"); | ||
| 705 | return 1 if $process->{successfullyDone} and $process->{successfullyDone} =~ /putFileInLocalDir/ and $execute{retryBecauseOfError}; | ||
| 706 | if ($File->{localFilesystemPath} and $File->{localFilesystemPath} ne '.') { | ||
| 707 | $logger->info("moving file '".$File->{filename}."' into local dir ".$File->{localFilesystemPath}); | ||
| 708 | move($File->{filename}, $File->{localFilesystemPath}."/".$File->{filename}) or do { | ||
| 709 | $logger->error("couldn't move ".$File->{filename}." into ".$File->{localFilesystemPath}.": $!".longmess()); | ||
| 710 | $process->{hadErrors} = 1; | ||
| 711 | return 0; | ||
| 712 | }; | ||
| 713 | } else { | ||
| 714 | if ($File->{localFilesystemPath} eq '.') { | ||
| 715 | $logger->info("\$File->{localFilesystemPath} is '.', didn't move files"); | ||
| 716 | } else { | ||
| 717 | $logger->error("no \$File->{localFilesystemPath} defined, therefore no files processed with putFileInLocalDir".longmess()); | ||
| 718 | return 0; | ||
| 719 | } | ||
| 720 | } | ||
| 721 | $process->{successfullyDone}.="putFileInLocalDir"; | ||
| 722 | return 1; | ||
| 723 | } | ||
| 724 | |||
| 725 | # mark to be removed or be moved to history after upload | ||
| 726 | sub markUploadForHistoryDelete ($) { | ||
| 727 | my ($arg) = @_; | ||
| 728 | my $logger = get_logger(); | ||
| 729 | my ($File) = EAI::Common::extractConfigs("",$arg,"File"); | ||
| 730 | if ($File->{dontKeepHistory}) { | ||
| 731 | push @{$execute{filesUploadedToDelete}}, $File->{filename}; | ||
| 732 | } elsif (!$File->{dontMoveIntoHistory}) { | ||
| 733 | push @{$execute{filesToMoveinHistoryUpload}}, $File->{filename}; | ||
| 734 | } | ||
| 735 | } | ||
| 736 | |||
| 737 | # upload files to FTP | ||
| 738 | sub uploadFileToFTP ($) { | ||
| 739 | my ($arg) = @_; | ||
| 740 | my $logger = get_logger(); | ||
| 741 | my ($FTP,$File,$process) = EAI::Common::extractConfigs("uploading files to FTP",$arg,"FTP","File","process"); | ||
| 742 | return 1 if $process->{successfullyDone} and $process->{successfullyDone} =~ /uploadFileToFTP/ and $execute{retryBecauseOfError}; | ||
| 743 | markUploadForHistoryDelete($arg) unless ($FTP->{localDir}); | ||
| 744 | if (defined($FTP->{remoteDir})) { | ||
| 745 | $logger->debug ("upload of file '".$File->{filename}."' using FTP"); | ||
| 746 | EAI::Common::setErrSubject("Upload of file to FTP remoteDir ".$FTP->{remoteDir}); | ||
| 747 | if (!EAI::FTP::putFile ($FTP,{fileToWrite => $File->{filename}})) { | ||
| 748 | $process->{hadErrors} = 1; | ||
| 749 | return 0; | ||
| 750 | } | ||
| 751 | } else { | ||
| 752 | $logger->warn("no \$FTP->{remoteDir} defined, therefore no files processed with uploadFileToFTP".longmess()); | ||
| 753 | } | ||
| 754 | $process->{successfullyDone}.="uploadFileToFTP"; | ||
| 755 | return 1; | ||
| 756 | } | ||
| 757 | |||
| 758 | # upload files using an upload command program | ||
| 759 | sub uploadFileCMD ($) { | ||
| 760 | my ($arg) = @_; | ||
| 761 | my $logger = get_logger(); | ||
| 762 | my ($FTP,$File,$process) = EAI::Common::extractConfigs("uploading files with CMD",$arg,"FTP","File","process"); | ||
| 763 | return 1 if $process->{successfullyDone} and $process->{successfullyDone} =~ /uploadFileCMD/ and $execute{retryBecauseOfError}; | ||
| 764 | markUploadForHistoryDelete($arg) unless ($FTP->{localDir}); | ||
| 765 | if ($process->{uploadCMD}) { | ||
| 766 | $logger->debug ("upload of file '".$File->{filename}."' using uploadCMD ".$process->{uploadCMD}); | ||
| 767 | EAI::Common::setErrSubject("Uploading of file with ".$process->{uploadCMD}); | ||
| 768 | system $process->{uploadCMD}; | ||
| 769 | my $errHappened; | ||
| 770 | if ($? == -1) { | ||
| 771 | $logger->error($process->{uploadCMD}." failed: $!".longmess()); | ||
| 772 | $errHappened = 1; | ||
| 773 | } elsif ($? & 127) { | ||
| 774 | $logger->error($process->{uploadCMD}." unexpected finished returning ".($? & 127).", ".(($? & 128) ? 'with' : 'without')." coredump".longmess()); | ||
| 775 | $errHappened = 1; | ||
| 776 | } elsif ($? != 0) { | ||
| 777 | $logger->error($process->{uploadCMD}." finished returning ".($? >> 8).", err: $!".longmess()); | ||
| 778 | $errHappened = 1; | ||
| 779 | } else { | ||
| 780 | $logger->info("finished upload using ".$process->{uploadCMD}); | ||
| 781 | } | ||
| 782 | # remove produced files | ||
| 783 | unlink ($process->{uploadCMDPath}."/".$File->{filename}) or $logger->error("couldn't remove $File->{filename} in ".$process->{uploadCMDPath}.": $!".longmess()); | ||
| 784 | # take error log from uploadCMD | ||
| 785 | if (-e $process->{uploadCMDLogfile} and $errHappened) { | ||
| 786 | my $err = do { | ||
| 787 | local $/ = undef; | ||
| 788 | open (FHERR, "<".$process->{uploadCMDLogfile}) or $logger->error("couldn't read uploadCMD log file ".$process->{uploadCMDLogfile}.": $!".longmess()); | ||
| 789 | <FHERR>; | ||
| 790 | }; | ||
| 791 | $logger->error($process->{uploadCMD}." returned following: $err".longmess()); | ||
| 792 | $process->{hadErrors} = 1; | ||
| 793 | return 0; | ||
| 794 | } | ||
| 795 | } else { | ||
| 796 | $logger->error("no \$process->{uploadCMD} defined, therefore no files processed with uploadFileCMD".longmess()); | ||
| 797 | return 0; | ||
| 798 | } | ||
| 799 | $process->{successfullyDone}.="uploadFileCMD"; | ||
| 800 | return 1; | ||
| 801 | } | ||
| 802 | |||
| 803 | # general procedure to upload files via FTP or CMD or to put into local dir | ||
| 804 | sub uploadFile ($) { | ||
| 805 | my ($arg) = @_; | ||
| 806 | my $logger = get_logger(); | ||
| 807 | my ($File,$process) = EAI::Common::extractConfigs("",$arg,"File","process"); | ||
| 808 | if ($File->{localFilesystemPath}) { | ||
| 809 | return putFileInLocalDir($arg); | ||
| 810 | } elsif ($process->{uploadCMD}) { | ||
| 811 | return uploadFileCMD($arg); | ||
| 812 | } else { | ||
| 813 | return uploadFileToFTP($arg); | ||
| 814 | } | ||
| 815 | } | ||
| 816 | |||
| 817 | my $retrySeconds; # seconds to wait for next retry, can change depending on settings (plannedUntil, errors, etc.) | ||
| 818 | # final processing steps for processEnd (cleanup, FTP removal/archiving) or retry after pausing. No context argument as it always depends on all loads/common | ||
| 819 | sub processingEnd { | ||
| 820 | my $logger = get_logger(); | ||
| 821 | my $processFailed; | ||
| 822 | # incremental checking for errors in processes | ||
| 823 | $processFailed = ($common{process}{hadErrors} ? 1 : 0) unless @loads; | ||
| 824 | $processFailed += ($_->{process}{hadErrors} ? 1 : 0) for @loads; | ||
| 825 | $logger->info("processingEnd: \$processFailed: $processFailed"); | ||
| 826 | unless ($processFailed) { | ||
| 827 | # archiving/removing on the FTP server only if not a local redo | ||
| 828 | if (!$common{task}{redoFile}) { | ||
| 829 | EAI::Common::setErrSubject("FTP archiving/removal"); | ||
| 830 | my (@filesToRemove,@filesToArchive); | ||
| 831 | if ($common{process}{filenames} and !@loads) { # only take common part if no loads were defined. | ||
| 832 | my (%filesToRemove, %filesToArchive); # hash to collect this only once | ||
| 833 | for (@{$common{process}{filenames}}) { | ||
| 834 | # "onlyArchive" files are not processed and there is no need to check whether they were processed, | ||
| 835 | # else only pass the actual processed files for archiving/removal | ||
| 836 | $filesToRemove{$_} = 1 if $common{FTP}{fileToRemove} and ($common{process}{filesProcessed}{$_} or $common{FTP}{onlyArchive}); | ||
| 837 | $filesToArchive{$_} = 1 if $common{FTP}{fileToArchive} and ($common{process}{filesProcessed}{$_} or $common{FTP}{onlyArchive}); | ||
| 838 | } | ||
| 839 | @filesToArchive = keys(%filesToArchive); @filesToRemove = keys(%filesToRemove); | ||
| 840 | if (@filesToArchive or @filesToRemove) { | ||
| 841 | openFTPConn(\%common); | ||
| 842 | $logger->info("file cleanup: ".(@filesToArchive ? "\narchiving @filesToArchive" : "").(@filesToRemove ? "\nremoving @filesToRemove" : "")." on FTP Server..."); | ||
| 843 | EAI::FTP::archiveFiles ({filesToArchive => \@filesToArchive, archiveDir => $common{FTP}{archiveDir}, remoteDir => $common{FTP}{remoteDir}, timestamp => $common{task}{customHistoryTimestamp}}) if @filesToArchive; | ||
| 844 | EAI::FTP::removeFiles ({filesToRemove => \@filesToRemove, remoteDir => $common{FTP}{remoteDir}}) if @filesToRemove; | ||
| 845 | } | ||
| 846 | } | ||
| 847 | for my $load (@loads) { | ||
| 848 | my (%filesToRemove, %filesToArchive); # hash to collect this only once | ||
| 849 | if ($load->{process}{filenames}) { | ||
| 850 | for (@{$load->{process}{filenames}}) { | ||
| 851 | $filesToRemove{$_} = 1 if $load->{FTP}{fileToRemove} and ($load->{process}{filesProcessed}{$_} or $load->{FTP}{onlyArchive}); | ||
| 852 | $filesToArchive{$_} = 1 if $load->{FTP}{fileToArchive} and ($load->{process}{filesProcessed}{$_} or $load->{FTP}{onlyArchive}); | ||
| 853 | } | ||
| 854 | @filesToArchive = keys(%filesToArchive); @filesToRemove = keys(%filesToRemove); | ||
| 855 | if (@filesToArchive or @filesToRemove) { | ||
| 856 | openFTPConn($load); | ||
| 857 | $logger->info("file cleanup: ".(@filesToArchive ? "\narchiving @filesToArchive, " : "").(@filesToRemove ? "\nremoving @filesToRemove" : "")." on FTP Server..."); | ||
| 858 | EAI::FTP::archiveFiles ({filesToArchive => \@filesToArchive, archiveDir => $load->{FTP}{archiveDir}, remoteDir => $load->{FTP}{remoteDir}, timestamp => $common{task}{customHistoryTimestamp}}) if @filesToArchive; | ||
| 859 | EAI::FTP::removeFiles ({filesToRemove => \@filesToRemove, remoteDir => $load->{FTP}{remoteDir}}) if @filesToRemove; | ||
| 860 | } | ||
| 861 | } | ||
| 862 | } | ||
| 863 | } | ||
| 864 | |||
| 865 | # clean up locally | ||
| 866 | EAI::Common::setErrSubject("local archiving/removal"); | ||
| 867 | moveFilesToHistory($common{task}{customHistoryTimestamp}); | ||
| 868 | deleteFiles(); | ||
| 869 | if ($common{task}{plannedUntil}) { | ||
| 870 | $execute{processEnd} = 0; # reset, if repetition is planned | ||
| 871 | $retrySeconds = $common{task}{retrySecondsPlanned}; | ||
| 872 | } else { | ||
| 873 | $execute{processEnd} = 1; | ||
| 874 | } | ||
| 875 | if ($execute{retryBecauseOfError}) { | ||
| 876 | my @filesProcessed = sort keys %{$common{process}{filesProcessed}}; | ||
| 877 | for my $load (@loads) { | ||
| 878 | push @filesProcessed, sort keys %{$load->{process}{filesProcessed}}; | ||
| 879 | } | ||
| 880 | # send success mail, if successful after first failure | ||
| 881 | my $retryScript = $execute{scriptname}.(defined($execute{addToScriptName}) ? " ".$execute{addToScriptName} : ""); | ||
| 882 | EAI::Common::sendGeneralMail("", $execute{errmailaddress},"","","Successful retry of $retryScript","@filesProcessed succesfully done on retry"); | ||
| 883 | } | ||
| 884 | $execute{firstRunSuccess} = 1 if $common{task}{plannedUntil}; # for planned retries (plannedUntil) -> no more error messages (files might be gone) | ||
| 885 | $execute{retryBecauseOfError} = 0; | ||
| 886 | } else { | ||
| 887 | if ($common{task}{plannedUntil} and $execute{firstRunSuccess}) { | ||
| 888 | $retrySeconds = $common{task}{retrySecondsPlanned}; | ||
| 889 | } else { | ||
| 890 | $retrySeconds = $common{task}{retrySecondsErr}; | ||
| 891 | $execute{retryBecauseOfError} = 1; | ||
| 892 | $execute{failcount}++; | ||
| 893 | } | ||
| 894 | $logger->debug("processingEnd: process failed, \$retrySeconds $retrySeconds, \$execute{failcount}: $execute{failcount}"); | ||
| 895 | } | ||
| 896 | # $execute{processEnd} is only set unless ($processFailed) or $common{task}{plannedUntil} is set | ||
| 897 | unless ($execute{processEnd}) { | ||
| 898 | # refresh config for getting changes, also refresh changes in logging configuration | ||
| 899 | $logger->info("process has not ended, refreshing configs"); | ||
| 900 | readConfigs($execute{envraw}); | ||
| 901 | doExecuteOnInit(); | ||
| 902 | EAI::Common::setupLogging(); | ||
| 903 | # pausing processing/retry | ||
| 904 | $retrySeconds = 60 if !$retrySeconds; # sanity fallback if retrySecondsErr not set | ||
| 905 | my $failcountFinish; | ||
| 906 | my $retrySecondsXfails = (defined($common{task}{retrySecondsXfails}) ? $common{task}{retrySecondsXfails} : 0); | ||
| 907 | if ($execute{failcount} > $retrySecondsXfails) { | ||
| 908 | $logger->info("fail count reached $retrySecondsXfails, so now retrySeconds are switched to $common{task}{retrySecondsErrAfterXfails}") if $common{task}{retrySecondsErrAfterXfails}; | ||
| 909 | $failcountFinish = 1 if !$common{task}{retrySecondsErrAfterXfails}; | ||
| 910 | $retrySeconds = $common{task}{retrySecondsErrAfterXfails}; | ||
| 911 | } | ||
| 912 | my $nextStartTime = calcNextStartTime($retrySeconds); | ||
| 913 | my $currentTime = EAI::DateUtil::get_curtime("%02d%02d%02d"); | ||
| 914 | my $endTime = $common{task}{plannedUntil}; | ||
| 915 | $endTime .= ($endTime eq "2359" ? "59" : (length($endTime) == 4 ? "00" : "")) if $endTime; # amend HHMM time with seconds, special case 235959 | ||
| 916 | $endTime = "235959" if !$endTime and $processFailed; # set to retry until end of day for failed processes (can be shortened with $common{task}{retrySecondsXfails}) | ||
| 917 | $endTime = "000000->not set" if !$endTime; # if neither planned nor process failed then endtime is undefined and needs to be lower than any currentTime for next decision | ||
| 918 | $logger->info("----------------------------------------------------------------------------------------------"); | ||
| 919 | if ($failcountFinish or $nextStartTime >= $endTime or ($common{task}{retryEndsAfterMidnight} and ($nextStartTime =~ /1....../ or (substr($execute{startingTime},0,2) > substr($currentTime,0,2))))) { | ||
| 920 | $logger->info("finished processing due to reaching set error count \$common{task}{retrySecondsXfails} $common{task}{retrySecondsXfails} and \$common{task}{retrySecondsErrAfterXfails} is false") if $failcountFinish; | ||
| 921 | $logger->info("finished processing due to defined ending retry after midnight: nextStartTime=$nextStartTime, startingTime=$execute{startingTime}, currentTime=$currentTime, \$common{task}{retryEndsAfterMidnight}=$common{task}{retryEndsAfterMidnight}") if ($common{task}{retryEndsAfterMidnight} and ($nextStartTime =~ /1....../ or (substr($execute{startingTime},0,2) > substr($currentTime,0,2)))); | ||
| 922 | $logger->info("finished processing due to time out: next start time($nextStartTime) >= endTime($endTime)") if $nextStartTime >= $endTime; | ||
| 923 | moveFilesToHistory($common{task}{customHistoryTimestamp}); | ||
| 924 | deleteFiles(); | ||
| 925 | $execute{processEnd}=1; | ||
| 926 | } else { | ||
| 927 | # reset hadErrors flag, successfullyDone (only for planned retries) and filenames/filesProcessed | ||
| 928 | unless (@loads) { | ||
| 929 | $common{process}{hadErrors} = 0; | ||
| 930 | $common{process}{successfullyDone} = "" if $common{task}{plannedUntil}; # only reset for planned retries | ||
| 931 | delete($common{process}{filesProcessed}); | ||
| 932 | delete($common{process}{filenames}); | ||
| 933 | } | ||
| 934 | for (@loads) { | ||
| 935 | $_->{process}{hadErrors} = 0; | ||
| 936 | $_->{process}{successfullyDone} = "" if $common{task}{plannedUntil}; # only reset for planned retries | ||
| 937 | delete($_->{process}{filesProcessed}); | ||
| 938 | delete($_->{process}{filenames}); | ||
| 939 | } | ||
| 940 | $logger->info("Retrying in ".$retrySeconds." seconds because of ".($execute{retryBecauseOfError} ? "occurred error" : "planned retry")." until ".$endTime.", next run: ".$nextStartTime); | ||
| 941 | sleep $retrySeconds; | ||
| 942 | } | ||
| 943 | } else { | ||
| 944 | $logger->info("------> finished $execute{scriptname}"); | ||
| 945 | } | ||
| 946 | # reset error mail filter for planned tasks .. | ||
| 947 | $EAI::Common::alreadySent = 0 unless $execute{retryBecauseOfError}; | ||
| 948 | return $execute{processEnd}; | ||
| 949 | } | ||
| 950 | |||
| 951 | my $processingInitialized = 0; # specifies that the process was initialized | ||
| 952 | # wrapper for processingEnd to be used at the beginning of the process loop | ||
| 953 | sub processingContinues { | ||
| 954 | if ($processingInitialized) { | ||
| 955 | # second start: process loop finished, normal call to processingEnd() and return its inverted result | ||
| 956 | return !processingEnd(); | ||
| 957 | } else { | ||
| 958 | # at the first start always return true to enter the process loop | ||
| 959 | $processingInitialized = 1; | ||
| 960 | return 1; | ||
| 961 | } | ||
| 962 | } | ||
| 963 | |||
| 964 | sub standardLoop (;$) { | ||
| 965 | my ($getAddtlDBData) = @_; | ||
| 966 | my $logger = get_logger(); | ||
| 967 | $logger->info("starting standard loop"); | ||
| 968 | while (processingContinues()) { | ||
| 969 | if ($common{DB}{DSN}) { | ||
| 970 | openDBConn(\%common,1) or $logger->error("failed opening DB connection".longmess()); | ||
| 971 | } | ||
| 972 | if ($common{FTP}{remoteHost}) { | ||
| 973 | openFTPConn(\%common,1) or $logger->error("failed opening FTP connection".longmess()); | ||
| 974 | } | ||
| 975 | if (@loads) { | ||
| 976 | $logger->info("processing loads in standard loop"); | ||
| 977 | for my $load (@loads) { | ||
| 978 | if (getFiles($load)) { | ||
| 979 | getAdditionalDBData($load) if $getAddtlDBData; | ||
| 980 | readFileData($load); | ||
| 981 | dumpDataIntoDB($load); | ||
| 982 | markProcessed($load); | ||
| 983 | } | ||
| 984 | } | ||
| 985 | } else { | ||
| 986 | $logger->info("processing common in standard loop"); | ||
| 987 | if (getFiles(\%common)) { | ||
| 988 | getAdditionalDBData(\%common) if $getAddtlDBData; | ||
| 989 | readFileData(\%common); | ||
| 990 | dumpDataIntoDB(\%common); | ||
| 991 | markProcessed(\%common); | ||
| 992 | } | ||
| 993 | } | ||
| 994 | } | ||
| 995 | $processingInitialized = 0; | ||
| 996 | } | ||
| 997 | |||
| 998 | # helps to calculate next start time | ||
| 999 | sub calcNextStartTime ($) { | ||
| 1000 | my ($seconds) = @_; | ||
| 1001 | return EAI::DateUtil::get_curtime("%02d%02d%02d",$seconds); | ||
| 1002 | } | ||
| 1003 | |||
| 1004 | # generally available procedure for pausing processing | ||
| 1005 | sub processingPause ($) { | ||
| 1006 | my ($pauseSeconds) = @_; | ||
| 1007 | my $logger = get_logger(); | ||
| 1008 | $logger->info("pausing ".$pauseSeconds." seconds, resume processing: ".calcNextStartTime($pauseSeconds)); | ||
| 1009 | sleep $pauseSeconds; | ||
| 1010 | } | ||
| 1011 | |||
| 1012 | # moving files into history folder | ||
| 1013 | sub moveFilesToHistory (;$) { | ||
| 1014 | my ($archiveTimestamp) = @_; | ||
| 1015 | my $logger = get_logger(); | ||
| 1016 | $archiveTimestamp = EAI::DateUtil::get_curdatetime() if !$archiveTimestamp; | ||
| 1017 | my $redoDir = ($common{task}{redoFile} ? $execute{redoDir}."/" : ""); | ||
| 1018 | EAI::Common::setErrSubject("local archiving"); | ||
| 1019 | for my $histFolder ("historyFolder", "historyFolderUpload") { | ||
| 1020 | my @filenames = (); | ||
| 1021 | if ($histFolder eq "historyFolderUpload") { | ||
| 1022 | @filenames = @{$execute{filesToMoveinHistoryUpload}} if $execute{filesToMoveinHistoryUpload} and @{$execute{filesToMoveinHistoryUpload}}; | ||
| 1023 | $redoDir = ""; # no redoDir for uploads ! | ||
| 1024 | } else { | ||
| 1025 | @filenames = @{$execute{filesToMoveinHistory}} if $execute{filesToMoveinHistory} and @{$execute{filesToMoveinHistory}}; | ||
| 1026 | } | ||
| 1027 | for (@filenames) { | ||
| 1028 | my ($strippedName, $ext) = /(.+)\.(.+?)$/; | ||
| 1029 | # if done from a redoDir, then add this folder to file (e.g. if done from redo/user specific folder then Filename_20190219_124409.txt becomes Filename_20190219_124409_redo_userspecificfolder_.txt) | ||
| 1030 | my $cutOffSpec = $archiveTimestamp; | ||
| 1031 | if ($redoDir) { | ||
| 1032 | my $redoSpec = $redoDir; | ||
| 1033 | $redoSpec =~ s/[\/\\\*\|\?:<>"]/_/g; | ||
| 1034 | $cutOffSpec = $archiveTimestamp.'_'.$redoSpec; | ||
| 1035 | } | ||
| 1036 | my $histTarget = $execute{$histFolder}."/".$strippedName."_".$cutOffSpec.".".$ext; | ||
| 1037 | $logger->info("moving local ".($common{task}{redoFile} ? "re-done " : "")."file $redoDir$_ into $histTarget"); | ||
| 1038 | rename $redoDir.$_, $histTarget or $logger->error("error when moving local file $redoDir$_ into $histTarget: $!".longmess()); | ||
| 1039 | } | ||
| 1040 | } | ||
| 1041 | @{$execute{filesToMoveinHistoryUpload}}=(); | ||
| 1042 | @{$execute{filesToMoveinHistory}}=(); | ||
| 1043 | } | ||
| 1044 | |||
| 1045 | # removing files | ||
| 1046 | sub deleteFiles () { | ||
| 1047 | my $logger = get_logger(); | ||
| 1048 | my $redoDir = ($common{task}{redoFile} ? $execute{redoDir}."/" : ""); | ||
| 1049 | EAI::Common::setErrSubject("local cleanup"); | ||
| 1050 | my %alreadyDeleted; # to avoid unnecessary errors when unlinking below | ||
| 1051 | for my $whatToDelete ("filesToDelete","filesUploadedToDelete") { | ||
| 1052 | #$redoDir = "" if $whatToDelete eq "filesUploadedToDelete"; | ||
| 1053 | my @filenames = @{$execute{$whatToDelete}} if $execute{$whatToDelete} and @{$execute{$whatToDelete}}; | ||
| 1054 | for (@filenames) { | ||
| 1055 | unless ($alreadyDeleted{"$redoDir$_"}) { | ||
| 1056 | $logger->info("removing local ".($common{task}{redoFile} ? "re-done " : "")."file $redoDir$_ "); | ||
| 1057 | unlink $redoDir.$_ or $logger->error("error when removing local file $redoDir$_ : $!".longmess()); | ||
| 1058 | $alreadyDeleted{"$redoDir$_"} = 1; | ||
| 1059 | } | ||
| 1060 | } | ||
| 1061 | @{$execute{$whatToDelete}}=(); | ||
| 1062 | } | ||
| 1063 | } | ||
| 1064 | 1; | ||
| 1065 | __END__ | ||