Пример #1
0
def main():
    # Create our RenderingTheWorld tile store that will manage the queue and subdivision.
    # We pass it the function that decides whether a tile should be subdivided, and an initial tile.
    rendering_the_world_tilestore = RenderingTheWorldTileStore(subdivide, seeds=(Tile(TileCoord(0, 0, 0)),))
    # Start the tilestream by getting a list of all tiles to be generated.
    tilestream = rendering_the_world_tilestore.list()
    tilestream = imap(Logger(logger, logging.INFO, 'get %(tilecoord)s'), tilestream)
    # Create the tile store that will generate our tiles, in this case it's a demo WMTS server at OpenGeo.
    # Getting tiles from this store will either return the tile as a PNG file, or set an error on the tile
    # if there are no features in this tile.
    generate_tilestore = WMTSTileStore(
        url='http://v2.suite.opengeo.org/geoserver/gwc/service/wmts/',
        layer='medford:buildings',
        style='_null',
        format='image/png',
        tile_matrix_set='EPSG:900913',
        tile_matrix=lambda z: 'EPSG:900913:{0:d}'.format(z))
    tilestream = generate_tilestore.get(tilestream)
    tilestream = imap(Logger(logger, logging.INFO, 'got %(tilecoord)s, error=%(error)s'), tilestream)
    # Put the tile back into the RenderingTheWorld tile store.  This check whether the tile should be
    # subdivided, and, if so, adds the tile's children to the list of tiles to be generated.
    tilestream = rendering_the_world_tilestore.put(tilestream)
    # Get rid of tiles that returned an error (i.e. where there was no data).
    tilestream = imap(DropErrors(), tilestream)
    # Store the generated tiles in the output tile store, in our case a local MBTiles file.
    output_tilestore = MBTilesTileStore(sqlite3.connect('medford_buildings.mbtiles'))
    tilestream = output_tilestore.put(tilestream)
    tilestream = imap(Logger(logger, logging.INFO, 'saved %(tilecoord)s'), tilestream)
    # Go!
    consume(tilestream, None)
Пример #2
0
 def add_logger(self):
     if not self.options.quiet and \
             not self.options.verbose and \
             not self.options.debug:
         def log_tiles(tile):
             variables = dict()
             variables.update(tile.__dict__)
             variables.update(tile.tilecoord.__dict__)
             sys.stdout.write("{tilecoord}          \r".format(**variables))
             sys.stdout.flush()
             return tile
         self.imap(log_tiles)
     elif self.options.verbose:
         self.imap(Logger(logger, logging.INFO, '%(tilecoord)s'))
Пример #3
0
def main():
    # Create our input and output TileStores
    input_tilestore = TileStore.load('tiles.openstreetmap_org')
    output_tilestore = TileStore.load('local.mbtiles')
    # 1. Generate a list of tiles to download from a BoundingPyramid
    #    4/8/5 is the root tile, corresponding to Central Europe
    #    +3/+1/+1 specifies up to zoom level 4 + 3 = 7 and an extent of one tile in the X and Y directions
    bounding_pyramid = BoundingPyramid.from_string('4/8/5:+3/+1/+1')
    bounding_pyramid_tilestore = BoundingPyramidTileStore(bounding_pyramid)
    tilestream = bounding_pyramid_tilestore.list()
    # 2. Filter out tiles that already downloaded
    tilestream = (tile for tile in tilestream if tile not in output_tilestore)
    # 3. Get the tile from openstreetmap.org
    tilestream = input_tilestore.get(tilestream)
    # 4. Save the tile to local.mbtiles
    tilestream = output_tilestore.put(tilestream)
    # 5. Log the fact that the tile was downloaded
    tilestream = imap(Logger(logger, logging.INFO, 'downloaded %(tilecoord)s'), tilestream)
    # Go!
    consume(tilestream, None)
Пример #4
0
    def _generate_tiles(self) -> None:
        if self._options.role in ("slave") and not self._options.tiles:
            assert self._queue_tilestore is not None
            # Get the metatiles from the SQS/Redis queue
            self._gene.set_store(self._queue_tilestore)
            self._gene.imap(lambda tile: tile if "layer" in tile.metadata else None)

        if self._options.role != "server":
            self._count_metatiles = self._gene.counter()

        self._gene.get(
            TimedTileStoreWrapper(
                MultiTileStore(TilestoreGetter(self)),
                stats_name="get",
            ),
            "Get tile",
        )

        if self._options.role in ("local", "slave") and "logging" in self._gene.get_main_config().config:
            self._gene.imap(
                DatabaseLogger(
                    self._gene.get_main_config().config["logging"],
                    self._options is not None and self._options.daemon,
                )
            )
            self._gene.init(
                self._queue_tilestore
                if "error_file" in self._gene.get_main_config().config["generation"]
                else None,
                self._options.daemon,
            )
        else:
            self._gene.init(daemon=self._options.daemon)

        if self._options.role == "hash":
            self._gene.imap(HashLogger("empty_metatile_detection"))
        elif not self._options.near:
            assert self._count_metatiles_dropped is not None
            self._gene.imap(MultiAction(HashDropperGetter(self, True, self._count_metatiles_dropped)))

        def add_elapsed_togenerate(metatile: Tile) -> Optional[Tile]:
            if metatile is not None:
                metatile.elapsed_togenerate = metatile.tilecoord.n ** 2  # type: ignore
                return metatile
            return None

        self._gene.imap(add_elapsed_togenerate)

        # Split the metatile image into individual tiles
        self._gene.add_metatile_splitter()
        self._gene.imap(Logger(logger, logging.INFO, "%(tilecoord)s, %(formated_metadata)s"))

        if self._count_tiles is not None:
            self._gene.imap(self._count_tiles)

        self._gene.process(key="pre_hash_post_process")

        if self._options.role == "hash":
            self._gene.imap(HashLogger("empty_tile_detection"))
        elif not self._options.near:
            assert self._count_tiles_dropped is not None
            self._gene.imap(MultiAction(HashDropperGetter(self, False, self._count_tiles_dropped)))

        if self._options.role != "server":
            self._gene.process()

        if self._options.role in ("local", "slave"):
            self._count_tiles_stored = self._gene.counter_size()

            if self._options.time:

                def log_size(tile: Tile) -> Tile:
                    assert tile.data is not None
                    sys.stdout.write(f"size: {len(tile.data)}\n")
                    return tile

                self._gene.imap(log_size)

            assert self._cache_tilestore is not None
            self._gene.put(self._cache_tilestore, "Store the tile")

        if self._options.role == "slave" and not self._options.tiles:

            def delete_from_store(tile: Tile) -> Tile:
                assert self._queue_tilestore is not None
                if hasattr(tile, "metatile"):
                    metatile: Tile = tile.metatile  # type: ignore
                    metatile.elapsed_togenerate -= 1  # type: ignore
                    if metatile.elapsed_togenerate == 0:  # type: ignore
                        self._queue_tilestore.delete_one(metatile)
                else:
                    self._queue_tilestore.delete_one(tile)
                return tile

            self._gene.imap(delete_from_store)

        if self._options.role in ("local", "slave") and "logging" in self._gene.get_main_config().config:
            self._gene.imap(
                DatabaseLogger(
                    self._gene.get_main_config().config["logging"],
                    self._options is not None and self._options.daemon,
                )
            )
        self._gene.init(daemon=self._options.daemon)
