/*---------------------------------------------------------------------------*\
========= |
\\ / F ield | OpenFOAM: The Open Source CFD Toolbox
\\ / O peration | Website: https://openfoam.org
\\ / A nd | Copyright (C) 2017-2026 OpenFOAM Foundation
\\/ M anipulation |
-------------------------------------------------------------------------------
License
This file is part of OpenFOAM.
OpenFOAM is free software: you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
OpenFOAM 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 General Public License
for more details.
You should have received a copy of the GNU General Public License
along with OpenFOAM. If not, see .
\*---------------------------------------------------------------------------*/
#include "fileOperation.H"
#include "decomposedBlockData.H"
#include "polyMesh.H"
#include "Time.H"
#include "OSspecific.H"
#include "read.H"
/* * * * * * * * * * * * * * * Static Member Data * * * * * * * * * * * * * */
namespace Foam
{
autoPtr fileOperation::fileHandlerPtr_;
defineTypeNameAndDebug(fileOperation, 0);
defineRunTimeSelectionTable(fileOperation, word);
}
const Foam::NamedEnum
Foam::fileOperation::pathTypeNames_
{
"notFound",
"absolute",
"objectPath",
"writeObject",
"uncollatedProc",
"globalProc",
"localProc",
"parentObjectPath",
"findInstance",
"uncollatedProcInstance",
"globalProcInstance",
"localProcInstance"
};
Foam::word Foam::fileOperation::defaultFileHandler
(
debug::optimisationSwitches().lookupOrAddDefault
(
"fileHandler",
// Foam::fileOperations::uncollatedFileOperation::typeName,
word("uncollated")
)
);
Foam::word Foam::fileOperation::processorsBaseDir = "processors";
// * * * * * * * * * * * * * Private Member Functions * * * * * * * * * * * //
Foam::fileMonitor& Foam::fileOperation::monitor() const
{
if (!monitorPtr_.valid())
{
monitorPtr_.reset
(
new fileMonitor
(
regIOobject::fileModificationChecking == IOobject::inotify
|| regIOobject::fileModificationChecking == IOobject::inotifyMaster
)
);
}
return monitorPtr_();
}
Foam::instantList Foam::fileOperation::sortTimes
(
const fileNameList& dirEntries
)
{
// Initialise instant list
instantList Times(dirEntries.size() + 1);
label nTimes = 0;
// Check for "constant"
forAll(dirEntries, i)
{
if (dirEntries[i] == Time::constantName)
{
Times[nTimes].value() = Time::constantValue;
Times[nTimes].name() = dirEntries[i];
nTimes++;
break;
}
}
// Read and parse all the entries in the directory
forAll(dirEntries, i)
{
scalar timeValue;
if (readScalar(dirEntries[i].c_str(), timeValue))
{
Times[nTimes].value() = timeValue;
Times[nTimes].name() = dirEntries[i];
nTimes++;
}
}
// Reset the length of the times list
Times.setSize(nTimes);
if (nTimes > 1)
{
std::sort(&Times[0], Times.end(), instant::less());
}
return Times;
}
void Foam::fileOperation::mergeTimes
(
const instantList& extraTimes,
instantList& times
)
{
if (extraTimes.size())
{
const bool haveConstant =
times.size() > 0 && times[0].name() == Time::constantName;
const bool haveExtraConstant =
extraTimes.size() > 0 && extraTimes[0].name() == Time::constantName;
// Combine times
instantList combinedTimes(times.size()+extraTimes.size());
label sz = 0;
label extrai = 0;
if (haveExtraConstant)
{
extrai = 1;
if (!haveConstant)
{
combinedTimes[sz++] = extraTimes[0]; // constant
}
}
forAll(times, i)
{
combinedTimes[sz++] = times[i];
}
for (; extrai < extraTimes.size(); extrai++)
{
combinedTimes[sz++] = extraTimes[extrai];
}
combinedTimes.setSize(sz);
times.transfer(combinedTimes);
// Sort
if (times.size() > 1)
{
label starti = 0;
if (times[0].name() == Time::constantName)
{
starti = 1;
}
std::sort(×[starti], times.end(), instant::less());
// Filter out duplicates
label newi = starti+1;
for (label i = newi; i < times.size(); i++)
{
if (times[i].value() != times[i-1].value())
{
if (newi != i)
{
times[newi] = times[i];
}
newi++;
}
}
times.setSize(newi);
}
}
}
bool Foam::fileOperation::isFileOrDir(const bool isFile, const fileName& f)
{
return
(isFile && Foam::isFile(f))
|| (!isFile && Foam::isDir(f));
}
Foam::tmpNrc
Foam::fileOperation::lookupProcessorsPath(const fileName& fName) const
{
// If path is local to a processor (e.g. contains 'processor2')
// find the corresponding actual processor directory (e.g. 'processors4')
// and index (2)
fileName path;
fileName pDir;
fileName local;
label gStart;
label gSz;
label numProcs;
label proci =
splitProcessorPath(fName, path, pDir, local, gStart, gSz, numProcs);
if (proci != -1)
{
const fileName procPath(path/pDir);
HashTable::const_iterator iter =
procsDirs_.find(procPath);
if (iter != procsDirs_.end())
{
return iter();
}
// Read all directories to see any beginning with processor
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
DynamicList procDirs;
// Note: use parallel synchronised reading so cache will be same
// order on all processors
fileNameList dirNames(readDir(path, fileType::directory));
// Extract info from processorsDDD or processorDDD:
// - highest processor number
// - directory+offset containing data for proci
label maxProc = -1;
forAll(dirNames, i)
{
const fileName& dirN = dirNames[i];
// Analyse directory name
fileName rp, rd, rl;
label rStart, rSize, rNum;
label readProci =
splitProcessorPath(dirN, rp, rd, rl, rStart, rSize, rNum);
maxProc = max(maxProc, readProci);
if (proci == readProci)
{
// Found "processorDDD". No need for index.
procDirs.append
(
dirIndex
(
dirN,
Tuple2(PROCUNCOLLATED, -1)
)
);
}
else if (proci >= rStart && proci < rStart+rSize)
{
// "processorsDDD_start-end"
// Found the file that contains the data for proci
procDirs.append
(
dirIndex
(
dirN,
Tuple2(PROCOBJECT, proci-rStart)
)
);
}
if (rNum != -1)
{
// Direct detection of processorsDDD
maxProc = rNum-1;
if (rStart == -1)
{
// "processorsDDD"
procDirs.append
(
dirIndex
(
dirN,
Tuple2(PROCBASEOBJECT, proci)
)
);
}
}
}
if (!Pstream::parRun())
{
// If (as a side effect) we found the number of decompositions
// use it
if (maxProc != -1)
{
const_cast(*this).setNProcs(maxProc+1);
}
}
if (returnReduce(procDirs.size(), sumOp()))
{
procsDirs_.insert(procPath, procDirs);
if (debug)
{
Pout<< "fileOperation::lookupProcessorsPath : For:" << procPath
<< " detected:" << procDirs << endl;
}
// Make sure to return a reference
return procsDirs_[procPath];
}
}
return tmpNrc(new dirIndexList(0, dirIndex()));
}
bool Foam::fileOperation::exists(IOobject& io) const
{
// Generate output filename for object
fileName objPath(objectPath(io));
// Test for either directory or a (valid) file & IOobject
bool ok;
if (io.name().empty())
{
ok = isDir(objPath);
}
else
{
// IOobject::headerOk assumes local scope
ok = isFile(objPath) && io.headerOk();
}
if (!ok)
{
// Re-test with searched for objectPath. This is for backwards
// compatibility
fileName originalPath(filePath(io.objectPath(false)));
if (originalPath != objPath)
{
// Test for either directory or a (valid) file & IOobject
if (io.name().empty())
{
ok = isDir(originalPath);
}
else
{
// IOobject::headerOk assumes local scope
ok = isFile(originalPath) && io.headerOk();
}
}
}
return ok;
}
bool Foam::fileOperation::exists(const dirIndexList& pDirs, IOobject& io) const
{
return exists(io);
}
void Foam::fileOperation::searchInstance
(
const dirIndexList& pDirs,
IOobject& io,
const IOobject& startIo,
const scalar startValue,
const word& stopInstance,
const instantList& ts
) const
{
const Time& time = io.time();
// Find the instance at or immediately below the start time
label instancei;
for (instancei = ts.size() - 1; instancei >= 0; -- instancei)
{
if
(
ts[instancei].name() == time.constant()
|| ts[instancei].value() <= startValue
)
{
break;
}
}
// Error if the object must be read
auto notFound = [&]()
{
if
(
startIo.readOpt() == IOobject::MUST_READ
|| startIo.readOpt() == IOobject::MUST_READ_IF_MODIFIED
)
{
if (io.name().empty())
{
FatalErrorInFunction
<< "Cannot find directory " << io.local();
}
else
{
FatalErrorInFunction
<< "Cannot find file \"" << io.name()
<< "\" in directory " << io.local();
}
FatalIOError
<< " in times " << startIo.instance() << " down to "
<< (stopInstance == word::null ? time.constant() : stopInstance)
<< exit(FatalError);
}
};
// Create a numeric stop time
const scalar stopValue =
stopInstance == word::null ? -vGreat : instant(stopInstance).value();
// Search remaining instances
for (; instancei >= 0; -- instancei)
{
if (ts[instancei].value() < stopValue)
{
notFound();
io.instance() = stopInstance;
return;
}
io.instance() = ts[instancei].name();
if (exists(pDirs, io)) return;
}
// Ensure that the constant instance has been checked
if (stopValue <= 0 && (!ts.size() || ts[0].name() != time.constant()))
{
io.instance() = time.constant();
if (exists(pDirs, io)) return;
}
// Everything has been searched and nothing has been found. Return the
// constant instance, or the stop instance (if any).
notFound();
io.instance() = stopValue <= 0 ? time.constant() : stopInstance;
return;
}
// * * * * * * * * * * * * * * * * Constructors * * * * * * * * * * * * * * //
Foam::fileOperation::fileOperation(label comm)
:
comm_(comm)
{}
Foam::autoPtr Foam::fileOperation::New
(
const word& type,
const bool verbose
)
{
wordConstructorTable::iterator cstrIter =
wordConstructorTablePtr_->find(type);
if (cstrIter == wordConstructorTablePtr_->end())
{
FatalErrorInFunction
<< "Unknown fileOperation type "
<< type << nl << nl
<< "Valid fileOperation types are" << endl
<< wordConstructorTablePtr_->sortedToc()
<< abort(FatalError);
}
return autoPtr(cstrIter()(verbose));
}
// * * * * * * * * * * * * * * * * Destructor * * * * * * * * * * * * * * * //
Foam::fileOperation::~fileOperation()
{}
// * * * * * * * * * * * * * * * Member Functions * * * * * * * * * * * * * //
Foam::fileName Foam::fileOperation::objectPath(const IOobject& io) const
{
return io.objectPath(false);
}
bool Foam::fileOperation::writeObject
(
const regIOobject& io,
IOstream::streamFormat fmt,
IOstream::versionNumber ver,
IOstream::compressionType cmp,
const bool write
) const
{
if (write)
{
const fileName filePath(io.objectPath());
mkDir(filePath.path());
autoPtr osPtr
(
NewOFstream
(
filePath,
fmt,
ver,
cmp
)
);
if (!osPtr.valid())
{
return false;
}
Ostream& os = osPtr();
// If any of these fail, return (leave error handling to Ostream class)
if (!os.good())
{
return false;
}
if (!io.writeHeader(os))
{
return false;
}
// Write the data to the Ostream
if (!io.writeData(os))
{
return false;
}
IOobject::writeEndDivider(os);
}
return true;
}
Foam::fileName Foam::fileOperation::filePath(const fileName& fName) const
{
if (debug)
{
Pout<< "fileOperation::filePath :" << " fName:" << fName << endl;
}
fileName path;
fileName pDir;
fileName local;
label gStart;
label gSz;
label numProcs;
label proci =
splitProcessorPath(fName, path, pDir, local, gStart, gSz, numProcs);
if (numProcs != -1)
{
WarningInFunction << "Filename is already adapted:" << fName << endl;
}
// Give preference to processors variant
if (proci != -1)
{
// Get all processor directories
tmpNrc procDirs(lookupProcessorsPath(fName));
forAll(procDirs(), i)
{
const fileName& procDir = procDirs()[i].first();
fileName collatedName(path/procDir/local);
if (exists(collatedName))
{
if (debug)
{
Pout<< "fileOperation::filePath : " << collatedName << endl;
}
return collatedName;
}
}
}
if (exists(fName))
{
if (debug)
{
Pout<< "fileOperation::filePath : " << fName << endl;
}
return fName;
}
else
{
if (debug)
{
Pout<< "fileOperation::filePath : Not found" << endl;
}
return fileName::null;
}
}
Foam::label Foam::fileOperation::addWatch(const fileName& fName) const
{
return monitor().addWatch(fName);
}
bool Foam::fileOperation::removeWatch(const label watchIndex) const
{
return monitor().removeWatch(watchIndex);
}
Foam::label Foam::fileOperation::findWatch
(
const labelList& watchIndices,
const fileName& fName
) const
{
forAll(watchIndices, i)
{
if (getFile(watchIndices[i]) == fName)
{
return i;
}
}
return -1;
}
void Foam::fileOperation::addWatches
(
regIOobject& rio,
const fileNameList& files
) const
{
const labelList& watchIndices = rio.watchIndices();
DynamicList