- Timestamp:
- May 4, 2020, 8:34:21 PM (7 years ago)
- Branches:
- debian/bullseye, master
- Children:
- 82eff76
- Parents:
- 97efbbf
- Location:
- src/gnuboat
- Files:
-
- 6 added
- 8 edited
-
common/webservice/HttpErrors.py (modified) (3 diffs)
-
deviceservice_impl/Config.py (modified) (2 diffs)
-
deviceservice_impl/ValidatorWorkaround.py (added)
-
deviceservice_impl/__init__.py (modified) (5 diffs)
-
deviceservice_impl/controllers/DeviceController.py (modified) (6 diffs)
-
deviceservice_impl/controllers/DeviceLogsController.py (modified) (2 diffs)
-
deviceservice_impl/controllers/DeviceMapsController.py (modified) (1 diff)
-
deviceservice_impl/controllers/MapserviceController.py (modified) (1 diff)
-
deviceservice_impl/demo/DemoLog.py (added)
-
deviceservice_impl/demo/DemoMaps.py (added)
-
deviceservice_impl/demo/DemoRrd.py (added)
-
deviceservice_impl/demo/DeviceserviceEntry.py (added)
-
deviceservice_impl/demo/__init__.py (added)
-
deviceservice_impl/tests/__init__.py (modified) (6 diffs)
Legend:
- Unmodified
- Added
- Removed
-
src/gnuboat/common/webservice/HttpErrors.py
r97efbbf r9b8dd22 17 17 18 18 from werkzeug.exceptions import ( 19 BadRequest, Unauthorized, NotFound, InternalServerError 19 BadRequest, Unauthorized, NotFound, InternalServerError, 20 RequestEntityTooLarge, GatewayTimeout, BadGateway 20 21 ) 21 22 from connexion.exceptions import ProblemException … … 79 80 80 81 82 class GnuboatPayloadToLarge(ProblemException, RequestEntityTooLarge): 83 def __init__( 84 self, 85 type="paylod-to-large", 86 title=None, 87 detail=None, 88 instance=None, 89 **kwargs 90 ): 91 super(GnuboatPayloadToLarge, self).__init__( 92 status=413, 93 title="Payload To Large Error", 94 detail=detail, 95 type=type, 96 instance=instance, 97 **kwargs 98 ) 99 100 81 101 class GnuboatInternalServerError(ProblemException, InternalServerError): 82 102 def __init__( … … 96 116 **kwargs 97 117 ) 118 119 120 class GnuboatGatewayTimeout(ProblemException, GatewayTimeout): 121 def __init__( 122 self, 123 type="gateway-timeout", 124 title=None, 125 detail=None, 126 instance=None, 127 **kwargs 128 ): 129 super(GnuboatGatewayTimeout, self).__init__( 130 status=504, 131 title="Gateway Timeout", 132 detail=detail, 133 type=type, 134 instance=instance, 135 **kwargs 136 ) 137 138 139 class GnuboatBadGateway(ProblemException, BadGateway): 140 def __init__( 141 self, 142 type="bad-gateway", 143 title=None, 144 detail=None, 145 instance=None, 146 **kwargs 147 ): 148 super(GnuboatBadGateway, self).__init__( 149 status=502, 150 title="Bad Gateway", 151 detail=detail, 152 type=type, 153 instance=instance, 154 **kwargs 155 ) -
src/gnuboat/deviceservice_impl/Config.py
r97efbbf r9b8dd22 20 20 DEBUG = False 21 21 TESTING = False 22 MAX_CONTENT_LENGTH = 500 * 1024 * 1024 22 23 23 24 … … 25 26 # array used for shutdown command with subprocess 26 27 SHUTDOWN_COMMAND = ['sudo', 'shutdown', '-h', 'now'] 28 DEVICE_DATABASE = '/var/lib/gnuboat/gnuboat.rrd' 29 LOG_DIRECTORY = '/var/log/gnuboat' 27 30 28 31 29 32 class DevelopmentConfig(Config): 30 33 DEBUG = True 31 MAPSERVICE = 'http://localhost:8080' 32 MAPSERVICE_API_KEY = 'test_key' 34 MAPSERVICE = 'http://localhost:8080/mapservice/v1/' 35 MAPSERVICE_API_KEY = 'test_key_jane' 36 MAPSERVICE_DEVICE = 1 37 # Timeout to connect to mapservice in seconds 38 MAPSERVICE_TIMEOUT = 30 33 39 DEVICE_DATABASE = '/tmp/gnuboat-device.rrd' 34 SHUTDOWN_COMMAND = ['echo', '1'] 40 DEMO = True 41 SHUTDOWN_COMMAND = ['echo', 'Shutdown Requested'] 42 LOG_DIRECTORY = '/tmp/gnuboat-device/logs' 43 MAP_DIRECTORY = '/tmp/gnuboat-device/maps' 44 35 45 36 46 class TestingConfig(DevelopmentConfig): -
src/gnuboat/deviceservice_impl/__init__.py
r97efbbf r9b8dd22 18 18 import connexion 19 19 import flask 20 from flask import redirect 20 21 from flask_cors import CORS 21 22 from werkzeug.utils import import_string 22 23 import os 24 from pathlib import Path 23 25 26 from gnuboat.deviceservice_impl.ValidatorWorkaround import ValidatorWorkaround 24 27 from gnuboat.deviceservice import encoder 25 28 26 from pathlib import Path27 29 28 30 def load_config_object(config_name): … … 37 39 elif os.path.isfile(config_file): 38 40 from gnuboat.common.webservice import Config as configure 39 config_object = configure.config_from_file(config_file, 40 load_config_object('')) 41 config_object = configure.config_from_file( 42 config_file, load_config_object('') 43 ) 41 44 else: 42 45 config_object = load_config_object('Production') … … 46 49 CORS(application) 47 50 48 #@app.route("/") 49 #def index(): 50 #return render_template("index.html") 51 52 @app.route("/") 53 def index(): 54 return redirect("/client/index.html", code=302) 55 51 56 52 57 def setup_app(app_name, config, template_folder=None): … … 57 62 validate_responses=True, 58 63 strict_validation=True, 64 validator_map={'response': ValidatorWorkaround} 59 65 ) 60 66 application.config.from_object(config) 61 67 62 68 application.static_url_path = '/client' 63 69 # Remove the old rule from Map._rules. … … 65 71 application.url_map._rules.remove(rule) # There is probably only one. 66 72 67 # Remove the old rule from Map._rules_by_endpoint. In this case we can just 73 # Remove the old rule from Map._rules_by_endpoint. In this case we can just 68 74 # start fresh. 69 application.url_map._rules_by_endpoint['static'] = [] 75 application.url_map._rules_by_endpoint['static'] = [] 70 76 71 77 # Add the updated rule. 72 application.add_url_rule(f'{application.static_url_path}/<path:filename>', 73 endpoint='static', 74 view_func=application.send_static_file) 78 application.add_url_rule( 79 f'{application.static_url_path}/<path:filename>', 80 endpoint='static', 81 view_func=application.send_static_file 82 ) 83 84 if 'DEMO' in application.config and application.config['DEMO']: 85 from gnuboat.deviceservice_impl.demo import create_demo 86 create_demo(application) -
src/gnuboat/deviceservice_impl/controllers/DeviceController.py
r97efbbf r9b8dd22 20 20 import rrdtool 21 21 import os 22 import datetime 22 23 23 24 import gnuboat.common.device.rrdschema as rrdschema 24 25 from gnuboat.common.webservice.HttpErrors import ( 25 GnuboatBadRequest, GnuboatUnauthorized,26 26 GnuboatNotFound, GnuboatInternalServerError 27 27 ) … … 33 33 result = rrdtool.lastupdate(rrdfile) 34 34 except Exception as e: 35 raise GnuboatInternalServerError(detail='Could not query rrd database. Error: {}'.format(repr(e))) 35 raise GnuboatInternalServerError( 36 detail='Could not query rrd database. Error: {}'.format(repr(e))) 36 37 if 'ds' not in result: 37 38 raise GnuboatNotFound(detail='No databset found') 39 if (datetime.datetime.now() - result['date']).total_seconds() > 10: 40 raise GnuboatNotFound(detail='Last entry is older than 10s') 38 41 return { 39 42 'speedThroughWater': result['ds']['speedthroughwater'], … … 49 52 def track_get(): 50 53 rrdfile = _rrdfile_get() 51 54 52 55 track = {} 53 56 for archive in rrdschema.archives: 54 result = _rrd_fetch(rrdfile, archive.resolution, '{}s'.format(archive.duration)) 57 result = _rrd_fetch(rrdfile, archive.resolution, 58 '{}s'.format(archive.duration)) 55 59 56 60 start, end, interval = result[0] … … 64 68 watertemperature = keys.index('watertemperature') 65 69 gpsfix = keys.index('gpsfix') 66 70 67 71 i = 0 68 72 for dataset in result[2]: … … 79 83 } 80 84 i += 1 81 85 82 86 return track 83 87 … … 111 115 def _rrd_fetch(rrdfile, interval, period): 112 116 try: 113 return rrdtool.fetch(rrdfile, 'AVERAGE', '--resolution', str(interval), '--start', '-{}'.format(period), '--align-start') 117 return rrdtool.fetch( 118 rrdfile, 'AVERAGE', '--resolution', str(interval), 119 '--start', '-{}'.format(period), '--align-start' 120 ) 114 121 except Exception as e: 115 raise GnuboatInternalServerError(detail='Could not fetch from rrd database. Error: {}'.format(repr(e))) 116 122 raise GnuboatInternalServerError( 123 detail=('Could not fetch from rrd database. ' 124 'Error: {}').format(repr(e))) 125 117 126 118 127 def gpsfix_to_enum(gpsfix): 119 128 if gpsfix == 2: 120 return "2D" ;129 return "2D" 121 130 elif gpsfix == 3: 122 return "3D" ;131 return "3D" 123 132 else: 124 return "-" ;133 return "-" -
src/gnuboat/deviceservice_impl/controllers/DeviceLogsController.py
r97efbbf r9b8dd22 16 16 ''' 17 17 import connexion 18 import flask 19 from werkzeug.utils import secure_filename 20 from pathlib import Path 21 import io 22 import zipfile 23 import os 24 from datetime import datetime, timezone 18 25 19 26 from gnuboat.common.webservice.HttpErrors import ( … … 21 28 GnuboatNotFound, GnuboatInternalServerError 22 29 ) 30 from gnuboat.common.datahandler import loghandler 31 32 33 class LogEntryCallback: 34 def __init__(self): 35 self._entries = [] 36 self._start = None 37 self._end = None 38 39 def valid(self): 40 if self._start is None: 41 return False 42 if self._end is None: 43 return False 44 if len(self._entries) < 1: 45 return False 46 return True 47 48 def start(self): 49 return self._start 50 51 def end(self): 52 return self._end 53 54 def entries(self): 55 return self._entries 56 57 def callback(self, dataset): 58 self._entries.append(dataset) 59 60 # check / set start and end date 61 entry_datetime = dataset.datetime_object() 62 if self.start() is None or entry_datetime < self.start(): 63 self._start = entry_datetime 64 if self.end() is None or self.end() < entry_datetime: 65 self._end = entry_datetime 23 66 24 67 25 68 def logfiles_get(): 26 raise GnuboatInternalServerError 69 logdir = logdirectory_get() 70 files = sorted(logdir.glob('*.log')) 71 result = [] 72 for path in files: 73 result.append(path.name) 74 return result 27 75 28 76 29 def logs_get( ):30 raise GnuboatInternalServerError77 def logs_get(name): 78 logdir = logdirectory_get() 31 79 32 def logs_track_get(): 33 raise GnuboatInternalServerError 80 logfiles = name.split(',') 81 if len(logfiles) < 1: 82 raise GnuboatNotFound(detail='Logfile {} not found'.format(name)) 83 elif len(logfiles) == 1: 84 logfile = logdir.joinpath(secure_filename(name)) 85 if not logfile.is_file(): 86 raise GnuboatNotFound( 87 detail='Logfile {} does not exists'.format(name)) 88 response = flask.send_file( 89 logfile.resolve(), 90 mimetype='text/plain', 91 as_attachment=True, 92 attachment_filename=name 93 ) 94 response.direct_passthrough = False 95 return response 96 else: 97 archive_name = 'gnuboat-logs-{}'.format( 98 datetime.utcnow().strftime('%Y-%m-%d')) 99 zip_buffer = io.BytesIO() 100 with zipfile.ZipFile( 101 zip_buffer, mode='w', compression=zipfile.ZIP_DEFLATED 102 ) as zip_file: 103 for logfile in logfiles: 104 logfile = secure_filename(logfile) 105 zip_file.write( 106 logdir.joinpath(logfile).resolve(), 107 os.path.join(archive_name, logfile) 108 ) 109 zip_buffer.seek(0) 110 response = flask.send_file( 111 zip_buffer, 112 mimetype='application/zip', 113 as_attachment=True, 114 attachment_filename='{}.zip'.format(archive_name) 115 ) 116 response.direct_passthrough = False 117 return response 34 118 119 120 def logs_track_get(name): 121 logfile = logdirectory_get().joinpath(secure_filename(name)) 122 if not logfile.is_file(): 123 raise GnuboatNotFound(detail='Logfile {} not found'.format(name)) 124 125 log_callback = LogEntryCallback() 126 log_handler = loghandler.LogHandler() 127 result = log_handler.gnuboat_read_file( 128 logfile, log_callback.callback, False, False 129 ) 130 if not result.success(): 131 raise GnuboatInternalServerError( 132 detail='Could not parse logfile {}'.format(name)) 133 134 result = {} 135 for entry in log_callback.entries(): 136 location = entry.location() 137 result[ 138 entry.datetime_object().replace(tzinfo=timezone.utc).timestamp() 139 ] = { 140 'speedOverGround': entry.speed_over_ground(), 141 'courseOverGround': entry.course_over_ground(), 142 'waterDepth': entry.water_depth(), 143 'waterTemperature': entry.water_temperature(), 144 'position': [location.longitude, location.latitude], 145 'gpsFix': '3D' if entry.gps_status() == 'A' else '-' 146 } 147 return result 148 149 150 def logdirectory_get(): 151 if 'LOG_DIRECTORY' not in flask.current_app.config: 152 raise GnuboatInternalServerError( 153 detail='LOG_DIRECTORY not configured or not accessible' 154 ) 155 return Path(flask.current_app.config['LOG_DIRECTORY']) -
src/gnuboat/deviceservice_impl/controllers/DeviceMapsController.py
r97efbbf r9b8dd22 16 16 ''' 17 17 import connexion 18 import flask 19 from werkzeug.utils import secure_filename 20 from pathlib import Path 21 import sqlite3 22 from hashlib import shake_256 23 import io 24 import tempfile 25 import os 26 import base64 18 27 19 28 from gnuboat.common.webservice.HttpErrors import ( 20 Gnuboat BadRequest, GnuboatUnauthorized,21 Gnuboat NotFound, GnuboatInternalServerError29 GnuboatNotFound, GnuboatInternalServerError, 30 GnuboatBadRequest 22 31 ) 23 32 24 33 34 def map_name_to_file(name): 35 map_dir = _get_map_directory() 36 return map_dir.joinpath('{}.mbtiles'.format(_map_name_to_hash(name))) 37 38 25 39 def maps_get(): 26 raise GnuboatInternalServerError 40 result = [] 41 map_dir = _get_map_directory() 42 for map_db in map_dir.glob('*.mbtiles'): 43 try: 44 metadata = {'tilejson': '2.0.0'} 45 connection = sqlite3.connect(str(map_db.resolve())) 46 except Exception as e: 47 flask.current_app.logger.error( 48 'Failed to open map {}. Error: {}'.format( 49 map_db.resolve(), repr(e))) 50 continue 51 52 name = _get_metadata(connection, 'name', str(map_db)) 53 if name is None: 54 connection.close() 55 flask.current_app.logger.error( 56 ('Name not found in map {} ' 57 'metadata --> Skipping').format(map_db.resolve())) 58 continue 59 metadata['name'] = name 60 url = flask.url_for( 61 ('/deviceservice/v1.gnuboat_deviceservice_' 62 'controllers_device_maps_controller_maps_tile_get'), 63 mapname=_map_name_to_hash(name), zoom=99, x_tile="98", 64 y_tile="97", _external=True 65 ) 66 url = url.replace('/99/', '/{z}/').replace( 67 '/98/', '/{x}/').replace('/97.', '/{y}.') 68 metadata['tiles'] = [url] 69 _add_metadata(connection, 'description', str(map_db), metadata) 70 _add_metadata(connection, 'version', str(map_db), metadata) 71 _add_metadata(connection, 'attribution', str(map_db), metadata) 72 _add_metadata(connection, 'template', str(map_db), metadata) 73 _add_metadata(connection, 'legend', str(map_db), metadata) 74 _add_metadata(connection, 'schema', str(map_db), metadata) 75 _add_metadata(connection, 'minzoom', str(map_db), metadata) 76 _add_metadata(connection, 'maxzoom', str(map_db), metadata) 77 _add_metadata(connection, 'bounds', str(map_db), metadata) 78 _add_metadata(connection, 'center', str(map_db), metadata) 79 _add_metadata(connection, 'data', str(map_db), metadata) 80 _add_metadata(connection, 'grids', str(map_db), metadata) 81 82 if 'minzoom' not in metadata or 'maxzoom' not in metadata: 83 cursor = connection.cursor() 84 try: 85 cursor.execute( 86 ('SELECT MIN(zoom_level), MAX(zoom_level) ' 87 'FROM tiles') 88 ) 89 zoomlevels = cursor.fetchall() 90 if 'minzoom' not in metadata: 91 metadata['minzoom'] = zoomlevels[0][0] 92 if 'maxzoom' not in metadata: 93 metadata['maxzoom'] = zoomlevels[0][1] 94 except Expcetion as e: 95 flask.current_app.logger.error( 96 ('Could not get min and max ' 97 'zoomlevel from map {}').format(str(map_db))) 98 result.append(metadata) 99 100 connection.close() 101 return result 102 103 104 def maps_tile_get(mapname, zoom, x_tile, y_tile): 105 map_dir = _get_map_directory() 106 map_db = map_dir.joinpath('{}.mbtiles'.format(secure_filename(mapname))) 107 if not map_db.is_file(): 108 raise GnuboatNotFound(detail='Map {} does not exist'.format(mapname)) 109 110 try: 111 connection = sqlite3.connect(str(map_db.resolve())) 112 except Exception as e: 113 raise GnuboatInternalServerError( 114 detail=('Could not open map {} ' 115 'to serve tiles').format(mapname)) 116 cursor = connection.cursor() 117 try: 118 cursor.execute( 119 ('SELECT tile_data FROM tiles WHERE ' 120 'zoom_level=? AND tile_column=? and tile_row=?'), 121 (zoom, x_tile, y_tile)) 122 except: 123 connection.close() 124 raise GnuboatInternalServerError( 125 detail=('Could not get tile ' 126 '{z}/{x}/{y} of map {} to serve tiles').format( 127 zoom, x_tile, y_tile, mapname)) 128 results = cursor.fetchall() 129 if len(results) != 1: 130 raise GnuboatNotFound(detail='Could not find tile {}/{}/{}/{}'.format( 131 mapname, zoom, x_tile, y_tile)) 132 connection.close() 133 134 response = flask.send_file( 135 io.BytesIO(results[0][0]), 136 mimetype='image/png', 137 as_attachment=True, 138 attachment_filename='{}.png'.format(y_tile) 139 ) 140 response.direct_passthrough = False 141 return response 142 143 144 def maps_upload(body=None): 145 if body is None: 146 raise GnuboatBadRequest(detail='No map given') 147 148 database_content = base64.b64decode(body) 149 file_handle, path = tempfile.mkstemp(suffix='.mbtiles') 150 with open(file_handle, 'wb') as f: 151 f.write(database_content) 152 153 try: 154 connection = sqlite3.connect(path) 155 name = _get_metadata(connection, 'name', path) 156 connection.close() 157 except Exception as e: 158 raise GnuboatInternalServerError( 159 detail='Could not create temporary database: {}'.format(repr(e)) 160 ) 161 finally: 162 os.remove(path) 163 164 if name is None: 165 raise GnuboatBadRequest( 166 detail=('No name for map in mbtile-file set. ' 167 'Please add a name to the mbtiles metadata table ' 168 '(it\'s a SQLite database)')) 169 170 map_path = _get_map_directory().joinpath( 171 '{}.mbtiles'.format(_map_name_to_hash(name))) 172 if map_path.is_file(): 173 raise GnuboatBadRequest(detail='Map with this name already exists') 174 with open(map_path, 'wb') as file_handle: 175 file_handle.write(database_content) 176 return maps_get() 177 178 179 def _map_name_to_hash(name): 180 return shake_256(name.encode('utf-8')).hexdigest(32) 181 182 183 def _add_metadata(connection, name, db, result_dict): 184 value = _get_metadata(connection, name, db) 185 if value is not None: 186 if name == 'minzoom' or name == 'maxzoom': 187 value = int(value) 188 if name == 'bounds' or name == 'center': 189 value = [float(i) for i in value.split(',')] 190 if name == 'data' or name == 'grids': 191 flask.current_app.logger.error( 192 ('Please report a bug to implement ' 193 'map metadata extraction of type {} with example value {}') 194 .format(name, value)) 195 result_dict[name] = value 196 197 198 def _get_metadata(connection, name, db): 199 cursor = connection.cursor() 200 try: 201 cursor.execute('SELECT value FROM metadata WHERE name=?', (name,)) 202 except Exception as e: 203 flask.current_app.logger.info( 204 '{} not found in map {} metadata'.format(name, db)) 205 return None 206 results = cursor.fetchall() 207 if len(results) != 1: 208 flask.current_app.logger.info( 209 '{} not found in map {} metadata'.format(name, db)) 210 return None 211 return results[0][0] 212 213 214 def _get_map_directory(): 215 if 'MAP_DIRECTORY' not in flask.current_app.config: 216 raise GnuboatInternalServerError( 217 detail='MAP_DIRECTORY not configured or not accessible' 218 ) 219 return Path(flask.current_app.config['MAP_DIRECTORY']) -
src/gnuboat/deviceservice_impl/controllers/MapserviceController.py
r97efbbf r9b8dd22 16 16 ''' 17 17 import connexion 18 import flask 19 from werkzeug.utils import secure_filename 20 import socket 21 from urllib.parse import urlparse 22 from urllib3.exceptions import RequestError 23 from enum import Enum 24 import datetime 25 import json 26 import os 18 27 19 28 from gnuboat.common.webservice.HttpErrors import ( 20 GnuboatBadRequest, GnuboatUnauthorized, 21 GnuboatNotFound, GnuboatInternalServerError 22 ) 23 24 25 def devices_get(): 26 raise GnuboatInternalServerError 27 28 29 def log_create(): 30 raise GnuboatInternalServerError 29 GnuboatBadRequest, GnuboatUnauthorized, 30 GnuboatNotFound, GnuboatInternalServerError, 31 GnuboatPayloadToLarge, GnuboatGatewayTimeout, 32 GnuboatBadGateway 33 ) 34 from gnuboat.deviceservice_impl.controllers.DeviceLogsController import ( 35 logdirectory_get 36 ) 37 from gnuboat.mapservice_client.configuration import ( 38 Configuration as MsConfiguration 39 ) 40 from gnuboat.mapservice_client.api_client import ApiClient as MsApiClient 41 from gnuboat.mapservice_client.api.waters_api import WatersApi as MsWatersApi 42 from gnuboat.mapservice_client.api.devices_api import ( 43 DevicesApi as MsDevicesApi 44 ) 45 from gnuboat.mapservice_client.api.logs_api import LogsApi as MsLogsApi 46 from gnuboat.mapservice_client.models.log_creation import ( 47 LogCreation as MsLogCreation 48 ) 49 from gnuboat.mapservice_client.exceptions import ApiException as MsApiException 50 51 52 class MapserviceStatus(Enum): 53 NO_API_KEY = 0 54 NO_DEVICE = 1 55 DEVICE_NOT_FOUND = 2 56 NO_CONNECTION = 4 57 OK = 7 31 58 32 59 33 60 def mapservice_status(): 34 raise GnuboatInternalServerError 35 36 def waters_get(): 37 raise GnuboatInternalServerError 61 mapservice_status = _mapservice_status() 62 flask.mapservice_status = mapservice_status 63 64 if mapservice_status == MapserviceStatus.NO_CONNECTION: 65 return mapservice_status.name, 504 66 return mapservice_status.name 67 68 69 def waters_get( 70 name=None, 71 order_by=None, 72 offset=None, 73 limit=None): 74 if _mapservice_status() != MapserviceStatus.OK: 75 raise GnuboatBadRequest( 76 detail='Mapservice not available. See remote status for help') 77 78 configuration = _mapservice_configuration() 79 with MsApiClient(configuration) as api_client: 80 try: 81 waters = MsWatersApi(api_client).waters_get( 82 name=name, order_by=order_by, offset=offset, limit=limit 83 ) 84 except Exception as e: 85 _handle_api_exception(e) 86 87 results = [] 88 for water in waters: 89 gauges = [] 90 if water.gauges is not None: 91 for gauge in water.gauges: 92 gauges.append({ 93 'gaugeId': gauge.gauge_id, 94 'location': gauge.location, 95 'name': gauge.name, 96 'referenceWaterLevelGaugeHeight': 97 gauge.reference_water_level_gauge_height, 98 }) 99 results.append({ 100 'waterId': water.water_id, 101 'name': water.name, 102 'gauges': gauges, 103 }) 104 return results 105 106 107 def log_create(log_creation=None): 108 if _mapservice_status() != MapserviceStatus.OK: 109 raise GnuboatBadRequest( 110 detail='Mapservice not available. See remote status for help') 111 112 log_dir = logdirectory_get() 113 logfile = secure_filename(log_creation.logfile) 114 logfile_path = log_dir.joinpath(logfile) 115 if not logfile_path.is_file(): 116 raise GnuboatNotFound(detail='Logfile {} not found'.format(logfile)) 117 118 # building log_creation for the mapservice 119 log_creation_mapservice = MsLogCreation( 120 water=log_creation.water, 121 device=_mapservice_device_get().device_id, 122 gauge=log_creation.gauge, 123 gauge_height=log_creation.gauge_height, 124 comment=log_creation.comment, 125 ) 126 127 configuration = _mapservice_configuration() 128 with MsApiClient(configuration) as api_client: 129 # create log 130 try: 131 log_metadata = MsLogsApi(api_client).logs_log_create( 132 log_creation=log_creation_mapservice 133 ) 134 except Exception as e: 135 _handle_api_exception(e) 136 137 # read log file content from local storage 138 with open(logfile_path, 'rb') as logfilehandle: 139 file_content = logfilehandle.read() 140 # upload log content to newly created log from above 141 try: 142 log_metadata = MsLogsApi(api_client).logs_log_upload( 143 log_id=log_metadata.log_id, body=file_content 144 ) 145 except Exception as e: 146 _handle_api_exception(e) 147 148 if log_creation.delete: 149 os.remove(logfile_path) 150 151 152 def _mapservice_url(): 153 if 'MAPSERVICE' in flask.current_app.config: 154 url = flask.current_app.config['MAPSERVICE'] 155 if url.endswith('/'): 156 return url[:-1] 157 return url 158 configuration = MsConfiguration() 159 if configuration.host: 160 return configuration.host 161 raise GnuboatInternalServerError( 162 detail=('No host for mapservice configured ' 163 '(See MAPSERVICE config option)')) 164 165 166 def _mapservice_api_key(): 167 if 'MAPSERVICE_API_KEY' not in flask.current_app.config: 168 raise GnuboatInternalServerError( 169 detail='MAPSERVICE_API_KEY not configured' 170 ) 171 return flask.current_app.config['MAPSERVICE_API_KEY'] 172 173 174 def _mapservice_device(): 175 if 'MAPSERVICE_DEVICE' not in flask.current_app.config: 176 raise GnuboatInternalServerError( 177 detail='MAPSERVICE_DEVICE not configured' 178 ) 179 return flask.current_app.config['MAPSERVICE_DEVICE'] 180 181 182 def _mapservice_device_get(): 183 if hasattr(flask, 'mapservice_device') and flask.mapservice_device: 184 return flask.mapservice_device 185 186 device_id = _mapservice_device() 187 configuration = _mapservice_configuration() 188 with MsApiClient(configuration) as api_client: 189 try: 190 device = MsDevicesApi(api_client).devices_get_by_id(device_id) 191 except Exception as e: 192 flask.mapservice_device = False 193 body = json.loads(e.body) 194 if 'detail' in body: 195 flask.current_app.logger.error( 196 'Failed to get device: {}'.format(body['detail'])) 197 return False 198 199 flask.mapservice_device = device 200 return device 201 202 203 def _mapservice_configuration(): 204 configuration = MsConfiguration() 205 configuration.host = _mapservice_url() 206 configuration.api_key['X-API-KEY'] = _mapservice_api_key() 207 return configuration 208 209 210 def _mapservice_status(): 211 try: 212 mapservice_api_key = _mapservice_api_key() 213 except: 214 return MapserviceStatus.NO_API_KEY 215 216 try: 217 mapservice_device = _mapservice_device() 218 except: 219 return MapserviceStatus.NO_DEVICE 220 221 if hasattr(flask, 'mapservice_device') and not flask.mapservice_device: 222 return MapserviceStatus.DEVICE_NOT_FOUND 223 224 # prevent to many status polls 225 if hasattr(flask, 'mapservice_check') and \ 226 hasattr(flask, 'mapservice_status'): 227 if (datetime.datetime.now() - flask.mapservice_check).total_seconds() \ 228 < 60: 229 return flask.mapservice_status 230 231 mapservice_url = _mapservice_url() 232 233 fragments = urlparse(mapservice_url) 234 if fragments.hostname is None: 235 raise GnuboatInternalServerError( 236 detail='No hostname for mapservice set') 237 if fragments.port is None: 238 if fragments.scheme == 'http': 239 fragments.port = 80 240 elif fragments.scheme == 'https': 241 fragments.port = 443 242 else: 243 raise GnuboatInternalServerError( 244 detail='Could not determine port for mapservice') 245 246 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 247 s.settimeout(5) 248 try: 249 s.connect((fragments.hostname, int(fragments.port))) 250 s.shutdown(socket.SHUT_RDWR) 251 except: 252 flask.mapservice_status = MapserviceStatus.NO_CONNECTION 253 return MapserviceStatus.NO_CONNECTION 254 finally: 255 flask.mapservice_check = datetime.datetime.now() 256 s.close() 257 258 if hasattr(flask, 'mapservice_device') and flask.mapservice_device: 259 flask.mapservice_status = MapserviceStatus.OK 260 return MapserviceStatus.OK 261 262 device = _mapservice_device_get() 263 if not device: 264 flask.mapservice_status = MapserviceStatus.DEVICE_NOT_FOUND 265 return MapserviceStatus.DEVICE_NOT_FOUND 266 flask.mapservice_status = MapserviceStatus.OK 267 return MapserviceStatus.OK 268 269 270 def _handle_api_exception(exception): 271 if isinstance(exception, MsApiException): 272 if exception.body is None: 273 raise GnuboatInternalServerError( 274 detail='Unkown error occured: {}'.format(repr(exception))) 275 276 response_body = json.loads(exception.body) 277 if 'status' not in response_body: 278 raise GnuboatInternalServerError( 279 detail='Unkown error occured: {}'.format(repr(exception))) 280 status = response_body['status'] 281 if 'detail' in response_body: 282 detail = response_body['detail'] 283 else: 284 detail = '' 285 elif isinstance(exception, RequestError): 286 status = '502' 287 detail = 'Could not connect to server {}:{}/{}'.format( 288 exception.pool.host, exception.pool.port, exception.url 289 ) 290 else: 291 status = 502 292 detail = 'An unexpected error occured: {}'.format(repr(exception)) 293 294 if status == 400: 295 raise GnuboatBadRequest(detail=detail) 296 if status == 401: 297 raise GnuboatUnauthorized(detail=detail) 298 if status == 404: 299 raise GnuboatNotFound(detail=detail) 300 if status == 413: 301 raise GnuboatPayloadToLarge(detail=detail) 302 if status == 500: 303 raise GnuboatInternalServerError(detail=detail) 304 if status == 504: 305 raise GnuboatGatewayTimeout(detail=detail) -
src/gnuboat/deviceservice_impl/tests/__init__.py
r97efbbf r9b8dd22 18 18 import logging 19 19 import flask 20 from flask import request_started, request 20 21 import connexion 21 22 from flask_cors import CORS … … 25 26 import time 26 27 import random 27 28 import gnuboat.common.device.rrdschema as rrdschema 29 28 from pathlib import Path 29 import datetime 30 import shutil 31 import subprocess 32 import socket 33 34 from gnuboat.common.device import rrdhandler as rrdhandler 35 import gnuboat.common.datahandler.loghandler as loghandler 36 import gnuboat.common.datahandler.logdataset as logdataset 37 38 from gnuboat.deviceservice_impl.controllers.DeviceMapsController import ( 39 _map_name_to_hash 40 ) 30 41 from gnuboat.deviceservice.encoder import JSONEncoder 42 43 logperiod = 2 44 duration = 12 * 60 * 60 45 timestamp = int(time.time()) 46 start_time = timestamp - duration - logperiod 47 latitude_min = 10.0 48 latitude_max = 10.9 49 longitude_min = 42.0 50 longitude_max = 42.9 31 51 32 52 33 53 def create_app(testcase): 34 54 logging.getLogger('connexion.operation').setLevel('ERROR') 35 app = connexion.App(__name__, 36 specification_dir='../../deviceservice/openapi/') 55 app = connexion.App( 56 __name__, 57 specification_dir='../../deviceservice/openapi/' 58 ) 37 59 application = app.app 38 60 CORS(application) 39 61 application.json_encoder = JSONEncoder 40 app.add_api('openapi.yaml', 62 app.add_api( 63 'openapi.yaml', 41 64 validate_responses=True, 42 65 strict_validation=True, … … 46 69 'gnuboat.deviceservice_impl.Config.TestingConfig') 47 70 application.app_context().push() 48 71 49 72 _create_rrdfile(testcase, application) 50 73 _create_logs(testcase, application) 74 _create_maps(testcase, application) 75 76 _mapservice_start(testcase) 77 51 78 return application 52 79 … … 58 85 def tearDown(testcase): 59 86 os.remove(testcase.rrdfile) 87 shutil.rmtree(testcase.logdir) 88 shutil.rmtree(testcase.mapdir) 89 if testcase.mapservice_process is not None: 90 testcase.mapservice_process.terminate() 91 (stdout_data, stderr_data) = \ 92 testcase.mapservice_process.communicate(timeout=10) 93 if stdout_data: 94 stdout_data = stdout_data.decode('utf-8') 95 print('MAPSERVICE STDOUT: {}'.format(stdout_data)) 96 if stderr_data: 97 stderr_data = stderr_data.decode('utf-8') 98 print('MAPSERVICE STDERR: {}'.format(stderr_data)) 60 99 61 100 62 101 def _create_rrdfile(testcase, application): 63 rrd_file_handle, testcase.rrdfile = tempfile.mkstemp(suffix='.rrd', prefix='gnuboat-tests') 102 rrd_file_handle, testcase.rrdfile = tempfile.mkstemp( 103 suffix='.rrd', prefix='gnuboat-tests' 104 ) 64 105 application.config['DEVICE_DATABASE'] = testcase.rrdfile 65 66 logperiod = 2 67 duration = 24 * 60 * 60 68 timestamp = int(time.time()) 69 start_time = timestamp - duration - logperiod 70 latitude_min = 10.0 71 latitude_max = 10.9 72 longitude_min = 42.0 73 longitude_max = 42.9 74 75 _rrd_create_database(testcase.rrdfile, logperiod, str(start_time)) 106 # we remove it here, because rrdcreate creates only databases, 107 # if the file does not exists 108 os.remove(testcase.rrdfile) 109 110 rrdhandler.rrd_create_database( 111 testcase.rrdfile, logperiod, str(start_time) 112 ) 76 113 for current_time in range(timestamp - duration, timestamp, logperiod): 77 114 latitude = random.uniform(latitude_min, latitude_max) … … 84 121 gpsFix = 3 85 122 # update rrd database for the webservice 86 _rrd_update(123 rrdhandler.rrd_update( 87 124 testcase.rrdfile, '{}:{}:{}:{}:{}:{}:{}:{}:{}'.format( 88 125 current_time, latitude, longitude, speedThroughWater, … … 91 128 ) 92 129 ) 93 94 def _rrd_create_database(database_file, logperiod, start_time='N'): 95 rrd_data_sources = [ 96 'DS:latitude:GAUGE:15:-90:90', 'DS:longitude:GAUGE:15:-180:180', 97 'DS:speedthroughwater:GAUGE:15:U:U', 'DS:speedoverground:GAUGE:15:U:U', 98 'DS:courseoverground:GAUGE:15:U:U', 'DS:waterdepth:GAUGE:15:0:10000', 99 'DS:watertemperature:GAUGE:15:-10:50', 'DS:gpsfix:GAUGE:15:-999:3' 100 ] 101 102 step = logperiod 103 archives = rrdschema.archives 104 rrd_archives = [] 105 for i in range(0, len(archives)): 106 rrd_archives += [ 107 'RRA:AVERAGE:0.5:{:d}:{:d}'.format( 108 _steps(archives[i].resolution, step), 109 _rows( 110 archives[i].duration, archives[i].resolution, step 111 ) 112 ) 113 ] 114 115 rrdtool.create( 116 database_file, "--start", start_time, "--step", str(step), 117 rrd_data_sources, rrd_archives 118 ) 119 120 121 def _rrd_update(rrdfile, value_string): 122 rrdtool.update(rrdfile, value_string) 123 124 def _rows(duration, resolution, step): 125 return int( 126 round(float(duration) / _steps(resolution, float(step)) / float(step)) 127 ) 128 129 130 def _steps(resolution, step): 131 return int(round(float(resolution) / float(step))) 130 131 @application.before_request 132 def add_measurement(): 133 if 'DEVICE_DATABASE' not in flask.current_app.config: 134 return 135 result = rrdtool.lastupdate( 136 flask.current_app.config['DEVICE_DATABASE']) 137 if ((datetime.datetime.now() - result['date']).total_seconds() < 138 logperiod): 139 # last update is not longer ago than logperiod. Skip new update 140 return 141 142 latitude = random.uniform(latitude_min, latitude_max) 143 longitude = random.uniform(longitude_min, longitude_max) 144 speedThroughWater = random.randint(0, 10) 145 speedOverGround = random.randint(-2, 15) 146 courseOverGround = random.randint(0, 360) 147 waterDepth = random.randint(0, 20) 148 waterTemperature = random.randint(2, 25) 149 gpsFix = 3 150 151 rrdhandler.rrd_update( 152 flask.current_app.config['DEVICE_DATABASE'], 153 '{}:{}:{}:{}:{}:{}:{}:{}:{}'.format( 154 int(time.time()), latitude, longitude, speedThroughWater, 155 speedOverGround, courseOverGround, waterDepth, 156 waterTemperature, gpsFix) 157 ) 158 159 160 def _create_logs(testcase, application): 161 logdir = Path(tempfile.mkdtemp(prefix='gnuboat-tests-logs')) 162 testcase.logdir = logdir 163 application.config['LOG_DIRECTORY'] = str(logdir.resolve()) 164 165 duration = 24 * 60 * 60 166 end_time = datetime.datetime.now() 167 start_time = end_time - datetime.timedelta(seconds=duration) 168 169 log = loghandler.LogHandler(logdir.resolve()) 170 current_time = start_time 171 while (current_time <= end_time): 172 latitude = random.uniform(latitude_min, latitude_max) 173 longitude = random.uniform(longitude_min, longitude_max) 174 speedThroughWater = random.randint(0, 6) 175 speedOverGround = random.randint(-3, 8) 176 courseOverGround = random.randint(0, 360) 177 waterDepth = random.randint(0, 20) 178 waterTemperature = random.randint(2, 25) 179 180 dataset = logdataset.LogDataset( 181 datetime=current_time, 182 gps_status='A', 183 latitude=latitude, 184 latitude_direction='N', 185 longitude=longitude, 186 longitude_direction='E', 187 speed_over_ground=speedOverGround, 188 course_over_ground=courseOverGround, 189 water_depth=waterDepth, 190 water_temperature=waterTemperature 191 ) 192 log.gnuboat_write(3, current_time, dataset, True, False, False) 193 current_time += datetime.timedelta(seconds=logperiod) 194 195 log.gnuboat_close() 196 for logfile in logdir.glob('*.log'): 197 shutil.copy(logfile, logdir.joinpath('test-1.log')) 198 shutil.copy(logfile, logdir.joinpath('test-2.log')) 199 break 200 201 202 def _create_maps(testcase, application): 203 mapdir = Path(tempfile.mkdtemp(prefix='gnuboat-tests-maps')) 204 testcase.mapdir = mapdir 205 application.config['MAP_DIRECTORY'] = str(mapdir.resolve()) 206 207 shutil.copy( 208 os.path.join( 209 os.path.dirname(__file__), 210 '../../samples/maps/000-forggensee.mbtiles' 211 ), 212 mapdir.joinpath('{}.mbtiles'.format(_map_name_to_hash('Forggensee'))) 213 ) 214 215 216 def _mapservice_start(testcase): 217 if 'TestMapserviceController' not in testcase.id(): 218 testcase.mapservice_process = None 219 else: 220 mapservice_env = dict(os.environ) 221 mapservice_env['FLASK_ENV'] = 'Testing' 222 testcase.mapservice_process = subprocess.Popen( 223 [ 224 'gnuboat-dev-mapservice', '--bind=localhost:8080', 225 '--log-level=debug' 226 ], 227 env=mapservice_env, shell=True, 228 stdout=subprocess.PIPE, stderr=subprocess.PIPE 229 ) 230 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 231 s.settimeout(10) 232 if s.connect_ex(('localhost', int(8090))) == 0: 233 s.shutdown(socket.SHUT_RDWR)
Note:
See TracChangeset
for help on using the changeset viewer.
