5416: Merge branch 'master' into 5416-arv-git-httpd
[arvados.git] / services / api / app / controllers / database_controller.rb
1 class DatabaseController < ApplicationController
2   skip_before_filter :find_object_by_uuid
3   skip_before_filter :render_404_if_no_object
4   before_filter :admin_required
5   def reset
6     raise ArvadosModel::PermissionDeniedError unless Rails.env == 'test'
7
8     # Sanity check: If someone has actually logged in here, this might
9     # not really be a throwaway database. Client test suites should
10     # use @example.com email addresses when creating user records, so
11     # we can tell they're not valuable.
12     user_uuids = User.
13       where('email is null or email not like ?', '%@example.com').
14       collect &:uuid
15     fixture_uuids =
16       YAML::load_file(File.expand_path('../../../test/fixtures/users.yml',
17                                        __FILE__)).
18       values.collect { |u| u['uuid'] }
19     unexpected_uuids = user_uuids - fixture_uuids
20     if unexpected_uuids.any?
21       logger.error("Running in test environment, but non-fixture users exist: " +
22                    "#{unexpected_uuids}")
23       raise ArvadosModel::PermissionDeniedError
24     end
25
26     require 'active_record/fixtures'
27
28     # What kinds of fixtures do we have?
29     fixturesets = Dir.glob(Rails.root.join('test', 'fixtures', '*.yml')).
30       collect { |yml| yml.match(/([^\/]*)\.yml$/)[1] }
31
32     table_names = '"' + ActiveRecord::Base.connection.tables.join('","') + '"'
33
34     attempts_left = 20
35     begin
36       ActiveRecord::Base.transaction do
37         # Avoid deadlock by locking all tables before doing anything
38         # drastic.
39         ActiveRecord::Base.connection.execute \
40         "LOCK TABLE #{table_names} IN ACCESS EXCLUSIVE MODE"
41
42         # Delete existing fixtures (and everything else) from fixture
43         # tables
44         fixturesets.each do |x|
45           x.classify.constantize.unscoped.delete_all
46         end
47
48         # create_fixtures() is a no-op for cached fixture sets, so
49         # uncache them all.
50         ActiveRecord::Fixtures.reset_cache
51         ActiveRecord::Fixtures.
52           create_fixtures(Rails.root.join('test', 'fixtures'), fixturesets)
53
54         # Dump cache of permissions etc.
55         Rails.cache.clear
56         ActiveRecord::Base.connection.clear_query_cache
57
58         # Reload database seeds
59         DatabaseSeeds.install
60       end
61     rescue ActiveRecord::StatementInvalid => e
62       if "#{e.inspect}" =~ /deadlock detected/i and (attempts_left -= 1) > 0
63         logger.info "Waiting for lock -- #{e.inspect}"
64         sleep 0.5
65         retry
66       end
67       raise
68     end
69
70     # Done.
71     send_json success: true
72   end
73 end