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
112 const QFileInfoList projectFiles = currentDir.entryInfoList( nameFilterList, QDir::Files, QDir::Name );
113 for (
int x = 0; x < projectFiles.size(); x++ )
117 if ( projectFiles.isEmpty() )
121 return projectFiles.at( 0 );
124void QgsServer::printRequestParameters(
const QMap<QString, QString> ¶meterMap,
Qgis::MessageLevel logLevel )
131 QMap<QString, QString>::const_iterator pIt = parameterMap.constBegin();
132 for ( ; pIt != parameterMap.constEnd(); ++pIt )
138QString QgsServer::configPath(
const QString &defaultConfigPath,
const QString &configPath )
140 QString cfPath( defaultConfigPath );
141 const QString projectFile = sSettings()->projectFile();
142 if ( !projectFile.isEmpty() )
144 cfPath = projectFile;
149 if ( configPath.isEmpty() )
152 if ( getenv(
"QGIS_PROJECT_FILE" ) )
154 cfPath = getenv(
"QGIS_PROJECT_FILE" );
157 else if ( !defaultConfigPath.isEmpty() )
171void QgsServer::initLocale()
174 if ( !sSettings()->overrideSystemLocale().isEmpty() )
176 QLocale::setDefault( QLocale( sSettings()->overrideSystemLocale() ) );
179 QLocale currentLocale;
180 if ( sSettings()->showGroupSeparator() )
182 currentLocale.setNumberOptions( currentLocale.numberOptions() &= ~QLocale::NumberOption::OmitGroupSeparator );
186 currentLocale.setNumberOptions( currentLocale.numberOptions() |= QLocale::NumberOption::OmitGroupSeparator );
188 QLocale::setDefault( currentLocale );
191bool QgsServer::init()
207#if defined( SERVER_SKIP_ECW )
220 if ( !sSettings()->logFile().isEmpty() )
224 else if ( sSettings()->logStderr() )
237 for (
const QgsDatumTransform::GridDetails &grid : details.
grids )
241 gridMessage.append( u
"This transformation requires the grid file '%1', which is not available for use on the system.\n"_s.arg( grid.
shortName ) );
250 for (
const QgsDatumTransform::GridDetails &grid : preferredOperation.
grids )
254 gridMessage.append( u
"This transformation requires the grid file '%1', which is not available for use on the system.\n"_s.arg( grid.
shortName ) );
255 if ( !grid.
url.isEmpty() )
259 gridMessage.append( u
"This grid is part of the '%1' package, available for download from %2.\n"_s.arg( grid.
packageName, grid.
url ) );
263 gridMessage.append( u
"This grid is available for download from %1.\n"_s.arg( grid.
url ) );
269 QString accuracyMessage;
271 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 ).arg( availableOperation.
accuracy ).arg( preferredOperation.
name ).arg( preferredOperation.
accuracy );
272 else if ( preferredOperation.
accuracy >= 0 )
273 accuracyMessage = u
"Current transform '%1' has an unknown accuracy, while the preferred transformation '%2' has accuracy %3 meters.\n"_s
274 .arg( availableOperation.
name, preferredOperation.
name )
275 .arg( preferredOperation.
accuracy );
278 + gridMessage + accuracyMessage;
284 const QString longMessage = u
"No transform is available between %1 and %2: %3"_s
295 sSettings()->logSummary();
297 setupNetworkAccessManager();
298 QDomImplementation::setInvalidDataPolicy( QDomImplementation::DropInvalidChars );
318 QString defaultConfigFilePath;
319 const QFileInfo projectFileInfo = defaultProjectFile();
320 if ( projectFileInfo.exists() )
322 defaultConfigFilePath = projectFileInfo.absoluteFilePath();
327 const QFileInfo adminSLDFileInfo = defaultAdminSLD();
328 if ( adminSLDFileInfo.exists() )
330 defaultConfigFilePath = adminSLDFileInfo.absoluteFilePath();
334 sConfigFilePath =
new QString( defaultConfigFilePath );
337 sCapabilitiesCache =
new QgsCapabilitiesCache( sSettings()->capabilitiesCacheSize() );
341 sServiceRegistry =
new QgsServiceRegistry();
343 sServerInterface =
new QgsServerInterfaceImpl( sCapabilitiesCache, sServiceRegistry, sSettings() );
348 sServiceRegistry->init( modulePath, sServerInterface );
365 qunsetenv( var.toUtf8().data() );
369 qputenv( var.toUtf8().data(), val.toUtf8() );
371 sSettings()->load( var );
380 qApp->processEvents();
386#ifdef HAVE_SERVER_PYTHON_PLUGINS
388 if ( accessControls )
417 sServerInterface->setRequestHandler( &requestHandler );
425 const QString configFilePath = configPath( *sConfigFilePath, request.
serverParameters().
map() );
426 sServerInterface->setConfigFilePath( configFilePath );
430 sServerInterface->setConfigFilePath( project->
fileName() );
437 responseDecorator.
start();
442 response.
sendError( 500, u
"Internal Server Error"_s );
452 printRequestParameters( params.
toMap(), logLevel );
457 const QString configFilePath = configPath( *sConfigFilePath, params.
map() );
460 if ( !configFilePath.isEmpty() )
463 project = mConfigCache->project( configFilePath, sServerInterface->serverSettings() );
472 sServerInterface->setConfigFilePath( project->
fileName() );
476 sServerInterface->setConfigFilePath( QString() );
481 responseDecorator.
ready();
491 if ( params.
service().isEmpty() )
493 QgsServerApi *api = sServiceRegistry->apiForRequest( request );
502 u
"Service configuration error"_s,
503 QStringLiteral(
"Service unknown or unsupported. Current supported services "
504 "(case-sensitive): WMS WFS WCS WMTS SampleService, or use a WFS3 "
505 "(OGC API Features) endpoint" )
515 QStringLiteral(
"Project file error. For OWS services: please provide a SERVICE "
516 "and a MAP parameter pointing to a valid QGIS project file" )
522 const QString value = QString(
"attachment; filename=\"%1\"" ).arg( params.
fileName() );
535 u
"Service configuration error"_s,
536 QStringLiteral(
"Service unknown or unsupported. Current supported services "
537 "(case-sensitive): WMS WFS WCS WMTS SampleService, or use a WFS3 "
538 "(OGC API Features) endpoint" )
546 responseDecorator.
write( ex );
553 response.
sendError( 500, u
"Internal Server Error"_s );
562 responseDecorator.
finish();
567 response.
sendError( 500, u
"Internal Server Error"_s );
573 sServerInterface->clearRequestHandler();
579 if ( sSettings->logProfile() )
581 std::function<void(
const QModelIndex &,
int )> profileFormatter;
582 profileFormatter = [&profileFormatter](
const QModelIndex &idx,
int level ) {
588 profileFormatter( subIdx, level + 1 );
595 profileFormatter( idx, 0 );
609#ifdef HAVE_SERVER_PYTHON_PLUGINS
610void 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())
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
Log a message from the server context.
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)