Index: src/mapservice/server_impl/CeleryWorker.py
===================================================================
--- src/mapservice/server_impl/CeleryWorker.py	(revision ae2ff15d6963a93c67e87e175ea31292b8bb3d28)
+++ src/mapservice/server_impl/CeleryWorker.py	(revision ae2ff15d6963a93c67e87e175ea31292b8bb3d28)
@@ -0,0 +1,62 @@
+'''
+    Copyright (C) 2020 EngSaS - Engineering Solutions and Services Langenbach. All rights reserved.
+
+    This program is free software: you can redistribute it and/or modify
+    it under the terms of the GNU General Public License as published by
+    the Free Software Foundation, either version 3 of the License, or
+    (at your option) any later version.
+
+    This program is distributed in the hope that it will be useful,
+    but WITHOUT ANY WARRANTY; without even the implied warranty of
+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+    GNU General Public License for more details.
+
+    You should have received a copy of the GNU General Public License
+    along with this program.  If not, see <http://www.gnu.org/licenses/>.
+'''
+from celery import Celery
+import flask
+from sqlalchemy import event
+
+from . import config_object, app, application, celery, setup_app
+from .database.Model import db
+from .tasks import tasks
+
+# see https://flask.palletsprojects.com/en/1.1.x/patterns/celery/
+def setup_celery(flask_app, celery_app):
+	celery_app.conf.update(flask_app.config)
+	TaskBase = celery_app.Task
+
+	class ContextTask(TaskBase):
+		abstract = True
+
+		def __call__(self, *args, **kwargs):
+			with flask_app.app_context():
+				@event.listens_for(db.engine, "connect")
+				def load_spatialite(dbapi_conn, connection_record):
+					if 'sqlite' in flask.current_app.config['SQLALCHEMY_DATABASE_URI']:
+						# From https://geoalchemy-2.readthedocs.io/en/latest/spatialite_tutorial.html
+						dbapi_conn.enable_load_extension(True)
+						dbapi_conn.load_extension('/usr/local/lib64/mod_spatialite')
+				
+				return TaskBase.__call__(self, *args, **kwargs)
+	
+	celery_app.Task = ContextTask
+	
+	with flask_app.app_context():
+		if not 'TILES_LITTLE_ZOOM_SCHEDULE' in flask.current_app.config:
+			flask.current_app.logger.error('TILES_LITTLE_ZOOM_SCHEDULE not configured')
+			raise ImportError('TILES_LITTLE_ZOOM_SCHEDULE not configured')
+		tiles_little_zoom_schedule = flask.current_app.config['TILES_LITTLE_ZOOM_SCHEDULE']
+		
+		celery_app.conf.beat_schedule = {
+			'add-log_little_zoom_slice': {
+				'task': 'gnuboat_mapservice.server_impl.tasks.tasks.log_little_zoom_slice',
+				'schedule': tiles_little_zoom_schedule
+			},
+		}
+	
+	return celery_app
+
+setup_app('GNUBoat Celery Worker', config_object)
+setup_celery(application, celery)
Index: src/mapservice/server_impl/Config.py
===================================================================
--- src/mapservice/server_impl/Config.py	(revision ae2ff15d6963a93c67e87e175ea31292b8bb3d28)
+++ src/mapservice/server_impl/Config.py	(revision ae2ff15d6963a93c67e87e175ea31292b8bb3d28)
@@ -0,0 +1,84 @@
+'''
+    Copyright (C) 2019 - 2020 EngSaS - Engineering Solutions and Services Langenbach. All rights reserved.
+
+    This program is free software: you can redistribute it and/or modify
+    it under the terms of the GNU General Public License as published by
+    the Free Software Foundation, either version 3 of the License, or
+    (at your option) any later version.
+
+    This program is distributed in the hope that it will be useful,
+    but WITHOUT ANY WARRANTY; without even the implied warranty of
+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+    GNU General Public License for more details.
+
+    You should have received a copy of the GNU General Public License
+    along with this program.  If not, see <http://www.gnu.org/licenses/>.
+'''
+
+from celery.schedules import crontab
+from pathlib import Path
+import os
+import yaml
+
+def load_from_file(config_file):
+	config_from_file = yaml.safe_load(open(config_file))
+	config = Config()
+	
+	for entry in config_from_file:
+		setattr(config, entry, config_from_file[entry])
+		
+	return config
+
+class Config(object):
+	DEBUG = False
+	TESTING = False
+	CREATE_TEST_DATABASE = False
+	SQLALCHEMY_TRACK_MODIFICATIONS = False
+	MAIL_SERVER = 'localhost'
+	MAIL_PORT = 25
+	MAIL_DEFAULT_SENDER = 'GNUBoat Mapservice <gnuboat@engsas.de>'
+	MAPSERVICE_WEBCLIENT = '/'
+	CELERY_BROKER_URL = 'pyamqp://guest@localhost//'
+	CELERY_IMPORTS = ("gnuboat_mapservice.server_impl.tasks")
+	CELERY_RESULT_BACKEND = "cache"
+	CELERY_CACHE_BACKEND = 'memcached://127.0.0.1:11211'
+	# pixel size of tiles to be generated
+	TILES_SIZES = [256, 512]
+	# Min required data points to get no nodata value in a raster pixel
+	TILES_DENSITIES = [10, 100]
+	TILES_DENSITY_BASEE = 100
+	# How many years are data points allowed to be old, before they are excluded from calculations
+	TILES_POINT_AGE_MAX = 10
+	# log_process generates tiles for this zoom range. all lower zoomlevels (0 - x) are generated by a periodic task (s. TILES_LITTLE_ZOOM_SCHEDULE option).
+	# Those zoomlevels are not rendered by log_process(), because they contain few details, but large areas
+	TILES_ZOOM_RANGE = {'minimum': 10, 'maximum': 19}
+	# schedule, when to run the job to generate tiles for low zoomlevels (0 - TILES_ZOOM_RANGE['minimum']),
+	# As format see https://docs.celeryproject.org/en/stable/userguide/periodic-tasks.html#crontab-schedules
+	# If TILES_ZOOM_RANGE['minimum'] = 10 it might need up to 4097 slice jobs per tile_size and density
+	TILES_LITTLE_ZOOM_SCHEDULE = crontab(0, 0, day_of_month='2') # execute every second day of each month
+	TILES_SKIP_EMPTY = True
+	# Maximum size of the raster files generated during tile process in bits
+	TILES_RASTER_FILE_SIZE_MAX = 512 * 1024 * 1024 * 8
+
+class ProductionConfig(Config):
+	SQLALCHEMY_DATABASE_URI = 'mysql://gnuboat:gnuboat@localhost/gnuboat_mapservice'
+
+class DevelopmentConfig(Config):
+	DEBUG = True
+	CREATE_TEST_DATABASE = True
+	SQLALCHEMY_DATABASE_URI = 'sqlite:////tmp/test.db'
+	MAPSERVICE_WEBCLIENT = 'http://localhost:8081'
+	#SERVER_NAME = 'gnuboat-mapservice:8080'
+	HOST = 'localhost'
+	SERVER_NAME = 'localhost:8080'
+	TILES_CACHE_PATH = os.path.join(Path.home(), '.cache/gnuboat/tiles')
+	TILES_SIZES = [256]
+
+class TestingConfig(DevelopmentConfig):
+	"""
+		Configuration for testing purposes only (like tox/nosetests)
+	"""
+	TESTING = True
+	DEBUG = False
+	CELERY_BROKER_URL = ''
+	SQLALCHEMY_DATABASE_URI = 'sqlite:////tmp/gnuboat-ci-tests.db'
Index: src/mapservice/server_impl/HttpErrors.py
===================================================================
--- src/mapservice/server_impl/HttpErrors.py	(revision ae2ff15d6963a93c67e87e175ea31292b8bb3d28)
+++ src/mapservice/server_impl/HttpErrors.py	(revision ae2ff15d6963a93c67e87e175ea31292b8bb3d28)
@@ -0,0 +1,35 @@
+'''
+    Copyright (C) 2019 - 2020 EngSaS - Engineering Solutions and Services Langenbach. All rights reserved.
+
+    This program is free software: you can redistribute it and/or modify
+    it under the terms of the GNU General Public License as published by
+    the Free Software Foundation, either version 3 of the License, or
+    (at your option) any later version.
+
+    This program is distributed in the hope that it will be useful,
+    but WITHOUT ANY WARRANTY; without even the implied warranty of
+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+    GNU General Public License for more details.
+
+    You should have received a copy of the GNU General Public License
+    along with this program.  If not, see <http://www.gnu.org/licenses/>.
+'''
+
+from werkzeug.exceptions import BadRequest, Unauthorized, NotFound, InternalServerError
+from connexion.exceptions import ProblemException 
+
+class MapserviceBadRequest(ProblemException, BadRequest):
+	def __init__(self, type="bad-request", title=None, detail=None, instance=None, **kwargs):
+		super(MapserviceBadRequest, self).__init__(status=400, title="Bad Request", detail=detail, type=type, instance=instance, **kwargs)
+		
+class MapserviceUnauthorized(ProblemException, Unauthorized):
+	def __init__(self, type="unauthorized", title="Access denied", detail="You need to login to access the requested resource", instance=None, **kwargs):
+		super(MapserviceUnauthorized, self).__init__(status=401, title=title, detail=detail, type=type, instance=instance, **kwargs)
+		
+class MapserviceNotFound(ProblemException, NotFound):
+	def __init__(self, type="not-found", title="Resouce not found", detail="The requested resource was not found", instance=None, **kwargs):
+		super(MapserviceNotFound, self).__init__(status=404, title=title, detail=detail, type=type, instance=instance, **kwargs)
+
+class MapserviceInternalServerError(ProblemException, InternalServerError):
+	def __init__(self, type="internal-server-error", title=None, detail=None, instance=None, **kwargs):
+		super(MapserviceInternalServerError, self).__init__(status=500, title="Internal Server Error", detail=detail, type=type, instance=instance, **kwargs)
Index: src/mapservice/server_impl/ValidatorWorkaround.py
===================================================================
--- src/mapservice/server_impl/ValidatorWorkaround.py	(revision ae2ff15d6963a93c67e87e175ea31292b8bb3d28)
+++ src/mapservice/server_impl/ValidatorWorkaround.py	(revision ae2ff15d6963a93c67e87e175ea31292b8bb3d28)
@@ -0,0 +1,54 @@
+"""Hacks needed to circumvent connexion validation
+
+There is a bug on the connexion library concerning content negotiation and
+response validation. See https://github.com/zalando/connexion/issues/860 and
+https://github.com/zalando/connexion/pull/760
+
+Until this issue is fixed, we need to find a way to avoid a false validation
+error when a requests sends an 'application/geo+json' accept header
+"""
+import functools
+import logging
+
+from connexion.decorators.response import ResponseValidator
+from connexion import problem
+from connexion.exceptions import NonConformingResponseBody, NonConformingResponseHeaders
+from connexion.utils import has_coroutine
+
+logger = logging.getLogger(__name__)
+
+
+class ValidatorWorkaround(ResponseValidator):
+
+	def validate_response_with_request(self, request, data, status_code, headers, url):
+		if request.headers.get('accept', '') == 'application/geo+json':
+			logging.debug('Circumventing validation for application/geo+json')
+			return True
+		return self.validate_response(data, status_code, headers, url)
+
+	def __call__(self, function):
+		"""
+		:type function: types.FunctionType
+		:rtype: types.FunctionType
+		"""
+		def _wrapper(request, response):
+			connexion_response = \
+				self.operation.api.get_connexion_response(response, self.mimetype)
+			self.validate_response_with_request(
+				request,
+				connexion_response.body, connexion_response.status_code,
+				connexion_response.headers, request.url)
+
+			return response
+
+		if has_coroutine(function):
+			from .coroutine_wrappers import get_response_validator_wrapper
+			wrapper = get_response_validator_wrapper(function, _wrapper)
+
+		else:  # pragma: 3 no cover
+			@functools.wraps(function)
+			def wrapper(request):
+				response = function(request)
+				return _wrapper(request, response)
+
+		return wrapper
Index: src/mapservice/server_impl/__init__.py
===================================================================
--- src/mapservice/server_impl/__init__.py	(revision ae2ff15d6963a93c67e87e175ea31292b8bb3d28)
+++ src/mapservice/server_impl/__init__.py	(revision ae2ff15d6963a93c67e87e175ea31292b8bb3d28)
@@ -0,0 +1,74 @@
+'''
+    Copyright (C) 2019 - 2020 EngSaS - Engineering Solutions and Services Langenbach. All rights reserved.
+
+    This program is free software: you can redistribute it and/or modify
+    it under the terms of the GNU General Public License as published by
+    the Free Software Foundation, either version 3 of the License, or
+    (at your option) any later version.
+
+    This program is distributed in the hope that it will be useful,
+    but WITHOUT ANY WARRANTY; without even the implied warranty of
+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+    GNU General Public License for more details.
+
+    You should have received a copy of the GNU General Public License
+    along with this program.  If not, see <http://www.gnu.org/licenses/>.
+'''
+
+import connexion
+import flask
+from flask_cors import CORS
+from flask_mail import Mail
+from sqlalchemy import event
+from celery import Celery
+from werkzeug.utils import import_string
+import os
+
+from .. import encoder
+from .database.Model import db, User, ApiKey, db_setup, load_spatialite
+from .ValidatorWorkaround import ValidatorWorkaround
+
+def load_config_object(config_name):
+	return import_string('gnuboat_mapservice.server_impl.Config.{}Config'.format(config_name))
+
+# determine requested configuration
+config_file = '/etc/gnuboat/mapservice.conf'
+if 'FLASK_ENV' in os.environ and os.environ['FLASK_ENV']:
+	config_object = load_config_object(os.environ['FLASK_ENV'].title())
+elif os.path.isfile(config_file):
+	from . import Config as configure
+	config_object = configure.load_from_file(config_file)
+else:
+	config_object = load_config_object('Production')
+
+app = connexion.App(__name__, specification_dir='../openapi/')
+application = app.app
+CORS(application)
+mail = Mail()
+celery = Celery(__name__, broker=config_object.CELERY_BROKER_URL)
+
+@application.before_first_request
+def create_database():
+	@event.listens_for(db.engine, "connect")
+	def load_spatialite_extension(dbapi_conn, connection_record):
+		load_spatialite(dbapi_conn, connection_record)
+			
+
+	if flask.current_app.config['CREATE_TEST_DATABASE'] == True:
+		from .demo import DbSetup as demoDbSetup
+		demoDbSetup.setup()
+	else:
+		db_setup()
+
+@application.route("/mapservice/")
+def index():
+	return render_template('index.html')
+
+def setup_app(app_name, config):
+	application.json_encoder = encoder.JSONEncoder
+	app.add_api('openapi.yaml', arguments={'title': app_name}, validate_responses=True, strict_validation=True, validator_map={'response': ValidatorWorkaround})
+	application.config.from_object(config)
+
+	db.init_app(application)
+	mail.init_app(application)
+	celery.config_from_object(config)
Index: src/mapservice/server_impl/controllers/DevicesController.py
===================================================================
--- src/mapservice/server_impl/controllers/DevicesController.py	(revision ae2ff15d6963a93c67e87e175ea31292b8bb3d28)
+++ src/mapservice/server_impl/controllers/DevicesController.py	(revision ae2ff15d6963a93c67e87e175ea31292b8bb3d28)
@@ -0,0 +1,75 @@
+'''
+    Copyright (C) 2019 EngSaS - Engineering Solutions and Services Langenbach. All rights reserved.
+
+    This program is free software: you can redistribute it and/or modify
+    it under the terms of the GNU General Public License as published by
+    the Free Software Foundation, either version 3 of the License, or
+    (at your option) any later version.
+
+    This program is distributed in the hope that it will be useful,
+    but WITHOUT ANY WARRANTY; without even the implied warranty of
+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+    GNU General Public License for more details.
+
+    You should have received a copy of the GNU General Public License
+    along with this program.  If not, see <http://www.gnu.org/licenses/>.
+'''
+import connexion
+
+from ..database.Model import User, Device, db
+from ..HttpErrors import MapserviceBadRequest, MapserviceUnauthorized, MapserviceNotFound
+
+def devices_get(name=None, order_by=None, offset=None, limit=None):
+	query = None
+	
+	user = User.loggedin_user()
+	if user is None:
+		raise MapserviceUnauthorized
+
+	query = Device.query.filter_by(owner = user)
+	if name is not None:
+		query = query.filter(Device.name.like('%{}%'.format(name)))
+
+	result = []
+	for device in query.offset(offset).limit(limit):
+		result.append(device.to_dict())
+	return result
+
+def devices_get_by_id(id):
+	user = User.loggedin_user()
+	if user is None:
+		raise MapserviceUnauthorized
+	
+	device = Device.query.filter_by(owner = user).filter_by(id=id).all()
+	if len(device) != 1:
+		raise MapserviceNotFound
+	return device[0].to_dict()
+
+def devices_create(device_creation):
+	user = User.loggedin_user()
+	if user is None:
+		raise MapserviceUnauthorized
+	
+	comment = ""
+	if device_creation.comment:
+		comment = device_creation.comment
+	
+	device = Device(name=device_creation.name, owner=user, sensor_depth=device_creation.sensor_depth, comment=comment)
+	db.session.add(device)
+	db.session.commit()
+	return device.to_dict()
+
+def devices_device_delete(id):
+	user = User.loggedin_user()
+	if user is None:
+		raise MapserviceUnauthorized
+	
+	if not Device.query.filter_by(owner = user).filter_by(id=id).delete():
+		raise MapserviceBadRequest(detail="Could not delete device with id {}".format(id))
+	db.session.commit()
+	
+	query = Device.query.filter_by(owner = user)
+	result = []
+	for device in query:
+		result.append(device.to_dict())
+	return result
Index: src/mapservice/server_impl/controllers/LogsController.py
===================================================================
--- src/mapservice/server_impl/controllers/LogsController.py	(revision ae2ff15d6963a93c67e87e175ea31292b8bb3d28)
+++ src/mapservice/server_impl/controllers/LogsController.py	(revision ae2ff15d6963a93c67e87e175ea31292b8bb3d28)
@@ -0,0 +1,135 @@
+'''
+    Copyright (C) 2019 - 2020 EngSaS - Engineering Solutions and Services Langenbach. All rights reserved.
+
+    This program is free software: you can redistribute it and/or modify
+    it under the terms of the GNU General Public License as published by
+    the Free Software Foundation, either version 3 of the License, or
+    (at your option) any later version.
+
+    This program is distributed in the hope that it will be useful,
+    but WITHOUT ANY WARRANTY; without even the implied warranty of
+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+    GNU General Public License for more details.
+
+    You should have received a copy of the GNU General Public License
+    along with this program.  If not, see <http://www.gnu.org/licenses/>.
+'''
+import connexion
+
+from ..database.Model import User, Log, LogEntry, Water, Device, Gauge, ProcessingStatus, Queue, db
+from ..HttpErrors import MapserviceBadRequest, MapserviceUnauthorized, MapserviceNotFound
+from ..tasks.tasks import log_process
+
+def logs_get(submitter=None, order_by=None, offset=None, limit=None):
+	query = None
+	
+	if submitter is not None:
+		submitter = User.query.filter_by(username=submitter).all()
+		if len(submitter) != 1:
+			raise MapserviceNotFound(detail="Could not find the submitter with id {}".format(submitter))
+		submitter = submitter[0]
+
+	query = None
+	if submitter is not None:
+		query = Log.query.filter_by(submitter = submitter)
+		
+	if query is None:
+		query = Log.query
+	
+	result = []
+	for log in query.offset(offset).limit(limit):
+		result.append(log.meta_data())
+	return result
+
+def logs_log_get_by_id(id):
+	log = Log.query.filter_by(id=id).all()
+	if len(log) != 1:
+		raise MapserviceNotFound
+	if connexion.request.headers['Accept'] == "application/geo+json":
+		return log[0].to_geojson(), 200, {'Content-Type': 'application/geo+json; charset=utf-8'}
+	return log[0].log()
+
+def logs_log_create(log_creation):
+	user = User.loggedin_user()
+	if user is None:
+		raise MapserviceUnauthorized
+
+	water = Water.query.filter_by(id=log_creation.water).all()
+	if len(water) != 1:
+		raise MapserviceBadRequest(detail='Water {} not found database'.format(log_creation.water))
+	water = water[0]
+	
+	device = Device.query.filter_by(id=log_creation.device).all()
+	if len(device) != 1:
+		raise MapserviceBadRequest(detail='Device {} not found in database'.format(log_creation.device))
+	device = device[0]
+	
+	gauge = Gauge.query.filter_by(id=log_creation.gauge).all()
+	if len(gauge) != 1:
+		raise MapserviceBadRequest(detail='Gauge {} not found in database'.format(log_creation.gauge))
+	gauge = gauge[0]
+	
+	if log_creation.gauge_height is None:
+		raise MapserviceBadRequest(detail='Gauge Height (Stage) missing')
+	else:
+		try:
+			float(log_creation.gauge_height)
+		except ValueError:
+			raise MapserviceBadRequest(detail='Gauge Height (Stage) {} is no number'.format(log_creation.gauge_height))
+
+	if log_creation.comment is None:
+		log_creation.comment = ""
+	
+	log = Log(submitter=user, water=water, device=device, gauge=gauge, gauge_height=log_creation.gauge_height, start=None, end=None, comment=log_creation.comment)
+	db.session.add(log)
+	db.session.commit()
+	return log.meta_data()
+
+def logs_log_upload(log_id, body=None):
+	user = User.loggedin_user()
+	if user is None:
+		raise MapserviceUnauthorized
+	
+	if body is None or not body:
+		raise MapserviceBadRequest(detail='No log data')
+	
+	processing_state = ProcessingStatus.query.filter_by(label='Queued for Parsing').all()
+	if len(processing_state) != 1:
+		raise MapserviceBadRequest(detail='Processing status Queued for Parsing not found database')
+	processing_state = processing_state[0]
+	
+	log = Log.query.filter_by(id=log_id).all()
+	if len(log) != 1:
+		raise MapserviceBadRequest(detail='Log {} not found database'.format(log_id))
+	log = log[0]
+	
+	# check if Log has already log entries
+	if LogEntry.query.filter_by(log=log).count() > 0:
+		raise MapserviceBadRequest(detail='Log {} has already log entries. Aborting'.format(log_id))
+
+	# Add Log to Queued table and change the processing state of Log
+	queue = Queue(log=log)
+	db.session.add(queue)
+	log.processingstatus = processing_state
+	db.session.commit()
+	
+	# request log parsing
+	log_process.delay(log.id, body.decode())
+	
+	return log.meta_data()
+
+def logs_log_delete(id):
+	user = User.loggedin_user()
+	if user is None:
+		raise MapserviceUnauthorized
+	
+	if not Log.query.filter_by(submitter = user).filter_by(id=id).delete():
+		raise MapserviceBadRequest(detail="Could not delete log with id {}".format(id))
+	db.session.commit()
+	
+	query = Log.query.filter_by(submitter = user)
+	result = []
+	for log in query:
+		result.append(log.meta_data())
+	return result
+
Index: src/mapservice/server_impl/controllers/TilesController.py
===================================================================
--- src/mapservice/server_impl/controllers/TilesController.py	(revision ae2ff15d6963a93c67e87e175ea31292b8bb3d28)
+++ src/mapservice/server_impl/controllers/TilesController.py	(revision ae2ff15d6963a93c67e87e175ea31292b8bb3d28)
@@ -0,0 +1,58 @@
+'''
+    Copyright (C) 2020 EngSaS - Engineering Solutions and Services Langenbach. All rights reserved.
+
+    This program is free software: you can redistribute it and/or modify
+    it under the terms of the GNU General Public License as published by
+    the Free Software Foundation, either version 3 of the License, or
+    (at your option) any later version.
+
+    This program is distributed in the hope that it will be useful,
+    but WITHOUT ANY WARRANTY; without even the implied warranty of
+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+    GNU General Public License for more details.
+
+    You should have received a copy of the GNU General Public License
+    along with this program.  If not, see <http://www.gnu.org/licenses/>.
+'''
+
+import connexion
+import flask
+import os
+
+from ..HttpErrors import MapserviceInternalServerError, MapserviceBadRequest, MapserviceNotFound
+
+def tiles_tile_get(accuracy, resolution, zoom, x_tile, y_tile):
+	if not 'TILES_CACHE_PATH' in flask.current_app.config or not os.access(flask.current_app.config['TILES_CACHE_PATH'], os.R_OK):
+		raise MapserviceInternalServerError(detail='TILES_CACHE_PATH not configured or not accessible')
+	tiles_cache_path = flask.current_app.config['TILES_CACHE_PATH']
+	
+	if not 'TILES_DENSITIES' in flask.current_app.config:
+		raise MapserviceInternalServerError(details='TILES_DENSITIES not configured')
+	tiles_densities = flask.current_app.config['TILES_DENSITIES']
+	
+	if not 'TILES_DENSITY_BASEE' in flask.current_app.config:
+		raise MapserviceInternalServerError(details='TILES_DENSITY_BASEE not configured')
+	tiles_densitiy_base = flask.current_app.config['TILES_DENSITY_BASEE']
+	
+	if not 'TILES_SKIP_EMPTY' in flask.current_app.config:
+		raise MapserviceInternalServerError(details='TILES_SKIP_EMPTY not configured')
+	tiles_skip_empty = flask.current_app.config['TILES_SKIP_EMPTY']
+	
+	if accuracy == 'high':
+		accuracy = '{}_{}'.format(max(tiles_densities), tiles_densitiy_base)
+	elif accuracy == 'low':
+		accuracy = '{}_{}'.format(min(tiles_densities), tiles_densitiy_base)
+	else:
+		raise MapserviceBadRequest(details='No valid accuracy requested. Valid are high, low. Requested was: {}'.format(accuracy))
+	
+	tile__empty_path = os.path.join(tiles_cache_path, '{}/{}/empty_tile.png'.format(accuracy, resolution))
+	tile_path = os.path.join(tiles_cache_path, '{}/{}/{}/{}/{}.png'.format(accuracy, resolution, zoom, x_tile, y_tile))
+	if not os.path.isfile(tile_path):
+		if not tiles_skip_empty or not os.path.isfile(tile__empty_path):
+			raise MapserviceNotFound(detail='Tile ({}, {}) for accuracy {} with resolution {} at zoomlevel {} not found'.format(x_tile, y_tile, accuracy, resolution, zoom))
+		tile_path = tile__empty_path
+	
+	response = flask.send_file(tile_path, mimetype='image/png', as_attachment=True, attachment_filename='{}.png'.format(y_tile))
+	response.direct_passthrough = False
+	#response.headers['Content-Transfer-Encoding']='base64'
+	return response
Index: src/mapservice/server_impl/controllers/UsersController.py
===================================================================
--- src/mapservice/server_impl/controllers/UsersController.py	(revision ae2ff15d6963a93c67e87e175ea31292b8bb3d28)
+++ src/mapservice/server_impl/controllers/UsersController.py	(revision ae2ff15d6963a93c67e87e175ea31292b8bb3d28)
@@ -0,0 +1,128 @@
+'''
+    Copyright (C) 2019 - 2020 EngSaS - Engineering Solutions and Services Langenbach. All rights reserved.
+
+    This program is free software: you can redistribute it and/or modify
+    it under the terms of the GNU General Public License as published by
+    the Free Software Foundation, either version 3 of the License, or
+    (at your option) any later version.
+
+    This program is distributed in the hope that it will be useful,
+    but WITHOUT ANY WARRANTY; without even the implied warranty of
+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+    GNU General Public License for more details.
+
+    You should have received a copy of the GNU General Public License
+    along with this program.  If not, see <http://www.gnu.org/licenses/>.
+'''
+import connexion
+
+import datetime
+import hashlib
+import re
+import flask
+from flask import request, render_template
+from flask_mail import Message
+
+from .. import mail
+from ..database.Model import User, ApiKey, db
+from ..HttpErrors import MapserviceBadRequest, MapserviceUnauthorized, MapserviceNotFound
+
+mail_regex = re.compile('[^@]+@[^@]+\.[^@]+')
+
+def users_activate(activationCode):
+	user = User.query.filter_by(activation_code=activationCode).all()
+	
+	webclient = flask.current_app.config['MAPSERVICE_WEBCLIENT']
+	
+	if len(user) != 1:
+		return 'Bad Request', 302, {'Location': 'activation_failed.html'}
+	
+	user = user[0]
+	user.activated = True
+	user.activation_code = ""
+	db.session.commit()
+	return 'Success', 302, {'Location': '{}/login'.format(webclient)}
+
+def users_api_key_create():
+	user = User.loggedin_user()
+	if user is None:
+		raise MapserviceUnauthorized
+	
+	api_key = hashlib.md5("{}{}".format(datetime.datetime.now().strftime("%Y%m%d%H%M%S"), user.salt).encode()).hexdigest()
+	user.apikeys.append(ApiKey(user=user, key=api_key))
+	db.session.commit()
+
+	result = []
+	for apiKey in user.apikeys:
+		result.append(apiKey.key)
+	return result
+
+def users_api_key_delete(api_key):
+	user = User.loggedin_user()
+	if user is None:
+		raise MapserviceUnauthorized
+	
+	if not ApiKey.query.filter_by(key=api_key).delete():
+		raise MapserviceBadRequest(detail="Could not delete api key {}".format(api_key))
+	db.session.commit()
+	
+	result = []
+	for apiKey in user.apikeys:
+		result.append(apiKey.key)
+	return result
+
+def users_get():
+	user = User.loggedin_user()
+	if user is None:
+		raise MapserviceUnauthorized
+	
+	return user_to_dict(user)
+
+def users_register(user_creation):
+	if user_creation is None:
+		raise MapserviceBadRequest(detail='No data specified')
+	if user_creation.username is None or not user_creation.username:
+		raise MapserviceBadRequest(detail='No username given')
+	if user_creation.password is None or not user_creation.password:
+		raise MapserviceBadRequest(detail='No password given')
+	if user_creation.first_name is None or not user_creation.first_name:
+		raise MapserviceBadRequest(detail='No first name given')
+	if user_creation.last_name is None or not user_creation.last_name:
+		raise MapserviceBadRequest(detail='No last name given')
+	if user_creation.email is None or not user_creation.email:
+		raise MapserviceBadRequest(detail='No email given')
+	if not mail_regex.match(user_creation.email):
+		raise MapserviceBadRequest(detail='Email contains more than one @, no @ or no .')
+	if user_creation.license_accepted is None or not user_creation.license_accepted:
+		raise MapserviceBadRequest(detail='You must accept the license to register an account')
+	
+	# add user to the database
+	user = User.factory(user_creation.username, user_creation.password, user_creation.email)
+	user.first_name = user_creation.first_name
+	user.last_name = user_creation.last_name
+	user.license_accepted = user_creation.license_accepted
+	db.session.add(user)
+	db.session.commit()
+	
+	# send activation mail
+	activation_url = '{}/activate/{}'.format(request.base_url, user.activation_code)
+	
+	message = Message("Activate your GNUBoat account", recipients=[user.email])
+	message.body = 'Hello {},\nthank you for support the project with your own measurings. To activate your GNUBoat account, visit {}.\nKind regards,\nYour GNUBoat team'.format(user.first_name, activation_url)
+	message.html = render_template('activation_mail.html', first_name=user.first_name, activation_url=activation_url)
+	mail.send(message)
+	
+	return user_to_dict(user)
+
+def user_to_dict(user):
+	# create user dict and remove not needed entries
+	result = user.to_dict()
+	del result['password']
+	del result['salt']
+	del result['activationCode']
+	
+	# add api keys of the user to the result dict
+	result['apiKeys'] = []
+	for apiKey in user.apikeys:
+		result['apiKeys'].append(apiKey.key)
+	return result
Index: src/mapservice/server_impl/controllers/WatersController.py
===================================================================
--- src/mapservice/server_impl/controllers/WatersController.py	(revision ae2ff15d6963a93c67e87e175ea31292b8bb3d28)
+++ src/mapservice/server_impl/controllers/WatersController.py	(revision ae2ff15d6963a93c67e87e175ea31292b8bb3d28)
@@ -0,0 +1,150 @@
+'''
+    Copyright (C) 2019 EngSaS - Engineering Solutions and Services Langenbach. All rights reserved.
+
+    This program is free software: you can redistribute it and/or modify
+    it under the terms of the GNU General Public License as published by
+    the Free Software Foundation, either version 3 of the License, or
+    (at your option) any later version.
+
+    This program is distributed in the hope that it will be useful,
+    but WITHOUT ANY WARRANTY; without even the implied warranty of
+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+    GNU General Public License for more details.
+
+    You should have received a copy of the GNU General Public License
+    along with this program.  If not, see <http://www.gnu.org/licenses/>.
+'''
+import connexion
+
+from ..database.Model import User, Water, Gauge, Log, db
+from ..HttpErrors import MapserviceBadRequest, MapserviceUnauthorized, MapserviceNotFound
+
+def waters_get(name=None, manager=None, stakeholder=None, order_by=None, offset=None, limit=None):
+	query = None
+	
+	if manager is not None:
+		manager = User.query.filter_by(username=manager).all()
+		if len(manager) != 1:
+			raise MapserviceNotFound(detail="Could not find the manager with id {}".format(manager))
+		manager = manager[0]
+
+	query = Water.query
+	if manager is not None:
+		query = query.filter_by(manager = manager)
+	if name is not None:
+		query = query.filter(Water.name.like('%{}%'.format(name)))
+	
+	waters = []
+	for water in query.offset(offset).limit(limit):
+		waters.append(water)
+		
+	# handle stakeholder
+	if stakeholder is not None:
+		stakeholder = User.query.filter_by(username=stakeholder).all()
+		if len(stakeholder) != 1:
+			raise MapserviceNotFound(details='Stakeholder not found')
+		stakeholder = stakeholder[0]
+		
+		# add waters, where the stakeholder has added logs to
+		query_log = Log.query.filter_by(submitter=stakeholder).all()
+		for log in query_log:
+			already_found = False
+			for water in waters:
+				if water.id == log.water.id:
+					already_found = True
+					break
+			if not already_found:
+				waters.append(log.water)
+		
+		# add waters, where the stakeholder has added gauges to
+		query_gauge = Gauge.query.filter_by(manager=stakeholder).all()
+		for gauge in query_gauge:
+			already_found = False
+			for water in waters:
+				if water.id == gauge.water.id:
+					already_found = True
+					break
+			if not already_found:
+				waters.append(gauge.water)
+				
+	result = []
+	for water in waters:
+		result.append(water.to_dict())
+	
+	return result
+
+def waters_get_by_id(id):
+	water = Water.query.filter_by(id=id).all()
+	if len(water) != 1:
+		raise MapserviceNotFound
+	return water[0].to_dict()
+
+def waters_create(water_creation):
+	user = User.loggedin_user()
+	if user is None:
+		raise MapserviceUnauthorized
+	
+	water = Water(name=water_creation.name, manager=user, osm_id=water_creation.osm_id, osm_type=water_creation.osm_type)
+	db.session.add(water)
+	db.session.commit()
+	return water.to_dict()
+
+def waters_gauge_get_by_id(water_id, gauge_id):
+	water = Water.query.filter_by(id=water_id).all()
+	if len(water) != 1:
+		raise MapserviceBadRequest(detail="Water with id {} not found".format(water_id))
+	water = water[0]
+
+	gauge = Gauge.query.filter_by(water=water).filter_by(id=gauge_id).all()
+	if len(gauge) != 1:
+		raise MapserviceNotFound(detail="Did not find gauge with id {} for water {}".format(gauge_id, water.name))
+	if connexion.request.headers['Accept'] == "application/geo+json":
+		return gauge[0].to_geojson(), 200, {'Content-Type': 'application/geo+json; charset=utf-8'}
+	return gauge[0].to_dict()
+
+
+def waters_gauge_create(water_id, gauge_creation):
+	user = User.loggedin_user()
+	if user is None:
+		raise MapserviceUnauthorized
+	
+	water = Water.query.filter_by(id=water_id).all()
+	if len(water) != 1:
+		raise MapserviceBadRequest(detail="Did not find water with id {}".format(water_id))
+	water = water[0]
+	
+	location = 'SRID=4326;POINT({:.6} {:.6})'.format(gauge_creation.location[0], gauge_creation.location[1])
+	gauge = Gauge(name=gauge_creation.name, manager=user, water=water, location=location, reference_water_level_gauge_height=gauge_creation.reference_water_level_gauge_height, comment=gauge_creation.comment)
+	db.session.add(gauge)
+	db.session.commit()
+	return gauge.to_dict()
+
+def waters_gauges_get(water_id, name, manager, order_by, offset, limit):
+	water = Water.query.filter_by(id=water_id).all()
+	if len(water) != 1:
+		raise MapserviceBadRequest(detail="Did not find water with id {}".format(water_id))
+	
+	query = None
+	
+	if manager is not None:
+		manager = User.query.filter_by(username=manager).all()
+		if len(manager) != 1:
+			raise MapserviceNotFound(detail="Could not find the manager with id {}".format(manager))
+		manager = manager[0]
+
+	query = Gauge.query.filter_by(id=water_id)
+	if manager is not None:
+		if manager and name is not None:
+			query = query.filter_by(manager = manager).filter(Gauge.name.like('%{}%'.format(name)))
+		elif manager:
+			query = query.filter_by(manager = manager)
+	elif name is not None:
+		query = query.filter(Gauge.name.like('%{}%'.format(name)))
+	
+	result = []
+	for gauge in query.offset(offset).limit(limit):
+		if connexion.request.headers['Accept'] == "application/geo+json":
+			result.append(gauge.to_geojson())
+		else:
+			result.append(gauge.to_dict())
+	return result
Index: src/mapservice/server_impl/database/Model.py
===================================================================
--- src/mapservice/server_impl/database/Model.py	(revision ae2ff15d6963a93c67e87e175ea31292b8bb3d28)
+++ src/mapservice/server_impl/database/Model.py	(revision ae2ff15d6963a93c67e87e175ea31292b8bb3d28)
@@ -0,0 +1,409 @@
+'''
+    Copyright (C) 2019 - 2020 EngSaS - Engineering Solutions and Services Langenbach. All rights reserved.
+
+    This program is free software: you can redistribute it and/or modify
+    it under the terms of the GNU General Public License as published by
+    the Free Software Foundation, either version 3 of the License, or
+    (at your option) any later version.
+
+    This program is distributed in the hope that it will be useful,
+    but WITHOUT ANY WARRANTY; without even the implied warranty of
+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+    GNU General Public License for more details.
+
+    You should have received a copy of the GNU General Public License
+    along with this program.  If not, see <http://www.gnu.org/licenses/>.
+'''
+import flask
+from flask_sqlalchemy import SQLAlchemy
+from sqlalchemy import inspect, text, Enum, event, select, func
+from sqlalchemy.orm.attributes import get_history
+from geoalchemy2 import Geometry
+from geoalchemy2.shape import to_shape
+from sqlalchemy_utc import UtcDateTime
+from sqlalchemy_utils import create_view, database_exists, create_database
+import hashlib
+import datetime
+import enum
+import connexion
+from pathlib import Path
+import sys
+import os
+
+db = SQLAlchemy()
+
+class OsmType(enum.Enum):
+	Node = 1
+	Way = 2
+	Relation = 3
+
+def wkb_to_dict(wkbelement):
+	point = to_shape(wkbelement)
+	return {'longitude': point.x, 'latitude': point.y}
+
+class User(db.Model):
+	__tablename__ = "users"
+	
+	id = db.Column(db.Integer, primary_key=True, autoincrement=True)
+	username = db.Column(db.String(255), nullable=False, unique=True)
+	password = db.Column(db.String(50), nullable=False)
+	salt = db.Column(db.String(50), nullable=False)
+	email = db.Column(db.String(255), nullable=False)
+	first_name = db.Column(db.String(255))
+	last_name = db.Column(db.String(255))
+	activated = db.Column(db.Boolean(), default=False)
+	activation_code = db.Column(db.String(255), default='1234')
+	#activation_code = db.Column(db.String(255), server_default=text('LEFT(MD5(NOW()), 50)'))
+	license_accepted = db.Column(db.Boolean(), default=False)
+	
+	def to_dict(user):
+		result = {
+			'username': user.username,
+			'password': user.password,
+			'salt': user.salt,
+			'email': user.email,
+			'firstName': "",
+			'lastName': "",
+			'activated': user.activated,
+			'licenseAccepted': user.license_accepted
+		}
+		if user.first_name is not None:
+			result['firstName'] = user.first_name
+		if user.last_name is not None:
+			result['lastName'] = user.last_name
+		if user.activation_code is not None:
+			result['activationCode'] = user.activation_code
+		
+		return result
+	
+	def factory(username, password, email):
+		salt = hashlib.md5('{}{}'.format(username, datetime.datetime.utcnow().strftime('%Y%m%d%H%M%S')).encode()).hexdigest()
+		password = hashlib.md5('{}{}'.format(password, salt).encode()).hexdigest()
+		activation_code = hashlib.md5('{}'.format(datetime.datetime.utcnow().strftime('%Y%m%d%H%M%S')).encode()).hexdigest()
+		return User(username=username, password=password, email=email, salt=salt, activated=False, activation_code=activation_code)
+	
+	def password_verify(self, password):
+		return hashlib.md5("{}{}".format(password, self.salt).encode()).hexdigest() == self.password
+	
+	@staticmethod
+	def loggedin_username():
+		if not 'user' in connexion.context:
+			return None
+		return connexion.context['user']
+
+	@staticmethod
+	def loggedin_user():
+		username = User.loggedin_username()
+		if username is None:
+			return None
+		user = User.query.filter_by(username=username).all()
+		if len(user) != 1:
+			return None
+		return user[0]
+
+class ApiKey(db.Model):
+	__tablename__ = "apikeys"
+
+	id = db.Column(db.Integer, primary_key=True, autoincrement=True)
+	user_id = db.Column(db.BigInteger, db.ForeignKey('users.id'))
+	key = db.Column(db.String(255), nullable=False, unique=True)
+	user = db.relationship("User", backref=db.backref("apikeys"), lazy=True)
+	
+class Water(db.Model):
+	__tablename__ = "waters"
+	
+	id = db.Column(db.Integer, primary_key=True, autoincrement=True)
+	name = db.Column(db.String(255), nullable=False)
+	manager_id = db.Column(db.Integer, db.ForeignKey('users.id'))
+	osm_id = db.Column(db.Integer)
+	osm_type = db.Column(Enum(OsmType))
+	manager = db.relationship("User", backref=db.backref("waters"), lazy=True)
+	
+	def to_dict(obj):
+		result = { 'waterId': obj.id, 'name': obj.name }
+		if obj.manager:
+			result['manager'] = obj.manager.username
+		if obj.osm_id:
+			result['osmId'] = obj.osm_id
+		if obj.osm_type:
+			result['osmType'] = obj.osm_type.name
+		if obj.gauges:
+			result['gauges'] = []
+			for gauge in obj.gauges:
+				result['gauges'].append(gauge.to_dict())
+		if obj.logs:
+			logs = []
+			for log in obj.logs:
+				logs.append(log.meta_data())
+			result['logs'] = logs
+		return result
+	
+class Gauge(db.Model):
+	__tablename__ = "gauges"
+	
+	id = db.Column(db.Integer, primary_key=True, autoincrement=True)
+	name = db.Column(db.String(255), nullable=False)
+	manager_id = db.Column(db.Integer, db.ForeignKey('users.id'))
+	water_id = db.Column(db.Integer, db.ForeignKey('waters.id'))
+	# POINT(Lon Lat)
+	location = db.Column(Geometry(geometry_type='POINT', srid=4326, management=True))
+	reference_water_level_gauge_height = db.Column(db.Float, nullable = False)
+	comment = db.Column(db.String(255))
+	#osm_id = db.Column(db.Integer)
+	#osm_type = db.Column(db.String(255))
+	#osm_class = db.Column(db.String(255))
+	manager = db.relationship("User", backref=db.backref("gauges"), lazy=True)
+	water = db.relationship("Water", backref=db.backref("gauges"), lazy=True)
+	
+	def to_dict(obj):
+		result = { 'gaugeId': obj.id, 'name': obj.name }
+		if obj.manager:
+			result['manager'] = obj.manager.username
+		location = wkb_to_dict(obj.location)
+		result['location'] = [location['longitude'], location['latitude']]
+		result['referenceWaterLevelGaugeHeight'] = obj.reference_water_level_gauge_height
+		if obj.water:
+			result['water'] = { 'label': obj.water.name, 'id': obj.water.id }
+		if obj.logs:
+			logs = []
+			for log in obj.logs:
+				logs.append(log.meta_data())
+			result['logs'] = logs
+		if obj.comment:
+			result['comment'] = obj.comment
+		return result
+	
+	def to_geojson(obj):
+		location = wkb_to_dict(obj.location)
+		result = {
+			'type': 'Feature',
+			'geometry': {
+				'type': 'Point',
+				'coordinates': [location['longitude'], location['latitude']]
+			},
+			'properties': {
+				'name': obj.name,
+				'referenceWaterLevelGaugeHeight': obj.reference_water_level_gauge_height
+			}
+		}
+		if obj.manager:
+			result['properties']['manager'] = obj.manager.username
+		if obj.comment:
+			result['properties']['comment'] = obj.comment
+		return result
+	
+class Device(db.Model):
+	__tablename__ = "devices"
+	
+	id = db.Column(db.Integer, primary_key=True, autoincrement=True)
+	name = db.Column(db.String(255), nullable=False)
+	owner_id = db.Column(db.Integer, db.ForeignKey('users.id'))
+	sensor_depth = db.Column(db.Float, nullable=False)
+	comment = db.Column(db.String(255))
+	
+	owner = db.relationship("User", backref=db.backref("devices"), lazy=True)
+	
+	def to_dict(obj):
+		result = { 'deviceId': obj.id, 'name': obj.name, 'sensorDepth': obj.sensor_depth }
+		if obj.logs:
+			logs = []
+			for log in obj.logs:
+				logs.append(log.meta_data())
+			result['logs'] = logs
+		if obj.comment:
+			result['comment'] = obj.comment
+		return result
+
+class ProcessingStatus(db.Model):
+	__tablename__ = "processingstatus"
+	
+	id = db.Column(db.Integer, primary_key=True, autoincrement=True)
+	label = db.Column(db.String(255), nullable=False)
+	
+	@staticmethod
+	def insert_states():
+		states = [ 'Undefined', 'Queued for Parsing', 'Parsing', 'Queued for Processing', 'Processing', 'Deployed', 'To Old', 'Error' ]
+		changed = False
+		for state in states:
+			query = ProcessingStatus.query.filter_by(label=state).all()
+			if len(query) != 1:
+				state = ProcessingStatus(label=state)
+				db.session.add(state)
+				changed = True
+		if changed:
+			db.session.commit()
+
+class Log(db.Model):
+	__tablename__ = "logs"
+	
+	id = db.Column(db.Integer, primary_key=True, autoincrement=True)
+	submitter_id = db.Column(db.Integer, db.ForeignKey('users.id'))
+	water_id = db.Column(db.Integer, db.ForeignKey('waters.id'))
+	device_id = db.Column(db.Integer, db.ForeignKey('devices.id'))
+	gauge_id = db.Column(db.Integer, db.ForeignKey('gauges.id'))
+	gauge_height = db.Column(db.Float, nullable=False)
+	start = db.Column(UtcDateTime, nullable=True)
+	end = db.Column(UtcDateTime, nullable=True)
+	processing_state = db.Column(db.Integer, db.ForeignKey('processingstatus.id'), default=1)
+	comment = db.Column(db.String(255))
+	
+	submitter = db.relationship("User", backref=db.backref("logs"), lazy=True)
+	water = db.relationship("Water", backref=db.backref("logs"), lazy=True)
+	device = db.relationship("Device", backref=db.backref("logs"), lazy=True)
+	gauge = db.relationship("Gauge", backref=db.backref("logs"), lazy=True)
+	processingstatus = db.relationship("ProcessingStatus", backref=db.backref("logs"), lazy=True)
+	
+	def meta_data(obj):
+		result = {
+			'logId': obj.id,
+			'submitter': obj.submitter.username,
+			'water': {
+				'id': obj.water.id,
+				'label': obj.water.name,
+			},
+			'device': {
+				'id': obj.device.id,
+				'label': obj.device.name,
+			},
+			'gauge': {
+				'id': obj.gauge.id,
+				'label': obj.gauge.name,
+			},
+			'gaugeHeight': obj.gauge_height,
+			'start': '',
+			'end': '',
+			'processingState': {
+				'id': obj.processingstatus.id,
+				'label': obj.processingstatus.label
+			}
+		}
+		if obj.start is not None:
+			result['start'] = obj.start.isoformat('T')
+		if obj.end is not None:
+			result['end'] = obj.end.isoformat('T')
+			
+		entries_count = 0
+		if obj.log_entries:
+			entries_count = len(obj.log_entries)
+		result['entriesCount'] = entries_count
+		if obj.comment:
+			result['comment'] = obj.comment
+		return result
+	
+	def log(obj):
+		result = { 'metaData': obj.meta_data() }
+		entries = []
+		if obj.log_entries:
+			for log in obj.log_entries:
+				entries.append(log.to_dict())
+		result['entries'] = entries
+		return result
+	
+	def to_geojson(obj):
+		result = {
+			'type': 'FeatureCollection',
+			'features': []
+		}
+		if obj.log_entries:
+			for log in obj.log_entries:
+				location = wkb_to_dict(log.location)
+				feature = {
+					'type': 'Feature',
+					'geometry': {
+						'type': 'Point',
+						'coordinates': [location['longitude'], location['latitude']]
+					},
+					'properties': {
+						'datetime': log.datetime.isoformat('T')
+					}
+				}
+				if log.water_depth is not None:
+					feature['properties']['waterDepth'] = log.water_depth
+				result['features'].append(feature)
+		return result
+
+class LogEntry(db.Model):
+	__tablename__ = "logentries"
+	
+	id = db.Column(db.Integer, primary_key=True, autoincrement=True)
+	log_id = db.Column(db.Integer, db.ForeignKey('logs.id'))
+	datetime = db.Column(UtcDateTime, nullable=False)
+	# POINT(Lon Lat)
+	location = db.Column(Geometry(geometry_type='POINT', srid=4326, management=True))
+	water_depth = db.Column(db.Float)
+	
+	log = db.relationship("Log", backref=db.backref("log_entries"), lazy=True)
+	
+	def to_dict(obj):
+		result = {'datetime': obj.datetime.isoformat('T') }
+		location = wkb_to_dict(obj.location)
+		result['location'] = [location['longitude'], location['latitude']]
+		if obj.water_depth:
+			result['waterDepth'] = obj.water_depth
+		return result
+
+class LogView(db.Model):
+	__table__ = create_view(
+		name='logview',
+		metadata=db.Model.metadata,
+		selectable=select(
+			[
+				Log.id,
+				Log.submitter_id,
+				Log.water_id,
+				Log.device_id,
+				Log.gauge_id,
+				Log.gauge_height,
+				Log.start,
+				Log.end,
+				ProcessingStatus.label,
+				func.Envelope(func.MakeLine(LogEntry.location)).label('envelope')
+			],
+			from_obj=(Log.__table__.join(LogEntry, Log.id == LogEntry.log_id).join(ProcessingStatus, Log.processing_state == ProcessingStatus.id)),
+			group_by=(Log.id)
+		),
+		cascade_on_drop=False
+	)
+
+class Queue(db.Model):
+	__tablename__ = "queue"
+	
+	log_id = db.Column(db.Integer, db.ForeignKey('logs.id'), primary_key=True)
+	datetime = db.Column(UtcDateTime, nullable=False, default=datetime.datetime.now(datetime.timezone.utc))
+
+	log = db.relationship("Log", backref=db.backref("queue"), lazy=True)
+
+def db_setup(force = False):
+	if not database_exists(db.engine.url) or force:
+		create_database(db.engine.url)
+		if 'sqlite' in flask.current_app.config['SQLALCHEMY_DATABASE_URI']:
+			result = db.engine.execute('SELECT count(name) FROM sqlite_master WHERE type="table" AND name="spatial_ref_sys"')
+			if result.fetchone()[0] == 1:
+				print('Spatial lite extension already loaded')
+			else:
+				print("Initiate spatial meta data for Spatialite...")
+				db.engine.execute(select([func.InitSpatialMetaData()]))
+				print("...Finished")
+		db.create_all()
+		ProcessingStatus.insert_states()
+		
+def load_spatialite(dbapi_conn, connection_record):
+	if not 'sqlite' in flask.current_app.config['SQLALCHEMY_DATABASE_URI']:
+		return
+	
+	paths = [os.path.join(sys.prefix, 'lib'), os.path.join(sys.prefix, 'lib64'), '/usr/lib', '/usr/lib64']
+	for path in paths:
+		if _load_spatialite_from_path(path, dbapi_conn, connection_record):
+			return True
+	raise FileNotFoundError('mod_spatialite not found in folders {}'.format(', '.join(paths)))
+			
+def _load_spatialite_from_path(search_path, dbapi_conn, connection_record):
+	for path in Path(search_path).rglob('mod_spatialite.so*'):
+		if os.path.exists(path):
+			if flask.current_app.config['DEBUG'] and (not 'TESTING' in flask.current_app.config or not flask.current_app.config['TESTING']):
+				print('Enabling spatial lite extension. This may take a while')
+			# From https://geoalchemy-2.readthedocs.io/en/latest/spatialite_tutorial.html
+			dbapi_conn.enable_load_extension(True)
+			dbapi_conn.load_extension(str(path.resolve()))
+			return True
+	return False
Index: src/mapservice/server_impl/demo/DbSetup.py
===================================================================
--- src/mapservice/server_impl/demo/DbSetup.py	(revision ae2ff15d6963a93c67e87e175ea31292b8bb3d28)
+++ src/mapservice/server_impl/demo/DbSetup.py	(revision ae2ff15d6963a93c67e87e175ea31292b8bb3d28)
@@ -0,0 +1,151 @@
+'''
+    Copyright (C) 2019 - 2020 EngSaS - Engineering Solutions and Services Langenbach. All rights reserved.
+
+    This program is free software: you can redistribute it and/or modify
+    it under the terms of the GNU General Public License as published by
+    the Free Software Foundation, either version 3 of the License, or
+    (at your option) any later version.
+
+    This program is distributed in the hope that it will be useful,
+    but WITHOUT ANY WARRANTY; without even the implied warranty of
+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+    GNU General Public License for more details.
+
+    You should have received a copy of the GNU General Public License
+    along with this program.  If not, see <http://www.gnu.org/licenses/>.
+'''
+
+import os
+import pytz
+import flask
+
+from ..database.Model import db, User, ApiKey, Water, OsmType, Gauge, Device, Log, Queue, ProcessingStatus, db_setup
+from ..tasks.tasks import log_process
+
+def setup():
+	db_setup()
+	
+	print("CREATING DATABASE DEMO CONTENT...")
+	with db.session.no_autoflush:
+		test_user_john = None
+		query = User.query.filter_by(username='john').all()
+		if len(query) == 1:
+			test_user_john = query[0]
+		else:
+			test_user_john = User.factory('john', 'testpass2', 'john@example.org')
+			test_user_john.activation_code = 'dac9630aec642a428cd73f4be0a03569'
+			test_user_john.license_accepted = True
+			db.session.add(test_user_john)
+			db.session.commit()
+		
+		test_user_jane = None
+		query = User.query.filter_by(username='jane').all()
+		if len(query) == 1:
+			test_user_jane = query[0]
+		else:
+			test_user_jane = User.factory('jane', 'testpass', 'jane@example.org')
+			test_user_jane.activated = True
+			test_user_jane.first_name = 'Jane'
+			test_user_jane.license_accepted = True
+			db.session.add(test_user_jane)
+			db.session.commit()
+			
+		if len(ApiKey.query.filter_by(key='DelApiKey4711').all()) < 1:
+			db.session.add(ApiKey(user=test_user_jane, key='DelApiKey4711'))
+			db.session.commit()
+		if len(ApiKey.query.filter_by(key='test_key_jane').all()) < 1:
+			db.session.add(ApiKey(user=test_user_jane, key='test_key_jane'))
+			db.session.commit()
+		
+		mississippi = None
+		query = Water.query.filter_by(name='Mississippi').all()
+		if len(query) == 1:
+			mississippi = query[0]
+		else:
+			mississippi = Water(name='Mississippi', manager=test_user_jane, osm_id=1756854, osm_type=OsmType.Relation)
+			db.session.add(mississippi)
+			db.session.commit()
+		
+		if len(Water.query.filter_by(name='Forggensee').all()) < 1:
+			forggensee = Water(name='Forggensee', manager=test_user_john, osm_id=897899, osm_type=OsmType.Relation)
+			db.session.add(forggensee)
+			db.session.commit()
+		
+		pfuhlersee = None
+		query = Water.query.filter_by(name='Pfuhler See').all()
+		if len(query) == 1:
+			pfuhlersee = query[0]
+		else:
+			pfuhlersee = Water(name='Pfuhler See', manager=test_user_jane, osm_id=225888565, osm_type=OsmType.Way)
+			db.session.add(pfuhlersee)
+			db.session.commit()
+		
+		new_orleans = None
+		query = Gauge.query.filter_by(name='New Orleans').all()
+		if len(query) == 1:
+			new_orleans = query[0]
+		else:
+			new_orleans = Gauge(name='New Orleans', manager=test_user_jane, water=mississippi, location='SRID=4326;POINT(-90.136111 29.934722)', reference_water_level_gauge_height=3)
+			db.session.add(new_orleans)
+			db.session.commit()
+			
+		pfuhlersee_gauge = None
+		query = Gauge.query.filter_by(name='Stairs at Kiosk').all()
+		if len(query) == 1:
+			pfuhlersee_gauge = query[0]
+		else:
+			pfuhlersee_gauge = Gauge(name='Stairs at Kiosk', manager=test_user_jane, water=pfuhlersee, location='SRID=4326;POINT(10.0427 48.4275)', reference_water_level_gauge_height=0.4, comment='Level zero is the level of the step where the handrail is fixed.')
+			db.session.add(pfuhlersee_gauge)
+			db.session.commit()
+		
+		gnuboat_one = None
+		query = Device.query.filter_by(name='GnuBoat 1').all()
+		if len(query) == 1:
+			gnuboat_one = query[0]
+		else:
+			gnuboat_one = Device(name='GnuBoat 1', owner=test_user_jane, sensor_depth=0.2, comment='SUP attachment')
+			db.session.add(gnuboat_one)
+			db.session.commit()
+		
+		log_file = 'sample-logs/nmea0183-2017-12-09.log'
+		sample_log = os.path.join('/usr/share/doc/gnuboat', log_file)
+		if os.path.isfile(sample_log):
+			_sample_log_add(pfuhlersee, pfuhlersee_gauge, 0, gnuboat_one, test_user_jane, sample_log)
+		else:
+			sample_log = os.path.join(os.path.dirname(__file__), '../../../../../../', log_file)
+			if os.path.isfile(sample_log):
+				_sample_log_add(pfuhlersee, pfuhlersee_gauge, 0, gnuboat_one, test_user_jane, sample_log)
+			else:
+				print('Demo log not found --> Skipping')
+		
+		print("...Finished")
+
+def _sample_log_add(water, gauge, gauge_height, device, submitter, log_file):
+	if len(Log.query.filter_by(submitter=submitter).all()) > 0:
+		return None
+	
+	log = Log(submitter=submitter, water=water, device=device, gauge=gauge, gauge_height=0, comment='Demo Log from {}'.format(log_file))
+	db.session.add(log)
+	db.session.commit()
+	
+	if not 'CELERY_BROKER_URL' in flask.current_app.config or not flask.current_app.config['CELERY_BROKER_URL']:
+		print('Do not add log, since their is no CELERY_BROKER_URL configured')
+		return log
+	
+	with open(log_file, 'r') as logfile:
+		data = logfile.read()
+  
+	processing_state = ProcessingStatus.query.filter_by(label='Queued for Parsing').all()
+	if len(processing_state) != 1:
+		raise MapserviceBadRequest(detail='Processing status Queued for Parsing not found database')
+	processing_state = processing_state[0]
+	
+	# Add Log to Queued table and change the processing state of Log
+	queue = Queue(log=log)
+	db.session.add(queue)
+	log.processingstatus = processing_state
+	db.session.commit()
+	
+	# request log parsing
+	log_process.delay(log.id, data)
+	return log
Index: src/mapservice/server_impl/security/Security.py
===================================================================
--- src/mapservice/server_impl/security/Security.py	(revision ae2ff15d6963a93c67e87e175ea31292b8bb3d28)
+++ src/mapservice/server_impl/security/Security.py	(revision ae2ff15d6963a93c67e87e175ea31292b8bb3d28)
@@ -0,0 +1,37 @@
+'''
+    Copyright (C) 2019 - 2020 EngSaS - Engineering Solutions and Services Langenbach. All rights reserved.
+
+    This program is free software: you can redistribute it and/or modify
+    it under the terms of the GNU General Public License as published by
+    the Free Software Foundation, either version 3 of the License, or
+    (at your option) any later version.
+
+    This program is distributed in the hope that it will be useful,
+    but WITHOUT ANY WARRANTY; without even the implied warranty of
+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+    GNU General Public License for more details.
+
+    You should have received a copy of the GNU General Public License
+    along with this program.  If not, see <http://www.gnu.org/licenses/>.
+'''
+from ..database.Model import ApiKey, User
+
+def auth_basic(username, password, required_scopes=None):
+	user = User.query.filter_by(username=username).all()
+	if len(user) != 1:
+		return None
+	if user[0].password_verify(password):
+		return {'sub': user[0].username}
+	return None
+
+def auth_api(apikey, required_scopes=None):
+	keys = ApiKey.query.filter_by(key=apikey).all()
+	if len(keys) != 1:
+		return None
+	
+	key_db = keys[0]
+	if apikey == key_db.key:
+		return {'sub': key_db.user.username }
+
+	# optional: raise exception for custom error response
+	return None
Index: src/mapservice/server_impl/tasks/__init__.py
===================================================================
--- src/mapservice/server_impl/tasks/__init__.py	(revision ae2ff15d6963a93c67e87e175ea31292b8bb3d28)
+++ src/mapservice/server_impl/tasks/__init__.py	(revision ae2ff15d6963a93c67e87e175ea31292b8bb3d28)
@@ -0,0 +1,17 @@
+'''
+    Copyright (C) 2019 - 2020 EngSaS - Engineering Solutions and Services Langenbach. All rights reserved.
+
+    This program is free software: you can redistribute it and/or modify
+    it under the terms of the GNU General Public License as published by
+    the Free Software Foundation, either version 3 of the License, or
+    (at your option) any later version.
+
+    This program is distributed in the hope that it will be useful,
+    but WITHOUT ANY WARRANTY; without even the implied warranty of
+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+    GNU General Public License for more details.
+
+    You should have received a copy of the GNU General Public License
+    along with this program.  If not, see <http://www.gnu.org/licenses/>.
+'''
+from .tasks import log_process
Index: src/mapservice/server_impl/tasks/tasks.py
===================================================================
--- src/mapservice/server_impl/tasks/tasks.py	(revision ae2ff15d6963a93c67e87e175ea31292b8bb3d28)
+++ src/mapservice/server_impl/tasks/tasks.py	(revision ae2ff15d6963a93c67e87e175ea31292b8bb3d28)
@@ -0,0 +1,605 @@
+'''
+    Copyright (C) 2019 - 2020 EngSaS - Engineering Solutions and Services Langenbach. All rights reserved.
+
+    This program is free software: you can redistribute it and/or modify
+    it under the terms of the GNU General Public License as published by
+    the Free Software Foundation, either version 3 of the License, or
+    (at your option) any later version.
+
+    This program is distributed in the hope that it will be useful,
+    but WITHOUT ANY WARRANTY; without even the implied warranty of
+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+    GNU General Public License for more details.
+
+    You should have received a copy of the GNU General Public License
+    along with this program.  If not, see <http://www.gnu.org/licenses/>.
+'''
+import celery
+import flask
+from flask import render_template, url_for
+import datetime
+from flask_mail import Message
+import os
+from dateutil.relativedelta import relativedelta
+import math
+import xml.etree.ElementTree as ET
+from subprocess import CalledProcessError
+import tempfile
+import shutil
+
+from osgeo import ogr
+from osgeo import osr
+from osgeo import gdal
+from osgeo import gdalconst
+import mercantile
+
+from gnuboat_common.datahandler import loghandler
+from gnuboat_common.spatial import tilegenerator
+from gnuboat_common.spatial.tilegenerator import RasterSlice, LngLatBbox, ZoomRange
+
+from .. import mail, celery as celery_app
+from ..database.Model import User, Log, LogEntry, Water, ProcessingStatus, Queue, db
+from .tileconfig import TileConfig
+
+class LogEntryCallback:
+	def __init__(self):
+		self._entries = []
+		self._start = None
+		self._end = None
+
+	def valid(self):
+		if self._start is None:
+			return False
+		if self._end is None:
+			return False
+		if len(self._entries) < 1:
+			return False
+		return True
+
+	def start(self):
+		return self._start
+	
+	def end(self):
+		return self._end
+
+	def entries(self):
+		return self._entries
+
+	def callback(self, dataset):
+		self._entries.append(dataset)
+        
+		# check / set start and end date
+		entry_datetime = dataset.datetime_object()
+		if self.start() is None or entry_datetime < self.start():
+			self._start = entry_datetime
+		if self.end() is None or self.end() < entry_datetime:
+			self._end = entry_datetime
+
+class LogsLocked(Exception):
+	pass
+
+class SliceJob(dict):
+	"""
+		Summarize all data needed to generate the tiles for a slice
+		and also to cleanup the whole generation chain afterwards
+		
+		tile_slice: The slice, which should be rastered
+		query: query used in the vrt source file
+		log_id: Id of the log, initiating the job (before slicing)
+		envelope: Enlarged envelope of the complete job (TileGenerator.LngLatBbox)
+		
+		It's derived from dict to be json serialisable
+	"""
+	def __init__(self, tile_slice, query, log_id, envelope, epsg_code):
+		super(SliceJob, self).__init__({'tile_slice': tile_slice, 'query': query, 'log_id': log_id, 'envelope': envelope, 'epsg_code': epsg_code})
+		
+	def tile_slice(self):
+		return self['tile_slice']
+	
+	def query(self):
+		return self['query']
+	
+	def log_id(self):
+		return self['log_id']
+	
+	def envelope(self):
+		return self['envelope']
+	
+	def epsg_code(self):
+		return self['epsg_code']
+	
+	def from_dict(dictionary):
+		if dictionary is None:
+			return None
+		return SliceJob(RasterSlice.from_dict(dictionary['tile_slice']), dictionary['query'], dictionary['log_id'], LngLatBbox.from_dict(dictionary['envelope']), dictionary['epsg_code'])
+
+# query to get all logentries in the enlarged envelope, younger than age_date
+query = """SELECT MakePointZ(ST_x(entries.location), ST_y(entries.location), (entries.water_depth + (logs.gauge_height - gauges.reference_water_level_gauge_height)), ST_srid(entries.location))
+FROM logentries as entries, logs, gauges
+WHERE entries.log_id=logs.id AND gauges.id=logs.gauge_id
+	AND ST_Within(entries.location, Envelope(MakeLine(PointFromText("POINT({longitude_west} {latitude_south})", {epsg_code}), PointFromText("POINT({longitude_east} {latitude_north})", {epsg_code}))))
+	AND entries.datetime > \"{age_date}\""""
+
+# query for retrieving processing state of affected logentries
+query_select_processing_state = """SELECT COUNT(id) FROM logs
+WHERE processing_state={processing_state} AND id IN (
+	SELECT log_id FROM logentries WHERE
+		ST_Within(logentries.location, Envelope(MakeLine(PointFromText("POINT({longitude_west} {latitude_south})", {epsg_code}), PointFromText("POINT({longitude_east} {latitude_north})", {epsg_code}))))
+		AND datetime {age_condition} \"{age_date}\"
+		GROUP BY log_id)"""
+	
+# query for updateting processing state of all affected logentries
+query_update_processing_state = """UPDATE logs SET processing_state={processing_state}
+WHERE id IN (
+	SELECT log_id FROM logentries WHERE
+		ST_Within(logentries.location, Envelope(MakeLine(PointFromText("POINT({longitude_west} {latitude_south})", {epsg_code}), PointFromText("POINT({longitude_east} {latitude_north})", {epsg_code}))))
+		AND datetime {age_condition} \"{age_date}\"
+		GROUP BY log_id)"""
+
+query_logs = """SELECT logentries.log_id, COUNT(logentries.id) as entries
+FROM logentries
+WHERE ST_Within(logentries.location, Envelope(MakeLine(PointFromText("POINT({longitude_west} {latitude_south})", {epsg_code}), PointFromText("POINT({longitude_east} {latitude_north})", {epsg_code}))))
+	AND logentries.datetime > \"{age_date}\" GROUP BY log_id"""
+
+@celery_app.task
+def log_process(log_id, log_content):
+	"""
+		Chain for processing a new log
+		1. Parse the log and add it to the datapase (s. log_parse)
+		2. Generate tiles out of the new and old data (s. log_slice)
+	"""
+	chain = log_parse.s(log_id, log_content) | log_slice.s()
+	chain()
+
+@celery_app.task
+def log_parse(log_id, log_content):
+	"""Background task to parse new logs"""
+	
+	log = _log_by_id(log_id)
+	_update_log_state(log_id, 'Parsing')
+	
+	queue = Queue.query.filter_by(log_id=log.id).all()
+	if len(queue) != 1:
+		_mail_error(log_id, 'No queue for log file')
+		_cleanup_error(log_id)
+		raise LookupError('Could not find queue for log {}'.format(log.id))
+	queue = queue[0]
+	queue_date = queue.datetime
+	
+	log_callback = LogEntryCallback()
+	log_handler = loghandler.LogHandler()
+	result = log_handler.gnuboat_read(log_content.splitlines(), log_callback.callback, False, False)
+	if not result.success():
+		_mail_error(log_id, result.errors())
+		_cleanup_error(log_id)
+		raise SyntaxError('Could not parse logfile {}: {}'.format(log.id, '\n'.join(result.errors())))
+	if not log_callback.valid():
+		_mail_error(log_id, 'Log has no entries')
+		_cleanup_error(log_id)
+		raise SyntaxError('Could not parse logfile {}: {}'.format(log.id, 'Log has no entries'))
+	
+	for entry in log_callback.entries():
+		if entry.water_depth() is not None:
+			location = entry.location()
+			log_entry = LogEntry(log=log, datetime=entry.datetime_object(), location='SRID=4326;POINT({} {})'.format(location.longitude, location.latitude), water_depth=entry.water_depth())
+			db.session.add(log_entry)
+	
+	# set queue for processing
+	queue.datetime = datetime.datetime.now(datetime.timezone.utc)
+	db.session.add(queue)
+	db.session.commit()
+	
+	# update state and start / end time of the log, gained from log parsing
+	log.start = log_callback.start()
+	log.end = log_callback.end()
+	_update_log_state(log_id, 'Queued for Processing')
+	
+	message = Message("Parsed log file successfully", recipients=[log.submitter.email])
+	message.html = render_template('log_parsed.html',
+		first_name=log.submitter.first_name,
+		queue_date=queue_date.isoformat('T'),
+		water_link=_water_link(log.water.id),
+		water_name=log.water.name)
+	mail.send(message)
+	
+	return log_id
+
+@celery_app.task(autoretry_for=(LogsLocked,), default_retry_delay=1800)
+def log_slice(log_id):
+	"""
+		Background task to process new logs
+		If another job is already processing the same logs, a LogsLocked Exception
+		is raised and an auto retry after 30 minutes is triggered.
+	"""
+	try:
+		tiles_config = _get_tile_config()
+	except Exception as error:
+		_update_log_state(log_id, 'Error')
+		raise error
+	try:
+		sqlalchemy_database_uri = _get_database_uri()
+	except Exception as error:
+		_update_log_state(log_id, 'Error')
+		raise error
+
+	processing_state_processing = _processing_state_get('Processing')
+	processing_state_deployed = _processing_state_get('Deployed')
+	processing_state_to_old = _processing_state_get('To Old')
+	processing_state_error = _processing_state_get('Error')
+	
+	try:
+		_tile_cache_create(tiles_config)
+	except Exception as error:
+		_update_log_state(log_id, 'Error')
+		raise error
+
+	tilegen = tilegenerator.TileGenerator(tile_sizes = tiles_config.sizes, densities = tiles_config.densities, density_base = tiles_config.densitiy_base)
+	
+	newer_than = datetime.datetime.utcnow() - relativedelta(years=tiles_config.points_age_max)
+	
+	# Extend envelope of source log to the next tile borders
+	connection = ogr.Open(sqlalchemy_database_uri, gdal.GA_ReadOnly)
+	if connection is None:
+		raise ConnectionError('Could not open database connection')
+	envelope = connection.ExecuteSQL("SELECT envelope FROM logview WHERE id={}".format(log_id))
+	if envelope is None:
+		raise LookupError('Could query envelope for log {}'.format(log_id))
+	west, east, south, north = envelope.GetExtent()
+	envelope_spatial_ref = envelope.GetSpatialRef()
+	epsg_code = envelope_spatial_ref.GetAuthorityCode(None)
+	input_epsg = "{}:{}".format(envelope_spatial_ref.GetAuthorityName(None), epsg_code)
+	envelope_enlarged = tilegen.fit_extent_to_tiles(tilegenerator.LngLatBbox(west, south, east, north), tiles_config.zoom_range)
+	
+	# Check that none of the affected logs are currently processed by another job
+	result = db.engine.execute(query_select_processing_state.format(processing_state=processing_state_processing.id, epsg_code=epsg_code,
+		longitude_west=envelope_enlarged.west(), latitude_south=envelope_enlarged.south(),
+		longitude_east=envelope_enlarged.east(), latitude_north=envelope_enlarged.north(),
+		age_condition=">", age_date=newer_than.isoformat('T'))).first()
+	if result[0] > 0:
+		# there are logs, which are currently processed by another job
+		raise LogsLocked('{} logs are currently processed by another job'.format(result[0]))
+	
+	# just for informational purpose
+	if flask.current_app.debug:
+		result = db.engine.execute(query_logs.format(processing_state=processing_state_processing.id, epsg_code=epsg_code,
+			longitude_west=envelope_enlarged.west(), latitude_south=envelope_enlarged.south(),
+			longitude_east=envelope_enlarged.east(), latitude_north=envelope_enlarged.north(),
+			age_date=newer_than.isoformat('T')))
+		count_logentries = 0
+		logs = 0
+		for rows in result:
+			logs += 1
+			count_logentries += rows[1]
+		flask.current_app.logger.info('Processing log {}, found {} datasets from {} logs in enlarged envelope younger than {}'.format(log_id, count_logentries, logs, newer_than.isoformat('T')))
+	
+	# update processing state of logentries, which will be processed
+	db.engine.execute(query_update_processing_state.format(processing_state=processing_state_processing.id, epsg_code=epsg_code,
+		longitude_west=envelope_enlarged.west(), latitude_south=envelope_enlarged.south(),
+		longitude_east=envelope_enlarged.east(), latitude_north=envelope_enlarged.north(),
+		age_condition=">", age_date=newer_than.isoformat('T')))
+	db.session.commit()
+	# update processing state of logentries, which are to old
+	db.engine.execute(query_update_processing_state.format(processing_state=processing_state_to_old.id, epsg_code=epsg_code,
+		longitude_west=envelope_enlarged.west(), latitude_south=envelope_enlarged.south(),
+		longitude_east=envelope_enlarged.east(), latitude_north=envelope_enlarged.north(),
+		age_condition="<=", age_date=newer_than.isoformat('T')))
+	db.session.commit()
+	
+	data_query = query.format(epsg_code=epsg_code,
+			longitude_west=envelope_enlarged.west(), latitude_south=envelope_enlarged.south(),
+			longitude_east=envelope_enlarged.east(), latitude_north=envelope_enlarged.north(),
+			age_date=newer_than.isoformat('T'))
+
+	# create temporary directory
+	try:
+		datasource_file = _datasource_vrt_create(data_query)
+	except Exception as error:
+		flask.current_app.logger.error('Could not open the output file for the ogr data source description: {}'.format(error))
+		db.engine.execute(query_update_processing_state.format(processing_state=processing_state_error.id, epsg_code=epsg_code,
+			longitude_west=envelope_enlarged.west(), latitude_south=envelope_enlarged.south(),
+			longitude_east=envelope_enlarged.east(), latitude_north=envelope_enlarged.north(),
+			age_condition=">", age_date=newer_than.isoformat('T')))
+		db.session.commit()
+		os.remove(datasource_file)
+		raise error
+	
+	slices = tilegen.slices(datasource_file, zoom_range = tiles_config.zoom_range, raster_file_size_max = tiles_config.raster_file_size_max)
+	slice_jobs = []
+	for tile_slice in slices:
+		slice_jobs.append(SliceJob(tile_slice, data_query, log_id, envelope_enlarged, epsg_code))
+	os.remove(datasource_file)
+	
+	if flask.current_app.debug:
+		flask.current_app.logger.info('Created {} tasks to process log {}'.format(len(slice_jobs), log_id))
+	
+	celery.chord((log_generate_tiles.s(slice_job) for slice_job in slice_jobs), log_cleanup.s()).delay()
+	return True
+
+@celery_app.task
+def log_generate_tiles(slice_job):
+	try:
+		tiles_config = _get_tile_config()
+	except Exception as error:
+		if slice_job.log_id() is not None:
+			_update_log_state(slice_job.log_id(), 'Error')
+		raise error
+	try:
+		sqlalchemy_database_uri = _get_database_uri()
+	except Exception as error:
+		if slice_job.log_id() is not None:
+			_update_log_state(slice_job.log_id(), 'Error')
+		raise error
+
+	slice_job = SliceJob.from_dict(slice_job)
+
+	if slice_job.log_id() is not None:
+		processing_state_processing = _processing_state_get('Processing')
+		processing_state_deployed = _processing_state_get('Deployed')
+		processing_state_to_old = _processing_state_get('To Old')
+		processing_state_error = _processing_state_get('Error')
+	
+	# create temporary directory
+	try:
+		datasource_file = _datasource_vrt_create(slice_job.query())
+	except Exception as error:
+		flask.current_app.logger.error('Could not open the output file for the ogr data source description: {}'.format(error))
+		os.remove(datasource_file)
+		raise error
+
+	temp_directory = tempfile.mkdtemp(prefix='gnuboat-tasks')
+	
+	tilegen = tilegenerator.TileGenerator(tile_sizes = tiles_config.sizes, densities = tiles_config.densities, density_base = tiles_config.densitiy_base)
+	try:
+		result_paths = tilegen.run(datasource_file, temp_directory, slice_job.tile_slice())
+	except CalledProcessError as e:
+		flask.current_app.logger.error('Could not generate tiles. {} exited with the error: {}'.format(e.cmd, e.returncode))
+		flask.current_app.logger.error('Output of gdal2tiles: {}'.format(e.output))
+		if slice_job.log_id() is not None:
+			db.engine.execute(query_update_processing_state.format(processing_state=processing_state_error.id, epsg_code=epsg_code,
+				longitude_west=slice_job.envelope().west(), latitude_south=slice_job.envelope().south(),
+				longitude_east=slice_job.envelope().east(), latitude_north=slice_job.envelope().north(),
+				age_condition=">", age_date=newer_than.isoformat('T')))
+			db.session.commit()
+		os.remove(datasource_file)
+		shutil.rmtree(temp_directory)
+		raise e
+	except Exception as e:
+		flask.current_app.logger.error('Could not raster the data and generate tiles. Error: {}'.format(repr(e)))
+		if slice_job.log_id() is not None:
+			db.engine.execute(query_update_processing_state.format(processing_state=processing_state_error.id, epsg_code=epsg_code,
+				longitude_west=slice_job.envelope().west(), latitude_south=slice_job.envelope().south(),
+				longitude_east=slice_job.envelope().east(), latitude_north=slice_job.envelope().north(),
+				age_condition=">", age_date=newer_than.isoformat('T')))
+			db.session.commit()
+		os.remove(datasource_file)
+		shutil.rmtree(temp_directory)
+		raise e
+	
+	for path in result_paths:
+		tilegen.move_tiles_in_place(path.path, os.path.join(tiles_config.cache_path, path.prefixes['density'], path.prefixes['tile_size']), skip_empty=tiles_config.skip_empty)
+		
+	# delete temporary directory
+	shutil.rmtree(temp_directory)
+	os.remove(datasource_file)
+	
+	return slice_job
+
+@celery_app.task
+def log_cleanup(slice_jobs):
+	log_id = None
+	envelope = None
+	epsg_code = None
+	for slice_job in slice_jobs:
+		slice_job = SliceJob.from_dict(slice_job)
+		if envelope is None:
+			envelope = slice_job.envelope()
+			epsg_code = slice_job.epsg_code()
+		if log_id is None:
+			log_id = slice_job.log_id()
+
+	processing_state_deployed = _processing_state_get('Deployed')
+	
+	try:
+		tiles_config = _get_tile_config()
+	except Exception as error:
+		_update_log_state(log_id, 'Error')
+		raise error
+	newer_than = datetime.datetime.utcnow() - relativedelta(years=tiles_config.points_age_max)
+
+	# update processing state of logentries, to deployed
+	db.engine.execute(query_update_processing_state.format(processing_state=processing_state_deployed.id, epsg_code=epsg_code,
+		longitude_west=envelope.west(), latitude_south=envelope.south(),
+		longitude_east=envelope.east(), latitude_north=envelope.north(),
+		age_condition=">", age_date=newer_than.isoformat('T')))
+	_queue_delete(log_id)
+	db.session.commit()
+	
+	log = log = _log_by_id(log_id)
+	message = Message("Parsed log file successfully", recipients=[log.submitter.email])
+	message.html = render_template('log_processed.html',
+		first_name=log.submitter.first_name,
+		water_link=_water_link(log.water.id),
+		water_name=log.water.name)
+	mail.send(message)
+	
+	return True
+
+@celery_app.task
+def log_little_zoom_slice():
+	"""
+		Generate all little zoomlevels, which are not process per log with log_process
+	"""
+	flask.current_app.logger.info('Recreating tiles for little zoomlevels')
+	try:
+		tiles_config = _get_tile_config()
+	except Exception as error:
+		_update_log_state(log_id, 'Error')
+		raise error
+	try:
+		sqlalchemy_database_uri = _get_database_uri()
+	except Exception as error:
+		raise error
+
+	try:
+		_tile_cache_create(tiles_config)
+	except Exception as error:
+		raise error
+
+	zoom_range_little_zoom = tilegenerator.ZoomRange(0, tiles_config.zoom_range.minimum())
+	
+	newer_than = datetime.datetime.utcnow() - relativedelta(years=tiles_config.points_age_max)
+	
+	## query to get all logentries in the world, younger than age_date
+	query = """SELECT MakePointZ(ST_x(entries.location), ST_y(entries.location), (entries.water_depth + (logs.gauge_height - gauges.reference_water_level_gauge_height)), ST_srid(entries.location))
+FROM logentries as entries, logs, gauges
+WHERE entries.log_id=logs.id AND gauges.id=logs.gauge_id AND entries.datetime > \"{age_date}\"""".format(age_date=newer_than.isoformat('T'))
+	
+	try:
+		datasource_file = _datasource_vrt_create(query)
+	except Exception as error:
+		flask.current_app.logger.error('Could not open the output file for the ogr data source description: {}'.format(error))
+		os.remove(datasource_file)
+		raise error
+	
+	tilegen = tilegenerator.TileGenerator(tile_sizes = tiles_config.sizes, densities = tiles_config.densities, density_base = tiles_config.densitiy_base)
+	try:
+		slices = tilegen.slices(datasource_file, zoom_range = zoom_range_little_zoom, raster_file_size_max = tiles_config.raster_file_size_max)
+	except Exception as e:
+		flask.current_app.logger.error('Slicing of little zoom job failed. Error: {}'.format(repr(e)))
+		raise e
+	
+	slice_jobs = []
+	for tile_slice in slices:
+		slice_jobs.append(SliceJob(tile_slice, query, None, None, None))
+	os.remove(datasource_file)
+	
+	if flask.current_app.debug:
+		flask.current_app.logger.info('Created {} tasks to create tiles for zoomlevels {} - {}'.format(len(slice_jobs), zoom_range_little_zoom.minimum(), zoom_range_little_zoom.maximum()))
+	# cleanup is not needed, because the processing state is not changed and also no mails are send
+	celery.group((log_generate_tiles.s(slice_job) for slice_job in slice_jobs)).delay()
+	return True
+
+def _log_by_id(log_id):
+	log = Log.query.filter_by(id=log_id).all()
+	if len(log) != 1:
+		flask.current_app.logger.warn('Could not find log {}'.format(log_id))
+		raise LookupError('Could not find log {}'.format(log_id))
+	return log[0]
+
+def _queue_delete(log_id):
+	if not Queue.query.filter_by(log_id=log_id).delete():
+		flask.current_app.logger.error('Could not delete queue for log {}'.format(log.id))
+	db.session.commit()
+
+def _processing_state_get(status):
+	processing_state = ProcessingStatus.query.filter_by(label=status).all()
+	if len(processing_state) != 1:
+		flask.current_app.logger.error('Processing status {} not found database'.format(status))
+		raise LookupError('Processing status {} not found database'.format(status))
+	return processing_state[0]
+
+def _update_log_state(log_id, status):
+	processing_state = _processing_state_get(status)
+	log = _log_by_id(log_id)
+	log.processingstatus = processing_state
+	db.session.add(log)
+	db.session.commit()
+	
+def _cleanup_error(log_id):
+	_update_log_state(log_id, 'Error')
+	_queue_delete(log_id)
+
+def _mail_error(log_id, error_message):
+	log = _log_by_id(log_id)
+	queue = Queue.query.filter_by(log_id=log.id).all()
+	if len(queue) != 1:
+		queue_date = ''
+	else:
+		queue_date = queue[0].isoformat('T')
+	
+	message = Message("Error parsing log file", recipients=[log.submitter.email])
+	message.html = render_template('log_parsing_error.html',
+		first_name=log.submitter.first_name,
+		queue_date=queue_date,
+		water_link=_water_link(log.water.id),
+		water_name=log.water.name,
+		errors=error_message)
+	mail.send(message)
+
+def _get_database_uri():
+	if not 'SQLALCHEMY_DATABASE_URI' in flask.current_app.config:
+		raise ImportError('SQLALCHEMY_DATABASE_URI not configured')
+	return flask.current_app.config['SQLALCHEMY_DATABASE_URI']
+
+def _get_tile_config():
+	if not 'TILES_CACHE_PATH' in flask.current_app.config:
+		flask.current_app.logger.error('TILES_CACHE_PATH not configured')
+		raise ImportError('TILES_CACHE_PATH not configured')
+	
+	if not 'TILES_SIZES' in flask.current_app.config:
+		flask.current_app.logger.error('TILES_SIZES not configured')
+		raise ImportError('TILES_SIZES not configured')
+	
+	if not 'TILES_DENSITIES' in flask.current_app.config:
+		flask.current_app.logger.error('TILES_DENSITIES not configured')
+		raise ImportError('TILES_DENSITIES not configured')
+	
+	if not 'TILES_DENSITY_BASEE' in flask.current_app.config:
+		flask.current_app.logger.error('TILES_DENSITY_BASEE not configured')
+		raise ImportError('TILES_DENSITY_BASEE not configured')
+	
+	if not 'TILES_POINT_AGE_MAX' in flask.current_app.config:
+		flask.current_app.logger.error('TILES_POINT_AGE_MAX not configured')
+		raise ImportError('TILES_POINT_AGE_MAX not configured')
+	
+	if not 'TILES_ZOOM_RANGE' in flask.current_app.config:
+		flask.current_app.logger.error('TILES_ZOOM_RANGE not configured')
+		raise ImportError('TILES_ZOOM_RANGE not configured')
+	
+	if not 'TILES_SKIP_EMPTY' in flask.current_app.config:
+		flask.current_app.logger.error('TILES_SKIP_EMPTY not configured')
+		raise ImportError('TILES_SKIP_EMPTY not configured')
+	
+	if not 'TILES_RASTER_FILE_SIZE_MAX' in flask.current_app.config:
+		flask.current_app.logger.error('TILES_RASTER_FILE_SIZE_MAX not configured')
+		raise ImportError('TILES_RASTER_FILE_SIZE_MAX not configured')
+		
+	return TileConfig(flask.current_app.config['TILES_CACHE_PATH'],
+		flask.current_app.config['TILES_SIZES'], flask.current_app.config['TILES_DENSITIES'],
+		flask.current_app.config['TILES_DENSITY_BASEE'], flask.current_app.config['TILES_POINT_AGE_MAX'],
+		ZoomRange.from_dict(flask.current_app.config['TILES_ZOOM_RANGE']),
+		flask.current_app.config['TILES_RASTER_FILE_SIZE_MAX'],
+		flask.current_app.config['TILES_SKIP_EMPTY'])
+
+def _tile_cache_create(tiles_config):
+	# create tile cache directory, if it does not exists
+	if not os.path.exists(tiles_config.cache_path):
+		# Path does not exist, try to create it
+		os.makedirs(tiles_config.cache_path)
+	elif not os.access(tiles_config.cache_path, os.W_OK):
+		raise PermissionError('TILES_CACHE_PATH {} is not writeable'.format(tiles_config.cache_path))
+
+def _datasource_vrt_create(query):
+	# Create Datasource for SQL database
+	output = tempfile.NamedTemporaryFile(mode='wb', prefix='gnuboat-tasks', suffix='.vrt', delete=False)
+	xml_data_source = ET.Element("OGRVRTDataSource")
+	xml_layer = ET.SubElement(xml_data_source, "OGRVRTLayer", {"name": "tmp_corrected_joined_points"})
+	xml_source = ET.SubElement(xml_layer, 'SrcDataSource')
+	xml_source.text = _get_database_uri()
+	xml_source_sql = ET.SubElement(xml_layer, "SrcSQL")
+	xml_source_sql.text = query
+	xml_geometry_type = ET.SubElement(xml_layer, "GeometryType")
+	xml_geometry_type.text = "wkbPoint"
+	xml_tree = ET.ElementTree(xml_data_source)
+	xml_tree.write(output, encoding="UTF-8", xml_declaration=False)
+	output.close()
+	return os.path.join(tempfile.gettempdir(), output.name)
+
+def _water_link(log_id):
+	webclient_url = ''
+	if not 'MAPSERVICE_WEBCLIENT' in flask.current_app.config:
+		flask.current_app.logger.error('MAPSERVICE_WEBCLIENT not configured')
+	else:
+		webclient_url = flask.current_app.config['MAPSERVICE_WEBCLIENT']
+	return '{}/water/{}'.format(webclient_url, log_id)
+
Index: src/mapservice/server_impl/tasks/tileconfig.py
===================================================================
--- src/mapservice/server_impl/tasks/tileconfig.py	(revision ae2ff15d6963a93c67e87e175ea31292b8bb3d28)
+++ src/mapservice/server_impl/tasks/tileconfig.py	(revision ae2ff15d6963a93c67e87e175ea31292b8bb3d28)
@@ -0,0 +1,46 @@
+# -*- coding: utf-8 -*-
+'''
+    Copyright (C) 2020 EngSaS - Engineering Solutions and Services Langenbach. All rights reserved.
+
+    This program is free software: you can redistribute it and/or modify
+    it under the terms of the GNU General Public License as published by
+    the Free Software Foundation, either version 3 of the License, or
+    (at your option) any later version.
+
+    This program is distributed in the hope that it will be useful,
+    but WITHOUT ANY WARRANTY; without even the implied warranty of
+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+    GNU General Public License for more details.
+
+    You should have received a copy of the GNU General Public License
+    along with this program.  If not, see <http://www.gnu.org/licenses/>.
+'''
+
+try:
+	from dataclasses import dataclass
+	
+	@dataclass
+	class TileConfig:
+		cache_path: str
+		sizes: Array[int]
+		densities: Array[int]
+		densitiy_base: int
+		points_age_max: int
+		zoom_range: Array[int]
+		raster_file_size_max: [int]
+		skip_empty: bool
+		
+except ImportError:
+	class TileConfig:
+		"""
+			Workaround for @dataclass, until python 3.7 is available in main distros
+		"""
+		def __init__(self, cache_path, sizes, densities, densitiy_base, points_age_max, zoom_range, raster_file_size_max, skip_empty):
+			self.cache_path = cache_path
+			self.sizes = sizes
+			self.densities = densities
+			self.densitiy_base = densitiy_base
+			self.points_age_max = points_age_max
+			self.zoom_range = zoom_range
+			self.raster_file_size_max = raster_file_size_max
+			self.skip_empty = skip_empty