Пример #5
0
 def __call__(self, tile):
     if tile and tile.error:
         Logger.__call__(self, tile)
     return tile
Пример #6
0
    def gene(self, options, gene, layer):
        count_metatiles = None
        count_metatiles_dropped = Count()
        count_tiles = None
        count_tiles_dropped = Count()

        if options.role == 'slave' or options.get_hash or options.get_bbox:
            gene.layer = gene.layers[layer]
        else:
            gene.set_layer(layer, options)

        if options.get_bbox:
            try:
                tilecoord = parse_tilecoord(options.get_bbox)
                print \
                    "Tile bounds: [%i,%i,%i,%i]" % \
                    gene.layer['grid_ref']['obj'].extent(tilecoord)
                exit()
            except ValueError as e:  # pragma: no cover
                exit(
                    "Tile '%s' is not in the format 'z/x/y' or z/x/y:+n/+n\n%r"
                    % (options.get_bbox, e))

        if options.get_hash:
            options.role = 'hash'
            options.test = 1

        sqs_tilestore = None
        if options.role in ('master', 'slave'):
            # Create SQS queue
            sqs_tilestore = SQSTileStore(
                gene.get_sqs_queue())  # pragma: no cover

        cache_tilestore = None
        if options.role in ('local', 'slave'):
            cache_tilestore = gene.get_tilesstore(options.cache)

        meta = gene.layer['meta']
        if options.tiles:
            gene.set_store(TilesFileStore(options.tiles))

        elif options.role in ('local', 'master'):
            # Generate a stream of metatiles
            gene.init_tilecoords()
            gene.add_geom_filter()

        elif options.role == 'slave':
            # Get the metatiles from the SQS queue
            gene.set_store(sqs_tilestore)  # pragma: no cover

        elif options.role == 'hash':
            try:
                z, x, y = (int(v) for v in options.get_hash.split('/'))
                if meta:
                    gene.set_tilecoords(
                        [TileCoord(z, x, y, gene.layer['meta_size'])])
                else:
                    gene.set_tilecoords([TileCoord(z, x, y)])
            except ValueError as e:  # pragma: no cover
                exit("Tile '%s' is not in the format 'z/x/y'\n%r" %
                     (options.get_hash, e))

        # At this stage, the tilestream contains metatiles that intersect geometry
        gene.add_logger()

        count_metatiles = gene.counter()

        if options.role == 'master':  # pragma: no cover
            # Put the metatiles into the SQS queue
            gene.put(sqs_tilestore)

        elif options.role in ('local', 'slave', 'hash'):
            if gene.layer['type'] == 'wms':
                params = gene.layer['params'].copy()
                if 'STYLES' not in params:
                    params['STYLES'] = ','.join(gene.layer['wmts_style']
                                                for l in gene.layer['layers'])
                if gene.layer['generate_salt']:
                    params['SALT'] = str(random.randint(0, sys.maxint))
                for dim in gene.layer['dimensions']:
                    params[dim['name']] = dim['value']
                for dim in gene.options.dimensions:
                    dim = dim.split('=')
                    if len(dim) != 2:  # pragma: no cover
                        exit('the DIMENTIONS option should be like this '
                             'DATE=2013 VERSION=13.')
                    params[dim[0]] = dim[1]

                # Get the metatile image from the WMS server
                gene.get(
                    URLTileStore(
                        tilelayouts=(WMSTileLayout(
                            url=gene.layer['url'],
                            layers=','.join(gene.layer['layers']),
                            srs=gene.layer['grid_ref']['srs'],
                            format=gene.layer['mime_type'],
                            border=gene.layer['meta_buffer'] if meta else 0,
                            tilegrid=gene.get_grid()['obj'],
                            params=params,
                        ), ),
                        headers=gene.layer['headers'],
                    ), "Get tile from WMS")
            elif gene.layer['type'] == 'mapnik':
                from tilecloud.store.mapnik_ import MapnikTileStore
                from tilecloud_chain.mapnik_ import MapnikDropActionTileStore

                grid = gene.get_grid()
                if gene.layer['output_format'] == 'grid':
                    gene.get(
                        MapnikDropActionTileStore(
                            tilegrid=grid['obj'],
                            mapfile=gene.layer['mapfile'],
                            image_buffer=gene.layer['meta_buffer']
                            if meta else 0,
                            data_buffer=gene.layer['data_buffer'],
                            output_format=gene.layer['output_format'],
                            resolution=gene.layer['resolution'],
                            layers_fields=gene.layer['layers_fields'],
                            drop_empty_utfgrid=gene.
                            layer['drop_empty_utfgrid'],
                            store=cache_tilestore,
                            queue_store=sqs_tilestore,
                            count=count_tiles_dropped,
                            proj4_literal=grid['proj4_literal'],
                        ), "Create Mapnik grid tile")
                else:
                    gene.get(
                        MapnikTileStore(
                            tilegrid=grid['obj'],
                            mapfile=gene.layer['mapfile'],
                            image_buffer=gene.layer['meta_buffer']
                            if meta else 0,
                            data_buffer=gene.layer['data_buffer'],
                            output_format=gene.layer['output_format'],
                            proj4_literal=grid['proj4_literal'],
                        ), "Create Mapnik tile")

            def wrong_content_type_to_error(tile):
                if tile is not None and tile.content_type is not None \
                        and tile.content_type.find("image/") != 0:
                    if tile.content_type.find(
                            "application/vnd.ogc.se_xml") == 0:
                        tile.error = "WMS server error: %s" % (
                            self._re_rm_xml_tag.sub('', tile.data))
                    else:  # pragma: no cover
                        tile.error = "%s is not an image format, error: %s" % (
                            tile.content_type, tile.data)
                return tile

            gene.imap(wrong_content_type_to_error)

            # Handle errors
            gene.add_error_filters()

            if meta:
                if options.role == 'hash':
                    gene.imap(HashLogger('empty_metatile_detection'))
                elif not options.near:
                    # Discard tiles with certain content
                    if 'empty_metatile_detection' in gene.layer:
                        empty_tile = gene.layer['empty_metatile_detection']

                        gene.imap(
                            HashDropper(
                                empty_tile['size'],
                                empty_tile['hash'],
                                store=cache_tilestore,
                                queue_store=sqs_tilestore,
                                count=count_metatiles_dropped,
                            ))

                def add_elapsed_togenerate(metatile):
                    if metatile is not None:
                        metatile.elapsed_togenerate = metatile.tilecoord.n**2
                        return True
                    return False  # pragma: no cover

                gene.ifilter(add_elapsed_togenerate)

                # Split the metatile image into individual tiles
                gene.add_metatile_splitter()
                gene.imap(Logger(logger, logging.INFO, '%(tilecoord)s'))

                # Handle errors
                gene.add_error_filters()

            self.count_tiles = gene.counter()

            if 'pre_hash_post_process' in gene.layer:
                gene.process(gene.layer['pre_hash_post_process'])

            if options.role == 'hash':
                gene.imap(HashLogger('empty_tile_detection'))
            elif not options.near:
                # Discard tiles with certain content
                if 'empty_tile_detection' in gene.layer:
                    empty_tile = gene.layer['empty_tile_detection']

                    gene.imap(
                        HashDropper(
                            empty_tile['size'],
                            empty_tile['hash'],
                            store=cache_tilestore,
                            queue_store=sqs_tilestore,
                            count=count_tiles_dropped,
                        ))

            gene.process()

        if options.role in ('local', 'slave'):
            gene.add_error_filters()
            gene.ifilter(DropEmpty(gene))
            count_tiles = gene.counter(size=True)

            if options.time:

                def log_size(tile):
                    sys.stdout.write('size: %i\n' % len(tile.data))
                    return tile

                gene.imap(log_size)

            gene.put(cache_tilestore, "Store the tile")
        else:
            count_tiles = gene.counter(size=True)

        gene.add_error_filters()
        if options.generated_tiles_file:  # pragma: no cover
            generated_tiles_file = open(options.generated_tiles_file, 'a')

            def do(tile):
                generated_tiles_file.write('%s\n' % (tile.tilecoord, ))
                return tile

            gene.imap(do)

        if options.role == 'slave':  # pragma: no cover
            if meta:

                def decr_tile_in_metatile(tile):
                    tile.metatile.elapsed_togenerate -= 1
                    if tile.metatile.elapsed_togenerate == 0:
                        sqs_tilestore.delete_one(tile.metatile)
                    return True

                gene.ifilter(decr_tile_in_metatile)
            else:
                gene.delete(sqs_tilestore)

        if options.time is not None:

            class LogTime:
                n = 0
                t1 = None

                def __call__(self, tile):
                    self.n += 1
                    if self.n == options.time:
                        self.t1 = datetime.now()
                    elif self.n == 2 * options.time:
                        t2 = datetime.now()
                        d = (t2 - self.t1) / options.time
                        sys.stdout.write(
                            'time: %i\n' %
                            ((d.days * 24 * 3600 + d.seconds) * 1000000 +
                             d.microseconds))
                    return tile

            gene.imap(LogTime())

            gene.consume(options.time * 3)
        else:
            gene.consume()

            if not options.quiet and options.role in ('local', 'slave'):
                nb_tiles = count_tiles.nb + count_tiles_dropped.nb
                print """The tile generation of layer '%s' is finish
%sNb generated tiles: %i
Nb tiles dropped: %i
Nb tiles stored: %i
Nb error: %i
Total time: %s
Total size: %s
Time per tiles: %i ms
Size per tile: %i o
""" % \
                    (
                        gene.layer['name'],
                        """Nb generated metatiles: %i
Nb metatiles dropped: %i
""" %
                        (
                            count_metatiles.nb, count_metatiles_dropped.nb
                        ) if meta else '',
                        nb_tiles,
                        count_tiles_dropped.nb,
                        count_tiles.nb,
                        gene.error,
                        duration_format(gene.duration),
                        size_format(count_tiles.size),
                        (gene.duration / nb_tiles * 1000).seconds if nb_tiles != 0 else 0,
                        count_tiles.size / count_tiles.nb if count_tiles.nb != 0 else -1
                    )

        if cache_tilestore is not None and hasattr(cache_tilestore,
                                                   'connection'):
            cache_tilestore.connection.close()

        if options.role != 'hash' and options.time is None and 'sns' in gene.config:  # pragma: no cover
            if 'region' in gene.config['sns']:
                connection = sns.connect_to_region(
                    gene.config['sns']['region'])
            else:
                connection = boto.connect_sns()
            connection.publish(
                gene.config['sns']['topic'], """The tile generation is finish
Layer: %(layer)s
Role: %(role)s
Host: %(host)s
Command: %(cmd)s

%(meta)sNb generated tiles: %(nb_tiles)i
Nb tiles dropped: %(nb_tiles_dropped)i
Total time: %(duration)s [s]
Time per tiles: %(tile_duration)i [ms]""" % {
                    'role':
                    options.role,
                    'layer':
                    gene.layer['name'],
                    'host':
                    socket.getfqdn(),
                    'cmd':
                    ' '.join([quote(arg) for arg in sys.argv]),
                    'meta':
                    """Nb generated metatiles: %(nb_metatiles)i
Nb metatiles dropped: %(nb_metatiles_dropped)i
""" % {
                        'nb_metatiles': count_metatiles.nb,
                        'nb_metatiles_dropped': count_metatiles_dropped.nb,
                    } if meta else '',
                    'nb_tiles':
                    nb_tiles if meta else count_metatiles.nb,
                    'nb_tiles_dropped':
                    count_tiles_dropped.nb
                    if meta else count_metatiles_dropped.nb,
                    'duration':
                    duration_format(gene.duration),
                    'tile_duration': (gene.duration / nb_tiles *
                                      1000).seconds if nb_tiles != 0 else 0,
                }, "Tile generation (%(layer)s - %(role)s)" % {
                    'role': options.role,
                    'layer': gene.layer['name']
                })
