]> git.openstreetmap.org Git - chef.git/blob - cookbooks/planet/files/default/replication-bin/replicate-changesets
move nominatim traffic back to poldi/pummelzacken
[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 # changeset class keeps some information about changesets downloaded from the
20 # database - enough to let us know which changesets are closed/open & recently
21 # closed.
22 class Changeset
23   attr_reader :id, :created_at, :closed_at, :num_changes
24
25   def initialize(row)
26     @id = row["id"].to_i
27     @created_at = Time.parse(row["created_at"])
28     @closed_at = Time.parse(row["closed_at"])
29     @num_changes = row["num_changes"].to_i
30   end
31
32   def closed?(t)
33     (@closed_at < t) || (@num_changes >= CHANGES_LIMIT)
34   end
35
36   def open?(t)
37     !closed?(t)
38   end
39
40   def activity_between?(t1, t2)
41     ((@closed_at >= t1) && (@closed_at < t2)) || ((@created_at >= t1) && (@created_at < t2))
42   end
43 end
44
45 ##
46 # builds an XML representation of a changeset from the database
47 class ChangesetBuilder
48   def initialize(now, conn)
49     @now = now
50     @conn = conn
51   end
52
53   def changeset_xml(cs)
54     xml = XML::Node.new("changeset")
55     xml["id"] = cs.id.to_s
56     xml["created_at"] = cs.created_at.getutc.xmlschema
57     xml["closed_at"] = cs.closed_at.getutc.xmlschema if cs.closed?(@now)
58     xml["open"] = cs.open?(@now).to_s
59     xml["num_changes"] = cs.num_changes.to_s
60
61     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}")
62     xml["user"] = res[0]["display_name"]
63     xml["uid"] = res[0]["id"]
64
65     unless res[0]["min_lat"].nil? ||
66            res[0]["max_lat"].nil? ||
67            res[0]["min_lon"].nil? ||
68            res[0]["max_lon"].nil?
69       xml["min_lat"] = (res[0]["min_lat"].to_f / GEO_SCALE).to_s
70       xml["max_lat"] = (res[0]["max_lat"].to_f / GEO_SCALE).to_s
71       xml["min_lon"] = (res[0]["min_lon"].to_f / GEO_SCALE).to_s
72       xml["max_lon"] = (res[0]["max_lon"].to_f / GEO_SCALE).to_s
73     end
74
75     add_tags(xml, cs)
76     add_comments(xml, cs)
77
78     xml
79   end
80
81   def add_tags(xml, cs)
82     res = @conn.exec("select k, v from changeset_tags where changeset_id=#{cs.id}")
83     res.each do |row|
84       tag = XML::Node.new("tag")
85       tag["k"] = row["k"]
86       tag["v"] = row["v"]
87       xml << tag
88     end
89   end
90
91   def add_comments(xml, cs)
92     # grab the visible changeset comments as well
93     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")
94     xml["comments_count"] = res.num_tuples.to_s
95
96     # early return if there aren't any comments
97     return unless res.num_tuples > 0
98
99     discussion = XML::Node.new("discussion")
100     res.each do |row|
101       comment = XML::Node.new("comment")
102       comment["uid"] = row["author_id"]
103       comment["user"] = row["author"]
104       comment["date"] = Time.parse(row["created_at"]).getutc.xmlschema
105       text = XML::Node.new("text")
106       text.content = row["body"]
107       comment << text
108       discussion << comment
109     end
110     xml << discussion
111   end
112 end
113
114 ##
115 # state and connections associated with getting changeset data
116 # replicated to a file.
117 class Replicator
118   def initialize(config)
119     @config = YAML.load(File.read(config))
120     @state = YAML.load(File.read(@config["state_file"]))
121     @conn = PGconn.connect(@config["db"])
122     @now = Time.now.getutc
123   end
124
125   def open_changesets
126     last_run = @state["last_run"]
127     last_run = (@now - 60) if last_run.nil?
128     @state["last_run"] = @now
129     # pretty much all operations on a changeset will modify its closed_at
130     # time (see rails_port's changeset model). so it is probably enough
131     # for us to look at anything that was closed recently, and filter from
132     # there.
133     changesets = @conn
134                  .exec("select id, created_at, closed_at, num_changes from changesets where closed_at > ((now() at time zone 'utc') - '1 hour'::interval)")
135                  .map { |row| Changeset.new(row) }
136                  .select { |cs| cs.activity_between?(last_run, @now) }
137
138     # set for faster presence lookups by ID
139     cs_ids = Set.new(changesets.map(&:id))
140
141     # but also add any changesets which have new comments
142     new_ids = @conn
143               .exec("select distinct changeset_id from changeset_comments where created_at >= '#{last_run}' and created_at < '#{@now}' and visible")
144               .map { |row| row["changeset_id"].to_i }
145               .select { |c_id| !cs_ids.include?(c_id) }
146
147     new_ids.each do |id|
148       @conn
149         .exec("select id, created_at, closed_at, num_changes from changesets where id=#{id}")
150         .map { |row| Changeset.new(row) }
151         .each { |cs| changesets << cs }
152     end
153
154     changesets.sort_by(&:id)
155   end
156
157   # creates an XML file containing the changeset information from the
158   # list of changesets output by open_changesets.
159   def changeset_dump(changesets)
160     doc = XML::Document.new
161     doc.root = XML::Node.new("osm")
162     { "version" => "0.6",
163       "generator" => "replicate_changesets.rb",
164       "copyright" => "OpenStreetMap and contributors",
165       "attribution" => "http://www.openstreetmap.org/copyright",
166       "license" => "http://opendatacommons.org/licenses/odbl/1-0/" }
167       .each { |k, v| doc.root[k] = v }
168
169     builder = ChangesetBuilder.new(@now, @conn)
170     changesets.each do |cs|
171       doc.root << builder.changeset_xml(cs)
172     end
173
174     doc.to_s
175   end
176
177   # saves new state (including the changeset dump xml)
178   def save!
179     File.open(@config["state_file"], "r") do |fl|
180       fl.flock(File::LOCK_EX)
181
182       sequence = (@state.key?("sequence") ? @state["sequence"] + 1 : 0)
183       data_file = @config["data_dir"] + format("/%03d/%03d/%03d.osm.gz", sequence / 1000000, (sequence / 1000) % 1000, (sequence % 1000))
184       tmp_state = @config["state_file"] + ".tmp"
185       tmp_data = "/tmp/changeset_data.osm.tmp"
186       # try and write the files to tmp locations and then
187       # move them into place later, to avoid in-progress
188       # clashes, or people seeing incomplete files.
189       begin
190         FileUtils.mkdir_p(File.dirname(data_file))
191         Zlib::GzipWriter.open(tmp_data) do |fh|
192           fh.write(changeset_dump(open_changesets))
193         end
194         @state["sequence"] = sequence
195         File.open(tmp_state, "w") do |fh|
196           fh.write(YAML.dump(@state))
197         end
198         FileUtils.mv(tmp_data, data_file)
199         FileUtils.mv(tmp_state, @config["state_file"])
200         fl.flock(File::LOCK_UN)
201
202       rescue
203         STDERR.puts("Error! Couldn't update state.")
204         fl.flock(File::LOCK_UN)
205         raise
206       end
207     end
208   end
209 end
210
211 rep = Replicator.new(ARGV[0])
212 rep.save!