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