Пример #7
0
 def __call__(self, tile: Tile) -> Tile:
     if tile and tile.error:
         Logger.__call__(self, tile)
     return tile
Пример #8
0
    def _generate_tiles(self):
        if self._options.role in ("slave", "server"):
            # Get the metatiles from the SQS/Redis queue
            self._gene.set_store(self._queue_tilestore)  # pragma: no cover
            self._gene.imap(lambda tile: tile
                            if "layer" in tile.metadata else None)

        self._count_metatiles = self._gene.counter()

        self._gene.get(
            TimedTileStoreWrapper(
                MultiTileStore({
                    name: self._get_tilestore_for_layer(layer)
                    for name, layer in self._gene.layers.items()
                }),
                stats_name="get",
            ),
            "Get tile",
        )

        if self._options.role in ("local",
                                  "slave") and "logging" in self._gene.config:
            self._gene.imap(
                DatabaseLogger(
                    self._gene.config["logging"], self._options is not None
                    and self._options.daemon))
            self._gene.init(
                self._queue_tilestore
                if "error_file" in self._gene.config["generation"] else None,
                self._options.daemon,
            )
        else:
            self._gene.init(daemon=self._options.daemon)

        if self._options.role == "hash":
            self._gene.imap(HashLogger("empty_metatile_detection"))
        elif not self._options.near:
            droppers = {}
            assert self._cache_tilestore is not None
            for lname, layer in self._gene.layers.items():
                if "empty_metatile_detection" in layer:
                    empty_tile = layer["empty_metatile_detection"]
                    droppers[lname] = HashDropper(
                        empty_tile["size"],
                        empty_tile["hash"],
                        store=self._cache_tilestore,
                        queue_store=self._queue_tilestore,
                        count=self._count_metatiles_dropped,
                    )
            if droppers:
                self._gene.imap(MultiAction(droppers))

        def add_elapsed_togenerate(metatile):
            if metatile is not None:
                metatile.elapsed_togenerate = metatile.tilecoord.n**2
                return metatile
            return None  # pragma: no cover

        self._gene.imap(add_elapsed_togenerate)

        # Split the metatile image into individual tiles
        self._gene.add_metatile_splitter()
        self._gene.imap(
            Logger(logger, logging.INFO,
                   "%(tilecoord)s, %(formated_metadata)s"))

        self._gene.imap(self._count_tiles)

        self._gene.process(key="pre_hash_post_process")

        if self._options.role == "hash":
            self._gene.imap(HashLogger("empty_tile_detection"))
        elif not self._options.near:
            assert self._cache_tilestore is not None
            droppers = {}
            for lname, layer in self._gene.layers.items():
                if "empty_tile_detection" in layer:
                    empty_tile = layer["empty_tile_detection"]
                    droppers[lname] = HashDropper(
                        empty_tile["size"],
                        empty_tile["hash"],
                        store=self._cache_tilestore,
                        queue_store=self._queue_tilestore,
                        count=self._count_tiles_dropped,
                    )
            if len(droppers) != 0:
                self._gene.imap(MultiAction(droppers))

        self._gene.process()

        if self._options.role in ("local", "slave", "server"):
            self._count_tiles_stored = self._gene.counter(size=True)

            if self._options.time:

                def log_size(tile):
                    sys.stdout.write("size: {}\n".format(len(tile.data)))
                    return tile

                self._gene.imap(log_size)

            self._gene.put(self._cache_tilestore, "Store the tile")

        if self._options.role == "slave":  # pragma: no cover

            def delete_from_store(tile):
                if hasattr(tile, "metatile"):
                    tile.metatile.elapsed_togenerate -= 1
                    if tile.metatile.elapsed_togenerate == 0:
                        self._queue_tilestore.delete_one(tile.metatile)
                else:
                    self._queue_tilestore.delete_one(tile)
                return tile

            self._gene.imap(delete_from_store)

        if self._options.role in ("local",
                                  "slave") and "logging" in self._gene.config:
            self._gene.imap(
                DatabaseLogger(
                    self._gene.config["logging"], self._options is not None
                    and self._options.daemon))
        self._gene.init(daemon=self._options.daemon)
