]> git.openstreetmap.org Git - chef.git/blob - cookbooks/tile/templates/default/export.erb
Merge remote-tracking branch 'github/pull/786'
[chef.git] / cookbooks / tile / templates / default / export.erb
1 #!/usr/bin/python3 -u
2 # -*- coding: utf-8 -*-
3
4 import cairo
5 import http.cookies
6 import mapnik
7 import io
8 import os
9 import pyotp
10 import pyproj
11 import resource
12 import shutil
13 import signal
14 import sys
15 import tempfile
16 import urllib.parse
17 from PIL import Image
18
19 # Limit maximum CPU time
20 # The Postscript output format can sometimes take hours
21 resource.setrlimit(resource.RLIMIT_CPU,(180,180))
22
23 # Limit memory usage
24 # Some odd requests can cause extreme memory usage
25 resource.setrlimit(resource.RLIMIT_AS,(4000000000, 4000000000))
26
27 # Routine to output HTTP headers
28 def output_headers(content_type, filename = "", length = 0):
29   print("Content-Type: %s" % content_type)
30   if filename:
31     print("Content-Disposition: attachment; filename=\"%s\"" % filename)
32   if length:
33     print("Content-Length: %d" % length)
34   print("")
35
36 # Routine to output the contents of a file
37 def output_file(file):
38   file.seek(0)
39   shutil.copyfileobj(file, sys.stdout.buffer)
40
41 # Routine to get the size of a file
42 def file_size(file):
43   return os.fstat(file.fileno()).st_size
44
45 # Routine to retrieve BytesIO payload length
46 def bytesio_size(bio):
47   return bio.getbuffer().nbytes
48
49 # Routine to report an error
50 def output_error(message, status = "400 Bad Request"):
51   print("Status: %s" % status)
52   output_headers("text/plain")
53   print(message)
54
55 # Add a copyright notice for raster formats (PNG, JPEG, WEBP)
56 def add_copyright_notice_raster(image, map_width, map_height, format):
57   # Convert the Mapnik image to PNG and store it in a BytesIO object
58   png = image.tostring("png")
59   png_io = io.BytesIO(png)
60
61   # Load the PNG data from the BytesIO object into a Cairo ImageSurface
62   surface = cairo.ImageSurface.create_from_png(png_io)
63
64   add_copyright_notice_vector(surface, map_width, map_height)
65
66   # Convert the Cairo surface to PNG in a BytesIO object
67   output_io = io.BytesIO()
68   surface.write_to_png(output_io)
69
70   if format == "png":
71     return output_io
72   else:
73     # Open the output PNG image for conversion to other formats
74     img = Image.open(output_io)
75     img_io = io.BytesIO()
76     img.save(img_io, format=format)
77     return img_io
78
79 # Add a copyright notice for vector formats (SVG, PDF, PS)
80 def add_copyright_notice_vector(surface, map_width, map_height):
81   context = cairo.Context(surface)
82
83   # Set the font for the copyright notice
84   context.set_font_face(cairo.ToyFontFace("DejaVu"))
85   context.set_font_size(14)
86
87   # Define the copyright text
88   text = "© OpenStreetMap contributors"
89
90   text_extents = context.text_extents(text)
91   text_width = text_extents.width
92   text_height = text_extents.height
93
94   x_margin = 10
95   y_margin = 10
96
97   # Position the text at the bottom-right corner
98   x_position = map_width - text_width - x_margin
99   y_position = map_height - text_height - y_margin
100
101   # Draw a white box just large enough to fit the text
102   context.set_source_rgba(1, 1, 1, 0.5)
103   context.rectangle(x_position - x_margin, y_position - y_margin,
104                     text_width + 2 * x_margin, text_height + 2 * y_margin)
105   context.fill_preserve()
106
107   context.set_source_rgb(0, 0, 0)  # Black color for the text
108   context.move_to(x_position - x_margin / 2, y_position + y_margin)
109   context.show_text(text)
110
111 # Render and output map for raster formats (PNG, JPEG, WEBP)
112 def render_and_output_image(map, format):
113   image = mapnik.Image(map.width, map.height)
114   mapnik.render(map, image)
115
116   bytes_io = add_copyright_notice_raster(image, map.width, map.height, format)
117
118   if format == "png":
119     output_headers("image/png", "map.png", bytesio_size(bytes_io))
120   elif format == "jpeg":
121     output_headers("image/jpeg", "map.jpg", bytesio_size(bytes_io))
122   elif format == "webp":
123     output_headers("image/webp", "map.webp", bytesio_size(bytes_io))
124
125   output_file(bytes_io)
126
127 # Render and output map for vector formats (SVG, PDF, PS)
128 def render_and_output_vector(map, format):
129   with tempfile.NamedTemporaryFile(prefix="export") as file:
130     if format == "svg":
131       surface = cairo.SVGSurface(file.name, map.width, map.height)
132       surface.restrict_to_version(cairo.SVG_VERSION_1_2)
133     elif format == "pdf":
134       surface = cairo.PDFSurface(file.name, map.width, map.height)
135     elif format == "ps":
136       surface = cairo.PSSurface(file.name, map.width, map.height)
137
138     mapnik.render(map, surface)
139
140     add_copyright_notice_vector(surface, map.width, map.height)
141
142     surface.finish()
143
144     if format == "svg":
145       output_headers("image/svg+xml", "map.svg", file_size(file))
146     elif format == "pdf":
147       output_headers("application/pdf", "map.pdf", file_size(file))
148     elif format == "ps":
149       output_headers("application/postscript", "map.ps", file_size(file))
150
151     output_file(file)
152
153
154 # Create TOTP token validator
155 totp = pyotp.TOTP('<%= @totp_key %>', interval = 3600)
156
157 # Parse CGI parameters
158 query_string = os.environ.get('QUERY_STRING', '')
159 form = urllib.parse.parse_qs(query_string)
160
161 # Import cookies
162 cookies = http.cookies.SimpleCookie(os.environ.get('HTTP_COOKIE'))
163
164 # Make sure we have a user agent
165 if 'HTTP_USER_AGENT' not in os.environ:
166   os.environ['HTTP_USER_AGENT'] = 'NONE'
167
168 # Make sure we have a referer
169 if 'HTTP_REFERER' not in os.environ:
170   os.environ['HTTP_REFERER'] = 'NONE'
171
172 # Look for TOTP token
173 if '_osm_totp_token' in cookies:
174   token = cookies['_osm_totp_token'].value
175 else:
176   token = form.get("token", [None])[0]
177
178 # Get the load average
179 cputimes = [float(n) for n in open("/proc/stat").readline().rstrip().split()[1:-1]]
180 idletime = cputimes[3] / sum(cputimes)
181
182 # Process the request
183 if os.environ['REQUEST_METHOD'] == 'OPTIONS':
184   # Handle CORS preflight checks
185   print('Status: 204 No Content')
186   print('Access-Control-Allow-Origin: %s' % os.environ['HTTP_ORIGIN'])
187   print('Access-Control-Allow-Headers: X-CSRF-Token, X-Turbo-Request-Id')
188   print('Access-Control-Allow-Credentials: true')
189   print('')
190 elif not totp.verify(token, valid_window = 1):
191   # Abort if the request didn't have a valid TOTP token
192   output_error("Missing or invalid token")
193 elif idletime < 0.2:
194   # Abort if the CPU idle time on the machine is too low
195   output_error("The server is too busy at the moment. Please wait a few minutes before trying again.", "503 Service Unavailable")
196 <% @blocks["user_agents"].each do |user_agent| -%>
197 elif os.environ['HTTP_USER_AGENT'] == '<%= user_agent %>':
198   # Block scraper
199   output_error("The server is too busy at the moment. Please wait a few minutes before trying again.", "503 Service Unavailable")
200 <% end -%>
201 <% @blocks["referers"].each do |referer| -%>
202 elif os.environ['HTTP_REFERER'] == '<%= referer %>':
203   # Block scraper
204   output_error("The server is too busy at the moment. Please wait a few minutes before trying again.", "503 Service Unavailable")
205 <% end -%>
206 elif "bbox" not in form:
207   # No bounding box specified
208   output_error("No bounding box specified")
209 elif "scale" not in form:
210   # No scale specified
211   output_error("No scale specified")
212 elif "format" not in form:
213   # No format specified
214   output_error("No format specified")
215 else:
216   try:
217     # Create projection object
218     transformer = pyproj.Transformer.from_crs("EPSG:4326", "EPSG:3857", always_xy=True)
219
220     # Get the bounds of the area to render
221     bbox = [float(x) for x in form.get("bbox", [""])[0].split(",")]
222
223     if bbox[0] >= bbox[2] or bbox[1] >= bbox[3]:
224       # Bogus bounding box
225       output_error("Invalid bounding box")
226     else:
227       # Project the bounds to the map projection
228       bbox = mapnik.Box2d(*transformer.transform(bbox[0], bbox[1]),
229                           *transformer.transform(bbox[2], bbox[3]))
230
231       # Get the style to use
232       style = form.get("style", ["default"])[0]
233
234       # Calculate the size of the final rendered image
235       scale = float(form.get("scale")[0])
236       width = int(bbox.width() / scale / 0.00028)
237       height = int(bbox.height() / scale / 0.00028)
238
239       # Limit the size of map we are prepared to produce
240       if width * height > 4000000:
241         # Map is too large (limit is approximately A2 size)
242         output_error("Map too large")
243       else:
244         # Create map
245         map = mapnik.Map(width, height)
246
247         # Load map configuration
248         mapnik.load_map(map, "/srv/tile.openstreetmap.org/styles/%s/project.xml" % style)
249
250         # Zoom the map to the bounding box
251         map.zoom_to_box(bbox)
252
253         # Fork so that we can handle crashes rendering the map
254         pid = os.fork()
255
256         # Render the map
257         if pid == 0:
258           format = form.get("format", [None])[0]
259           if format in ["png", "jpeg", "webp"]:
260             render_and_output_image(map, format)
261           elif format in ["svg", "pdf", "ps"]:
262             render_and_output_vector(map, format)
263           else:
264             output_error("Unknown format")
265         else:
266           pid, status = os.waitpid(pid, 0)
267           if status & 0xff == signal.SIGXCPU:
268             output_error("CPU time limit exceeded", "509 Resource Limit Exceeded")
269           elif status & 0xff == signal.SIGSEGV:
270             output_error("Memory limit exceeded", "509 Resource Limit Exceeded")
271           elif status != 0:
272             output_error("Internal server error", "500 Internal Server Error")
273
274   except Exception as e:
275     output_error(f"An error occurred: {str(e)}")