22 #include "qgsconfig.h"
44 #include <QDomDocument>
45 #include <QNetworkDiskCache>
47 #include <QElapsedTimer>
50 #include <fcgi_stdio.h>
58 QString *QgsServer::sConfigFilePath =
nullptr;
62 bool QgsServer::sInitialized =
false;
71 if ( qobject_cast<QgsApplication *>( qApp ) ==
nullptr )
73 qFatal(
"A QgsApplication must exist before a QgsServer instance can be created." );
80 QFileInfo QgsServer::defaultAdminSLD()
82 return QFileInfo( QStringLiteral(
"admin.sld" ) );
85 void QgsServer::setupNetworkAccessManager()
87 const QSettings settings;
89 QNetworkDiskCache *cache =
new QNetworkDiskCache(
nullptr );
90 const qint64 cacheSize = sSettings()->cacheSize();
91 const QString cacheDirectory = sSettings()->cacheDirectory();
92 cache->setCacheDirectory( cacheDirectory );
93 cache->setMaximumCacheSize( cacheSize );
94 QgsMessageLog::logMessage( QStringLiteral(
"cacheDirectory: %1" ).arg( cache->cacheDirectory() ), QStringLiteral(
"Server" ), Qgis::MessageLevel::Info );
95 QgsMessageLog::logMessage( QStringLiteral(
"maximumCacheSize: %1" ).arg( cache->maximumCacheSize() ), QStringLiteral(
"Server" ), Qgis::MessageLevel::Info );
96 nam->setCache( cache );
99 QFileInfo QgsServer::defaultProjectFile()
101 const QDir currentDir;
102 fprintf( FCGI_stderr,
"current directory: %s\n", currentDir.absolutePath().toUtf8().constData() );
103 QStringList nameFilterList;
104 nameFilterList << QStringLiteral(
"*.qgs" )
105 << QStringLiteral(
"*.qgz" );
106 const QFileInfoList projectFiles = currentDir.entryInfoList( nameFilterList, QDir::Files, QDir::Name );
107 for (
int x = 0; x < projectFiles.size(); x++ )
109 QgsMessageLog::logMessage( projectFiles.at( x ).absoluteFilePath(), QStringLiteral(
"Server" ), Qgis::MessageLevel::Info );
111 if ( projectFiles.isEmpty() )
115 return projectFiles.at( 0 );
118 void QgsServer::printRequestParameters(
const QMap< QString, QString> ¶meterMap,
Qgis::MessageLevel logLevel )
120 if ( logLevel > Qgis::MessageLevel::Info )
125 QMap< QString, QString>::const_iterator pIt = parameterMap.constBegin();
126 for ( ; pIt != parameterMap.constEnd(); ++pIt )
132 QString QgsServer::configPath(
const QString &defaultConfigPath,
const QString &configPath )
134 QString cfPath( defaultConfigPath );
135 const QString projectFile = sSettings()->projectFile();
136 if ( !projectFile.isEmpty() )
138 cfPath = projectFile;
139 QgsDebugMsg( QStringLiteral(
"QGIS_PROJECT_FILE:%1" ).arg( cfPath ) );
143 if ( configPath.isEmpty() )
146 if ( getenv(
"QGIS_PROJECT_FILE" ) )
148 cfPath = getenv(
"QGIS_PROJECT_FILE" );
149 QgsMessageLog::logMessage( QStringLiteral(
"Using configuration file path from environment: %1" ).arg( cfPath ), QStringLiteral(
"Server" ), Qgis::MessageLevel::Info );
151 else if ( ! defaultConfigPath.isEmpty() )
153 QgsMessageLog::logMessage( QStringLiteral(
"Using default configuration file path: %1" ).arg( defaultConfigPath ), QStringLiteral(
"Server" ), Qgis::MessageLevel::Info );
159 QgsDebugMsg( QStringLiteral(
"MAP:%1" ).arg( cfPath ) );
165 void QgsServer::initLocale()
168 if ( ! sSettings()->overrideSystemLocale().isEmpty() )
170 QLocale::setDefault( QLocale( sSettings()->overrideSystemLocale() ) );
173 QLocale currentLocale;
174 if ( sSettings()->showGroupSeparator() )
176 currentLocale.setNumberOptions( currentLocale.numberOptions() &= ~QLocale::NumberOption::OmitGroupSeparator );
180 currentLocale.setNumberOptions( currentLocale.numberOptions() |= QLocale::NumberOption::OmitGroupSeparator );
182 QLocale::setDefault( currentLocale );
185 bool QgsServer::init()
201 #if defined(SERVER_SKIP_ECW)
214 if ( ! sSettings()->logFile().isEmpty() )
218 else if ( sSettings()->logStderr() )
232 QStringLiteral(
"QGIS Server" ), Qgis::MessageLevel::Warning );
243 if ( !grid.isAvailable )
245 gridMessage.append( QStringLiteral(
"This transformation requires the grid file '%1', which is not available for use on the system.\n" ).arg( grid.shortName ) );
253 QStringLiteral(
"QGIS Server" ), Qgis::MessageLevel::Warning );
266 if ( !grid.isAvailable )
268 gridMessage.append( QStringLiteral(
"This transformation requires the grid file '%1', which is not available for use on the system.\n" ).arg( grid.shortName ) );
269 if ( !grid.url.isEmpty() )
271 if ( !grid.packageName.isEmpty() )
273 gridMessage.append( QStringLiteral(
"This grid is part of the '%1' package, available for download from %2.\n" ).arg( grid.packageName, grid.url ) );
277 gridMessage.append( QStringLiteral(
"This grid is available for download from %1.\n" ).arg( grid.url ) );
283 QString accuracyMessage;
285 accuracyMessage = QStringLiteral(
"Current transform '%1' has an accuracy of %2 meters, while the preferred transformation '%3' has accuracy %4 meters.\n" ).arg( availableOperation.
name )
286 .arg( availableOperation.
accuracy ).arg( preferredOperation.
name ).arg( preferredOperation.
accuracy );
287 else if ( preferredOperation.
accuracy >= 0 )
288 accuracyMessage = QStringLiteral(
"Current transform '%1' has an unknown accuracy, while the preferred transformation '%2' has accuracy %3 meters.\n" )
289 .arg( availableOperation.
name, preferredOperation.
name )
290 .arg( preferredOperation.
accuracy );
292 const QString longMessage = QStringLiteral(
"The preferred transform between '%1' and '%2' is not available for use on the system.\n" ).arg( sourceCrs.
userFriendlyIdentifier(),
294 + gridMessage + accuracyMessage;
302 const QString longMessage = QStringLiteral(
"No transform is available between %1 and %2: %3" )
311 sSettings()->logSummary();
313 setupNetworkAccessManager();
314 QDomImplementation::setInvalidDataPolicy( QDomImplementation::DropInvalidChars );
333 QString defaultConfigFilePath;
334 const QFileInfo projectFileInfo = defaultProjectFile();
335 if ( projectFileInfo.exists() )
337 defaultConfigFilePath = projectFileInfo.absoluteFilePath();
338 QgsMessageLog::logMessage(
"Using default project file: " + defaultConfigFilePath, QStringLiteral(
"Server" ), Qgis::MessageLevel::Info );
342 const QFileInfo adminSLDFileInfo = defaultAdminSLD();
343 if ( adminSLDFileInfo.exists() )
345 defaultConfigFilePath = adminSLDFileInfo.absoluteFilePath();
349 sConfigFilePath =
new QString( defaultConfigFilePath );
363 sServiceRegistry->init( modulePath, sServerInterface );
366 QgsMessageLog::logMessage( QStringLiteral(
"Server initialized" ), QStringLiteral(
"Server" ), Qgis::MessageLevel::Info );
376 qunsetenv( var.toUtf8().data() );
380 qputenv( var.toUtf8().data(), val.toUtf8() );
382 sSettings()->load( var );
392 qApp->processEvents();
423 const QString configFilePath = configPath( *sConfigFilePath, request.
serverParameters().
map() );
435 responseDecorator.
start();
440 response.
sendError( 500, QStringLiteral(
"Internal Server Error" ) );
450 printRequestParameters( params.
toMap(), logLevel );
455 const QString configFilePath = configPath( *sConfigFilePath, params.
map() );
458 if ( ! configFilePath.isEmpty() )
494 throw QgsServerException( QStringLiteral(
"Project file error. For OWS services: please provide a SERVICE and a MAP parameter pointing to a valid QGIS project file" ) );
497 if ( ! params.
fileName().isEmpty() )
499 const QString value = QString(
"attachment; filename=\"%1\"" ).arg( params.
fileName() );
500 requestHandler.
setResponseHeader( QStringLiteral(
"Content-Disposition" ), value );
512 QStringLiteral(
"Service unknown or unsupported. Current supported services (case-sensitive): WMS WFS WCS WMTS SampleService, or use a WFS3 (OGC API Features) endpoint" ) );
518 responseDecorator.
write( ex );
525 response.
sendError( 500, QStringLiteral(
"Internal Server Error" ) );
534 responseDecorator.
finish();
539 response.
sendError( 500, QStringLiteral(
"Internal Server Error" ) );
548 if ( logLevel == Qgis::MessageLevel::Info )
550 QgsMessageLog::logMessage(
"Request finished in " + QString::number(
QgsApplication::profiler()->profileTime( QStringLiteral(
"handleRequest" ), QStringLiteral(
"server" ) ) * 1000.0 ) +
" ms", QStringLiteral(
"Server" ), Qgis::MessageLevel::Info );
551 if ( sSettings->logProfile() )
553 std::function <void(
const QModelIndex &,
int )> profileFormatter;
554 profileFormatter = [ &profileFormatter ](
const QModelIndex & idx,
int level )
557 .arg( level > 0 ? QString().fill(
'-', level ) +
' ' : QString() )
560 .arg( QString::number(
QgsApplication::profiler()->data( idx, QgsRuntimeProfilerNode::Roles::Elapsed ).toDouble() * 1000.0 ) ), QStringLiteral(
"Server" ), Qgis::MessageLevel::Info );
565 profileFormatter( subIdx, level + 1 );
573 profileFormatter( idx, 0 );
585 #ifdef HAVE_SERVER_PYTHON_PLUGINS
586 void QgsServer::initPython()
591 QgsMessageLog::logMessage( QStringLiteral(
"No server python plugins are available" ), QStringLiteral(
"Server" ), Qgis::MessageLevel::Info );
595 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)