2 # -*- coding: utf-8 -*-
14 # Limit maximum CPU time
15 # The Postscript output format can sometimes take hours
16 resource.setrlimit(resource.RLIMIT_CPU,(180,180))
19 # Some odd requests can cause extreme memory usage
20 resource.setrlimit(resource.RLIMIT_AS,(4000000000, 4000000000))
22 # Routine to output HTTP headers
23 def output_headers(content_type, filename = "", length = 0):
24 print "Content-Type: %s" % content_type
26 print "Content-Disposition: attachment; filename=\"%s\"" % filename
28 print "Content-Length: %d" % length
31 # Routine to output the contents of a file
32 def output_file(file):
34 shutil.copyfileobj(file, sys.stdout)
36 # Routine to get the size of a file
38 return os.fstat(file.fileno()).st_size
40 # Routine to report an error
41 def output_error(message, status = "400 Bad Request"):
42 print "Status: %s" % status
43 output_headers("text/html")
46 print "<title>Error</title>"
49 print "<h1>Error</h1>"
50 print "<p>%s</p>" % message
54 # Parse CGI parameters
55 form = cgi.FieldStorage()
57 # Make sure we have a user agent
58 if not os.environ.has_key('HTTP_USER_AGENT'):
59 os.environ['HTTP_USER_AGENT'] = 'NONE'
61 # Get the load average
62 cputimes = [float(n) for n in open("/proc/stat").readline().rstrip().split()[1:-1]]
63 idletime = cputimes[3] / sum(cputimes)
67 # Abort if the CPU idle time on the machine is too low
68 output_error("The server is too busy at the moment. Please wait a few minutes before trying again.", "503 Service Unavailable")
69 <% @blocks["user_agents"].each do |user_agent| -%>
70 elif os.environ['HTTP_USER_AGENT'] == '<%= user_agent %>':
72 output_error("The server is too busy at the moment. Please wait a few minutes before trying again.", "503 Service Unavailable")
74 elif not form.has_key("bbox"):
75 # No bounding box specified
76 output_error("No bounding box specified")
77 elif not form.has_key("scale"):
79 output_error("No scale specified")
80 elif not form.has_key("format"):
82 output_error("No format specified")
84 # Create projection object
85 prj = mapnik.Projection("+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0 +k=1.0 +units=m +nadgrids=@null +no_defs +over");
87 # Get the bounds of the area to render
88 bbox = [float(x) for x in form.getvalue("bbox").split(",")]
90 if bbox[0] >= bbox[2] or bbox[1] >= bbox[3]:
92 output_error("Invalid bounding box")
94 # Project the bounds to the map projection
95 bbox = mapnik.forward_(mapnik.Box2d(*bbox), prj)
97 # Get the style to use
98 style = form.getvalue("style", "default")
100 # Calculate the size of the final rendered image
101 scale = float(form.getvalue("scale"))
102 width = int(bbox.width() / scale / 0.00028)
103 height = int(bbox.height() / scale / 0.00028)
105 # Limit the size of map we are prepared to produce
106 if width * height > 4000000:
107 # Map is too large (limit is approximately A2 size)
108 output_error("Map too large")
111 map = mapnik.Map(width, height)
113 # Load map configuration
114 mapnik.load_map(map, "/srv/tile.openstreetmap.org/styles/%s/project.xml" % style)
116 # Zoom the map to the bounding box
117 map.zoom_to_box(bbox)
119 # Fork so that we can handle crashes rendering the map
124 if form.getvalue("format") == "png":
125 image = mapnik.Image(map.width, map.height)
126 mapnik.render(map, image)
127 png = image.tostring("png")
128 output_headers("image/png", "map.png", len(png))
129 sys.stdout.write(png)
130 elif form.getvalue("format") == "jpeg":
131 image = mapnik.Image(map.width, map.height)
132 mapnik.render(map, image)
133 jpeg = image.tostring("jpeg")
134 output_headers("image/jpeg", "map.jpg", len(jpeg))
135 sys.stdout.write(jpeg)
136 elif form.getvalue("format") == "svg":
137 file = tempfile.NamedTemporaryFile(prefix = "export")
138 surface = cairo.SVGSurface(file.name, map.width, map.height)
139 mapnik.render(map, surface)
141 output_headers("image/svg+xml", "map.svg", file_size(file))
143 elif form.getvalue("format") == "pdf":
144 file = tempfile.NamedTemporaryFile(prefix = "export")
145 surface = cairo.PDFSurface(file.name, map.width, map.height)
146 mapnik.render(map, surface)
148 output_headers("application/pdf", "map.pdf", file_size(file))
150 elif form.getvalue("format") == "ps":
151 file = tempfile.NamedTemporaryFile(prefix = "export")
152 surface = cairo.PSSurface(file.name, map.width, map.height)
153 mapnik.render(map, surface)
155 output_headers("application/postscript", "map.ps", file_size(file))
158 output_error("Unknown format '%s'" % form.getvalue("format"))
160 pid, status = os.waitpid(pid, 0)
161 if status & 0xff == signal.SIGXCPU:
162 output_error("CPU time limit exceeded", "509 Resource Limit Exceeded")
163 elif status & 0xff == signal.SIGSEGV:
164 output_error("Memory limit exceeded", "509 Resource Limit Exceeded")
166 output_error("Internal server error", "500 Internal Server Error")