Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
67 commits
Select commit Hold shift + click to select a range
cbab884
added filename and funcName to logging messages
Dec 20, 2019
29847ab
run black and flake8
Dec 28, 2019
7d5ce28
add setup.cfg for python plugin (flake8) and util confguration
Dec 28, 2019
7055924
remove arguments of flake8 which are already defined in setup.cfg
Dec 28, 2019
20ca771
add setup.cfg for python plugin (flake8) and util confguration
Dec 28, 2019
8aad628
Add archive_project command.
Dec 28, 2019
8c59325
Add archive feature. Archive project in Postgres. Delete project in F…
Dec 28, 2019
7c0b3a7
test template for archive_project module
Dec 29, 2019
e5769fb
add projectTypeName as class attribute
Dec 29, 2019
3e3eccb
add projectTypeName as class attribute
Dec 29, 2019
dcdbf41
Use of global var project_types
Jan 13, 2020
5662010
update requirements
Jan 13, 2020
a21668a
Merge pull request #257 from mapswipe/logging
Matthias-Schaub Jan 13, 2020
1c881a7
Merge pull request #262 from mapswipe/requirements
Matthias-Schaub Jan 13, 2020
431aab3
Merge pull request #259 from mapswipe/code-style
Matthias-Schaub Jan 13, 2020
7dce916
refactor code to only initialize sentry and slack. Sending messages s…
Jan 13, 2020
c25f242
Remove user attribute from slack config. This is only usefull if mess…
Jan 13, 2020
182cb0d
Rename attributes accourding to conventions.
Jan 13, 2020
0c29f5b
Merge pull request #261 from mapswipe/project_types
Matthias-Schaub Jan 13, 2020
619923b
Remove not needed attribute 'archive'
Jan 13, 2020
66d10d0
Change status instead of dedicated archived attribute
Jan 13, 2020
58a1e4c
Test status instead of dedicated archived attribute
Jan 13, 2020
462b5cb
correct missspelled entity 'group'
Jan 13, 2020
c7130fe
Revert "correct missspelled entity 'group'"
Jan 13, 2020
e84bf84
Revert "Test status instead of dedicated archived attribute"
Jan 13, 2020
6a87ffd
Correct missspelled entity 'GROUPS' to groups
Jan 13, 2020
6ceff96
merge with dev
Jan 13, 2020
c151417
integrate delete_project() functionality in main archive function and…
Jan 14, 2020
62edef7
Support lists of project ids for archive argument
Jan 14, 2020
e6bebfe
Support for a list of project ids as argument for archive function.
Jan 14, 2020
35240f4
--schedule option defaults now to 10 minutes.
Jan 14, 2020
5a2eb16
Create fb_db (Firbase sdk) when needed. Remove passing it to functions.
Jan 14, 2020
f264ee5
add ms as shorthand for mapswipe_workers command
Jan 14, 2020
117b3ec
Merge pull request #263 from mapswipe/archive-feature
Matthias-Schaub Jan 14, 2020
c9a25e0
Use scheduling only for run(). Simplified code. Run Black and Flake8.
Jan 14, 2020
3b8d8f3
add parameter type FileType and add docstrings.
Jan 14, 2020
1d85337
Merge branch 'dev' into scheduling
Matthias-Schaub Jan 14, 2020
ffe44d8
Merge pull request #265 from mapswipe/scheduling
Matthias-Schaub Jan 14, 2020
c03fed6
Merge branch 'dev' into logging
Jan 15, 2020
30cd2d6
Initalize slack, define slack messages and implement a send_slack_mes…
Jan 15, 2020
26f66ad
init sentry and assign sentry_sdk to variable name sentry similar to …
Jan 15, 2020
93aa16b
utilize slack helper module and definitions of sentry in definitions.py
Jan 15, 2020
75deaaf
renamed modules
Jan 15, 2020
106feab
Travis template. Run black and flake8.
Jan 15, 2020
1e27457
Travis template. Run black and flake8.
Jan 15, 2020
e47742a
add configuration for flake8
Jan 16, 2020
aacb2fe
Merge pull request #269 from mapswipe/travis
Matthias-Schaub Jan 16, 2020
39f6f50
Black
Jan 28, 2020
0d57903
Remove unused function.
Jan 28, 2020
928964c
load config now definied in definitions.py. Import CONFIG dict from d…
Jan 28, 2020
33da93c
Remove try-except statements where 'raise' is used in except-block. A…
Jan 28, 2020
3508291
Merge pull request #273 from mapswipe/auth
Matthias-Schaub Jan 28, 2020
c203d82
Merge branch 'dev' into logging
Jan 28, 2020
3e018bf
resolve of merge conflict dev <- logging.
Jan 28, 2020
963fb0c
'import ogr/osr' is deprecated. 'from osgeo import ogr'is now used.
Jan 28, 2020
c73bdca
Merge pull request #274 from mapswipe/osgeo
Matthias-Schaub Jan 28, 2020
fb0c999
Use official gdal docker image from osgeo.
Jan 28, 2020
92a5751
avoid circular imports
Jan 30, 2020
5b864ed
Correct wrong import location.
Jan 30, 2020
00b1e72
Correct wrong import location.
Jan 30, 2020
797f8a8
Change arguement type to string due to unresolved error when using cl…
Jan 31, 2020
4f34753
add archive and run commands to cli group of commands
Jan 31, 2020
843c60d
Set C.UTF-8 locale as default needed by the Click library.
Jan 31, 2020
5e57c33
Merge pull request #276 from mapswipe/circular_imports
Hagellach37 Feb 1, 2020
49f5d99
fix docker logging issue #277
Hagellach37 Feb 1, 2020
482c1c1
Merge pull request #278 from mapswipe/fix_logging
Hagellach37 Feb 1, 2020
8b9a3ae
call run method of scheduled task
Hagellach37 Feb 1, 2020
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions .travis
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
# This is a special configuration file to run tests on Travis-CI via
# GitHub notifications when changes are committed.
#
# For technical details, see http://travis-ci.org/

