Merge branch '20943-trashed-role-groups' refs #20943
[arvados.git] / services / api / config / arvados_config.rb
1 # Copyright (C) The Arvados Authors. All rights reserved.
2 #
3 # SPDX-License-Identifier: AGPL-3.0
4
5 #
6 # Load Arvados configuration from /etc/arvados/config.yml, using defaults
7 # from config.default.yml
8 #
9 # Existing application.yml is migrated into the new config structure.
10 # Keys in the legacy application.yml take precedence.
11 #
12 # Use "bundle exec config:dump" to get the complete active configuration
13 #
14 # Use "bundle exec config:migrate" to migrate application.yml and
15 # database.yml to config.yml.  After adding the output of
16 # config:migrate to /etc/arvados/config.yml, you will be able to
17 # delete application.yml and database.yml.
18
19 require "cgi"
20 require 'config_loader'
21 require 'open3'
22
23 begin
24   # If secret_token.rb exists here, we need to load it first.
25   require_relative 'secret_token.rb'
26 rescue LoadError
27   # Normally secret_token.rb is missing and the secret token is
28   # configured by application.yml (i.e., here!) instead.
29 end
30
31 # Load the defaults, used by config:migrate and fallback loading
32 # legacy application.yml
33 load_time = Time.now.utc
34 defaultYAML, stderr, status = Open3.capture3("arvados-server", "config-dump", "-config=-", "-skip-legacy", stdin_data: "Clusters: {xxxxx: {}}")
35 if !status.success?
36   puts stderr
37   raise "error loading config: #{status}"
38 end
39 confs = YAML.safe_load(defaultYAML)
40 clusterID, clusterConfig = confs["Clusters"].first
41 $arvados_config_defaults = clusterConfig
42 $arvados_config_defaults["ClusterID"] = clusterID
43 $arvados_config_defaults["SourceTimestamp"] = Time.rfc3339(confs["SourceTimestamp"])
44 $arvados_config_defaults["SourceSHA256"] = confs["SourceSHA256"]
45
46 if ENV["ARVADOS_CONFIG"] == "none"
47   # Don't load config. This magic value is set by packaging scripts so
48   # they can run "rake assets:precompile" without a real config.
49   $arvados_config_global = $arvados_config_defaults.deep_dup
50 else
51   # Load the global config file
52   Open3.popen2("arvados-server", "config-dump", "-skip-legacy") do |stdin, stdout, status_thread|
53     confs = YAML.safe_load(stdout)
54     if confs && !confs.empty?
55       # config-dump merges defaults with user configuration, so every
56       # key should be set.
57       clusterID, clusterConfig = confs["Clusters"].first
58       $arvados_config_global = clusterConfig
59       $arvados_config_global["ClusterID"] = clusterID
60       $arvados_config_global["SourceTimestamp"] = Time.rfc3339(confs["SourceTimestamp"])
61       $arvados_config_global["SourceSHA256"] = confs["SourceSHA256"]
62     else
63       # config-dump failed, assume we will be loading from legacy
64       # application.yml, initialize with defaults.
65       $arvados_config_global = $arvados_config_defaults.deep_dup
66     end
67   end
68 end
69
70 # Now make a copy
71 $arvados_config = $arvados_config_global.deep_dup
72 $arvados_config["LoadTimestamp"] = load_time
73
74 def arrayToHash cfg, k, v
75   val = {}
76   v.each do |entry|
77     val[entry.to_s] = {}
78   end
79   ConfigLoader.set_cfg cfg, k, val
80 end
81
82 # Declare all our configuration items.
83 arvcfg = ConfigLoader.new
84 arvcfg.declare_config "ClusterID", NonemptyString, :uuid_prefix
85 arvcfg.declare_config "ManagementToken", String, :ManagementToken
86 arvcfg.declare_config "SystemRootToken", String
87 arvcfg.declare_config "API.DisabledAPIs", Hash, :disable_api_methods, ->(cfg, k, v) { arrayToHash cfg, "API.DisabledAPIs", v }
88 arvcfg.declare_config "API.MaxRequestSize", Integer, :max_request_size
89 arvcfg.declare_config "API.MaxIndexDatabaseRead", Integer, :max_index_database_read
90 arvcfg.declare_config "API.MaxItemsPerResponse", Integer, :max_items_per_response
91 arvcfg.declare_config "API.MaxTokenLifetime", ActiveSupport::Duration
92 arvcfg.declare_config "API.RequestTimeout", ActiveSupport::Duration
93 arvcfg.declare_config "API.AsyncPermissionsUpdateInterval", ActiveSupport::Duration, :async_permissions_update_interval
94 arvcfg.declare_config "Users.AutoSetupNewUsers", Boolean, :auto_setup_new_users
95 arvcfg.declare_config "Users.AutoSetupNewUsersWithVmUUID", String, :auto_setup_new_users_with_vm_uuid
96 arvcfg.declare_config "Users.AutoSetupUsernameBlacklist", Hash, :auto_setup_name_blacklist, ->(cfg, k, v) { arrayToHash cfg, "Users.AutoSetupUsernameBlacklist", v }
97 arvcfg.declare_config "Users.NewUsersAreActive", Boolean, :new_users_are_active
98 arvcfg.declare_config "Users.AutoAdminUserWithEmail", String, :auto_admin_user
99 arvcfg.declare_config "Users.AutoAdminFirstUser", Boolean, :auto_admin_first_user
100 arvcfg.declare_config "Users.UserProfileNotificationAddress", String, :user_profile_notification_address
101 arvcfg.declare_config "Users.AdminNotifierEmailFrom", String, :admin_notifier_email_from
102 arvcfg.declare_config "Users.EmailSubjectPrefix", String, :email_subject_prefix
103 arvcfg.declare_config "Users.UserNotifierEmailFrom", String, :user_notifier_email_from
104 arvcfg.declare_config "Users.UserNotifierEmailBcc", Hash
105 arvcfg.declare_config "Users.NewUserNotificationRecipients", Hash, :new_user_notification_recipients, ->(cfg, k, v) { arrayToHash cfg, "Users.NewUserNotificationRecipients", v }
106 arvcfg.declare_config "Users.NewInactiveUserNotificationRecipients", Hash, :new_inactive_user_notification_recipients, method(:arrayToHash)
107 arvcfg.declare_config "Users.CanCreateRoleGroups", Boolean
108 arvcfg.declare_config "Users.RoleGroupsVisibleToAll", Boolean
109 arvcfg.declare_config "Login.LoginCluster", String
110 arvcfg.declare_config "Login.TrustedClients", Hash
111 arvcfg.declare_config "Login.RemoteTokenRefresh", ActiveSupport::Duration
112 arvcfg.declare_config "Login.TokenLifetime", ActiveSupport::Duration
113 arvcfg.declare_config "TLS.Insecure", Boolean, :sso_insecure
114 arvcfg.declare_config "AuditLogs.MaxAge", ActiveSupport::Duration, :max_audit_log_age
115 arvcfg.declare_config "AuditLogs.MaxDeleteBatch", Integer, :max_audit_log_delete_batch
116 arvcfg.declare_config "AuditLogs.UnloggedAttributes", Hash, :unlogged_attributes, ->(cfg, k, v) { arrayToHash cfg, "AuditLogs.UnloggedAttributes", v }
117 arvcfg.declare_config "SystemLogs.MaxRequestLogParamsSize", Integer, :max_request_log_params_size
118 arvcfg.declare_config "Collections.DefaultReplication", Integer, :default_collection_replication
119 arvcfg.declare_config "Collections.DefaultTrashLifetime", ActiveSupport::Duration, :default_trash_lifetime
120 arvcfg.declare_config "Collections.CollectionVersioning", Boolean, :collection_versioning
121 arvcfg.declare_config "Collections.PreserveVersionIfIdle", ActiveSupport::Duration, :preserve_version_if_idle
122 arvcfg.declare_config "Collections.TrashSweepInterval", ActiveSupport::Duration, :trash_sweep_interval
123 arvcfg.declare_config "Collections.BlobSigningKey", String, :blob_signing_key
124 arvcfg.declare_config "Collections.BlobSigningTTL", ActiveSupport::Duration, :blob_signature_ttl
125 arvcfg.declare_config "Collections.BlobSigning", Boolean, :permit_create_collection_with_unsigned_manifest, ->(cfg, k, v) { ConfigLoader.set_cfg cfg, "Collections.BlobSigning", !v }
126 arvcfg.declare_config "Collections.ForwardSlashNameSubstitution", String
127 arvcfg.declare_config "Containers.SupportedDockerImageFormats", Hash, :docker_image_formats, ->(cfg, k, v) { arrayToHash cfg, "Containers.SupportedDockerImageFormats", v }
128 arvcfg.declare_config "Containers.LogReuseDecisions", Boolean, :log_reuse_decisions
129 arvcfg.declare_config "Containers.DefaultKeepCacheRAM", Integer, :container_default_keep_cache_ram
130 arvcfg.declare_config "Containers.MaxDispatchAttempts", Integer, :max_container_dispatch_attempts
131 arvcfg.declare_config "Containers.MaxRetryAttempts", Integer, :container_count_max
132 arvcfg.declare_config "Containers.AlwaysUsePreemptibleInstances", Boolean, :preemptible_instances
133 arvcfg.declare_config "Containers.Logging.LogUpdatePeriod", ActiveSupport::Duration, :crunch_log_update_period
134 arvcfg.declare_config "Containers.Logging.LogUpdateSize", Integer, :crunch_log_update_size
135 arvcfg.declare_config "Services.Controller.ExternalURL", URI
136 arvcfg.declare_config "Services.Workbench1.ExternalURL", URI, :workbench_address
137 arvcfg.declare_config "Services.Websocket.ExternalURL", URI, :websocket_address
138 arvcfg.declare_config "Services.WebDAV.ExternalURL", URI, :keep_web_service_url
139 arvcfg.declare_config "RemoteClusters", Hash, :remote_hosts, ->(cfg, k, v) {
140   h = if cfg["RemoteClusters"] then
141         cfg["RemoteClusters"].deep_dup
142       else
143         {}
144       end
145   v.each do |clusterid, host|
146     if h[clusterid].nil?
147       h[clusterid] = {
148         "Host" => host,
149         "Proxy" => true,
150         "Scheme" => "https",
151         "Insecure" => false,
152         "ActivateUsers" => false
153       }
154     end
155   end
156   ConfigLoader.set_cfg cfg, "RemoteClusters", h
157 }
158 arvcfg.declare_config "RemoteClusters.*.Proxy", Boolean, :remote_hosts_via_dns
159 arvcfg.declare_config "StorageClasses", Hash
160
161 dbcfg = ConfigLoader.new
162
163 dbcfg.declare_config "PostgreSQL.ConnectionPool", Integer, :pool
164 dbcfg.declare_config "PostgreSQL.Connection.host", String, :host
165 dbcfg.declare_config "PostgreSQL.Connection.port", String, :port
166 dbcfg.declare_config "PostgreSQL.Connection.user", String, :username
167 dbcfg.declare_config "PostgreSQL.Connection.password", String, :password
168 dbcfg.declare_config "PostgreSQL.Connection.dbname", String, :database
169 dbcfg.declare_config "PostgreSQL.Connection.template", String, :template
170 dbcfg.declare_config "PostgreSQL.Connection.encoding", String, :encoding
171 dbcfg.declare_config "PostgreSQL.Connection.collation", String, :collation
172
173 application_config = {}
174 %w(application.default application).each do |cfgfile|
175   path = "#{::Rails.root.to_s}/config/#{cfgfile}.yml"
176   confs = ConfigLoader.load(path, erb: true)
177   # Ignore empty YAML file:
178   next if confs == nil
179   application_config.deep_merge!(confs['common'] || {})
180   application_config.deep_merge!(confs[::Rails.env.to_s] || {})
181 end
182
183 db_config = {}
184 path = "#{::Rails.root.to_s}/config/database.yml"
185 if !ENV['ARVADOS_CONFIG_NOLEGACY'] && File.exist?(path)
186   db_config = ConfigLoader.load(path, erb: true)
187 end
188
189 $remaining_config = arvcfg.migrate_config(application_config, $arvados_config)
190 dbcfg.migrate_config(db_config[::Rails.env.to_s] || {}, $arvados_config)
191
192 if application_config[:auto_activate_users_from]
193   application_config[:auto_activate_users_from].each do |cluster|
194     if $arvados_config.RemoteClusters[cluster]
195       $arvados_config.RemoteClusters[cluster]["ActivateUsers"] = true
196     end
197   end
198 end
199
200 if application_config[:host] || application_config[:port] || application_config[:scheme]
201   if !application_config[:host] || application_config[:host].empty?
202     raise "Must set 'host' when setting 'port' or 'scheme'"
203   end
204   $arvados_config.Services["Controller"]["ExternalURL"] = URI((application_config[:scheme] || "https")+"://"+application_config[:host]+
205                                                               (if application_config[:port] then ":#{application_config[:port]}" else "" end))
206 end
207
208 # Checks for wrongly typed configuration items, coerces properties
209 # into correct types (such as Duration), and optionally raise error
210 # for essential configuration that can't be empty.
211 arvcfg.coercion_and_check $arvados_config_defaults, check_nonempty: false
212 arvcfg.coercion_and_check $arvados_config_global, check_nonempty: false
213 arvcfg.coercion_and_check $arvados_config, check_nonempty: true
214 dbcfg.coercion_and_check $arvados_config, check_nonempty: true
215
216 # * $arvados_config_defaults is the defaults
217 # * $arvados_config_global is $arvados_config_defaults merged with the contents of /etc/arvados/config.yml
218 # These are used by the rake config: tasks
219 #
220 # * $arvados_config is $arvados_config_global merged with the migrated contents of application.yml
221 # This is what actually gets copied into the Rails configuration object.
222
223 if $arvados_config["Collections"]["DefaultTrashLifetime"] < 86400.seconds then
224   raise "default_trash_lifetime is %d, must be at least 86400" % Rails.configuration.Collections.DefaultTrashLifetime
225 end
226
227 default_storage_classes = []
228 $arvados_config["StorageClasses"].each do |cls, cfg|
229   if cfg["Default"]
230     default_storage_classes << cls
231   end
232 end
233 if default_storage_classes.length == 0
234   default_storage_classes = ["default"]
235 end
236 $arvados_config["DefaultStorageClasses"] = default_storage_classes.sort
237
238 #
239 # Special case for test database where there's no database.yml,
240 # because the Arvados config.yml doesn't have a concept of multiple
241 # rails environments.
242 #
243 if ::Rails.env.to_s == "test" && db_config["test"].nil?
244   $arvados_config["PostgreSQL"]["Connection"]["dbname"] = "arvados_test"
245 end
246 if ::Rails.env.to_s == "test"
247   # Use template0 when creating a new database. Avoids
248   # character-encoding/collation problems.
249   $arvados_config["PostgreSQL"]["Connection"]["template"] = "template0"
250   # Some test cases depend on en_US.UTF-8 collation.
251   $arvados_config["PostgreSQL"]["Connection"]["collation"] = "en_US.UTF-8"
252 end
253
254 if ENV["ARVADOS_CONFIG"] == "none"
255   # We need the postgresql connection URI to be valid, even if we
256   # don't use it.
257   $arvados_config["PostgreSQL"]["Connection"]["host"] = "localhost"
258   $arvados_config["PostgreSQL"]["Connection"]["user"] = "x"
259   $arvados_config["PostgreSQL"]["Connection"]["password"] = "x"
260   $arvados_config["PostgreSQL"]["Connection"]["dbname"] = "x"
261 end
262
263 if $arvados_config["PostgreSQL"]["Connection"]["password"].empty?
264   raise "Database password is empty, PostgreSQL section is: #{$arvados_config["PostgreSQL"]}"
265 end
266
267 dbhost = $arvados_config["PostgreSQL"]["Connection"]["host"]
268 if $arvados_config["PostgreSQL"]["Connection"]["port"] != 0
269   dbhost += ":#{$arvados_config["PostgreSQL"]["Connection"]["port"]}"
270 end
271
272 #
273 # If DATABASE_URL is set, then ActiveRecord won't error out if database.yml doesn't exist.
274 #
275 # For config migration, we've previously populated the PostgreSQL
276 # section of the config from database.yml
277 #
278 database_url = "postgresql://#{CGI.escape $arvados_config["PostgreSQL"]["Connection"]["user"]}:"+
279                       "#{CGI.escape $arvados_config["PostgreSQL"]["Connection"]["password"]}@"+
280                       "#{dbhost}/#{CGI.escape $arvados_config["PostgreSQL"]["Connection"]["dbname"]}?"+
281                       "template=#{$arvados_config["PostgreSQL"]["Connection"]["template"]}&"+
282                       "encoding=#{$arvados_config["PostgreSQL"]["Connection"]["client_encoding"]}&"+
283                       "collation=#{$arvados_config["PostgreSQL"]["Connection"]["collation"]}&"+
284                       "pool=#{$arvados_config["PostgreSQL"]["ConnectionPool"]}"
285
286 ENV["DATABASE_URL"] = database_url
287
288 Server::Application.configure do
289   # Copy into the Rails config object.  This also turns Hash into
290   # OrderedOptions so that application code can use
291   # Rails.configuration.API.Blah instead of
292   # Rails.configuration.API["Blah"]
293   ConfigLoader.copy_into_config $arvados_config, config
294   ConfigLoader.copy_into_config $remaining_config, config
295
296   # We don't rely on cookies for authentication, so instead of
297   # requiring a signing key in config, we assign a new random one at
298   # startup.
299   secrets.secret_key_base = rand(1<<255).to_s(36)
300 end