retry if couchdb command times out.
[couchdb_scripts.git] / ruby / destroy-all-test-users
1 #!/usr/bin/ruby
2
3 #
4 # Clean up cruft left over by bad tests.
5 #
6 # Removes all 'test_user_x' users from the users db, along with the
7 # corresponding indentities and storage db.
8 #
9
10 require 'couchrest'
11
12 users_db_name = 'users'
13 #user_db_name = 'tmp_users'
14 identities_db_name = 'identities'
15
16 netrc = File.read('/root/.netrc').split(' ')
17 auth = "%{username}:%{password}@" % {username: netrc[3], password: netrc[5]}
18 server = CouchRest::Server.new("http://#{auth}localhost:5984")
19 users_db = server.database(users_db_name)
20 identities_db = server.database(identities_db_name)
21
22 records = users_db.view('User/by_login', :reduce => false, :startkey => 'test_user_', :endkey => 'test_user_'+"\u{fff}")['rows']
23 records.each do |record|
24   user_id = record['id']
25   username = record['key']
26   tries = 0
27   begin
28     begin
29       doc = users_db.get(user_id)
30       users_db.delete_doc(doc)
31       puts "deleted #{users_db.name}/#{user_id} (#{username})"
32     rescue RestClient::ResourceNotFound
33     end
34     begin
35       storage_db = server.database("user-" + user_id)
36       storage_db.delete!
37       puts "  deleted #{storage_db.name}"
38     rescue RestClient::ResourceNotFound
39     end
40     identities_db.view('Identity/by_user_id', :reduce => false, :startkey => user_id, :endkey => user_id)['rows'].each do |row|
41       begin
42         doc = identities_db.get(row['id'])
43         identities_db.delete_doc(doc)
44         puts "  deleted #{identities_db.name}/#{row['id']}"
45       rescue RestClient::ResourceNotFound
46       end
47     end
48   rescue RestClient::RequestTimeout
49     tries += 1
50     if tries < 10
51       puts "Got timeout, retrying"
52       sleep 10
53       retry
54     else
55       puts "Retry limit reached"
56       exit(1)
57     end
58   end
59 end
60
61 users_db.compact!
62 identities_db.compact!
63
64 puts "DONE"