Пример #9
0
    def _gene(self, options, gene, layer, dimensions={}):
        count_metatiles = None
        count_metatiles_dropped = Count()
        count_tiles = None
        count_tiles_dropped = Count()
        count_tiles_stored = None

        if options.get_bbox:
            try:
                tilecoord = parse_tilecoord(options.get_bbox)
                print("Tile bounds: [%i,%i,%i,%i]" %
                      gene.layer['grid_ref']['obj'].extent(tilecoord))
                exit()
            except ValueError as e:  # pragma: no cover
                exit(
                    "Tile '%s' is not in the format 'z/x/y' or z/x/y:+n/+n\n%r"
                    % (options.get_bbox, e))

        if options.get_hash:
            options.role = 'hash'
            options.test = 1

        sqs_tilestore = None
        if options.role in ('master', 'slave'):
            # Create SQS queue
            sqs_tilestore = SQSTileStore(
                gene.get_sqs_queue())  # pragma: no cover

        cache_tilestore = None
        if options.role in ('local', 'slave'):
            cache_tilestore = gene.get_tilesstore(options.cache, dimensions)

        meta = gene.layer['meta']
        if options.tiles:
            gene.set_store(TilesFileStore(options.tiles))

        elif options.role in ('local', 'master'):
            # Generate a stream of metatiles
            gene.init_tilecoords()
            gene.add_geom_filter()

        if options.local_process_number is not None:  # pragma: no cover
            gene.add_local_process_filter()

        elif options.role == 'slave':
            # Get the metatiles from the SQS queue
            gene.set_store(sqs_tilestore)  # pragma: no cover

        elif options.role == 'hash':
            try:
                z, x, y = (int(v) for v in options.get_hash.split('/'))
                if meta:
                    gene.set_tilecoords(
                        [TileCoord(z, x, y, gene.layer['meta_size'])])
                else:
                    gene.set_tilecoords([TileCoord(z, x, y)])
            except ValueError as e:  # pragma: no cover
                exit("Tile '%s' is not in the format 'z/x/y'\n%r" %
                     (options.get_hash, e))

        # At this stage, the tilestream contains metatiles that intersect geometry
        gene.add_logger()

        count_metatiles = gene.counter()

        if options.role == 'master':  # pragma: no cover
            # Put the metatiles into the SQS queue
            gene.put(sqs_tilestore)
            count_tiles = gene.counter()

        elif options.role in ('local', 'slave', 'hash'):
            if gene.layer['type'] == 'wms':
                params = gene.layer['params'].copy()
                if 'STYLES' not in params:
                    params['STYLES'] = ','.join(
                        gene.layer['wmts_style']
                        for l in gene.layer['layers'].split(','))
                if gene.layer['generate_salt']:
                    params['SALT'] = str(random.randint(0, 999999))
                params.update(dimensions)

                # Get the metatile image from the WMS server
                gene.get(
                    URLTileStore(
                        tilelayouts=(WMSTileLayout(
                            url=gene.layer['url'],
                            layers=gene.layer['layers'],
                            srs=gene.layer['grid_ref']['srs'],
                            format=gene.layer['mime_type'],
                            border=gene.layer['meta_buffer'] if meta else 0,
                            tilegrid=gene.get_grid()['obj'],
                            params=params,
                        ), ),
                        headers=gene.layer['headers'],
                    ), "Get tile from WMS")
            elif gene.layer['type'] == 'mapnik':  # pragma: no cover
                from tilecloud.store.mapnik_ import MapnikTileStore
                from tilecloud_chain.mapnik_ import MapnikDropActionTileStore

                grid = gene.get_grid()
                if gene.layer['output_format'] == 'grid':
                    count_tiles = gene.counter()
                    gene.get(
                        MapnikDropActionTileStore(
                            tilegrid=grid['obj'],
                            mapfile=gene.layer['mapfile'],
                            image_buffer=gene.layer['meta_buffer']
                            if meta else 0,
                            data_buffer=gene.layer['data_buffer'],
                            output_format=gene.layer['output_format'],
                            resolution=gene.layer['resolution'],
                            layers_fields=gene.layer['layers_fields'],
                            drop_empty_utfgrid=gene.
                            layer['drop_empty_utfgrid'],
                            store=cache_tilestore,
                            queue_store=sqs_tilestore,
                            count=count_tiles_dropped,
                            proj4_literal=grid['proj4_literal'],
                        ), "Create Mapnik grid tile")
                else:
                    gene.get(
                        MapnikTileStore(
                            tilegrid=grid['obj'],
                            mapfile=gene.layer['mapfile'],
                            image_buffer=gene.layer['meta_buffer']
                            if meta else 0,
                            data_buffer=gene.layer['data_buffer'],
                            output_format=gene.layer['output_format'],
                            proj4_literal=grid['proj4_literal'],
                        ), "Create Mapnik tile")

            def wrong_content_type_to_error(tile):
                if tile is not None and tile.content_type is not None \
                        and tile.content_type.find("image/") != 0:
                    if tile.content_type.find(
                            "application/vnd.ogc.se_xml") == 0:
                        tile.error = "WMS server error: %s" % (
                            self._re_rm_xml_tag.sub(
                                '',
                                tile.data.decode('utf-8')
                                if PY3 else tile.data))
                    else:  # pragma: no cover
                        tile.error = "%s is not an image format, error: %s" % (
                            tile.content_type, tile.data)
                return tile

            gene.imap(wrong_content_type_to_error)

            # Handle errors
            gene.add_error_filters()

            if meta:
                if options.role == 'hash':
                    gene.imap(HashLogger('empty_metatile_detection'))
                elif not options.near:
                    # Discard tiles with certain content
                    if 'empty_metatile_detection' in gene.layer:
                        empty_tile = gene.layer['empty_metatile_detection']

                        gene.imap(
                            HashDropper(
                                empty_tile['size'],
                                empty_tile['hash'],
                                store=cache_tilestore,
                                queue_store=sqs_tilestore,
                                count=count_metatiles_dropped,
                            ))

                def add_elapsed_togenerate(metatile):
                    if metatile is not None:
                        metatile.elapsed_togenerate = metatile.tilecoord.n**2
                        return True
                    return False  # pragma: no cover

                gene.ifilter(add_elapsed_togenerate)

                # Split the metatile image into individual tiles
                gene.add_metatile_splitter()
                gene.imap(Logger(logger, logging.INFO, '%(tilecoord)s'))

                # Handle errors
                gene.add_error_filters()

            if gene.layer['type'] != 'mapnik' or gene.layer[
                    'output_format'] != 'grid':
                count_tiles = gene.counter()

            if 'pre_hash_post_process' in gene.layer:  # pragma: no cover
                gene.process(gene.layer['pre_hash_post_process'])

            if options.role == 'hash':
                gene.imap(HashLogger('empty_tile_detection'))
            elif not options.near:
                # Discard tiles with certain content
                if 'empty_tile_detection' in gene.layer:
                    empty_tile = gene.layer['empty_tile_detection']

                    gene.imap(
                        HashDropper(
                            empty_tile['size'],
                            empty_tile['hash'],
                            store=cache_tilestore,
                            queue_store=sqs_tilestore,
                            count=count_tiles_dropped,
                        ))

            gene.process()
        else:  # pragma: no cover
            count_tiles = gene.counter()

        if options.role in ('local', 'slave'):
            gene.add_error_filters()
            gene.ifilter(DropEmpty(gene))
            count_tiles_stored = gene.counter(size=True)

            if options.time:

                def log_size(tile):
                    sys.stdout.write('size: %i\n' % len(tile.data))
                    return tile

                gene.imap(log_size)

            gene.put(cache_tilestore, "Store the tile")

        gene.add_error_filters()
        if options.generated_tiles_file:  # pragma: no cover
            generated_tiles_file = open(options.generated_tiles_file, 'a')

            def do(tile):
                generated_tiles_file.write('%s\n' % (tile.tilecoord, ))
                return tile

            gene.imap(do)

        if options.role == 'slave':  # pragma: no cover
            if meta:

                def decr_tile_in_metatile(tile):
                    tile.metatile.elapsed_togenerate -= 1
                    if tile.metatile.elapsed_togenerate == 0:
                        sqs_tilestore.delete_one(tile.metatile)
                    return True

                gene.ifilter(decr_tile_in_metatile)
            else:
                gene.delete(sqs_tilestore)

        message = []
        if options.time is not None:

            class LogTime:
                n = 0
                t1 = None

                def __call__(self, tile):
                    self.n += 1
                    if self.n == options.time:
                        self.t1 = datetime.now()
                    elif self.n == 2 * options.time:
                        t2 = datetime.now()
                        d = (t2 - self.t1) / options.time
                        sys.stdout.write(
                            'time: %i\n' %
                            ((d.days * 24 * 3600 + d.seconds) * 1000000 +
                             d.microseconds))
                    return tile

            gene.imap(LogTime())

            gene.consume(options.time * 3)
        else:
            gene.consume()

            message = [
                "The tile generation of layer '{}{}' is finish".format(
                    gene.layer['name'], "" if len(dimensions) == 0
                    or gene.layer['type'] != 'wms' else " (%s)" %
                    ", ".join(["=".join(d) for d in dimensions.items()])),
            ]
            if options.role == "master":  # pragma: no cover
                message.append("Nb of generated jobs: {}".format(
                    count_tiles.nb))
            else:
                if meta:
                    message += [
                        "Nb generated metatiles: {}".format(
                            count_metatiles.nb),
                        "Nb metatiles dropped: {}".format(
                            count_metatiles_dropped.nb),
                    ]
                message += [
                    "Nb generated tiles: {}".format(count_tiles.nb),
                    "Nb tiles dropped: {}".format(count_tiles_dropped.nb),
                ]
                if options.role in ('local', 'slave'):
                    message += [
                        "Nb tiles stored: {}".format(count_tiles_stored.nb),
                        "Nb tiles in error: {}".format(gene.error),
                        "Total time: {}".format(duration_format(
                            gene.duration)),
                    ]
                    if count_tiles_stored.nb != 0:
                        message.append("Total size: {}".format(
                            size_format(count_tiles_stored.size)))
                    if count_tiles.nb != 0:
                        message.append("Time per tile: {:0.0f} ms".format(
                            (gene.duration / count_tiles.nb * 1000).seconds))
                    if count_tiles_stored.nb != 0:
                        message.append("Size per tile: {:0.0f} o".format(
                            count_tiles_stored.size / count_tiles_stored.nb))

            if not options.quiet and options.role in ('local', 'slave'):
                print("\n".join(message) + "\n")

        if cache_tilestore is not None and hasattr(cache_tilestore,
                                                   'connection'):
            cache_tilestore.connection.close()

        if options.role != 'hash' and options.time is None and 'sns' in gene.config:  # pragma: no cover
            if 'region' in gene.config['sns']:
                connection = sns.connect_to_region(
                    gene.config['sns']['region'])
            else:
                connection = boto.connect_sns()
            sns_message = [message[0]]
            sns_message += [
                "Layer: {}".format(gene.layer['name']),
                "Role: {}".format(options.role),
                "Host: {}".format(socket.getfqdn()),
                "Command: {}".format(' '.join([quote(arg)
                                               for arg in sys.argv])),
            ]
            sns_message += message[1:]
            connection.publish(
                gene.config['sns']['topic'], "\n".join(sns_message),
                "Tile generation (%(layer)s - %(role)s)" % {
                    'role': options.role,
                    'layer': gene.layer['name']
                })
