Changeset a88607b


Ignore:
Timestamp:
Mar 1, 2020, 12:25:19 PM (7 years ago)
Author:
Joachim Langenbach <joachim.langenbach@…>
Branches:
debian/bullseye, master
Children:
f601952
Parents:
bd0cb38
Message:

Celery background process for log parsing is now working

Location:
src
Files:
5 added
14 edited
1 moved

Legend:

Unmodified
Added
Removed
  • src/mapservice-webclient/src/app/logs/logs.component.html

    rbd0cb38 ra88607b  
    2929            <img *ngSwitchCase="2" class="pure-img state-icon" src='/resources/log-queued.svg' title='Status: {{log.processingState.label}}'>
    3030            <img *ngSwitchCase="3" class="pure-img state-icon" src='/resources/processing.svg' title='Status: {{log.processingState.label}}'>
    31             <img *ngSwitchCase="4" class="pure-img state-icon" src='/resources/log-processed.svg' title='Status: {{log.processingState.label}}'>
    32             <img *ngSwitchCase="4" class="pure-img state-icon" src='/resources/log-excluded.svg' title='Status: {{log.processingState.label}}'>
     31            <img *ngSwitchCase="4" class="pure-img state-icon" src='/resources/log-queued.svg' title='Status: {{log.processingState.label}}'>
     32            <img *ngSwitchCase="5" class="pure-img state-icon" src='/resources/processing.svg' title='Status: {{log.processingState.label}}'>
     33            <img *ngSwitchCase="6" class="pure-img state-icon" src='/resources/log-deployed.svg' title='Status: {{log.processingState.label}}'>
     34            <img *ngSwitchCase="7" class="pure-img state-icon" src='/resources/log-excluded.svg' title='Status: {{log.processingState.label}}'>
    3335            <img *ngSwitchDefault class="pure-img state-icon" src='/resources/log-undefined.svg' title='Status: {{log.processingState.label}}'>
    3436          </td>
  • src/mapservice-webclient/src/app/mygnuboat/logadd.component.ts

    rbd0cb38 ra88607b  
    1616  id: number,
    1717  originalObject: {},
    18 }
    19 
    20 interface LogCreated {
    21   metaData: LogMetaData,
    22   logGeoJson: LogGeoJson,
    2318}
    2419
    … …  
    3328  currentUser: User = undefined;
    3429  @Output() cancel = new EventEmitter();
    35   @Output() logCreated = new EventEmitter<LogCreated>();
    3630  @ViewChild('logFileInput') logFileInput;
    3731
    … …  
    218212      this.logsService.logsLogCreate(logCreation).pipe(first()).subscribe(result => {
    219213        this.logsService.logsLogUpload(result.logId, new Blob([fileReader.result], {type: 'text/plain'})).pipe(first()).subscribe(resultUpload => {
    220             var logCreated = {} as LogCreated;
    221             logCreated.metaData = result;
    222             logCreated.logGeoJson = resultUpload;
    223             this.logCreated.emit(logCreated);
    224214            this.isUploading = false;
    225215            this.logForm.reset();
  • src/mapservice-webclient/webpack.config.js

    rbd0cb38 ra88607b  
    5050          { from: '../common/icon/processing.svg', to: 'resources' },
    5151          { from: '../common/icon/log-excluded.svg', to: 'resources' },
    52           { from: '../common/icon/log-processed.svg', to: 'resources' },
     52          { from: '../common/icon/log-deployed.svg', to: 'resources' },
    5353          { from: '../common/icon/log-queued.svg', to: 'resources' },
    5454          { from: '../common/icon/log-undefined.svg', to: 'resources' }
  • src/mapservice/codegen/code_generator

    rbd0cb38 ra88607b  
    44SRC_GEN="${DIR}/../src-gen"
    55TARGET="${SRC_GEN}/openapi_server/"
     6CELERY_WORKER_SCRIPT="${SRC_GEN}/celery_worker"
    67
    78echo "Cleaning directory"
    … …  
    1112mkdir -p "${TARGET}"
    1213cd "${TARGET}"
    13 if [ ! -L server_impl ]; then
    14         ln -s ../../src/server_impl/
    15 fi
     14#if [ ! -L server_impl ]; then
     15#       ln -s ../../src/server_impl/
     16#fi
     17mkdir -p server_impl
     18cp -a ../../src/server_impl/* server_impl/
     19#mv server_impl/CeleryWorker.py ./
    1620
    1721#echo "Copying static files"
    … …  
    2731mkdir -p templates
    2832cp -a ../../templates/* templates/
     33ln -s ../templates server_impl/templates
    2934
    3035echo "Generating backend and client API code"
    … …  
    3742
    3843
     44echo "#!/bin/bash" > "${CELERY_WORKER_SCRIPT}"
     45echo 'export FLASK_ENV="development"' >> "${CELERY_WORKER_SCRIPT}"
     46echo "celery -A openapi_server.server_impl.CeleryWorker:celery worker -l info -E" >> "${CELERY_WORKER_SCRIPT}"
     47chmod +x "${CELERY_WORKER_SCRIPT}"
     48
    3949cd src-gen/
    4050tox > /tmp/openapi_tox.log
     51echo "###########################"
     52echo "#"
     53echo "# Do not forget to start the celery worker with"
     54echo "#   1. start RabbitMQ broker with"
     55echo "#       sudo service rabbitmq-server start"
     56echo "#   2. start celery worker with"
     57echo "#       cd ${SRC_GEN} && ${CELERY_WORKER_SCRIPT}"
     58echo "#"
     59echo "###########################"
     60export FLASK_ENV="development"
    4161python3 -m openapi_server
  • src/mapservice/codegen/templates/__init__.mustache

    rbd0cb38 ra88607b  
    1 import connexion
    2 from flask_cors import CORS
    3 from flask_mail import Mail
     1#import connexion
     2#from flask_cors import CORS
     3#from flask_mail import Mail
     4#from celery import Celery
    45
    5 app = connexion.App(__name__, specification_dir='./openapi/')
    6 application = app.app
    7 CORS(application)
    8 mail = Mail()
     6#app = connexion.App(__name__, specification_dir='./openapi/')
     7#application = app.app
     8#CORS(application)
     9#mail = Mail()
     10#celery = Celery(application.name)
  • src/mapservice/codegen/templates/__main__.mustache

    rbd0cb38 ra88607b  
    66{{/supportPython2}}
    77
    8 import flask
    9 from sqlalchemy import event
     8from {{packageName}}.server_impl import app, application, mail, celery, setup_app
    109
    11 from {{packageName}} import encoder, app, application, mail
    12 from {{packageName}}.server_impl.database.Model import db, User, ApiKey, db_setup, db_test_setup
    13 from {{packageName}}.server_impl.ValidatorWorkaround import ValidatorWorkaround
    14 
    15 @application.before_first_request
    16 def create_database():
    17         @event.listens_for(db.engine, "connect")
    18         def load_spatialite(dbapi_conn, connection_record):
    19                 if 'sqlite' in flask.current_app.config['SQLALCHEMY_DATABASE_URI']:
    20                         # From https://geoalchemy-2.readthedocs.io/en/latest/spatialite_tutorial.html
    21                         dbapi_conn.enable_load_extension(True)
    22                         dbapi_conn.load_extension('/usr/local/lib64/mod_spatialite')
    23 
    24         if flask.current_app.config['CREATE_TEST_DATABASE'] == True:
    25                 db_test_setup()
    26         else:
    27                 db_setup()
    28 
    29 @application.route("/mapservice/")
    30 def index():
    31         return render_template('index.html')
    32        
    3310def main():
    34         application.json_encoder = encoder.JSONEncoder
    35         app.add_api('openapi.yaml', arguments={'title': '{{appName}}'}, validate_responses=True, strict_validation=True, validator_map={'response': ValidatorWorkaround})
    36         application.config.from_object('{{packageName}}.server_impl.Config.DevelopmentConfig')
    37 
    38         db.init_app(application)
    39         mail.init_app(application)
    40 
    41         app.run(port={{serverPort}})
     11        setup_app('{{appName}}', 'DevelopmentConfig')
     12        app.run(host=application.config.get("HOST", "localhost"), port=application.config.get("PORT", {{serverPort}}))
    4213
    4314if __name__ == '__main__':
  • src/mapservice/codegen/templates/requirements.mustache

    rbd0cb38 ra88607b  
    1313sqlalchemy_utc
    1414sqlalchemy-utils
     15celery
    1516gnuboat_common
  • src/mapservice/openapi.yaml

    rbd0cb38 ra88607b  
    617617          description: Logs uploaded
    618618          content:
    619             application/geo+json:
    620               schema:
    621                 $ref: '#/components/schemas/LogGeoJson'
     619            application/json:
     620              schema:
     621                $ref: '#/components/schemas/LogMetaData'
    622622              examples:
    623623                Log:
    624                   $ref: '#/components/examples/LogGeoJson'
    625             application/json:
    626               schema:
    627                 $ref: '#/components/schemas/Log'
    628               examples:
    629                 Log:
    630                   $ref: '#/components/examples/Log'
     624                  $ref: '#/components/examples/LogMetaData'
    631625        '400':
    632626          $ref: '#/components/responses/BadRequest'
  • src/mapservice/src/server_impl/Config.py

    rbd0cb38 ra88607b  
    2525        MAIL_DEFAULT_SENDER = 'GNUBoat Mapservice <gnuboat@engsas.de>'
    2626        MAPSERVICE_WEBCLIENT = '/'
     27        CELERY_BROKER_URL = 'pyamqp://guest@localhost//'
     28        CELERY_IMPORTS = ("openapi_server.server_impl.tasks")
    2729
    2830class ProductionConfig(Config):
    … …  
    3335        CREATE_TEST_DATABASE = True
    3436        MAPSERVICE_WEBCLIENT = 'http://localhost:8081'
     37        #SERVER_NAME = 'gnuboat-mapservice:8080'
     38        HOST = 'localhost'
     39        SERVER_NAME = 'localhost:8080'
    3540
    3641class TestingConfig(Config):
  • src/mapservice/src/server_impl/__init__.py

    rbd0cb38 ra88607b  
     1'''
     2    Copyright (C) 2019 - 2020 EngSaS - Engineering Solutions and Services Langenbach. All rights reserved.
     3
     4    This program is free software: you can redistribute it and/or modify
     5    it under the terms of the GNU General Public License as published by
     6    the Free Software Foundation, either version 3 of the License, or
     7    (at your option) any later version.
     8
     9    This program is distributed in the hope that it will be useful,
     10    but WITHOUT ANY WARRANTY; without even the implied warranty of
     11    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
     12    GNU General Public License for more details.
     13
     14    You should have received a copy of the GNU General Public License
     15    along with this program.  If not, see <http://www.gnu.org/licenses/>.
     16'''
     17
     18import connexion
     19import flask
     20from flask_cors import CORS
     21from flask_mail import Mail
     22from sqlalchemy import event
     23from celery import Celery
     24from werkzeug.utils import import_string
     25import os
     26
     27from .. import encoder
     28from .database.Model import db, User, ApiKey, db_setup, db_test_setup
     29from .ValidatorWorkaround import ValidatorWorkaround
     30
     31# determine requested configuration
     32if 'FLASK_ENV' in os.environ and os.environ['FLASK_ENV']:
     33        config_name = os.environ['FLASK_ENV'].title()
     34else:
     35        config_name = 'Production'
     36config_name = 'openapi_server.server_impl.Config.{}Config'.format(config_name)
     37config = import_string(config_name)
     38
     39app = connexion.App(__name__, specification_dir='../openapi/')
     40application = app.app
     41CORS(application)
     42mail = Mail()
     43celery = Celery(__name__, broker=config.CELERY_BROKER_URL)
     44
     45@application.before_first_request
     46def create_database():
     47        @event.listens_for(db.engine, "connect")
     48        def load_spatialite(dbapi_conn, connection_record):
     49                if 'sqlite' in flask.current_app.config['SQLALCHEMY_DATABASE_URI']:
     50                        # From https://geoalchemy-2.readthedocs.io/en/latest/spatialite_tutorial.html
     51                        dbapi_conn.enable_load_extension(True)
     52                        dbapi_conn.load_extension('/usr/local/lib64/mod_spatialite')
     53
     54        if flask.current_app.config['CREATE_TEST_DATABASE'] == True:
     55                db_test_setup()
     56        else:
     57                db_setup()
     58
     59@application.route("/mapservice/")
     60def index():
     61        return render_template('index.html')
     62
     63def setup_app(app_name, config_name="Config"):
     64        application.json_encoder = encoder.JSONEncoder
     65        app.add_api('openapi.yaml', arguments={'title': app_name}, validate_responses=True, strict_validation=True, validator_map={'response': ValidatorWorkaround})
     66        application.config.from_object(config)
     67
     68        db.init_app(application)
     69        mail.init_app(application)
     70        celery.config_from_object(config)
  • src/mapservice/src/server_impl/controllers/LogsController.py

    rbd0cb38 ra88607b  
    1717import connexion
    1818
    19 from gnuboat_common.datahandler import loghandler
    20 
    2119from ..database.Model import User, Log, LogEntry, Water, Device, Gauge, ProcessingStatus, Queue, db
    2220from ..HttpErrors import MapserviceBadRequest, MapserviceUnauthorized, MapserviceNotFound
    23 
    24 class LogEntryCallback:
    25         def __init__(self):
    26                 self._entries = []
    27                 self._start = None
    28                 self._end = None
    29 
    30         def valid(self):
    31                 if self._start is None:
    32                         return False
    33                 if self._end is None:
    34                         return False
    35                 if len(self._entries) < 1:
    36                         return False
    37                 return True
    38 
    39         def start(self):
    40                 return self._start
    41        
    42         def end(self):
    43                 return self._end
    44 
    45         def entries(self):
    46                 return self._entries
    47 
    48         def callback(self, dataset):
    49                 self._entries.append(dataset)
    50        
    51                 # check / set start and end date
    52                 entry_datetime = dataset.datetime_object()
    53                 if self.start() is None or entry_datetime < self.start():
    54                         self._start = entry_datetime
    55                 if self.end() is None or self.end() < entry_datetime:
    56                         self._end = entry_datetime
     21from ..tasks.tasks import log_parse
    5722
    5823def logs_get(submitter=None, order_by=None, offset=None, limit=None):
    … …  
    12994                raise MapserviceBadRequest(detail='No log data')
    13095       
    131         processing_state = ProcessingStatus.query.filter_by(label='Queued').all()
     96        processing_state = ProcessingStatus.query.filter_by(label='Queued for Parsing').all()
    13297        if len(processing_state) != 1:
    133                 raise MapserviceBadRequest(detail='Processing status Queued not found database')
     98                raise MapserviceBadRequest(detail='Processing status Queued for Parsing not found database')
    13499        processing_state = processing_state[0]
    135100       
    … …  
    142107        if LogEntry.query.filter_by(log=log).count() > 0:
    143108                raise MapserviceBadRequest(detail='Log {} has already log entries. Aborting'.format(log_id))
    144        
    145         # updating start / end of Log according to log file
    146         body = body.decode()
    147         log_callback = LogEntryCallback()
    148         log_handler = loghandler.LogHandler()
    149         result = log_handler.gnuboat_read(body.splitlines(), log_callback.callback, False, False)
    150         if not result.success():
    151                 raise MapserviceBadRequest(detail='Could not parse logfile: {}'.format('\n'.join(result.errors())))
    152         if not log_callback.valid():
    153                 if len(log_callback.entries()) < 1:
    154                         raise MapserviceBadRequest(detail='No entry in logfile')
    155                 raise MapserviceBadRequest(detail='No start or end date found')
    156        
    157         for entry in log_callback.entries():
    158                 if entry.water_depth() is not None:
    159                         location = entry.location()
    160                         log_entry = LogEntry(log=log, datetime=entry.datetime_object(), location='SRID=4326;POINT({} {})'.format(location.longitude, location.latitude), water_depth=entry.water_depth())
    161                         db.session.add(log_entry)
    162        
     109
     110        # Add Log to Queued table and change the processing state of Log
    163111        queue = Queue(log=log)
    164112        db.session.add(queue)
    165        
    166         log.start = log_callback.start()
    167         log.end = log_callback.end()
    168113        log.processingstatus = processing_state
    169                
    170114        db.session.commit()
    171115       
    172         if connexion.request.headers['Accept'] == "application/geo+json":
    173                 return log.to_geojson(), 200, {'Content-Type': 'application/geo+json; charset=utf-8'}
    174         return log.log()
     116        # request log parsing
     117        log_parse.delay(log.id, body.decode())
     118       
     119        return log.meta_data()
    175120
    176121def logs_log_delete(id):
  • src/mapservice/src/server_impl/controllers/UsersController.py

    rbd0cb38 ra88607b  
    2424from flask_mail import Message
    2525
    26 from openapi_server import mail
     26from .. import mail
    2727from ..database.Model import User, ApiKey, db
    2828from ..HttpErrors import MapserviceBadRequest, MapserviceUnauthorized, MapserviceNotFound
    … …  
    8282        if user_creation is None:
    8383                raise MapserviceBadRequest(detail='No data specified')
    84         if user_creation.username is None or user_creation.username == "":
     84        if user_creation.username is None or not user_creation.username:
    8585                raise MapserviceBadRequest(detail='No username given')
    86         if user_creation.password is None or user_creation.password == "":
     86        if user_creation.password is None or not user_creation.password:
    8787                raise MapserviceBadRequest(detail='No password given')
    88         if user_creation.first_name is None or user_creation.first_name == "":
     88        if user_creation.first_name is None or not user_creation.first_name:
    8989                raise MapserviceBadRequest(detail='No first name given')
    90         if user_creation.last_name is None or user_creation.last_name == "":
     90        if user_creation.last_name is None or not user_creation.last_name:
    9191                raise MapserviceBadRequest(detail='No last name given')
    92         if user_creation.email is None or user_creation.email == "":
     92        if user_creation.email is None or not user_creation.email:
    9393                raise MapserviceBadRequest(detail='No email given')
    9494        if not mail_regex.match(user_creation.email):
  • src/mapservice/src/server_impl/database/Model.py

    rbd0cb38 ra88607b  
    2222from geoalchemy2.shape import to_shape
    2323from sqlalchemy_utc import UtcDateTime
    24 from sqlalchemy_utils import create_view
     24from sqlalchemy_utils import create_view, database_exists, create_database
    2525from shapely import wkb
    2626import hashlib
    … …  
    218218        @staticmethod
    219219        def insert_states():
    220                 states = [ 'Undefined', 'Queued', 'Processing', 'Processed', 'To Old' ]
     220                states = [ 'Undefined', 'Queued for Parsing', 'Parsing', 'Queued for Processing', 'Processing', 'Deployed', 'To Old', 'Error' ]
    221221                changed = False
    222222                for state in states:
    … …  
    366366
    367367def db_setup():
    368         if 'sqlite' in flask.current_app.config['SQLALCHEMY_DATABASE_URI']:
    369                 print("Initiate spatial meta data for Spatialite...")
    370                 db.engine.execute(select([func.InitSpatialMetaData()]))
    371                 print("...Finished")
    372         db.create_all()
    373         ProcessingStatus.insert_states()
     368        if not database_exists(db.engine.url):
     369                create_database(db.engine.url)
     370                if 'sqlite' in flask.current_app.config['SQLALCHEMY_DATABASE_URI']:
     371                        print("Initiate spatial meta data for Spatialite...")
     372                        db.engine.execute(select([func.InitSpatialMetaData()]))
     373                        print("...Finished")
     374                db.create_all()
     375                ProcessingStatus.insert_states()
    374376
    375377def db_test_setup():
    … …  
    383385                        test_user_john = query[0]
    384386                else:
    385                         test_user_john = User.factory('john', 'testpass2', 'john@example.org', license_accepted=True)
     387                        test_user_john = User.factory('john', 'testpass2', 'john@example.org')
    386388                        test_user_john.activation_code = 'dac9630aec642a428cd73f4be0a03569'
     389                        test_user_john.license_accepted = True
    387390                        db.session.add(test_user_john)
    388391                        db.session.commit()
    … …  
    393396                        test_user_jane = query[0]
    394397                else:
    395                         test_user_jane = User.factory('jane', 'testpass', 'jane@example.org', license_accepted=True)
     398                        test_user_jane = User.factory('jane', 'testpass', 'jane@example.org')
    396399                        test_user_jane.activated = True
    397400                        test_user_jane.first_name = 'Jane'
     401                        test_user_jane.license_accepted = True
    398402                        db.session.add(test_user_jane)
    399403                        db.session.commit()
  • src/mapservice/templates/activation_mail.html

    rbd0cb38 ra88607b  
    22<p>thank you for supporting the project with your own measurings. All your measurings are handled under the <a href="https://www.opendatacommons.org/licenses/odbl/summary/index.html" target="_blank">Open Data Commons Open Database License (ODbL)</a>, which you have already accepted. It is the same license as OpenStreetmap uses.</p>
    33<p>To activate your GNUBoat account, you need ot visit <a href="{{activation_url}}">{{activation_url}}</a>.</p>
    4 <p>Kind regards,<br>
    5 Your GNUBOat team</p>
     4<p>Kind regards,<br>Your GNUBoat team</p>
Note: See TracChangeset for help on using the changeset viewer.