Handling merging multiple pbf files in map importing.

This commit is contained in:
Roland 2022-10-27 20:22:11 -06:00
parent 2b84831205
commit 6854fa3692
No known key found for this signature in database
GPG key ID: 9D6DBD3ACF11AB93
5 changed files with 201 additions and 101 deletions

View file

@ -21,7 +21,7 @@ class ManageMap extends React.Component {
super(props);
this.state = {
files: null,
importing: null,
pending: null,
import_running: false,
selectedPaths: [],
dockerized: null,
@ -42,7 +42,7 @@ class ManageMap extends React.Component {
const importStatus = await getMapImportStatus();
this.setState({
files: importStatus['files'],
importing: importStatus['importing'],
pending: importStatus['pending'],
import_running: importStatus['import_running'],
dockerized: importStatus['dockerized'],
});
@ -102,7 +102,7 @@ class ManageMap extends React.Component {
<a href={`/media/${path}`}>{path}</a>
</TableCell>
<TableCell>
{path === this.state.importing ?
{this.state.pending && this.state.pending.indexOf(path) >= 0 ?
<SLoader active inline size='mini'/> :
imported ? 'yes' : 'no'}
</TableCell>
@ -111,7 +111,7 @@ class ManageMap extends React.Component {
}
render() {
const {files, selectedPaths, import_running, importing, dockerized} = this.state;
const {files, selectedPaths, import_running, pending, dockerized} = this.state;
let dockerWarning;
if (dockerized === true) {
@ -164,9 +164,9 @@ class ManageMap extends React.Component {
</Message.Content>
</Message>
let importingLoader = (
<Loader size='large' active={import_running} inline='centered'>Importing: {importing}</Loader>
);
const importingMessage = pending ?
pending.length > 1 ? 'Importing...' : `Importing ${pending[0]}`
: null;
let disabled = dockerized || !files || files.length === 0 || import_running;
let importButton = <Button
@ -205,7 +205,9 @@ class ManageMap extends React.Component {
<WROLModeMessage content='Cannot modify Map'/>
{dockerWarning}
{downloadMessage}
{importingLoader}
<Loader size='large' active={import_running} inline='centered'>
{importingMessage}
</Loader>
<Table>
<TableHeader>
<TableRow>

View file

@ -40,15 +40,15 @@ async def import_pbfs(_: Request, body: schema.ImportPost):
@bp.get('/files')
@openapi.description('Find any map files, get their import status')
def pbf(_: Request):
def get_files_status(_: Request):
paths = lib.get_import_status()
paths = sorted(paths, key=lambda i: str(i.path))
importing = lib.IMPORTING.get('path')
if importing:
importing = Path(importing).relative_to(get_media_directory())
pending = lib.IMPORTING.get('pending')
if pending:
pending = [Path(i).relative_to(get_media_directory()) for i in pending]
body = dict(
files=paths,
importing=importing,
pending=pending,
import_running=lib.IMPORT_EVENT.is_set(),
dockerized=DOCKERIZED,
)

View file

@ -16,8 +16,9 @@ from wrolpi.vars import PYTEST, PROJECT_DIR
logger = logger.getChild(__name__)
IMPORT_EVENT = Event()
IMPORTING = Manager().dict()
IMPORTING['path'] = None
IMPORTING = Manager().dict(dict(
pending=None,
))
def get_map_directory() -> Path:
@ -78,23 +79,50 @@ def get_or_create_map_file(pbf_path: Path, session: Session) -> MapFile:
import_logger = logger.getChild('import')
OSMIUM_BIN = which('osmium', '/usr/bin/osmium')
async def import_files(files: List[str]):
async def import_files(paths: List[str]):
if IMPORT_EVENT.is_set():
import_logger.warning('Map import already running...')
import_logger.error('Map import already running...')
return
# Import dumps, then pbfs.
import_order = ('.dump', '.pbf')
files = [get_media_directory() / i for i in files]
files = sorted(files, key=lambda i: import_order.index(i.suffix))
paths = [get_media_directory() / i for i in paths]
import_logger.warning(f'Importing: {", ".join(map(str, paths))}')
import_logger.warning(f'Importing: {", ".join(map(str, files))}')
dumps = [i for i in paths if i.suffix == '.dump']
pbfs = [i for i in paths if i.suffix == '.pbf']
any_success = False
try:
IMPORT_EVENT.set()
for path in files:
if pbfs:
success = False
try:
IMPORTING.update(dict(
pending=list(pbfs),
))
await run_import_command(*pbfs)
success = True
any_success = True
except Exception as e:
import_logger.warning('Failed to run import', exc_info=e)
finally:
IMPORTING.update(dict(
pending=None,
))
if success:
with get_db_session(commit=True) as session:
# Any previously imported PBFs are no longer imported.
for pbf_path in pbfs:
pbf_file = get_or_create_map_file(pbf_path, session)
pbf_file.imported = True
for pbf_file in session.query(MapFile):
pbf_file.imported = pbf_file.path in pbfs
for path in dumps:
# Import each dump individually.
if not path.is_file():
import_logger.fatal(f'Map file does not exist! {path}')
continue
@ -108,14 +136,18 @@ async def import_files(files: List[str]):
success = False
try:
IMPORTING['path'] = str(path)
await import_file(path)
IMPORTING.update(dict(
pending=str(path),
))
await run_import_command(path)
success = True
any_success = True
except Exception as e:
import_logger.warning('Failed to run import', exc_info=e)
finally:
IMPORTING['path'] = None
IMPORTING.update(dict(
pending=None,
))
if success:
with get_db_session(commit=True) as session:
@ -124,37 +156,50 @@ async def import_files(files: List[str]):
finally:
if any_success:
# A map was imported, remove the tile cache files.
clear_mod_tile()
await clear_mod_tile()
IMPORT_EVENT.clear()
BASH_BIN = which('bash', '/bin/bash', warn=True)
async def import_file(path: Path):
"""Run the map import script on the provided path.
async def run_import_command(*paths: Path):
"""Run the map import script on the provided paths.
Supports *.osm.pbf and *.dump files."""
if str(path).endswith('.osm.pbf'):
if not is_pbf_file(path):
import_logger.warning(f'Could not import non-pbf file: {path}')
raise ValueError('Invalid PBF file')
elif path.suffix == '.dump':
if not is_dump_file(path):
import_logger.warning(f'Could not import non-dump file: {path}')
raise ValueError('Invalid dump file')
else:
raise ValueError(f'Cannot import unknown file! {path}')
Can only import a single *.dump file, or a list of *.osm.pbf files. They cannot be mixed.
"""
paths = [i.absolute() for i in paths]
dumps = [i for i in paths if i.suffix == '.dump']
pbfs = [i for i in paths if i.suffix == '.pbf']
cmd = f'{BASH_BIN} {PROJECT_DIR}/scripts/import_map.sh {path.absolute()}'
import_logger.debug(f'Running import script: {cmd}')
# Only import a single dump, or a list of pbfs. No other combinations acceptable.
if not paths:
raise ValueError('Must import a file')
if not dumps and not pbfs:
raise ValueError('Cannot import unknown file!')
if dumps and pbfs:
raise ValueError('Cannot import mixed dumps and pbfs.')
if len(dumps) > 1:
raise ValueError('Cannot import more than one dump')
if dumps and not is_dump_file(dumps[0]):
import_logger.warning(f'Could not import non-dump file: {dumps}')
raise ValueError('Invalid dump file')
if pbfs:
for path in pbfs:
if not is_pbf_file(path):
import_logger.warning(f'Could not import non-pbf file: {path}')
raise ValueError('Invalid PBF file')
paths = ' '.join(str(i) for i in paths)
cmd = f'{BASH_BIN} {PROJECT_DIR}/scripts/import_map.sh {paths}'
import_logger.warning(f'Running map import command: {cmd}')
start = now()
proc = await asyncio.create_subprocess_shell(cmd, stderr=asyncio.subprocess.PIPE, stdout=asyncio.subprocess.PIPE)
stdout, stderr = await proc.communicate()
elapsed = now() - start
success = 'Successful' if proc.returncode == 0 else 'Unsuccessful'
import_logger.info(f'{success} import of {path.name} took {timedelta_to_timestamp(elapsed)}')
import_logger.info(f'{success} import of {repr(paths)} took {timedelta_to_timestamp(elapsed)}')
if proc.returncode != 0:
# Log all lines. Truncate long lines.
for line in stdout.decode().splitlines():
@ -180,7 +225,7 @@ MOD_TILE_CACHE_DIR = Path('/var/lib/mod_tile/ajt')
@wrol_mode_check
def clear_mod_tile():
async def clear_mod_tile():
"""Remove all cached map tile files"""
if PYTEST:
return
@ -188,5 +233,4 @@ def clear_mod_tile():
logger.warning('Clearing map tile cache files')
if MOD_TILE_CACHE_DIR.is_dir():
cmd = ('rm', '-r', MOD_TILE_CACHE_DIR)
subprocess.check_call(cmd)
await asyncio.create_subprocess_shell(f'rm -r {MOD_TILE_CACHE_DIR}')

View file

@ -5,89 +5,134 @@ from itertools import zip_longest
import mock
def assert_map_file_status(test_client, expected, status_code=HTTPStatus.OK):
request, response = test_client.get('/api/map/files')
assert response.status_code == status_code
for pbf, expected_ in zip_longest(response.json['files'], expected):
assert pbf['imported'] == expected_['imported']
assert pbf['path'].endswith(expected_['path'])
assert response.json['pending'] is None
@mock.patch('modules.map.lib.is_pbf_file', lambda i: True)
@mock.patch('modules.map.lib.is_dump_file', lambda i: True)
def test_status_and_import(test_client, test_session, test_directory):
def test_status_and_import(test_client, test_session, make_files_structure, mock_create_subprocess_shell):
"""PBF files can be imported, and the status of the import can be monitored."""
(test_directory / 'map/pbf').mkdir(parents=True)
(test_directory / 'map/dump').mkdir()
pbf1 = test_directory / 'map/pbf/some-country.osm.pbf'
pbf2 = test_directory / 'map/pbf/other-country.osm.pbf'
pbf1.touch()
pbf2.touch()
dump1 = test_directory / 'map/dump/dumpy.dump'
dump1.touch()
def check_status(response_json, expected_):
for pbf, expected_ in zip_longest(response_json['files'], expected_):
assert pbf['imported'] == expected_['imported']
assert pbf['path'].endswith(expected_['path'])
assert response.json['importing'] is None
pbf1, pbf2, dump1 = make_files_structure([
'map/pbf/some-country.osm.pbf',
'map/pbf/other-country.osm.pbf',
'map/dump/dumpy.dump',
])
# The PBF files can be found, but have not yet been imported.
request, response = test_client.get('/api/map/files')
assert response.status_code == HTTPStatus.OK
expected = [
{'imported': False, 'path': 'map/dump/dumpy.dump'},
{'imported': False, 'path': 'map/pbf/other-country.osm.pbf'},
{'imported': False, 'path': 'map/pbf/some-country.osm.pbf'},
]
check_status(response.json, expected)
assert_map_file_status(test_client, expected)
with mock.patch('modules.map.lib.import_file') as mock_import_file:
with mock.patch('modules.map.lib.asyncio') as mock_asyncio:
mock_asyncio.create_subprocess_shell = mock_create_subprocess_shell(return_code=0)
body = {'files': [str(pbf1), ], }
request, response = test_client.post('/api/map/import', content=json.dumps(body))
assert response.status_code == HTTPStatus.NO_CONTENT
# Only one PBF import is requested.
mock_import_file.assert_called_once()
request, response = test_client.get('/api/map/files')
assert response.status_code == HTTPStatus.OK
expected = [
{'imported': False, 'path': 'map/dump/dumpy.dump'},
{'imported': False, 'path': 'map/pbf/other-country.osm.pbf'},
{'imported': True, 'path': 'map/pbf/some-country.osm.pbf'},
]
check_status(response.json, expected)
assert_map_file_status(test_client, expected)
with mock.patch('modules.map.lib.import_file') as mock_import_file:
with mock.patch('modules.map.lib.asyncio') as mock_asyncio:
mock_asyncio.create_subprocess_shell = mock_create_subprocess_shell(return_code=0)
body = {'files': [str(pbf1), str(pbf2)]}
request, response = test_client.post('/api/map/import', content=json.dumps(body))
assert response.status_code == HTTPStatus.NO_CONTENT
# Both PBF imports are requested, but only one is performed.
mock_import_file.assert_called_once()
request, response = test_client.get('/api/map/files')
assert response.status_code == HTTPStatus.OK
expected = [
{'imported': False, 'path': 'map/dump/dumpy.dump'},
{'imported': True, 'path': 'map/pbf/other-country.osm.pbf'},
{'imported': True, 'path': 'map/pbf/some-country.osm.pbf'},
]
check_status(response.json, expected)
assert_map_file_status(test_client, expected)
with mock.patch('modules.map.lib.import_file') as mock_import_file:
with mock.patch('modules.map.lib.asyncio') as mock_asyncio:
mock_asyncio.create_subprocess_shell = mock_create_subprocess_shell(return_code=0)
body = {'files': [str(dump1), ]}
request, response = test_client.post('/api/map/import', content=json.dumps(body))
assert response.status_code == HTTPStatus.NO_CONTENT
# Dump is imported.
mock_import_file.assert_called_once()
request, response = test_client.get('/api/map/files')
assert response.status_code == HTTPStatus.OK
expected = [
{'imported': True, 'path': 'map/dump/dumpy.dump'},
{'imported': True, 'path': 'map/pbf/other-country.osm.pbf'},
{'imported': True, 'path': 'map/pbf/some-country.osm.pbf'},
]
check_status(response.json, expected)
assert_map_file_status(test_client, expected)
@mock.patch('modules.map.lib.is_pbf_file', lambda i: True)
@mock.patch('modules.map.lib.is_dump_file', lambda i: True)
def test_multiple_import(test_client, test_session, test_directory, make_files_structure, mock_create_subprocess_shell):
"""Multiple PBFs can be imported. Importing a second time overwrites the previous imports."""
pbf1, pbf2, pbf3, dump = make_files_structure([
'map/pbf/country1.osm.pbf',
'map/pbf/country2.osm.pbf',
'map/pbf/country3.osm.pbf',
'map/dumpy.dump',
])
with mock.patch('modules.map.lib.asyncio') as mock_asyncio:
mock_asyncio.create_subprocess_shell = mock_create_subprocess_shell(return_code=0)
body = {'files': [str(pbf2), str(pbf1)]}
request, response = test_client.post('/api/map/import', content=json.dumps(body))
assert response.status_code == HTTPStatus.NO_CONTENT
# Two PBFs can be merged and imported.
expected = [
{'imported': False, 'path': 'map/dumpy.dump'},
{'imported': True, 'path': 'map/pbf/country1.osm.pbf'},
{'imported': True, 'path': 'map/pbf/country2.osm.pbf'},
{'imported': False, 'path': 'map/pbf/country3.osm.pbf'},
]
assert_map_file_status(test_client, expected)
with mock.patch('modules.map.lib.asyncio') as mock_asyncio:
mock_asyncio.create_subprocess_shell = mock_create_subprocess_shell(return_code=0)
body = {'files': [str(pbf3), ]}
request, response = test_client.post('/api/map/import', content=json.dumps(body))
assert response.status_code == HTTPStatus.NO_CONTENT
# New imports overwrite old imports.
expected = [
{'imported': False, 'path': 'map/dumpy.dump'},
{'imported': False, 'path': 'map/pbf/country1.osm.pbf'},
{'imported': False, 'path': 'map/pbf/country2.osm.pbf'},
{'imported': True, 'path': 'map/pbf/country3.osm.pbf'},
]
assert_map_file_status(test_client, expected)
with mock.patch('modules.map.lib.asyncio') as mock_asyncio:
mock_asyncio.create_subprocess_shell = mock_create_subprocess_shell(return_code=0)
# Can't mix PBF and dump.
body = {'files': [str(dump), ]}
request, response = test_client.post('/api/map/import', content=json.dumps(body))
assert response.status_code == HTTPStatus.NO_CONTENT
# Dump does not overwrite.
expected = [
{'imported': True, 'path': 'map/dumpy.dump'},
{'imported': False, 'path': 'map/pbf/country1.osm.pbf'},
{'imported': False, 'path': 'map/pbf/country2.osm.pbf'},
{'imported': True, 'path': 'map/pbf/country3.osm.pbf'},
]
assert_map_file_status(test_client, expected)
def test_empty_import(test_client, test_session, test_directory):
"""Some files must be requested."""
with mock.patch('modules.map.lib.import_file') as mock_import_file:
body = {'files': []}
request, response = test_client.post('/api/map/import', content=json.dumps(body))
assert response.status_code == HTTPStatus.BAD_REQUEST
mock_import_file.assert_not_called()
assert 'validate' in response.json['error']
body = {'files': []}
request, response = test_client.post('/api/map/import', content=json.dumps(body))
assert response.status_code == HTTPStatus.BAD_REQUEST
assert 'validate' in response.json['error']

View file

@ -5,14 +5,11 @@ import pytest
from modules.map import lib
def test_get_map_paths(test_directory):
pbf_dir = test_directory / 'map/pbf'
pbf_dir.mkdir(parents=True)
pbf = pbf_dir / 'map.osm.pbf'
pbf.touch()
dump = pbf_dir / 'map.dump'
dump.touch()
def test_get_map_paths(test_directory, make_files_structure):
pbf, dump = make_files_structure([
'map/pbf/map.osm.pbf',
'map/pbf/map.dump',
])
with mock.patch('modules.map.lib.subprocess.check_output') as mock_check_output:
mock_check_output.return_value = b'OpenStreetMap Protocolbuffer Binary Format'
@ -24,18 +21,21 @@ def test_get_map_paths(test_directory):
@pytest.mark.asyncio
async def test_import_file(test_directory, mock_create_subprocess_shell):
async def test_run_import_command(test_directory, mock_create_subprocess_shell):
"""
Import map files. Files to import are checked for validity before importing. Any errors returned by
asyncio.create_subprocess_shell are caught and reported.
"""
pbf_file = test_directory / 'foo.osm.pbf'
with pytest.raises(ValueError):
await lib.import_file(pbf_file)
await lib.run_import_command(pbf_file)
pbf_file.touch()
with pytest.raises(ValueError):
await lib.import_file(pbf_file)
await lib.run_import_command(pbf_file)
dump_file = test_directory / 'dumpy.dump'
dump_file.touch()
with mock.patch('modules.map.lib.asyncio') as mock_asyncio, \
mock.patch('modules.map.lib.is_pbf_file') as mock_is_pbf_file:
@ -44,7 +44,7 @@ async def test_import_file(test_directory, mock_create_subprocess_shell):
communicate_return=(b'out', b'error')
)
mock_is_pbf_file.return_value = True
await lib.import_file(pbf_file)
await lib.run_import_command(pbf_file)
with mock.patch('modules.map.lib.asyncio') as mock_asyncio, \
mock.patch('modules.map.lib.is_pbf_file') as mock_is_pbf_file:
@ -55,4 +55,13 @@ async def test_import_file(test_directory, mock_create_subprocess_shell):
)
mock_is_pbf_file.return_value = True
with pytest.raises(ValueError):
await lib.import_file(pbf_file)
await lib.run_import_command(pbf_file)
with pytest.raises(ValueError) as e:
await lib.run_import_command()
assert 'Must import a file' in str(e)
# Can't import more than one dump.
with pytest.raises(ValueError) as e:
await lib.run_import_command(dump_file, dump_file)
assert 'more than one' in str(e)