]> git.openstreetmap.org Git - chef.git/blob - cookbooks/tile/templates/default/export.erb
devices: enable nvme.poll_queues if supported
[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 os
9 import pyotp
10 import pyproj
11 import resource
12 import shutil
13 import signal
14 import sys
15 import tempfile
16
17 # Limit maximum CPU time
18 # The Postscript output format can sometimes take hours
19 resource.setrlimit(resource.RLIMIT_CPU,(180,180))
20
21 # Limit memory usage
22 # Some odd requests can cause extreme memory usage
23 resource.setrlimit(resource.RLIMIT_AS,(4000000000, 4000000000))
24
25 # Routine to output HTTP headers
26 def output_headers(content_type, filename = "", length = 0):
27   print("Content-Type: %s" % content_type)
28   if filename:
29     print("Content-Disposition: attachment; filename=\"%s\"" % filename)
30   if length:
31     print("Content-Length: %d" % length)
32   print("")
33
34 # Routine to output the contents of a file
35 def output_file(file):
36   file.seek(0)
37   shutil.copyfileobj(file, sys.stdout.buffer)
38
39 # Routine to get the size of a file
40 def file_size(file):
41   return os.fstat(file.fileno()).st_size
42
43 # Routine to report an error
44 def output_error(message, status = "400 Bad Request"):
45   print("Status: %s" % status)
46   output_headers("text/html")
47   print("<html>")
48   print("<head>")
49   print("<title>Error</title>")
50   print("</head>")
51   print("<body>")
52   print("<h1>Error</h1>")
53   print("<p>%s</p>" % message)
54   print("</body>")
55   print("</html>")
56
57 # Create TOTP token validator
58 totp = pyotp.TOTP('<%= @totp_key %>', interval = 3600)
59
60 # Parse CGI parameters
61 form = cgi.FieldStorage()
62
63 # Import cookies
64 cookies = http.cookies.SimpleCookie(os.environ.get('HTTP_COOKIE'))
65
66 # Make sure we have a user agent
67 if 'HTTP_USER_AGENT' not in os.environ:
68   os.environ['HTTP_USER_AGENT'] = 'NONE'
69
70 # Make sure we have a referer
71 if 'HTTP_REFERER' not in os.environ:
72   os.environ['HTTP_REFERER'] = 'NONE'
73
74 # Look for TOTP token
75 if '_osm_totp_token' in cookies:
76   token = cookies['_osm_totp_token'].value
77 else:
78   token = None
79
80 # Get the load average
81 cputimes = [float(n) for n in open("/proc/stat").readline().rstrip().split()[1:-1]]
82 idletime = cputimes[3] / sum(cputimes)
83
84 # Process the request
85 if not totp.verify(token, valid_window = 1):
86   # Abort if the request didn't have a valid TOTP token
87   output_error("Missing or invalid token")
88 elif idletime < 0.2:
89   # Abort if the CPU idle time on the machine is too low
90   output_error("The server is too busy at the moment. Please wait a few minutes before trying again.", "503 Service Unavailable")
91 <% @blocks["user_agents"].each do |user_agent| -%>
92 elif os.environ['HTTP_USER_AGENT'] == '<%= user_agent %>':
93   # Block scraper
94   output_error("The server is too busy at the moment. Please wait a few minutes before trying again.", "503 Service Unavailable")
95 <% end -%>
96 <% @blocks["referers"].each do |referer| -%>
97 elif os.environ['HTTP_REFERER'] == '<%= referer %>':
98   # Block scraper
99   output_error("The server is too busy at the moment. Please wait a few minutes before trying again.", "503 Service Unavailable")
100 <% end -%>
101 elif "bbox" not in form:
102   # No bounding box specified
103   output_error("No bounding box specified")
104 elif "scale" not in form:
105   # No scale specified
106   output_error("No scale specified")
107 elif "format" not in form:
108   # No format specified
109   output_error("No format specified")
110 else:
111   # Create projection object
112   transformer = pyproj.Transformer.from_crs("EPSG:4326", "EPSG:3857", always_xy=True)
113
114   # Get the bounds of the area to render
115   bbox = [float(x) for x in form.getvalue("bbox").split(",")]
116
117   if bbox[0] >= bbox[2] or bbox[1] >= bbox[3]:
118     # Bogus bounding box
119     output_error("Invalid bounding box")
120   else:
121     # Project the bounds to the map projection
122     bbox = mapnik.Box2d(*transformer.transform(bbox[0], bbox[1]),
123                         *transformer.transform(bbox[2], bbox[3]))
124
125     # Get the style to use
126     style = form.getvalue("style", "default")
127
128     # Calculate the size of the final rendered image
129     scale = float(form.getvalue("scale"))
130     width = int(bbox.width() / scale / 0.00028)
131     height = int(bbox.height() / scale / 0.00028)
132
133     # Limit the size of map we are prepared to produce
134     if width * height > 4000000:
135       # Map is too large (limit is approximately A2 size)
136       output_error("Map too large")
137     else:
138       # Create map
139       map = mapnik.Map(width, height)
140
141       # Load map configuration
142       mapnik.load_map(map, "/srv/tile.openstreetmap.org/styles/%s/project.xml" % style)
143
144       # Zoom the map to the bounding box
145       map.zoom_to_box(bbox)
146
147       # Fork so that we can handle crashes rendering the map
148       pid = os.fork()
149
150       # Render the map
151       if pid == 0:
152         if form.getvalue("format") == "png":
153           image = mapnik.Image(map.width, map.height)
154           mapnik.render(map, image)
155           png = image.tostring("png")
156           output_headers("image/png", "map.png", len(png))
157           sys.stdout.buffer.write(png)
158         elif form.getvalue("format") == "jpeg":
159           image = mapnik.Image(map.width, map.height)
160           mapnik.render(map, image)
161           jpeg = image.tostring("jpeg")
162           output_headers("image/jpeg", "map.jpg", len(jpeg))
163           sys.stdout.buffer.write(jpeg)
164         elif form.getvalue("format") == "svg":
165           file = tempfile.NamedTemporaryFile(prefix = "export")
166           surface = cairo.SVGSurface(file.name, map.width, map.height)
167           surface.restrict_to_version(cairo.SVG_VERSION_1_2)
168           mapnik.render(map, surface)
169           surface.finish()
170           output_headers("image/svg+xml", "map.svg", file_size(file))
171           output_file(file)
172         elif form.getvalue("format") == "pdf":
173           file = tempfile.NamedTemporaryFile(prefix = "export")
174           surface = cairo.PDFSurface(file.name, map.width, map.height)
175           mapnik.render(map, surface)
176           surface.finish()
177           output_headers("application/pdf", "map.pdf", file_size(file))
178           output_file(file)
179         elif form.getvalue("format") == "ps":
180           file = tempfile.NamedTemporaryFile(prefix = "export")
181           surface = cairo.PSSurface(file.name, map.width, map.height)
182           mapnik.render(map, surface)
183           surface.finish()
184           output_headers("application/postscript", "map.ps", file_size(file))
185           output_file(file)
186         else:
187           output_error("Unknown format '%s'" % form.getvalue("format"))
188       else:
189         pid, status = os.waitpid(pid, 0)
190         if status & 0xff == signal.SIGXCPU:
191           output_error("CPU time limit exceeded", "509 Resource Limit Exceeded")
192         elif status & 0xff == signal.SIGSEGV:
193           output_error("Memory limit exceeded", "509 Resource Limit Exceeded")
194         elif status != 0:
195           output_error("Internal server error", "500 Internal Server Error")