Пример #10
0
    def _gene(self, options, gene, dimensions=None):
        if dimensions is None:  # pragma: no cover
            dimensions = {}
        self.dimensions = dimensions
        self.count_metatiles = None
        self.count_metatiles_dropped = Count()
        self.count_tiles = Count()
        self.count_tiles_dropped = Count()
        self.count_tiles_stored = None
        self.sqs_tilestore = None
        self.cache_tilestore = None

        if options.get_bbox:
            try:
                tilecoord = parse_tilecoord(options.get_bbox)
                print("Tile bounds: [{},{},{},{}]".format(*default_int(
                    gene.layer['grid_ref']['obj'].extent(tilecoord))))
                exit()
            except ValueError as e:  # pragma: no cover
                print(
                    "Tile '{}' is not in the format 'z/x/y' or z/x/y:+n/+n\n{}"
                    .format(options.get_bbox, repr(e)))
                exit(1)

        if options.get_hash:
            options.role = 'hash'
            options.test = 1

        if options.role in ('master', 'slave'):
            # Create SQS queue
            self.sqs_tilestore = SQSTileStore(
                gene.get_sqs_queue(),
                on_empty=await_message
                if options.daemon else maybe_stop)  # pragma: no cover

        if options.role in ('local', 'slave'):
            self.cache_tilestore = gene.get_tilesstore(options.cache,
                                                       dimensions)

        if options.tiles:
            gene.set_store(TilesFileStore(options.tiles, options.layer))

        elif options.role in ('local', 'master'):
            # Generate a stream of metatiles
            gene.init_tilecoords()
            gene.add_geom_filter()

        if options.role in ('local', 'master') and 'logging' in gene.config:
            gene.imap(
                DatabaseLoggerInit(gene.config['logging'], options is not None
                                   and options.daemon))

        if options.local_process_number is not None:  # pragma: no cover
            gene.add_local_process_filter()

        elif options.role == 'slave':
            # Get the metatiles from the SQS queue
            gene.set_store(self.sqs_tilestore)  # pragma: no cover

        elif options.role == 'hash':
            try:
                z, x, y = (int(v) for v in options.get_hash.split('/'))
                if gene.layer.get('meta'):
                    gene.set_tilecoords(
                        [TileCoord(z, x, y, gene.layer['meta_size'])])
                else:
                    gene.set_tilecoords([TileCoord(z, x, y)])
            except ValueError as e:  # pragma: no cover
                exit("Tile '{}' is not in the format 'z/x/y'\n{}".format(
                    options.get_hash, repr(e)))

        # At this stage, the tilestream contains metatiles that intersect geometry
        gene.add_logger()

        self.count_metatiles = gene.counter()

        if options.role == 'master':  # pragma: no cover
            # Put the metatiles into the SQS queue
            gene.put(self.sqs_tilestore)
            self.count_tiles = gene.counter()

        elif options.role in ('local', 'slave', 'hash'):
            gene.get(
                MultiTileStore({
                    name: self._get_tilestore_for_layer(layer, gene)
                    for name, layer in gene.layers.items()
                }), 'Get tile')

            def wrong_content_type_to_error(tile):
                if tile is not None and tile.content_type is not None \
                        and tile.content_type.find("image/") != 0:
                    if tile.content_type.find(
                            "application/vnd.ogc.se_xml") == 0:
                        tile.error = "WMS server error: {}".format(
                            (self._re_rm_xml_tag.sub('', tile.error)))
                    else:  # pragma: no cover
                        tile.error = "{} is not an image format, error: {}".format(
                            tile.content_type, tile.error)
                return tile

            gene.imap(wrong_content_type_to_error)
            gene.add_error_filters()

            if options.role == 'hash':
                if gene.layer.get('meta', False):
                    gene.imap(HashLogger('empty_metatile_detection'))
            elif not options.near:
                droppers = {}
                for lname, layer in gene.layers.items():
                    if 'empty_metatile_detection' in layer:
                        empty_tile = layer['empty_metatile_detection']
                        droppers[lname] = HashDropper(
                            empty_tile['size'],
                            empty_tile['hash'],
                            store=self.cache_tilestore,
                            queue_store=self.sqs_tilestore,
                            count=self.count_metatiles_dropped,
                        )
                if droppers:
                    gene.imap(MultiAction(droppers))

            def add_elapsed_togenerate(metatile):
                if metatile is not None:
                    metatile.elapsed_togenerate = metatile.tilecoord.n**2
                    return True
                return False  # pragma: no cover

            gene.ifilter(add_elapsed_togenerate)

            # Split the metatile image into individual tiles
            gene.add_metatile_splitter()
            gene.imap(Logger(logger, logging.INFO, '%(tilecoord)s'))

            gene.imap(self.count_tiles)

            gene.process(key='pre_hash_post_process')

            if options.role == 'hash':
                gene.imap(HashLogger('empty_tile_detection'))
            elif not options.near:
                droppers = {}
                for lname, layer in gene.layers.items():
                    if 'empty_tile_detection' in layer:
                        empty_tile = layer['empty_tile_detection']
                        droppers[lname] = HashDropper(
                            empty_tile['size'],
                            empty_tile['hash'],
                            store=self.cache_tilestore,
                            queue_store=self.sqs_tilestore,
                            count=self.count_tiles_dropped,
                        )
                if droppers:
                    gene.imap(MultiAction(droppers))

            gene.process()
        else:  # pragma: no cover
            self.count_tiles = gene.counter()

        if options.role in ('local', 'slave'):
            self.count_tiles_stored = gene.counter(size=True)

            if options.time:

                def log_size(tile):
                    sys.stdout.write('size: {}\n'.format(len(tile.data)))
                    return tile

                gene.imap(log_size)

            gene.put(self.cache_tilestore, "Store the tile")

        if options.generated_tiles_file:  # pragma: no cover
            generated_tiles_file = open(options.generated_tiles_file, 'a')

            def do(tile):
                generated_tiles_file.write('{}\n'.format(tile.tilecoord))
                return tile

            gene.imap(do)

        if options.role == 'slave':  # pragma: no cover

            def delete_from_store(tile):
                if hasattr(tile, 'metatile'):
                    tile.metatile.elapsed_togenerate -= 1
                    if tile.metatile.elapsed_togenerate == 0:
                        self.sqs_tilestore.delete_one(tile.metatile)
                else:
                    self.sqs_tilestore.delete_one(tile)
                return True

            gene.ifilter(delete_from_store)

        if options.role in ('local', 'slave') and 'logging' in gene.config:
            gene.imap(
                DatabaseLogger(gene.config['logging'], options is not None
                               and options.daemon))
        gene.add_error_filters()

        message = []
        if options.time is not None:

            class LogTime:
                n = 0
                t1 = None

                def __call__(self, tile):
                    self.n += 1
                    if self.n == options.time:
                        self.t1 = datetime.now()
                    elif self.n == 2 * options.time:
                        t2 = datetime.now()
                        d = (t2 - self.t1) / options.time
                        sys.stdout.write('time: {}\n'.format(
                            ((d.days * 24 * 3600 + d.seconds) * 1000000 +
                             d.microseconds)))
                    return tile

            gene.imap(LogTime())

            gene.consume(options.time * 3)
        else:
            gene.consume()

            if gene.layer is not None:
                message = [
                    "The tile generation of layer '{}{}' is finish".format(
                        gene.layer['name'], ""
                        if len(dimensions) == 0 or gene.layer['type'] != 'wms'
                        else " ({})".format(", ".join(
                            ["=".join(d) for d in dimensions.items()]))),
                ]
                if options.role == "master":  # pragma: no cover
                    message.append("Nb of generated jobs: {}".format(
                        self.count_tiles.nb))
                else:
                    if gene.layer.get('meta'):
                        message += [
                            "Nb generated metatiles: {}".format(
                                self.count_metatiles.nb),
                            "Nb metatiles dropped: {}".format(
                                self.count_metatiles_dropped.nb),
                        ]
            else:
                message = ["The tile generation is finish"]

            if options.role != "master":
                message += [
                    "Nb generated tiles: {}".format(self.count_tiles.nb),
                    "Nb tiles dropped: {}".format(self.count_tiles_dropped.nb),
                ]
                if options.role in ('local', 'slave'):
                    message += [
                        "Nb tiles stored: {}".format(
                            self.count_tiles_stored.nb),
                        "Nb tiles in error: {}".format(gene.error),
                        "Total time: {}".format(duration_format(
                            gene.duration)),
                    ]
                    if self.count_tiles_stored.nb != 0:
                        message.append("Total size: {}".format(
                            size_format(self.count_tiles_stored.size)))
                    if self.count_tiles.nb != 0:
                        message.append("Time per tile: {:0.0f} ms".format(
                            (gene.duration / self.count_tiles.nb *
                             1000).seconds))
                    if self.count_tiles_stored.nb != 0:
                        message.append("Size per tile: {:0.0f} o".format(
                            self.count_tiles_stored.size /
                            self.count_tiles_stored.nb))

            if not options.quiet and options.role in ('local', 'slave'):
                print("\n".join(message) + "\n")

        if self.cache_tilestore is not None and hasattr(
                self.cache_tilestore, 'connection'):
            self.cache_tilestore.connection.close()

        if options.role != 'hash' and options.time is None and 'sns' in gene.config:  # pragma: no cover
            if 'region' in gene.config['sns']:
                connection = sns.connect_to_region(
                    gene.config['sns']['region'])
            else:
                connection = boto.connect_sns()
            sns_message = [message[0]]
            sns_message += [
                "Layer: {}".format(gene.layer['name'] if gene.
                                   layer is not None else "(All layers)"),
                "Role: {}".format(options.role),
                "Host: {}".format(socket.getfqdn()),
                "Command: {}".format(' '.join([quote(arg)
                                               for arg in sys.argv])),
            ]
            sns_message += message[1:]
            connection.publish(
                gene.config['sns']['topic'], "\n".join(sns_message),
                "Tile generation ({layer!s} - {role!s})".format(
                    **{
                        'role':
                        options.role,
                        'layer':
                        gene.layer['name'] if gene.
                        layer is not None else "All layers"
                    }))
