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 );
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++ )
110 if ( projectFiles.isEmpty() )
114 return projectFiles.at( 0 );
117 void QgsServer::printRequestParameters(
const QMap< QString, QString> ¶meterMap,
Qgis::MessageLevel logLevel )
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" );
150 else if ( ! defaultConfigPath.isEmpty() )
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()
197 #if defined(SERVER_SKIP_ECW)
210 if ( ! sSettings()->logFile().isEmpty() )
214 else if ( sSettings()->logStderr() )
223 sSettings()->logSummary();
225 setupNetworkAccessManager();
226 QDomImplementation::setInvalidDataPolicy( QDomImplementation::DropInvalidChars );
245 QString defaultConfigFilePath;
246 QFileInfo projectFileInfo = defaultProjectFile();
247 if ( projectFileInfo.exists() )
249 defaultConfigFilePath = projectFileInfo.absoluteFilePath();
254 QFileInfo adminSLDFileInfo = defaultAdminSLD();
255 if ( adminSLDFileInfo.exists() )
257 defaultConfigFilePath = adminSLDFileInfo.absoluteFilePath();
261 sConfigFilePath =
new QString( defaultConfigFilePath );
275 sServiceRegistry->
init( modulePath, sServerInterface );
288 qunsetenv( var.toUtf8().data() );
292 qputenv( var.toUtf8().data(), val.toUtf8() );
294 sSettings()->load( var );
304 qApp->processEvents();
347 responseDecorator.
start();
352 response.
sendError( 500, QStringLiteral(
"Internal Server Error" ) );
362 printRequestParameters( params.
toMap(), logLevel );
367 QString configFilePath = configPath( *sConfigFilePath, params.
map() );
370 if ( ! configFilePath.isEmpty() )
406 throw QgsServerException( QStringLiteral(
"Project file error. For OWS services: please provide a SERVICE and a MAP parameter pointing to a valid QGIS project file" ) );
409 if ( ! params.
fileName().isEmpty() )
411 const QString value = QString(
"attachment; filename=\"%1\"" ).arg( params.
fileName() );
412 requestHandler.
setResponseHeader( QStringLiteral(
"Content-Disposition" ), value );
424 QStringLiteral(
"Service unknown or unsupported. Current supported services (case-sensitive): WMS WFS WCS WMTS SampleService, or use a WFS3 (OGC API Features) endpoint" ) );
430 responseDecorator.
write( ex );
437 response.
sendError( 500, QStringLiteral(
"Internal Server Error" ) );
446 responseDecorator.
finish();
451 response.
sendError( 500, QStringLiteral(
"Internal Server Error" ) );
463 if ( sSettings->logProfile() )
465 std::function <void(
const QModelIndex &,
int )> profileFormatter;
466 profileFormatter = [ &profileFormatter ](
const QModelIndex & idx,
int level )
469 .arg( level > 0 ? QString().fill(
'-', level ) +
' ' : QString() )
472 .arg( QString::number(
QgsApplication::profiler()->data( idx, QgsRuntimeProfilerNode::Roles::Elapsed ).toDouble() * 1000.0 ) ), QStringLiteral(
"Server" ),
Qgis::Info );
477 profileFormatter( subIdx, level + 1 );
485 profileFormatter( idx, 0 );
497 #ifdef HAVE_SERVER_PYTHON_PLUGINS
498 void QgsServer::initPython()
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.
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::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.
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.
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...
void init(const QString &nativeModulepath, QgsServerInterface *serverIface=nullptr)
Initialize registry, load modules and auto register services.
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)