language: python
python:
- "3.6"
- "3.7"
- "3.8"

before_install:
- pip install --upgrade pip setuptools
- pip install flake8 black
- flake8 --config=mapswipe_workers/setup.cfg mapswipe_workers/mapswipe_workers/*.py
- black --check mapswipe_workers/mapswipe_workers/*.py

install:
- pip install mapswipe_workers/
2 changes: 1 addition & 1 deletion docker-compose.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ services:
context: mapswipe_workers/
depends_on:
- postgres
command: mapswipe_workers --verbose run --schedule m
command: mapswipe_workers --verbose run --schedule
volumes:
- ./api-data:/var/lib/mapswipe_workers/api-data/:rw
- ./api-data/agg_results:/var/lib/mapswipe_workers/api-data/agg_results:rw
Expand Down
1 change: 0 additions & 1 deletion mapswipe_workers/.pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -7,4 +7,3 @@ repos:
rev: 3.7.9
hooks:
- id: flake8
args: ["--ignore=E501,W503"]
25 changes: 14 additions & 11 deletions mapswipe_workers/Dockerfile
Original file line number Diff line number Diff line change
@@ -1,12 +1,15 @@
# This image contains Python 3 and the latest pre-compiled version of GDAL
# Based on Debian (Including apt-get update && upgrade)
FROM thinkwhere/gdal-python:3.7-shippable
# https://github.com/OSGeo/gdal/tree/master/gdal/docker
# Image includes python3.6, gdal-python, gdal-bin
FROM osgeo/gdal:ubuntu-small-latest

# Install gdal-bin to get ogr2ogr tool
ENV LC_ALL=C.UTF-8
ENV LANG=C.UTF-8

# Install pip
RUN apt-get update
RUN apt-get --yes install gdal-bin
RUN apt-get --yes install python3-pip

# create directories for config, logs and data
# Create directories for config, logs and data
ARG config_dir=/usr/share/config/mapswipe_workers/
ARG repo_dir=/usr/local/mapswipe_workers/
ARG data_dir=/var/lib/mapswipe_workers/
Expand All @@ -26,7 +29,7 @@ RUN mkdir -p $data_dir"api-data/tasks/"
RUN mkdir -p $data_dir"api-data/yes_maybe/"
RUN mkdir -p $data_dir"api-data/hot_tm/"

# copy mapswipe workers repo from local repo
# Copy mapswipe workers repo from local repo
WORKDIR $repo_dir
COPY mapswipe_workers/ mapswipe_workers/
COPY sample_data/ sample_data/
Expand All @@ -35,8 +38,8 @@ COPY requirements.txt .
COPY setup.py .
COPY config $config_dir

# Install dependencies and mapswipe-workers
# RUN python setup.py install
RUN pip install .
# Update setuptools and install mapswipe-workers with dependencies (requirements.txt)
RUN pip3 install --upgrade setuptools
RUN pip3 install .

# we don't use a CMD here, this will be defined in docker-compose.yaml
# Don't use a CMD here, this will be defined in docker-compose.yaml
3 changes: 1 addition & 2 deletions mapswipe_workers/config/example-configuration.json
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,7 @@
},
"slack": {
"token": "your_slack_token",
"channel": "your_slack_channel",
"username": "your_slack_username"
"channel": "your_slack_channel"
},
"sentry": {
"dsn": "your_sentry_dsn_value"
Expand Down
2 changes: 1 addition & 1 deletion mapswipe_workers/config/logging.cfg
Original file line number Diff line number Diff line change
Expand Up @@ -30,4 +30,4 @@ formatter=mapswipeFormatter
args=('/var/log/mapswipe_workers/mapswipe_workers.log','D', 1, 14,)

[formatter_mapswipeFormatter]
format=%(asctime)s - %(name)s - %(levelname)s - %(message)s
format=%(asctime)s - %(levelname)s - %(filename)s - %(funcName)s - %(message)s
136 changes: 30 additions & 106 deletions mapswipe_workers/mapswipe_workers/auth.py
Original file line number Diff line number Diff line change
@@ -1,150 +1,74 @@
#!/usr/bin/python3
#
# Author: B. Herfort, M. Reinmuth, 2017
############################################

import json

import psycopg2
import firebase_admin
from firebase_admin import credentials
from firebase_admin import db

from mapswipe_workers.definitions import CONFIG_PATH
from mapswipe_workers.definitions import SERVICE_ACCOUNT_KEY_PATH
import psycopg2
from firebase_admin import credentials, db

from mapswipe_workers.definitions import CONFIG, SERVICE_ACCOUNT_KEY_PATH

def load_config():
"""
Loads the user configuration values.

Returns
-------
dictonary
"""
with open(CONFIG_PATH) as f:
CONFIG = json.load(f)
return CONFIG
def get_api_key(tileserver: str) -> str:
if tileserver == "custom":
return None
else:
return CONFIG["imagery"][tileserver]["api_key"]


def get_api_key(tileserver):
CONFIG = load_config()
try:
if tileserver == 'custom':
return None
else:
return CONFIG['imagery'][tileserver]['api_key']
except KeyError:
print(
f'Could not find the API key for imagery tileserver '
f'{tileserver} in {CONFIG_PATH}.'
)
raise


def get_tileserver_url(tileserver):
CONFIG = load_config()
try:
if tileserver == 'custom':
return None
else:
return CONFIG['imagery'][tileserver]['url']
except KeyError:
print('Could not find the url for imagery tileserver {} in {}.'.format(
tileserver,
CONFIG_PATH
))
raise


def init_firebase():
try:
# Is an App instance already initialized?
firebase_admin.get_app()
except ValueError:
cred = credentials.Certificate(SERVICE_ACCOUNT_KEY_PATH)
# Initialize the app with a service account, granting admin privileges
firebase_admin.initialize_app(cred)
def get_tileserver_url(tileserver: str) -> str:
if tileserver == "custom":
return None
else:
return CONFIG["imagery"][tileserver]["url"]


def firebaseDB():
def firebaseDB() -> object:
try:
# Is an App instance already initialized?
firebase_admin.get_app()
# Return the imported Firebase Realtime Database module
return db
except ValueError:
cred = credentials.Certificate(SERVICE_ACCOUNT_KEY_PATH)
config = load_config()
databaseName = config['firebase']['database_name']
databaseURL = f'https://{databaseName}.firebaseio.com'
databaseName = CONFIG["firebase"]["database_name"]
databaseURL = f"https://{databaseName}.firebaseio.com"

# Initialize the app with a service account, granting admin privileges
firebase_admin.initialize_app(cred, {
'databaseURL': databaseURL
})
firebase_admin.initialize_app(cred, {"databaseURL": databaseURL})

# Return the imported Firebase Realtime Database module
return db


class postgresDB(object):
"""Helper calss for Postgres interactions"""

_db_connection = None
_db_cur = None

def __init__(self):
CONFIG = load_config()
try:
host = CONFIG['postgres']['host']
port = CONFIG['postgres']['port']
dbname = CONFIG['postgres']['database']
user = CONFIG['postgres']['username']
password = CONFIG['postgres']['password']
except KeyError:
raise Exception(
f'Could not load postgres credentials '
f'from the configuration file'
)
host = CONFIG["postgres"]["host"]
port = CONFIG["postgres"]["port"]
dbname = CONFIG["postgres"]["database"]
user = CONFIG["postgres"]["username"]
password = CONFIG["postgres"]["password"]

self._db_connection = psycopg2.connect(
database=dbname,
user=user,
password=password,
host=host,
port=port
)
database=dbname, user=user, password=password, host=host, port=port,
)

def query(self, query, data=None):
self._db_cur = self._db_connection.cursor()
self._db_cur.execute(query, data)
self._db_connection.commit()
self._db_cur.close()

def copy_from(
self,
f,
table,
columns
):
def copy_from(self, f, table, columns):
self._db_cur = self._db_connection.cursor()
self._db_cur.copy_from(
f,
table,
columns=columns
)
self._db_cur.copy_from(f, table, columns=columns)
self._db_connection.commit()
self._db_cur.close()

def copy_expert(
self,
sql,
file,
):
def copy_expert(self, sql, file):
self._db_cur = self._db_connection.cursor()
self._db_cur.copy_expert(
sql,
file,
)
self._db_cur.copy_expert(sql, file)
self._db_connection.commit()
self._db_cur.close()

Expand Down
6 changes: 3 additions & 3 deletions mapswipe_workers/mapswipe_workers/base/base_project.py
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ def __init__(self, project_draft):
# def resultRequiredCounter(self):
# return self.resultRequiredCounter

def save_project(self, fb_db):
def save_project(self):
"""
Creates a projects with groups and tasks
and saves it in firebase and postgres
Expand Down Expand Up @@ -131,7 +131,6 @@ def save_project(self, fb_db):
)
try:
self.save_to_firebase(
fb_db,
project,
groups,
groupsOfTasks,
Expand Down Expand Up @@ -161,7 +160,7 @@ def save_project(self, fb_db):
)
raise CustomError(e)

def save_to_firebase(self, fb_db, project, groups, groupsOfTasks):
def save_to_firebase(self, project, groups, groupsOfTasks):

# remove wkt geometry attribute of projects and tasks
project.pop('geometry', None)
Expand All @@ -170,6 +169,7 @@ def save_to_firebase(self, fb_db, project, groups, groupsOfTasks):
groupsOfTasks[group_id][i].pop('geometry', None)


fb_db = auth.firebaseDB()
ref = fb_db.reference('')
# save project
ref.update({
Expand Down
50 changes: 23 additions & 27 deletions mapswipe_workers/mapswipe_workers/definitions.py
Original file line number Diff line number Diff line change
@@ -1,41 +1,37 @@
import os
import json
import logging
import logging.config
from logging.handlers import TimedRotatingFileHandler
import os

import sentry_sdk


class CustomError(Exception):
pass


def load_config(CONFIG_PATH) -> dict:
"""Read the configuration file."""
with open(CONFIG_PATH) as f:
return json.load(f)


ROOT_DIR = os.path.dirname(os.path.abspath(__file__))

CONFIG_DIR = os.path.abspath(
'/usr/share/config/mapswipe_workers/'
)
CONFIG_DIR = os.path.abspath("/usr/share/config/mapswipe_workers/")

CONFIG_PATH = os.path.join(
CONFIG_DIR,
'configuration.json'
)
CONFIG_PATH = os.path.join(CONFIG_DIR, "configuration.json")

SERVICE_ACCOUNT_KEY_PATH = os.path.join(
CONFIG_DIR,
'serviceAccountKey.json'
)
CONFIG = load_config(CONFIG_PATH)

LOGGING_CONFIG_PATH = os.path.join(
CONFIG_DIR,
'logging.cfg'
)
SERVICE_ACCOUNT_KEY_PATH = os.path.join(CONFIG_DIR, "serviceAccountKey.json")

DATA_PATH = os.path.abspath(
'/var/lib/mapswipe_workers/'
)
LOGGING_CONFIG_PATH = os.path.join(CONFIG_DIR, "logging.cfg")

logging.config.fileConfig(
fname=LOGGING_CONFIG_PATH,
disable_existing_loggers=True
)
logger = logging.getLogger('Mapswipe Workers')
DATA_PATH = os.path.abspath("/var/lib/mapswipe_workers/")

logging.config.fileConfig(fname=LOGGING_CONFIG_PATH, disable_existing_loggers=True)
logger = logging.getLogger("Mapswipe Workers")

class CustomError(Exception):
pass
sentry_sdk.init(CONFIG["sentry"]["dsn"])
sentry = sentry_sdk
Loading