]> git.openstreetmap.org Git - chef.git/blob - cookbooks/planet/files/default/replication-bin/replicate-changesets
Fsync all the things, all the time.
[chef.git] / cookbooks / planet / files / default / replication-bin / replicate-changesets
1 #!/usr/bin/ruby
2
3 require "rubygems"
4 require "pg"
5 require "yaml"
6 require "time"
7 require "fileutils"
8 require "xml/libxml"
9 require "zlib"
10 require "set"
11
12 # after this many changes, a changeset will be closed
13 CHANGES_LIMIT = 50000
14
15 # this is the scale factor for lat/lon values stored as integers in the database
16 GEO_SCALE = 10000000
17
18 ##
19 # replace characters which cannot be represented in XML 1.0.
20 def xml_sanitize(str)
21   str.gsub(/[\x00-\x08\x0b\x0c\x0e-\x1f]/, "?")
22 end
23
24 ##
25 # changeset class keeps some information about changesets downloaded from the
26 # database - enough to let us know which changesets are closed/open & recently
27 # closed.
28 class Changeset
29   attr_reader :id, :created_at, :closed_at, :num_changes
30
31   def initialize(row)
32     @id = row["id"].to_i
33     @created_at = Time.parse(row["created_at"])
34     @closed_at = Time.parse(row["closed_at"])
35     @num_changes = row["num_changes"].to_i
36   end
37
38   def closed?(t)
39     (@closed_at < t) || (@num_changes >= CHANGES_LIMIT)
40   end
41
42   def open?(t)
43     !closed?(t)
44   end
45
46   def activity_between?(t1, t2)
47     ((@closed_at >= t1) && (@closed_at < t2)) || ((@created_at >= t1) && (@created_at < t2))
48   end
49 end
50
51 ##
52 # builds an XML representation of a changeset from the database
53 class ChangesetBuilder
54   def initialize(now, conn)
55     @now = now
56     @conn = conn
57   end
58
59   def changeset_xml(cs)
60     xml = XML::Node.new("changeset")
61     xml["id"] = cs.id.to_s
62     xml["created_at"] = cs.created_at.getutc.xmlschema
63     xml["closed_at"] = cs.closed_at.getutc.xmlschema if cs.closed?(@now)
64     xml["open"] = cs.open?(@now).to_s
65     xml["num_changes"] = cs.num_changes.to_s
66
67     res = @conn.exec("select u.id, u.display_name, c.min_lat, c.max_lat, c.min_lon, c.max_lon from users u join changesets c on u.id=c.user_id where c.id=#{cs.id}")
68     xml["user"] = xml_sanitize(res[0]["display_name"])
69     xml["uid"] = res[0]["id"]
70
71     unless res[0]["min_lat"].nil? ||
72            res[0]["max_lat"].nil? ||
73            res[0]["min_lon"].nil? ||
74            res[0]["max_lon"].nil?
75       xml["min_lat"] = (res[0]["min_lat"].to_f / GEO_SCALE).to_s
76       xml["max_lat"] = (res[0]["max_lat"].to_f / GEO_SCALE).to_s
77       xml["min_lon"] = (res[0]["min_lon"].to_f / GEO_SCALE).to_s
78       xml["max_lon"] = (res[0]["max_lon"].to_f / GEO_SCALE).to_s
79     end
80
81     add_tags(xml, cs)
82     add_comments(xml, cs)
83
84     xml
85   end
86
87   def add_tags(xml, cs)
88     res = @conn.exec("select k, v from changeset_tags where changeset_id=#{cs.id}")
89     res.each do |row|
90       tag = XML::Node.new("tag")
91       tag["k"] = xml_sanitize(row["k"])
92       tag["v"] = xml_sanitize(row["v"])
93       xml << tag
94     end
95   end
96
97   def add_comments(xml, cs)
98     # grab the visible changeset comments as well
99     res = @conn.exec("select cc.author_id, u.display_name as author, cc.body, cc.created_at from changeset_comments cc join users u on cc.author_id=u.id where cc.changeset_id=#{cs.id} and cc.visible order by cc.created_at asc")
100     xml["comments_count"] = res.num_tuples.to_s
101
102     # early return if there aren't any comments
103     return unless res.num_tuples > 0
104
105     discussion = XML::Node.new("discussion")
106     res.each do |row|
107       comment = XML::Node.new("comment")
108       comment["uid"] = row["author_id"]
109       comment["user"] = xml_sanitize(row["author"])
110       comment["date"] = Time.parse(row["created_at"]).getutc.xmlschema
111       text = XML::Node.new("text")
112       text.content = xml_sanitize(row["body"])
113       comment << text
114       discussion << comment
115     end
116     xml << discussion
117   end
118 end
119
120 ##
121 # sync a file to guarantee it's on disk
122 def fsync(f)
123   File.open(f) do |fh|
124     fh.fsync
125   end
126 end
127
128 ##
129 # sync a directory to guarantee it's on disk. have to recurse to the root
130 # to guarantee sync for newly created directories.
131 def fdirsync(d)
132   while d != "/"
133     Dir.open(d) do |dh|
134       io = IO.for_fd(dh.fileno)
135       io.fsync
136     end
137     d = File.dirname(d)
138   end
139 end
140
141 ##
142 # state and connections associated with getting changeset data
143 # replicated to a file.
144 class Replicator
145   def initialize(config)
146     @config = YAML.load(File.read(config))
147     @state = YAML.load(File.read(@config["state_file"]))
148     @conn = PGconn.connect(@config["db"])
149     @now = Time.now.getutc
150   end
151
152   def open_changesets
153     last_run = @state["last_run"]
154     last_run = (@now - 60) if last_run.nil?
155     @state["last_run"] = @now
156     # pretty much all operations on a changeset will modify its closed_at
157     # time (see rails_port's changeset model). so it is probably enough
158     # for us to look at anything that was closed recently, and filter from
159     # there.
160     changesets = @conn
161                  .exec("select id, created_at, closed_at, num_changes from changesets where closed_at > ((now() at time zone 'utc') - '1 hour'::interval)")
162                  .map { |row| Changeset.new(row) }
163                  .select { |cs| cs.activity_between?(last_run, @now) }
164
165     # set for faster presence lookups by ID
166     cs_ids = Set.new(changesets.map(&:id))
167
168     # but also add any changesets which have new comments
169     new_ids = @conn
170               .exec("select distinct changeset_id from changeset_comments where created_at >= '#{last_run}' and created_at < '#{@now}' and visible")
171               .map { |row| row["changeset_id"].to_i }
172               .select { |c_id| !cs_ids.include?(c_id) }
173
174     new_ids.each do |id|
175       @conn
176         .exec("select id, created_at, closed_at, num_changes from changesets where id=#{id}")
177         .map { |row| Changeset.new(row) }
178         .each { |cs| changesets << cs }
179     end
180
181     changesets.sort_by(&:id)
182   end
183
184   # creates an XML file containing the changeset information from the
185   # list of changesets output by open_changesets.
186   def changeset_dump(changesets)
187     doc = XML::Document.new
188     doc.root = XML::Node.new("osm")
189     { "version" => "0.6",
190       "generator" => "replicate_changesets.rb",
191       "copyright" => "OpenStreetMap and contributors",
192       "attribution" => "http://www.openstreetmap.org/copyright",
193       "license" => "http://opendatacommons.org/licenses/odbl/1-0/" }
194       .each { |k, v| doc.root[k] = v }
195
196     builder = ChangesetBuilder.new(@now, @conn)
197     changesets.each do |cs|
198       doc.root << builder.changeset_xml(cs)
199     end
200
201     doc.to_s
202   end
203
204   # saves new state (including the changeset dump xml)
205   def save!
206     File.open(@config["state_file"], "r") do |fl|
207       fl.flock(File::LOCK_EX)
208
209       sequence = (@state.key?("sequence") ? @state["sequence"] + 1 : 0)
210       data_stem = @config["data_dir"] + format("/%03d/%03d/%03d", sequence / 1000000, (sequence / 1000) % 1000, (sequence % 1000))
211       data_file = data_stem + ".osm.gz"
212       data_state_file = data_stem + ".state.txt"
213       tmp_state = @config["state_file"] + ".tmp"
214       tmp_data = data_file + ".tmp"
215       # try and write the files to tmp locations and then
216       # move them into place later, to avoid in-progress
217       # clashes, or people seeing incomplete files.
218       begin
219         FileUtils.mkdir_p(File.dirname(data_file))
220         Zlib::GzipWriter.open(tmp_data) do |fh|
221           fh.write(changeset_dump(open_changesets))
222         end
223         @state["sequence"] = sequence
224         File.open(tmp_state, "w") do |fh|
225           fh.write(YAML.dump(@state))
226         end
227
228         # fsync the files in their old locations.
229         fsync(tmp_data)
230         fsync(tmp_state)
231
232         # sync the directory as well, to ensure that the file is reachable
233         # from the dirent and has been updated to account for any allocations.
234         fdirsync(File.dirname(tmp_data))
235         fdirsync(File.dirname(tmp_state))
236
237         # sanity check: the files we're moving into place
238         # should be non-empty.
239         raise "Temporary gzip file should exist, but doesn't." unless File.exist?(tmp_data)
240         raise "Temporary state file should exist, but doesn't." unless File.exist?(tmp_state)
241         raise "Temporary gzip file should be non-empty, but isn't." if File.zero?(tmp_data)
242         raise "Temporary state file should be non-empty, but isn't." if File.zero?(tmp_state)
243
244         FileUtils.mv(tmp_data, data_file)
245         FileUtils.cp(tmp_state, @config["state_file"])
246         FileUtils.mv(tmp_state, data_state_file)
247
248         # fsync the files in their new locations, in case the inodes have
249         # changed in the move / copy.
250         fsync(data_fie)
251         fsync(@config["state_file"])
252         fsync(data_state_file)
253
254         # sync the directory as well, to ensure that the file is reachable
255         # from the dirent and has been updated to account for any allocations.
256         fdirsync(File.dirname(data_file))
257         fdirsync(File.dirname(@config["state_file"]))
258
259         fl.flock(File::LOCK_UN)
260
261       rescue
262         STDERR.puts("Error! Couldn't update state.")
263         fl.flock(File::LOCK_UN)
264         raise
265       end
266     end
267   end
268 end
269
270 begin
271   rep = Replicator.new(ARGV[0])
272   rep.save!
273 rescue StandardError => e
274   STDERR.puts "ERROR: #{e.message}"
275   exit 1
276 end