45#include "qgsversion.h"
47#include <QDomDocument>
48#include <QElapsedTimer>
49#include <QNetworkDiskCache>
53using namespace Qt::StringLiterals;
56#include <fcgi_stdio.h>
64QString *QgsServer::sConfigFilePath =
nullptr;
68bool QgsServer::sInitialized =
false;
77 if ( !qobject_cast<QgsApplication *>( qApp ) )
79 qFatal(
"A QgsApplication must exist before a QgsServer instance can be created." );
86QFileInfo QgsServer::defaultAdminSLD()
88 return QFileInfo( u
"admin.sld"_s );
91void QgsServer::setupNetworkAccessManager()
93 const QSettings settings;
95 QNetworkDiskCache *cache =
new QNetworkDiskCache(
nullptr );
96 const QString cacheDirectory = sSettings()->cacheDirectory();
97 cache->setCacheDirectory( cacheDirectory );
98 qint64 cacheSize = sSettings()->cacheSize();
99 cache->setMaximumCacheSize( cacheSize );
102 nam->setCache( cache );
105QFileInfo QgsServer::defaultProjectFile()
107 const QDir currentDir;
108 fprintf( FCGI_stderr,
"current directory: %s\n", currentDir.absolutePath().toUtf8().constData() );
109 QStringList nameFilterList;
110 nameFilterList << u
"*.qgs"_s << u
"*.qgz"_s;
111 const QFileInfoList projectFiles = currentDir.entryInfoList( nameFilterList, QDir::Files, QDir::Name );
112 for (
int x = 0; x < projectFiles.size(); x++ )
116 if ( projectFiles.isEmpty() )
120 return projectFiles.at( 0 );
123void QgsServer::printRequestParameters(
const QMap<QString, QString> ¶meterMap,
Qgis::MessageLevel logLevel )
130 QMap<QString, QString>::const_iterator pIt = parameterMap.constBegin();
131 for ( ; pIt != parameterMap.constEnd(); ++pIt )
137QString QgsServer::configPath(
const QString &defaultConfigPath,
const QString &configPath )
139 QString cfPath( defaultConfigPath );
140 const QString projectFile = sSettings()->projectFile();
141 if ( !projectFile.isEmpty() )
143 cfPath = projectFile;
148 if ( configPath.isEmpty() )
151 if ( getenv(
"QGIS_PROJECT_FILE" ) )
153 cfPath = getenv(
"QGIS_PROJECT_FILE" );
156 else if ( !defaultConfigPath.isEmpty() )
170void QgsServer::initLocale()
173 if ( !sSettings()->overrideSystemLocale().isEmpty() )
175 QLocale::setDefault( QLocale( sSettings()->overrideSystemLocale() ) );
178 QLocale currentLocale;
179 if ( sSettings()->showGroupSeparator() )
181 currentLocale.setNumberOptions( currentLocale.numberOptions() &= ~QLocale::NumberOption::OmitGroupSeparator );
185 currentLocale.setNumberOptions( currentLocale.numberOptions() |= QLocale::NumberOption::OmitGroupSeparator );
187 QLocale::setDefault( currentLocale );
190bool QgsServer::init()
206#if defined( SERVER_SKIP_ECW )
219 if ( !sSettings()->logFile().isEmpty() )
223 else if ( sSettings()->logStderr() )
230 [](
const QgsCoordinateReferenceSystem &sourceCrs,
const QgsCoordinateReferenceSystem &destinationCrs,
const QgsDatumTransform::GridDetails &grid ) {
232 u
"Cannot use project transform between %1 and %2 - missing grid %3"_s
242 [](
const QgsCoordinateReferenceSystem &sourceCrs,
const QgsCoordinateReferenceSystem &destinationCrs,
const QgsDatumTransform::TransformDetails &details ) {
244 for (
const QgsDatumTransform::GridDetails &grid : details.
grids )
248 gridMessage.append( u
"This transformation requires the grid file '%1', which is not available for use on the system.\n"_s.arg( grid.
shortName ) );
252 u
"Cannot use project transform between %1 and %2 - %3.\n%4"_s
262 [](
const QgsCoordinateReferenceSystem &sourceCrs,
const QgsCoordinateReferenceSystem &destinationCrs,
const QgsDatumTransform::TransformDetails &preferredOperation,
const QgsDatumTransform::TransformDetails &availableOperation ) {
264 for (
const QgsDatumTransform::GridDetails &grid : preferredOperation.
grids )
268 gridMessage.append( u
"This transformation requires the grid file '%1', which is not available for use on the system.\n"_s.arg( grid.
shortName ) );
269 if ( !grid.
url.isEmpty() )
273 gridMessage.append( u
"This grid is part of the '%1' package, available for download from %2.\n"_s.arg( grid.
packageName, grid.
url ) );
277 gridMessage.append( u
"This grid is available for download from %1.\n"_s.arg( grid.
url ) );
283 QString accuracyMessage;
285 accuracyMessage = u
"Current transform '%1' has an accuracy of %2 meters, while the preferred transformation '%3' has accuracy %4 meters.\n"_s.arg( availableOperation.
name )
287 .arg( preferredOperation.
name )
288 .arg( preferredOperation.
accuracy );
289 else if ( preferredOperation.
accuracy >= 0 )
290 accuracyMessage = u
"Current transform '%1' has an unknown accuracy, while the preferred transformation '%2' has accuracy %3 meters.\n"_s.arg( availableOperation.
name, preferredOperation.
name )
291 .arg( preferredOperation.
accuracy );
293 const QString longMessage
313 sSettings()->logSummary();
315 setupNetworkAccessManager();
316 QDomImplementation::setInvalidDataPolicy( QDomImplementation::DropInvalidChars );
336 QString defaultConfigFilePath;
337 const QFileInfo projectFileInfo = defaultProjectFile();
338 if ( projectFileInfo.exists() )
340 defaultConfigFilePath = projectFileInfo.absoluteFilePath();
345 const QFileInfo adminSLDFileInfo = defaultAdminSLD();
346 if ( adminSLDFileInfo.exists() )
348 defaultConfigFilePath = adminSLDFileInfo.absoluteFilePath();
352 sConfigFilePath =
new QString( defaultConfigFilePath );
355 sCapabilitiesCache =
new QgsCapabilitiesCache( sSettings()->capabilitiesCacheSize() );
359 sServiceRegistry =
new QgsServiceRegistry();
361 sServerInterface =
new QgsServerInterfaceImpl( sCapabilitiesCache, sServiceRegistry, sSettings() );
366 sServiceRegistry->init( modulePath, sServerInterface );
383 qunsetenv( var.toUtf8().data() );
387 qputenv( var.toUtf8().data(), val.toUtf8() );
389 sSettings()->load( var );
398 qApp->processEvents();
404#ifdef HAVE_SERVER_PYTHON_PLUGINS
406 if ( accessControls )
434 sServerInterface->setRequestHandler( &requestHandler );
442 const QString configFilePath = configPath( *sConfigFilePath, request.
serverParameters().
map() );
443 sServerInterface->setConfigFilePath( configFilePath );
447 sServerInterface->setConfigFilePath( project->
fileName() );
454 responseDecorator.
start();
459 response.
sendError( 500, u
"Internal Server Error"_s );
469 printRequestParameters( params.
toMap(), logLevel );
474 const QString configFilePath = configPath( *sConfigFilePath, params.
map() );
477 if ( !configFilePath.isEmpty() )
480 project = mConfigCache->project( configFilePath, sServerInterface->serverSettings() );
489 sServerInterface->setConfigFilePath( project->
fileName() );
493 sServerInterface->setConfigFilePath( QString() );
498 responseDecorator.
ready();
508 if ( params.
service().isEmpty() )
510 QgsServerApi *api = sServiceRegistry->apiForRequest( request );
519 u
"Service configuration error"_s,
521 "Service unknown or unsupported. Current supported services "
522 "(case-sensitive): WMS WFS WCS WMTS SampleService, or use a WFS3 "
523 "(OGC API Features) endpoint"
534 "Project file error. For OWS services: please provide a SERVICE "
535 "and a MAP parameter pointing to a valid QGIS project file"
541 const QString value = QString(
"attachment; filename=\"%1\"" ).arg( params.
fileName() );
554 u
"Service configuration error"_s,
556 "Service unknown or unsupported. Current supported services "
557 "(case-sensitive): WMS WFS WCS WMTS SampleService, or use a WFS3 "
558 "(OGC API Features) endpoint"
567 responseDecorator.
write( ex );
574 response.
sendError( 500, u
"Internal Server Error"_s );
583 responseDecorator.
finish();
588 response.
sendError( 500, u
"Internal Server Error"_s );
594 sServerInterface->clearRequestHandler();
600 if ( sSettings->logProfile() )
602 std::function<void(
const QModelIndex &,
int )> profileFormatter;
603 profileFormatter = [&profileFormatter](
const QModelIndex &idx,
int level ) {
605 u
"Profile: %1%2, %3 : %4 ms"_s.arg( level > 0 ? QString().fill(
'-', level ) +
' ' : QString() )
616 profileFormatter( subIdx, level + 1 );
623 profileFormatter( idx, 0 );
637#ifdef HAVE_SERVER_PYTHON_PLUGINS
638void QgsServer::initPython()
@ ShortString
A heavily abbreviated string, for use when a compact representation is required.
MessageLevel
Level for messages This will be used both for message log and message bar in application.
@ Warning
Warning message.
@ Critical
Critical/error message.
@ Info
Information message.
A helper class that centralizes restrictions given by all the access control filter plugins.
void unresolveFilterFeatures()
Clear expression's cache computed from resolveFilterFeatures.
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 QString qgisAuthDatabaseUri()
Returns the URI to the user authentication database.
static QgsAuthManager * authManager()
Returns the application's authentication manager instance.
static QString qgisUserDatabaseFilePath()
Returns the path to the user qgis.db file.
void setup(const QString &pluginPath=QString(), const QString &authDatabasePath=QString())
Sets up the authentication manager configuration.
A cache for capabilities xml documents (by configuration file path).
void removeCapabilitiesDocument(const QString &path)
Removes capabilities document.
static QgsConfigCache * instance()
Returns the current instance.
static void initialize(QgsServerSettings *settings)
Initialize from settings.
void projectRemovedFromCache(const QString &path)
Emitted whenever a project is removed from the cache.
QString userFriendlyIdentifier(Qgis::CrsIdentifierType type=Qgis::CrsIdentifierType::MediumString) const
Returns a user friendly identifier for the CRS.
Defines a QGIS exception class.
bool isCanceled() const
Tells whether the operation has been canceled already.
A decorator for calling filter's hooks.
void start()
Call filters requestReady() method.
void finish() override
Finish the response, ending the transaction.
void ready()
Call filters projectReady() 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, const char *file=__builtin_FILE(), const char *function=__builtin_FUNCTION(), int line=__builtin_LINE(), Qgis::StringFormat format=Qgis::StringFormat::PlainText)
Adds a message to the log instance (and creates it if necessary).
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.
An interface hiding the details of reading input and writing output from/to a wms request mechanism.
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.
@ Elapsed
Node elapsed time.
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.
Encapsulates the resources for a particular client 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.
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
Provides an interface to retrieve and manipulate global parameters received from the client.
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.
Defines requests passed to QgsService classes.
QgsServerParameters serverParameters() const
Returns parameters.
Defines the response interface passed to QgsService.
virtual void write(const QString &data)
Write string This is a convenient method that will write directly to the underlying I/O device.
virtual QgsFeedback * feedback() const
Returns the socket feedback if any.
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.
A registry manager for QGIS server services.
Defines interfaces for QGIS server services.
virtual void executeRequest(const QgsServerRequest &request, QgsServerResponse &response, const QgsProject *project)=0
Executes the requests and sets result in QgsServerRequest.
#define QgsDebugMsgLevel(str, level)
Q_GLOBAL_STATIC(QgsServerSettings, sSettings)