]> git.openstreetmap.org Git - chef.git/blob - cookbooks/tile/files/default/ruby/expire.rb
Use simple-mmap gem for tile expiry
[chef.git] / cookbooks / tile / files / default / ruby / expire.rb
1 #!/usr/bin/ruby
2
3 require "rubygems"
4 require "proj4"
5 require "xml/libxml"
6 require "set"
7 require "time"
8 require "simple-mmap"
9
10 module Expire
11   # projection object to go from latlon -> spherical mercator
12   PROJ = Proj4::Projection.new(["+proj=merc", "+a=6378137", "+b=6378137",
13                                 "+lat_ts=0.0", "+lon_0=0.0", "+x_0=0.0",
14                                 "+y_0=0", "+k=1.0", "+units=m",
15                                 "+nadgrids=@null", "+no_defs +over"])
16
17   # width/height of the spherical mercator projection
18   SIZE = 40075016.6855784
19   # the size of the meta tile blocks
20   METATILE = 8
21   # the directory root for meta tiles
22   HASH_ROOT = "/tiles/default/"
23   # node cache file
24   NODE_CACHE_FILE = "/store/database/nodes"
25
26   # turns a spherical mercator coord into a tile coord
27   def self.tile_from_merc(point, zoom)
28     # renormalise into unit space [0,1]
29     point.x = 0.5 + point.x / SIZE
30     point.y = 0.5 - point.y / SIZE
31     # transform into tile space
32     point.x = point.x * 2**zoom
33     point.y = point.y * 2**zoom
34     # chop of the fractional parts
35     [point.x.to_int, point.y.to_int, zoom]
36   end
37
38   # turns a latlon -> tile x,y given a zoom level
39   def self.tile_from_latlon(latlon, zoom)
40     # first convert to spherical mercator
41     point = PROJ.forward(latlon)
42     tile_from_merc(point, zoom)
43   end
44
45   # this must match the definition of xyz_to_meta in mod_tile
46   def self.xyz_to_meta(x, y, z)
47     # mask off the final few bits
48     x &= ~(METATILE - 1)
49     y &= ~(METATILE - 1)
50     # generate the path
51     hash_path = (0..4).collect do |i|
52       (((x >> 4 * i) & 0xf) << 4) | ((y >> 4 * i) & 0xf)
53     end.reverse.join("/")
54     z.to_s + "/" + hash_path + ".meta"
55   end
56
57   # time to reset to, some very stupidly early time, before OSM started
58   EXPIRY_TIME = Time.parse("2000-01-01 00:00:00")
59
60   # expire the meta tile by setting the modified time back
61   def self.expire_meta(meta)
62     puts "Expiring #{meta}"
63     File.utime(EXPIRY_TIME, EXPIRY_TIME, meta)
64   end
65
66   def self.expire(change_file, min_zoom, max_zoom, tile_dirs)
67     do_expire(change_file, min_zoom, max_zoom) do |set|
68       new_set = Set.new
69       meta_set = Set.new
70
71       # turn all the tiles into expires, putting them in the set
72       # so that we don't expire things multiple times
73       set.each do |xy|
74         # this has to match the routine in mod_tile
75         meta = xyz_to_meta(xy[0], xy[1], xy[2])
76
77         # check each style working out what needs expiring
78         tile_dirs.each do |tile_dir|
79           meta_set.add(tile_dir + "/" + meta) if File.exist?(tile_dir + "/" + meta)
80         end
81
82         # add the parent into the set for the next round
83         new_set.add([xy[0] / 2, xy[1] / 2, xy[2] - 1])
84       end
85
86       # expire all meta tiles
87       meta_set.each do |meta|
88         expire_meta(meta)
89       end
90
91       # return the new set, consisting of all the parents
92       new_set
93     end
94   end
95
96   def self.do_expire(change_file, min_zoom, max_zoom, &_)
97     # read in the osm change file
98     doc = XML::Document.file(change_file)
99
100     # hash map to contain all the nodes
101     nodes = {}
102
103     # we put all the nodes into the hash, as it doesn't matter whether the node was
104     # added, deleted or modified - the tile will need updating anyway.
105     doc.find("//node").each do |node|
106       lat = node["lat"].to_f
107       if lat < -85
108         lat = -85
109       end
110       if lat > 85
111         lat = 85
112       end
113       point = Proj4::Point.new(Math::PI * node["lon"].to_f / 180,
114                                Math::PI * lat / 180)
115       nodes[node["id"].to_i] = tile_from_latlon(point, max_zoom)
116     end
117
118     # now we look for all the ways that have changed and put all of their nodes into
119     # the hash too. this will add too many nodes, as it is possible a long way will be
120     # changed at only a portion of its length. however, due to the non-local way that
121     # mapnik does text placement, it may stil not be enough.
122     #
123     # also, we miss cases where nodes are deleted from ways where that node is not
124     # itself deleted and the coverage of the point set isn't enough to encompass the
125     # change.
126     node_cache = NodeCache.new(NODE_CACHE_FILE)
127     doc.find("//way/nd").each do |node|
128       node_id = node["ref"].to_i
129
130       next if nodes.include? node_id
131
132       # this is a node referenced but not added, modified or deleted, so it should
133       # still be in the node cache.
134       if (entry = node_cache[node_id])
135         point = Proj4::Point.new(entry.lon, entry.lat)
136         nodes[node_id] = tile_from_merc(point, max_zoom)
137       end
138     end
139
140     # create a set of all the tiles at the maximum zoom level which are touched by
141     # any of the nodes we've collected. we'll create the tiles at other zoom levels
142     # by a simple recursion.
143     set = Set.new nodes.values
144
145     # expire tiles and shrink to the set of parents
146     (max_zoom).downto(min_zoom) do |_|
147       # allow the block to work on the set, returning the set at the next
148       # zoom level
149       set = yield set
150     end
151   end
152
153   # wrapper to access the osm2pgsql node cache
154   class NodeCache
155     # node cache entry
156     class Node
157       attr_reader :lon, :lat
158
159       def initialize(lon, lat)
160         @lat = lat.to_f / 100.0
161         @lon = lon.to_f / 100.0
162       end
163     end
164
165     # open the cache
166     def initialize(filename)
167       @cache = SimpleMmap::FileWindow.open(filename)
168
169       throw "Unexpected format" unless @cache[0..3].unpack("l").first == 1
170       throw "Unexpected ID size" unless @cache[4..7].unpack("l").first == 8
171
172       @max_id = @cache[8..15].unpack("q").first
173     end
174
175     # lookup a node
176     def [](id)
177       if id <= @max_id
178         offset = 16 + id * 8
179
180         lon, lat = @cache[offset..offset + 7].unpack("ll")
181
182         if lon != -2147483648 && lat != -2147483648
183           node = Node.new(lon, lat)
184         end
185       end
186
187       node
188     end
189   end
190 end