Пример #11
0
    def _generate_tiles(self):
        if self._options.role == 'slave':
            # Get the metatiles from the SQS queue
            self._gene.set_store(self._sqs_tilestore)  # pragma: no cover
            self._gene.ifilter(lambda tile: 'layer' in tile.metadata)

        self._gene.get(
            TimedTileStoreWrapper(MultiTileStore({
                name: self._get_tilestore_for_layer(layer)
                for name, layer in self._gene.layers.items()
            }),
                                  stats_name='get'), 'Get tile')

        def wrong_content_type_to_error(tile):
            if tile is not None and tile.content_type is not None \
                    and tile.content_type.find("image/") != 0:
                if tile.content_type.find("application/vnd.ogc.se_xml") == 0:
                    tile.error = "WMS server error: {}".format(
                        (self._re_rm_xml_tag.sub('', tile.error)))
                else:  # pragma: no cover
                    tile.error = "{} is not an image format, error: {}".format(
                        tile.content_type, tile.error)
            return tile

        self._gene.imap(wrong_content_type_to_error)
        if self._options.role in ('local',
                                  'slave') and 'logging' in self._gene.config:
            self._gene.imap(
                DatabaseLogger(
                    self._gene.config['logging'], self._options is not None
                    and self._options.daemon))
            self._gene.add_error_filters(
                self._sqs_tilestore if 'error_file' in
                self._gene.config['generation'] else None)
        else:
            self._gene.add_error_filters()

        if self._options.role == 'hash':
            self._gene.imap(HashLogger('empty_metatile_detection'))
        elif self._options.role == 'hash':
            pass
        elif not self._options.near:
            droppers = {}
            for lname, layer in self._gene.layers.items():
                if 'empty_metatile_detection' in layer:
                    empty_tile = layer['empty_metatile_detection']
                    droppers[lname] = HashDropper(
                        empty_tile['size'],
                        empty_tile['hash'],
                        store=self._cache_tilestore,
                        queue_store=self._sqs_tilestore,
                        count=self._count_metatiles_dropped,
                    )
            if droppers:
                self._gene.imap(MultiAction(droppers))

        def add_elapsed_togenerate(metatile):
            if metatile is not None:
                metatile.elapsed_togenerate = metatile.tilecoord.n**2
                return True
            return False  # pragma: no cover

        self._gene.ifilter(add_elapsed_togenerate)

        # Split the metatile image into individual tiles
        self._gene.add_metatile_splitter()
        self._gene.imap(
            Logger(logger, logging.INFO,
                   '%(tilecoord)s, %(formated_metadata)s'))

        self._gene.imap(self._count_tiles)

        self._gene.process(key='pre_hash_post_process')

        if self._options.role == 'hash':
            self._gene.imap(HashLogger('empty_tile_detection'))
        elif not self._options.near:
            droppers = {}
            for lname, layer in self._gene.layers.items():
                if 'empty_tile_detection' in layer:
                    empty_tile = layer['empty_tile_detection']
                    droppers[lname] = HashDropper(
                        empty_tile['size'],
                        empty_tile['hash'],
                        store=self._cache_tilestore,
                        queue_store=self._sqs_tilestore,
                        count=self._count_tiles_dropped,
                    )
            if len(droppers) != 0:
                self._gene.imap(MultiAction(droppers))

        self._gene.process()

        if self._options.role in ('local', 'slave'):
            self._count_tiles_stored = self._gene.counter(size=True)

            if self._options.time:

                def log_size(tile):
                    sys.stdout.write('size: {}\n'.format(len(tile.data)))
                    return tile

                self._gene.imap(log_size)

            self._gene.ifilter(lambda tile: tile is not None)
            self._gene.put(self._cache_tilestore, "Store the tile")

        if self._options.role == 'slave':  # pragma: no cover

            def delete_from_store(tile):
                if hasattr(tile, 'metatile'):
                    tile.metatile.elapsed_togenerate -= 1
                    if tile.metatile.elapsed_togenerate == 0:
                        self._sqs_tilestore.delete_one(tile.metatile)
                else:
                    self._sqs_tilestore.delete_one(tile)
                return True

            self._gene.ifilter(delete_from_store)

        if self._options.role in ('local',
                                  'slave') and 'logging' in self._gene.config:
            self._gene.imap(
                DatabaseLogger(
                    self._gene.config['logging'], self._options is not None
                    and self._options.daemon))
        self._gene.add_error_filters()