22 #include "qgsconfig.h"
43 #include <QDomDocument>
44 #include <QNetworkDiskCache>
46 #include <QElapsedTimer>
49 #include <fcgi_stdio.h>
57 QString *QgsServer::sConfigFilePath =
nullptr;
61 bool QgsServer::sInitialized =
false;
70 if ( qobject_cast<QgsApplication *>( qApp ) ==
nullptr )
72 qFatal(
"A QgsApplication must exist before a QgsServer instance can be created." );
79 QFileInfo QgsServer::defaultAdminSLD()
81 return QFileInfo( QStringLiteral(
"admin.sld" ) );
84 void QgsServer::setupNetworkAccessManager()
88 QNetworkDiskCache *cache =
new QNetworkDiskCache(
nullptr );
89 qint64 cacheSize = sSettings()->cacheSize();
90 QString cacheDirectory = sSettings()->cacheDirectory();
91 cache->setCacheDirectory( cacheDirectory );
92 cache->setMaximumCacheSize( cacheSize );
93 QgsMessageLog::logMessage( QStringLiteral(
"cacheDirectory: %1" ).arg( cache->cacheDirectory() ), QStringLiteral(
"Server" ), Qgis::MessageLevel::Info );
94 QgsMessageLog::logMessage( QStringLiteral(
"maximumCacheSize: %1" ).arg( cache->maximumCacheSize() ), QStringLiteral(
"Server" ), Qgis::MessageLevel::Info );
95 nam->setCache( cache );
98 QFileInfo QgsServer::defaultProjectFile()
101 fprintf( FCGI_stderr,
"current directory: %s\n", currentDir.absolutePath().toUtf8().constData() );
102 QStringList nameFilterList;
103 nameFilterList << QStringLiteral(
"*.qgs" )
104 << QStringLiteral(
"*.qgz" );
105 QFileInfoList projectFiles = currentDir.entryInfoList( nameFilterList, QDir::Files, QDir::Name );
106 for (
int x = 0; x < projectFiles.size(); x++ )
108 QgsMessageLog::logMessage( projectFiles.at( x ).absoluteFilePath(), QStringLiteral(
"Server" ), Qgis::MessageLevel::Info );
110 if ( projectFiles.isEmpty() )
114 return projectFiles.at( 0 );
117 void QgsServer::printRequestParameters(
const QMap< QString, QString> ¶meterMap,
Qgis::MessageLevel logLevel )
119 if ( logLevel > Qgis::MessageLevel::Info )
124 QMap< QString, QString>::const_iterator pIt = parameterMap.constBegin();
125 for ( ; pIt != parameterMap.constEnd(); ++pIt )
131 QString QgsServer::configPath(
const QString &defaultConfigPath,
const QString &configPath )
133 QString cfPath( defaultConfigPath );
134 QString projectFile = sSettings()->projectFile();
135 if ( !projectFile.isEmpty() )
137 cfPath = projectFile;
138 QgsDebugMsg( QStringLiteral(
"QGIS_PROJECT_FILE:%1" ).arg( cfPath ) );
142 if ( configPath.isEmpty() )
145 if ( getenv(
"QGIS_PROJECT_FILE" ) )
147 cfPath = getenv(
"QGIS_PROJECT_FILE" );
148 QgsMessageLog::logMessage( QStringLiteral(
"Using configuration file path from environment: %1" ).arg( cfPath ), QStringLiteral(
"Server" ), Qgis::MessageLevel::Info );
150 else if ( ! defaultConfigPath.isEmpty() )
152 QgsMessageLog::logMessage( QStringLiteral(
"Using default configuration file path: %1" ).arg( defaultConfigPath ), QStringLiteral(
"Server" ), Qgis::MessageLevel::Info );
158 QgsDebugMsg( QStringLiteral(
"MAP:%1" ).arg( cfPath ) );
164 void QgsServer::initLocale()
167 if ( ! sSettings()->overrideSystemLocale().isEmpty() )
169 QLocale::setDefault( QLocale( sSettings()->overrideSystemLocale() ) );
172 QLocale currentLocale;
173 if ( sSettings()->showGroupSeparator() )
175 currentLocale.setNumberOptions( currentLocale.numberOptions() &= ~QLocale::NumberOption::OmitGroupSeparator );
179 currentLocale.setNumberOptions( currentLocale.numberOptions() |= QLocale::NumberOption::OmitGroupSeparator );
181 QLocale::setDefault( currentLocale );
184 bool QgsServer::init()
200 #if defined(SERVER_SKIP_ECW)
213 if ( ! sSettings()->logFile().isEmpty() )
217 else if ( sSettings()->logStderr() )
231 QStringLiteral(
"QGIS Server" ), Qgis::MessageLevel::Warning );
242 if ( !grid.isAvailable )
244 gridMessage.append( QStringLiteral(
"This transformation requires the grid file '%1', which is not available for use on the system.\n" ).arg( grid.shortName ) );
252 QStringLiteral(
"QGIS Server" ), Qgis::MessageLevel::Warning );
265 if ( !grid.isAvailable )
267 gridMessage.append( QStringLiteral(
"This transformation requires the grid file '%1', which is not available for use on the system.\n" ).arg( grid.shortName ) );
268 if ( !grid.url.isEmpty() )
270 if ( !grid.packageName.isEmpty() )
272 gridMessage.append( QStringLiteral(
"This grid is part of the '%1' package, available for download from %2.\n" ).arg( grid.packageName, grid.url ) );
276 gridMessage.append( QStringLiteral(
"This grid is available for download from %1.\n" ).arg( grid.url ) );
282 QString accuracyMessage;
284 accuracyMessage = QStringLiteral(
"Current transform '%1' has an accuracy of %2 meters, while the preferred transformation '%3' has accuracy %4 meters.\n" ).arg( availableOperation.
name )
285 .arg( availableOperation.
accuracy ).arg( preferredOperation.
name ).arg( preferredOperation.
accuracy );
286 else if ( preferredOperation.
accuracy >= 0 )
287 accuracyMessage = QStringLiteral(
"Current transform '%1' has an unknown accuracy, while the preferred transformation '%2' has accuracy %3 meters.\n" )
288 .arg( availableOperation.
name, preferredOperation.
name )
289 .arg( preferredOperation.
accuracy );
291 const QString longMessage = QStringLiteral(
"The preferred transform between '%1' and '%2' is not available for use on the system.\n" ).arg( sourceCrs.
userFriendlyIdentifier(),
293 + gridMessage + accuracyMessage;
301 const QString longMessage = QStringLiteral(
"No transform is available between %1 and %2: %3" )
310 sSettings()->logSummary();
312 setupNetworkAccessManager();
313 QDomImplementation::setInvalidDataPolicy( QDomImplementation::DropInvalidChars );
332 QString defaultConfigFilePath;
333 QFileInfo projectFileInfo = defaultProjectFile();
334 if ( projectFileInfo.exists() )
336 defaultConfigFilePath = projectFileInfo.absoluteFilePath();
337 QgsMessageLog::logMessage(
"Using default project file: " + defaultConfigFilePath, QStringLiteral(
"Server" ), Qgis::MessageLevel::Info );
341 QFileInfo adminSLDFileInfo = defaultAdminSLD();
342 if ( adminSLDFileInfo.exists() )
344 defaultConfigFilePath = adminSLDFileInfo.absoluteFilePath();
348 sConfigFilePath =
new QString( defaultConfigFilePath );
362 sServiceRegistry->init( modulePath, sServerInterface );
365 QgsMessageLog::logMessage( QStringLiteral(
"Server initialized" ), QStringLiteral(
"Server" ), Qgis::MessageLevel::Info );
375 qunsetenv( var.toUtf8().data() );
379 qputenv( var.toUtf8().data(), val.toUtf8() );
381 sSettings()->load( var );
391 qApp->processEvents();
434 responseDecorator.
start();
439 response.
sendError( 500, QStringLiteral(
"Internal Server Error" ) );
449 printRequestParameters( params.
toMap(), logLevel );
454 QString configFilePath = configPath( *sConfigFilePath, params.
map() );
457 if ( ! configFilePath.isEmpty() )
493 throw QgsServerException( QStringLiteral(
"Project file error. For OWS services: please provide a SERVICE and a MAP parameter pointing to a valid QGIS project file" ) );
496 if ( ! params.
fileName().isEmpty() )
498 const QString value = QString(
"attachment; filename=\"%1\"" ).arg( params.
fileName() );
499 requestHandler.
setResponseHeader( QStringLiteral(
"Content-Disposition" ), value );
511 QStringLiteral(
"Service unknown or unsupported. Current supported services (case-sensitive): WMS WFS WCS WMTS SampleService, or use a WFS3 (OGC API Features) endpoint" ) );
517 responseDecorator.
write( ex );
524 response.
sendError( 500, QStringLiteral(
"Internal Server Error" ) );
533 responseDecorator.
finish();
538 response.
sendError( 500, QStringLiteral(
"Internal Server Error" ) );
547 if ( logLevel == Qgis::MessageLevel::Info )
549 QgsMessageLog::logMessage(
"Request finished in " + QString::number(
QgsApplication::profiler()->profileTime( QStringLiteral(
"handleRequest" ), QStringLiteral(
"server" ) ) * 1000.0 ) +
" ms", QStringLiteral(
"Server" ), Qgis::MessageLevel::Info );
550 if ( sSettings->logProfile() )
552 std::function <void(
const QModelIndex &,
int )> profileFormatter;
553 profileFormatter = [ &profileFormatter ](
const QModelIndex & idx,
int level )
556 .arg( level > 0 ? QString().fill(
'-', level ) +
' ' : QString() )
559 .arg( QString::number(
QgsApplication::profiler()->data( idx, QgsRuntimeProfilerNode::Roles::Elapsed ).toDouble() * 1000.0 ) ), QStringLiteral(
"Server" ), Qgis::MessageLevel::Info );
564 profileFormatter( subIdx, level + 1 );
572 profileFormatter( idx, 0 );
584 #ifdef HAVE_SERVER_PYTHON_PLUGINS
585 void QgsServer::initPython()
590 QgsMessageLog::logMessage( QStringLiteral(
"No server python plugins are available" ), QStringLiteral(
"Server" ), Qgis::MessageLevel::Info );
594 QgsMessageLog::logMessage( QStringLiteral(
"Server python plugins loaded" ), QStringLiteral(
"Server" ), Qgis::MessageLevel::Info );
MessageLevel
Level for messages This will be used both for message log and message bar in application.
static void skipGdalDriver(const QString &driver)
Sets the GDAL_SKIP environment variable to include the specified driver and then calls GDALDriverMana...
static QString pluginPath()
Returns the path to the application plugin directory.
static bool createDatabase(QString *errorMessage=nullptr)
initialize qgis.db
static void init(QString profileFolder=QString())
This method initializes paths etc for QGIS.
static QString pkgDataPath()
Returns the common root path of all application data directories.
static QString libexecPath()
Returns the path with utility executables (help viewer, crssync, ...)
static QStringList svgPaths()
Returns the paths to svg directories.
static QgsRuntimeProfiler * profiler()
Returns the application runtime profiler.
static const char * QGIS_APPLICATION_NAME
static const char * QGIS_ORGANIZATION_DOMAIN
static QString prefixPath()
Returns the path to the application prefix directory.
static const char * QGIS_ORGANIZATION_NAME
static QgsAuthManager * authManager()
Returns the application's authentication manager instance.
static QString qgisAuthDatabaseFilePath()
Returns the path to the user authentication database file: qgis-auth.db.
static QString qgisUserDatabaseFilePath()
Returns the path to the user qgis.db file.
bool init(const QString &pluginPath=QString(), const QString &authDatabasePath=QString())
init initialize QCA, prioritize qca-ossl plugin and optionally set up the authentication database
A cache for capabilities xml documents (by configuration file path)
static QgsConfigCache * instance()
Returns the current instance.
const QgsProject * project(const QString &path, const QgsServerSettings *settings=nullptr)
If the project is not cached yet, then the project is read from the path.
This class represents a coordinate reference system (CRS).
@ ShortString
A heavily abbreviated string, for use when a compact representation is required.
QString userFriendlyIdentifier(IdentifierType type=MediumString) const
Returns a user friendly identifier for the CRS.
Defines a QGIS exception class.
Class defining decorator for calling filter's hooks.
void finish() override
Finish the response, ending the transaction.
void start() SIP_THROW(QgsServerException)
Call filters requestReady() method.
static bool loadStandardTestFonts(const QStringList &loadstyles)
Loads standard test fonts from filesystem or qrc resource.
Exception class for WMS service exceptions (for compatibility only).
static void logMessage(const QString &message, const QString &tag=QString(), Qgis::MessageLevel level=Qgis::MessageLevel::Warning, bool notifyUser=true)
Adds a message to the log instance (and creates it if necessary).
network access manager for QGIS
static QgsNetworkAccessManager * instance(Qt::ConnectionType connectionType=Qt::BlockingQueuedConnection)
Returns a pointer to the active QgsNetworkAccessManager for the current thread.
Exception base class for service exceptions.
QString message() const
Returns the exception message.
Encapsulates a QGIS project, including sets of map layers and their styles, layouts,...
static void setInstance(QgsProject *project)
Set the current project singleton instance to project.
static QgsProviderRegistry * instance(const QString &pluginPath=QString())
Means of accessing canonical single instance.
This class is an interface hiding the details of reading input and writing output from/to a wms reque...
bool exceptionRaised() const
Pointer to last raised exception.
void parseInput()
Parses the input and creates a request neutral Parameter/Value map.
void setServiceException(const QgsServerException &ex)
Allow plugins to return a QgsMapServiceException.
void setResponseHeader(const QString &name, const QString &value)
Sets an HTTP response header.
QModelIndex index(int row, int column, const QModelIndex &parent=QModelIndex()) const override
int rowCount(const QModelIndex &parent=QModelIndex()) const override
void clear(const QString &group="startup")
clear Clear all profile data.
Scoped object for logging of the runtime for a single operation or group of operations.
The QgsServerApiContext class encapsulates the resources for a particular client request: the request...
Server generic API endpoint abstract base class.
virtual void executeRequest(const QgsServerApiContext &context) const =0
Executes a request by passing the given context to the API handlers.
virtual const QString rootPath() const =0
Returns the root path for the API.
Exception base class for server exceptions.
virtual QByteArray formatResponse(QString &responseFormat) const
Formats the exception for sending to client.
Interfaces exposed by QGIS Server and made available to plugins.
QgsServerSettings * serverSettings() override
Returns the server settings.
void setRequestHandler(QgsRequestHandler *requestHandler) override
Set the request handler.
void clearRequestHandler() override
Clear the request handler.
QgsServerFiltersMap filters() override
Returns the list of current QgsServerFilter.
void setConfigFilePath(const QString &configFilePath) override
Set the configuration file path.
static QgsServerLogger * instance()
Gets the singleton instance.
Qgis::MessageLevel logLevel() const
Gets the current log level.
void setLogLevel(Qgis::MessageLevel level)
Set the current log level.
void setLogFile(const QString &filename=QString())
Set the current log file.
void setLogStderr()
Activates logging to stderr.
void logMessage(const QString &message, const QString &tag, Qgis::MessageLevel level) override
Log a message from the server context.
QgsServerParameters provides an interface to retrieve and manipulate global parameters received from ...
QMap< QString, QString > toMap() const
Returns all parameters in a map.
QString map() const
Returns MAP parameter as a string or an empty string if not defined.
QString service() const
Returns SERVICE parameter as a string or an empty string if not defined.
QString fileName() const
Returns FILE_NAME parameter as a string or an empty string if not defined.
virtual QString version() const
Returns VERSION parameter as a string or an empty string if not defined.
static bool initPlugins(QgsServerInterface *interface)
Initializes the Python plugins.
QgsServerRequest Class defining request interface passed to services QgsService::executeRequest() met...
QgsServerParameters serverParameters() const
Returns parameters.
QgsServerResponse Class defining response interface passed to services QgsService::executeRequest() m...
virtual void write(const QString &data)
Write string This is a convenient method that will write directly to the underlying I/O device.
virtual void clear()=0
Reset all headers and content for this response.
virtual void sendError(int code, const QString &message)=0
Send error This method delegates error handling at the server level.
Provides a way to retrieve settings by prioritizing according to environment variables,...
QgsServer()
Creates the server instance.
void handleRequest(QgsServerRequest &request, QgsServerResponse &response, const QgsProject *project=nullptr)
Handles the request.
void putenv(const QString &var, const QString &val)
Set environment variable.
QgsServiceRegistry Class defining the registry manager for QGIS server services.
QgsServerApi * apiForRequest(const QgsServerRequest &request) const
Searches the API register for an API matching the request and returns a (possibly NULL) pointer to it...
QgsService * getService(const QString &name, const QString &version=QString())
Retrieve a service from its name.
QgsService Class defining interfaces for QGIS server services.
virtual void executeRequest(const QgsServerRequest &request, QgsServerResponse &response, const QgsProject *project)=0
Execute the requests and set result in QgsServerRequest.
Q_GLOBAL_STATIC(QgsServerSettings, sSettings)