12 # after this many changes, a changeset will be closed
15 # this is the scale factor for lat/lon values stored as integers in the database
19 # replace characters which cannot be represented in XML 1.0.
21 str.gsub(/[\x00-\x08\x0b\x0c\x0e-\x1f]/, "?")
25 # changeset class keeps some information about changesets downloaded from the
26 # database - enough to let us know which changesets are closed/open & recently
29 attr_reader :id, :created_at, :closed_at, :num_changes
33 @created_at = Time.parse(row["created_at"])
34 @closed_at = Time.parse(row["closed_at"])
35 @num_changes = row["num_changes"].to_i
39 (@closed_at < t) || (@num_changes >= CHANGES_LIMIT)
46 def activity_between?(t1, t2)
47 ((@closed_at >= t1) && (@closed_at < t2)) || ((@created_at >= t1) && (@created_at < t2))
52 # builds an XML representation of a changeset from the database
53 class ChangesetBuilder
54 def initialize(now, conn)
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
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"]
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
88 res = @conn.exec("select k, v from changeset_tags where changeset_id=#{cs.id}")
90 tag = XML::Node.new("tag")
91 tag["k"] = xml_sanitize(row["k"])
92 tag["v"] = xml_sanitize(row["v"])
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
102 # early return if there aren't any comments
103 return unless res.num_tuples.positive?
105 discussion = XML::Node.new("discussion")
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"])
114 discussion << comment
121 # sync a file to guarantee it's on disk
123 File.open(f, &:fsync)
127 # sync a directory to guarantee it's on disk. have to recurse to the root
128 # to guarantee sync for newly created directories.
137 # state and connections associated with getting changeset data
138 # replicated to a file.
140 def initialize(config)
141 @config = YAML.safe_load(File.read(config))
142 @state = YAML.safe_load(File.read(@config["state_file"]), [Time])
143 @conn = PG::Connection.connect(@config["db"])
144 # get current time from the database rather than the current system
145 @now = @conn.exec("select now() as now").map { |row| Time.parse(row["now"]) }[0]
149 last_run = @state["last_run"]
150 last_run = (@now - 60) if last_run.nil?
151 # pretty much all operations on a changeset will modify its closed_at
152 # time (see rails_port's changeset model). so it is probably enough
153 # for us to look at anything that was closed recently, and filter from
156 .exec("select id, created_at, closed_at, num_changes from changesets where closed_at > ((now() at time zone 'utc') - '1 hour'::interval)")
157 .map { |row| Changeset.new(row) }
158 .select { |cs| cs.activity_between?(last_run, @now) }
160 # set for faster presence lookups by ID
161 cs_ids = Set.new(changesets.map(&:id))
163 # but also add any changesets which have new comments
165 .exec("select distinct changeset_id from changeset_comments where created_at >= '#{last_run}' and created_at < '#{@now}' and visible")
166 .map { |row| row["changeset_id"].to_i }
167 .reject { |c_id| cs_ids.include?(c_id) }
171 .exec("select id, created_at, closed_at, num_changes from changesets where id=#{id}")
172 .map { |row| Changeset.new(row) }
173 .each { |cs| changesets << cs }
176 changesets.sort_by(&:id)
179 # creates an XML file containing the changeset information from the
180 # list of changesets output by open_changesets.
181 def changeset_dump(changesets)
182 doc = XML::Document.new
183 doc.root = XML::Node.new("osm")
184 { "version" => "0.6",
185 "generator" => "replicate_changesets.rb",
186 "copyright" => "OpenStreetMap and contributors",
187 "attribution" => "https://www.openstreetmap.org/copyright",
188 "license" => "https://opendatacommons.org/licenses/odbl/1-0/" }
189 .each { |k, v| doc.root[k] = v }
191 builder = ChangesetBuilder.new(@now, @conn)
192 changesets.each do |cs|
193 doc.root << builder.changeset_xml(cs)
200 @state.key?("sequence") ? @state["sequence"] + 1 : 0
204 @config["data_dir"] + format("/%03d/%03d/%03d", sequence / 1000000, (sequence / 1000) % 1000, (sequence % 1000))
208 @config["s3_dir"] + format("/%03d/%03d/%03d", sequence / 1000000, (sequence / 1000) % 1000, (sequence % 1000))
211 def write_tmp_files!(changesets)
212 data_file = data_stem + ".osm.gz"
213 tmp_state = @config["state_file"] + ".tmp"
214 tmp_data = data_file + ".tmp"
216 FileUtils.mkdir_p(File.dirname(data_file))
217 Zlib::GzipWriter.open(tmp_data) do |fh|
218 fh.write(changeset_dump(changesets))
220 File.write(tmp_state, YAML.dump(@state))
222 # fsync the files in their old locations.
226 # sync the directory as well, to ensure that the file is reachable
227 # from the dirent and has been updated to account for any allocations.
228 fdirsync(File.dirname(tmp_data))
229 fdirsync(File.dirname(tmp_state))
231 # sanity check: the files we're moving into place
232 # should be non-empty.
233 raise "Temporary gzip file should exist, but doesn't." unless File.exist?(tmp_data)
234 raise "Temporary state file should exist, but doesn't." unless File.exist?(tmp_state)
235 raise "Temporary gzip file should be non-empty, but isn't." if File.zero?(tmp_data)
236 raise "Temporary state file should be non-empty, but isn't." if File.zero?(tmp_state)
239 def move_tmp_files_into_place!
240 data_file = data_stem + ".osm.gz"
241 data_state_file = data_stem + ".state.txt"
242 tmp_state = @config["state_file"] + ".tmp"
243 tmp_data = data_file + ".tmp"
245 FileUtils.mv(tmp_data, data_file)
246 FileUtils.cp(tmp_state, @config["state_file"])
247 FileUtils.mv(tmp_state, data_state_file)
249 # fsync the files in their new locations, in case the inodes have
250 # changed in the move / copy.
252 fsync(@config["state_file"])
253 fsync(data_state_file)
255 # sync the directory as well, to ensure that the file is reachable
256 # from the dirent and has been updated to account for any allocations.
257 fdirsync(File.dirname(data_file))
258 fdirsync(File.dirname(@config["state_file"]))
261 s3_file = s3_stem + ".osm.gz"
262 s3_state_file = s3_stem + ".state.txt"
263 s3_state_config_file = @config["s3_dir"] + "/state.yaml"
265 system("/opt/awscli/v2/current/bin/aws", "--profile=osm-pds-upload", "s3", "cp", "--storage-class=INTELLIGENT_TIERING", "--no-progress", data_file, s3_file)
266 system("/opt/awscli/v2/current/bin/aws", "--profile=osm-pds-upload", "s3", "cp", "--storage-class=INTELLIGENT_TIERING", "--no-progress", data_state_file, s3_state_file)
267 system("/opt/awscli/v2/current/bin/aws", "--profile=osm-pds-upload", "s3", "cp", "--storage-class=INTELLIGENT_TIERING", "--no-progress", @config["state_file"], s3_state_config_file)
271 # saves new state (including the changeset dump xml)
273 File.open(@config["lock_file"], File::RDWR | File::CREAT, 0o600) do |fl|
274 # take the lock in non-blocking mode. if this process doesn't get the lock
275 # then another will be run from cron shortly. this prevents a whole bunch
276 # of processes queueing on the lock and causing weirdness if/when they
277 # get woken up in a random order.
278 got_lock = fl.flock(File::LOCK_EX | File::LOCK_NB)
279 break unless got_lock
281 # try and write the files to tmp locations and then
282 # move them into place later, to avoid in-progress
283 # clashes, or people seeing incomplete files.
285 changesets = open_changesets
286 @state["sequence"] = sequence
287 @state["last_run"] = @now
289 write_tmp_files!(changesets)
291 move_tmp_files_into_place!
293 fl.flock(File::LOCK_UN)
295 warn "Error! Couldn't update state."
296 fl.flock(File::LOCK_UN)
304 rep = Replicator.new(ARGV[0])
306 rescue StandardError => e
307 warn "ERROR: #{e.message}"
308 e.backtrace.each do |frame|
309 warn "ERROR: #{frame}"