Changeset 9b8dd22


Ignore:
Timestamp:
May 4, 2020, 8:34:21 PM (7 years ago)
Author:
Joachim Langenbach <joachim.langenbach@…>
Branches:
debian/bullseye, master
Children:
82eff76
Parents:
97efbbf
Message:

Added deviceservice implementation

Location:
src/gnuboat
Files:
6 added
8 edited

Legend:

Unmodified
Added
Removed
  • src/gnuboat/common/webservice/HttpErrors.py

    r97efbbf r9b8dd22  
    1717
    1818from werkzeug.exceptions import (
    19     BadRequest, Unauthorized, NotFound, InternalServerError
     19    BadRequest, Unauthorized, NotFound, InternalServerError,
     20    RequestEntityTooLarge, GatewayTimeout, BadGateway
    2021)
    2122from connexion.exceptions import ProblemException
    … …  
    7980
    8081
     82class 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
    81101class GnuboatInternalServerError(ProblemException, InternalServerError):
    82102    def __init__(
    … …  
    96116            **kwargs
    97117        )
     118
     119
     120class 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
     139class 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  
    2020    DEBUG = False
    2121    TESTING = False
     22    MAX_CONTENT_LENGTH = 500 * 1024 * 1024
    2223
    2324
    … …  
    2526    # array used for shutdown command with subprocess
    2627    SHUTDOWN_COMMAND = ['sudo', 'shutdown', '-h', 'now']
     28    DEVICE_DATABASE = '/var/lib/gnuboat/gnuboat.rrd'
     29    LOG_DIRECTORY = '/var/log/gnuboat'
    2730
    2831
    2932class DevelopmentConfig(Config):
    3033    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
    3339    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
    3545
    3646class TestingConfig(DevelopmentConfig):
  • src/gnuboat/deviceservice_impl/__init__.py

    r97efbbf r9b8dd22  
    1818import connexion
    1919import flask
     20from flask import redirect
    2021from flask_cors import CORS
    2122from werkzeug.utils import import_string
    2223import os
     24from pathlib import Path
    2325
     26from gnuboat.deviceservice_impl.ValidatorWorkaround import ValidatorWorkaround
    2427from gnuboat.deviceservice import encoder
    2528
    26 from pathlib import Path
    2729
    2830def load_config_object(config_name):
    … …  
    3739elif os.path.isfile(config_file):
    3840    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    )
    4144else:
    4245    config_object = load_config_object('Production')
    … …  
    4649CORS(application)
    4750
    48 #@app.route("/")
    49 #def index():
    50    #return render_template("index.html")
     51
     52@app.route("/")
     53def index():
     54    return redirect("/client/index.html", code=302)
     55
    5156
    5257def setup_app(app_name, config, template_folder=None):
    … …  
    5762        validate_responses=True,
    5863        strict_validation=True,
     64        validator_map={'response': ValidatorWorkaround}
    5965    )
    6066    application.config.from_object(config)
    61    
     67
    6268    application.static_url_path = '/client'
    6369    # Remove the old rule from Map._rules.
    … …  
    6571        application.url_map._rules.remove(rule)  # There is probably only one.
    6672
    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
    6874    # start fresh.
    69     application.url_map._rules_by_endpoint['static'] = [] 
     75    application.url_map._rules_by_endpoint['static'] = []
    7076
    7177    # 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  
    2020import rrdtool
    2121import os
     22import datetime
    2223
    2324import gnuboat.common.device.rrdschema as rrdschema
    2425from gnuboat.common.webservice.HttpErrors import (
    25     GnuboatBadRequest, GnuboatUnauthorized,
    2626    GnuboatNotFound, GnuboatInternalServerError
    2727)
    … …  
    3333        result = rrdtool.lastupdate(rrdfile)
    3434    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)))
    3637    if 'ds' not in result:
    3738        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')
    3841    return {
    3942        'speedThroughWater': result['ds']['speedthroughwater'],
    … …  
    4952def track_get():
    5053    rrdfile = _rrdfile_get()
    51    
     54
    5255    track = {}
    5356    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))
    5559
    5660        start, end, interval = result[0]
    … …  
    6468        watertemperature = keys.index('watertemperature')
    6569        gpsfix = keys.index('gpsfix')
    66        
     70
    6771        i = 0
    6872        for dataset in result[2]:
    … …  
    7983                }
    8084            i += 1
    81    
     85
    8286    return track
    8387
    … …  
    111115def _rrd_fetch(rrdfile, interval, period):
    112116    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        )
    114121    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
    117126
    118127def gpsfix_to_enum(gpsfix):
    119128    if gpsfix == 2:
    120         return "2D";
     129        return "2D"
    121130    elif gpsfix == 3:
    122         return "3D";
     131        return "3D"
    123132    else:
    124         return "-";
     133        return "-"
  • src/gnuboat/deviceservice_impl/controllers/DeviceLogsController.py

    r97efbbf r9b8dd22  
    1616'''
    1717import connexion
     18import flask
     19from werkzeug.utils import secure_filename
     20from pathlib import Path
     21import io
     22import zipfile
     23import os
     24from datetime import datetime, timezone
    1825
    1926from gnuboat.common.webservice.HttpErrors import (
    … …  
    2128    GnuboatNotFound, GnuboatInternalServerError
    2229)
     30from gnuboat.common.datahandler import loghandler
     31
     32
     33class 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
    2366
    2467
    2568def 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
    2775
    2876
    29 def logs_get():
    30     raise GnuboatInternalServerError
     77def logs_get(name):
     78    logdir = logdirectory_get()
    3179
    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
    34118
     119
     120def 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
     150def 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  
    1616'''
    1717import connexion
     18import flask
     19from werkzeug.utils import secure_filename
     20from pathlib import Path
     21import sqlite3
     22from hashlib import shake_256
     23import io
     24import tempfile
     25import os
     26import base64
    1827
    1928from gnuboat.common.webservice.HttpErrors import (
    20     GnuboatBadRequest, GnuboatUnauthorized,
    21     GnuboatNotFound, GnuboatInternalServerError
     29    GnuboatNotFound, GnuboatInternalServerError,
     30    GnuboatBadRequest
    2231)
    2332
    2433
     34def 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
    2539def 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
     104def 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
     144def 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
     179def _map_name_to_hash(name):
     180    return shake_256(name.encode('utf-8')).hexdigest(32)
     181
     182
     183def _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
     198def _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
     214def _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  
    1616'''
    1717import connexion
     18import flask
     19from werkzeug.utils import secure_filename
     20import socket
     21from urllib.parse import urlparse
     22from urllib3.exceptions import RequestError
     23from enum import Enum
     24import datetime
     25import json
     26import os
    1827
    1928from 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)
     34from gnuboat.deviceservice_impl.controllers.DeviceLogsController import (
     35    logdirectory_get
     36)
     37from gnuboat.mapservice_client.configuration import (
     38    Configuration as MsConfiguration
     39)
     40from gnuboat.mapservice_client.api_client import ApiClient as MsApiClient
     41from gnuboat.mapservice_client.api.waters_api import WatersApi as MsWatersApi
     42from gnuboat.mapservice_client.api.devices_api import (
     43    DevicesApi as MsDevicesApi
     44)
     45from gnuboat.mapservice_client.api.logs_api import LogsApi as MsLogsApi
     46from gnuboat.mapservice_client.models.log_creation import (
     47    LogCreation as MsLogCreation
     48)
     49from gnuboat.mapservice_client.exceptions import ApiException as MsApiException
     50
     51
     52class MapserviceStatus(Enum):
     53    NO_API_KEY = 0
     54    NO_DEVICE = 1
     55    DEVICE_NOT_FOUND = 2
     56    NO_CONNECTION = 4
     57    OK = 7
    3158
    3259
    3360def 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
     69def 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
     107def 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
     152def _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
     166def _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
     174def _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
     182def _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
     203def _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
     210def _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
     270def _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  
    1818import logging
    1919import flask
     20from flask import request_started, request
    2021import connexion
    2122from flask_cors import CORS
    … …  
    2526import time
    2627import random
    27 
    28 import gnuboat.common.device.rrdschema as rrdschema
    29 
     28from pathlib import Path
     29import datetime
     30import shutil
     31import subprocess
     32import socket
     33
     34from gnuboat.common.device import rrdhandler as rrdhandler
     35import gnuboat.common.datahandler.loghandler as loghandler
     36import gnuboat.common.datahandler.logdataset as logdataset
     37
     38from gnuboat.deviceservice_impl.controllers.DeviceMapsController import (
     39    _map_name_to_hash
     40)
    3041from gnuboat.deviceservice.encoder import JSONEncoder
     42
     43logperiod = 2
     44duration = 12 * 60 * 60
     45timestamp = int(time.time())
     46start_time = timestamp - duration - logperiod
     47latitude_min = 10.0
     48latitude_max = 10.9
     49longitude_min = 42.0
     50longitude_max = 42.9
    3151
    3252
    3353def create_app(testcase):
    3454    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    )
    3759    application = app.app
    3860    CORS(application)
    3961    application.json_encoder = JSONEncoder
    40     app.add_api('openapi.yaml',
     62    app.add_api(
     63        'openapi.yaml',
    4164        validate_responses=True,
    4265        strict_validation=True,
    … …  
    4669        'gnuboat.deviceservice_impl.Config.TestingConfig')
    4770    application.app_context().push()
    48    
     71
    4972    _create_rrdfile(testcase, application)
    50    
     73    _create_logs(testcase, application)
     74    _create_maps(testcase, application)
     75
     76    _mapservice_start(testcase)
     77
    5178    return application
    5279
    … …  
    5885def tearDown(testcase):
    5986    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))
    6099
    61100
    62101def _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    )
    64105    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    )
    76113    for current_time in range(timestamp - duration, timestamp, logperiod):
    77114        latitude = random.uniform(latitude_min, latitude_max)
    … …  
    84121        gpsFix = 3
    85122        # update rrd database for the webservice
    86         _rrd_update(
     123        rrdhandler.rrd_update(
    87124            testcase.rrdfile, '{}:{}:{}:{}:{}:{}:{}:{}:{}'.format(
    88125                current_time, latitude, longitude, speedThroughWater,
    … …  
    91128            )
    92129        )
    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
     160def _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
     202def _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
     216def _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.