CWL spec -> CWL standards
[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 'config_loader'
20 require 'open3'
21
22 begin
23   # If secret_token.rb exists here, we need to load it first.
24   require_relative 'secret_token.rb'
25 rescue LoadError
26   # Normally secret_token.rb is missing and the secret token is
27   # configured by application.yml (i.e., here!) instead.
28 end
29
30 if (File.exist?(File.expand_path '../omniauth.rb', __FILE__) and
31     not defined? WARNED_OMNIAUTH_CONFIG)
32   Rails.logger.warn <<-EOS
33 DEPRECATED CONFIGURATION:
34  Please move your SSO provider config into config/application.yml
35  and delete config/initializers/omniauth.rb.
36 EOS
37   # Real values will be copied from globals by omniauth_init.rb. For
38   # now, assign some strings so the generic *.yml config loader
39   # doesn't overwrite them or complain that they're missing.
40   Rails.configuration.Login["ProviderAppID"] = 'xxx'
41   Rails.configuration.Login["ProviderAppSecret"] = 'xxx'
42   Rails.configuration.Services["SSO"]["ExternalURL"] = '//xxx'
43   WARNED_OMNIAUTH_CONFIG = true
44 end
45
46 # Load the defaults, used by config:migrate and fallback loading
47 # legacy application.yml
48 Open3.popen2("arvados-server", "config-dump", "-config=-", "-skip-legacy") do |stdin, stdout, status_thread|
49   stdin.write("Clusters: {xxxxx: {}}")
50   stdin.close
51   confs = YAML.load(stdout, deserialize_symbols: false)
52   clusterID, clusterConfig = confs["Clusters"].first
53   $arvados_config_defaults = clusterConfig
54   $arvados_config_defaults["ClusterID"] = clusterID
55 end
56
57 # Load the global config file
58 Open3.popen2("arvados-server", "config-dump", "-skip-legacy") do |stdin, stdout, status_thread|
59   confs = YAML.load(stdout, deserialize_symbols: false)
60   if confs && !confs.empty?
61     # config-dump merges defaults with user configuration, so every
62     # key should be set.
63     clusterID, clusterConfig = confs["Clusters"].first
64     $arvados_config_global = clusterConfig
65     $arvados_config_global["ClusterID"] = clusterID
66   else
67     # config-dump failed, assume we will be loading from legacy
68     # application.yml, initialize with defaults.
69     $arvados_config_global = $arvados_config_defaults.deep_dup
70   end
71 end
72
73 # Now make a copy
74 $arvados_config = $arvados_config_global.deep_dup
75
76 def arrayToHash cfg, k, v
77   val = {}
78   v.each do |entry|
79     val[entry.to_s] = {}
80   end
81   ConfigLoader.set_cfg cfg, k, val
82 end
83
84 # Declare all our configuration items.
85 arvcfg = ConfigLoader.new
86 arvcfg.declare_config "ClusterID", NonemptyString, :uuid_prefix
87 arvcfg.declare_config "ManagementToken", String, :ManagementToken
88 arvcfg.declare_config "SystemRootToken", String
89 arvcfg.declare_config "Git.Repositories", String, :git_repositories_dir
90 arvcfg.declare_config "API.DisabledAPIs", Hash, :disable_api_methods, ->(cfg, k, v) { arrayToHash cfg, "API.DisabledAPIs", v }
91 arvcfg.declare_config "API.MaxRequestSize", Integer, :max_request_size
92 arvcfg.declare_config "API.MaxIndexDatabaseRead", Integer, :max_index_database_read
93 arvcfg.declare_config "API.MaxItemsPerResponse", Integer, :max_items_per_response
94 arvcfg.declare_config "API.AsyncPermissionsUpdateInterval", ActiveSupport::Duration, :async_permissions_update_interval
95 arvcfg.declare_config "API.RailsSessionSecretToken", NonemptyString, :secret_token
96 arvcfg.declare_config "Users.AutoSetupNewUsers", Boolean, :auto_setup_new_users
97 arvcfg.declare_config "Users.AutoSetupNewUsersWithVmUUID", String, :auto_setup_new_users_with_vm_uuid
98 arvcfg.declare_config "Users.AutoSetupNewUsersWithRepository", Boolean, :auto_setup_new_users_with_repository
99 arvcfg.declare_config "Users.AutoSetupUsernameBlacklist", Hash, :auto_setup_name_blacklist, ->(cfg, k, v) { arrayToHash cfg, "Users.AutoSetupUsernameBlacklist", v }
100 arvcfg.declare_config "Users.NewUsersAreActive", Boolean, :new_users_are_active
101 arvcfg.declare_config "Users.AutoAdminUserWithEmail", String, :auto_admin_user
102 arvcfg.declare_config "Users.AutoAdminFirstUser", Boolean, :auto_admin_first_user
103 arvcfg.declare_config "Users.UserProfileNotificationAddress", String, :user_profile_notification_address
104 arvcfg.declare_config "Users.AdminNotifierEmailFrom", String, :admin_notifier_email_from
105 arvcfg.declare_config "Users.EmailSubjectPrefix", String, :email_subject_prefix
106 arvcfg.declare_config "Users.UserNotifierEmailFrom", String, :user_notifier_email_from
107 arvcfg.declare_config "Users.NewUserNotificationRecipients", Hash, :new_user_notification_recipients, ->(cfg, k, v) { arrayToHash cfg, "Users.NewUserNotificationRecipients", v }
108 arvcfg.declare_config "Users.NewInactiveUserNotificationRecipients", Hash, :new_inactive_user_notification_recipients, method(:arrayToHash)
109 arvcfg.declare_config "Login.ProviderAppSecret", String, :sso_app_secret
110 arvcfg.declare_config "Login.ProviderAppID", String, :sso_app_id
111 arvcfg.declare_config "Login.LoginCluster", String
112 arvcfg.declare_config "Login.RemoteTokenRefresh", ActiveSupport::Duration
113 arvcfg.declare_config "TLS.Insecure", Boolean, :sso_insecure
114 arvcfg.declare_config "Services.SSO.ExternalURL", String, :sso_provider_url
115 arvcfg.declare_config "AuditLogs.MaxAge", ActiveSupport::Duration, :max_audit_log_age
116 arvcfg.declare_config "AuditLogs.MaxDeleteBatch", Integer, :max_audit_log_delete_batch
117 arvcfg.declare_config "AuditLogs.UnloggedAttributes", Hash, :unlogged_attributes, ->(cfg, k, v) { arrayToHash cfg, "AuditLogs.UnloggedAttributes", v }
118 arvcfg.declare_config "SystemLogs.MaxRequestLogParamsSize", Integer, :max_request_log_params_size
119 arvcfg.declare_config "Collections.DefaultReplication", Integer, :default_collection_replication
120 arvcfg.declare_config "Collections.DefaultTrashLifetime", ActiveSupport::Duration, :default_trash_lifetime
121 arvcfg.declare_config "Collections.CollectionVersioning", Boolean, :collection_versioning
122 arvcfg.declare_config "Collections.PreserveVersionIfIdle", ActiveSupport::Duration, :preserve_version_if_idle
123 arvcfg.declare_config "Collections.TrashSweepInterval", ActiveSupport::Duration, :trash_sweep_interval
124 arvcfg.declare_config "Collections.BlobSigningKey", NonemptyString, :blob_signing_key
125 arvcfg.declare_config "Collections.BlobSigningTTL", ActiveSupport::Duration, :blob_signature_ttl
126 arvcfg.declare_config "Collections.BlobSigning", Boolean, :permit_create_collection_with_unsigned_manifest, ->(cfg, k, v) { ConfigLoader.set_cfg cfg, "Collections.BlobSigning", !v }
127 arvcfg.declare_config "Collections.ForwardSlashNameSubstitution", String
128 arvcfg.declare_config "Containers.SupportedDockerImageFormats", Hash, :docker_image_formats, ->(cfg, k, v) { arrayToHash cfg, "Containers.SupportedDockerImageFormats", v }
129 arvcfg.declare_config "Containers.LogReuseDecisions", Boolean, :log_reuse_decisions
130 arvcfg.declare_config "Containers.DefaultKeepCacheRAM", Integer, :container_default_keep_cache_ram
131 arvcfg.declare_config "Containers.MaxDispatchAttempts", Integer, :max_container_dispatch_attempts
132 arvcfg.declare_config "Containers.MaxRetryAttempts", Integer, :container_count_max
133 arvcfg.declare_config "Containers.UsePreemptibleInstances", Boolean, :preemptible_instances
134 arvcfg.declare_config "Containers.MaxComputeVMs", Integer, :max_compute_nodes
135 arvcfg.declare_config "Containers.Logging.LogBytesPerEvent", Integer, :crunch_log_bytes_per_event
136 arvcfg.declare_config "Containers.Logging.LogSecondsBetweenEvents", ActiveSupport::Duration, :crunch_log_seconds_between_events
137 arvcfg.declare_config "Containers.Logging.LogThrottlePeriod", ActiveSupport::Duration, :crunch_log_throttle_period
138 arvcfg.declare_config "Containers.Logging.LogThrottleBytes", Integer, :crunch_log_throttle_bytes
139 arvcfg.declare_config "Containers.Logging.LogThrottleLines", Integer, :crunch_log_throttle_lines
140 arvcfg.declare_config "Containers.Logging.LimitLogBytesPerJob", Integer, :crunch_limit_log_bytes_per_job
141 arvcfg.declare_config "Containers.Logging.LogPartialLineThrottlePeriod", ActiveSupport::Duration, :crunch_log_partial_line_throttle_period
142 arvcfg.declare_config "Containers.Logging.LogUpdatePeriod", ActiveSupport::Duration, :crunch_log_update_period
143 arvcfg.declare_config "Containers.Logging.LogUpdateSize", Integer, :crunch_log_update_size
144 arvcfg.declare_config "Containers.Logging.MaxAge", ActiveSupport::Duration, :clean_container_log_rows_after
145 arvcfg.declare_config "Containers.SLURM.Managed.DNSServerConfDir", Pathname, :dns_server_conf_dir
146 arvcfg.declare_config "Containers.SLURM.Managed.DNSServerConfTemplate", Pathname, :dns_server_conf_template
147 arvcfg.declare_config "Containers.SLURM.Managed.DNSServerReloadCommand", String, :dns_server_reload_command
148 arvcfg.declare_config "Containers.SLURM.Managed.DNSServerUpdateCommand", String, :dns_server_update_command
149 arvcfg.declare_config "Containers.SLURM.Managed.ComputeNodeDomain", String, :compute_node_domain
150 arvcfg.declare_config "Containers.SLURM.Managed.ComputeNodeNameservers", Hash, :compute_node_nameservers, ->(cfg, k, v) { arrayToHash cfg, "Containers.SLURM.Managed.ComputeNodeNameservers", v }
151 arvcfg.declare_config "Containers.SLURM.Managed.AssignNodeHostname", String, :assign_node_hostname
152 arvcfg.declare_config "Containers.JobsAPI.Enable", String, :enable_legacy_jobs_api, ->(cfg, k, v) { ConfigLoader.set_cfg cfg, "Containers.JobsAPI.Enable", v.to_s }
153 arvcfg.declare_config "Containers.JobsAPI.GitInternalDir", String, :git_internal_dir
154 arvcfg.declare_config "Mail.MailchimpAPIKey", String, :mailchimp_api_key
155 arvcfg.declare_config "Mail.MailchimpListID", String, :mailchimp_list_id
156 arvcfg.declare_config "Services.Controller.ExternalURL", URI
157 arvcfg.declare_config "Services.Workbench1.ExternalURL", URI, :workbench_address
158 arvcfg.declare_config "Services.Websocket.ExternalURL", URI, :websocket_address
159 arvcfg.declare_config "Services.WebDAV.ExternalURL", URI, :keep_web_service_url
160 arvcfg.declare_config "Services.GitHTTP.ExternalURL", URI, :git_repo_https_base
161 arvcfg.declare_config "Services.GitSSH.ExternalURL", URI, :git_repo_ssh_base, ->(cfg, k, v) { ConfigLoader.set_cfg cfg, "Services.GitSSH.ExternalURL", "ssh://#{v}" }
162 arvcfg.declare_config "RemoteClusters", Hash, :remote_hosts, ->(cfg, k, v) {
163   h = if cfg["RemoteClusters"] then
164         cfg["RemoteClusters"].deep_dup
165       else
166         {}
167       end
168   v.each do |clusterid, host|
169     if h[clusterid].nil?
170       h[clusterid] = {
171         "Host" => host,
172         "Proxy" => true,
173         "Scheme" => "https",
174         "Insecure" => false,
175         "ActivateUsers" => false
176       }
177     end
178   end
179   ConfigLoader.set_cfg cfg, "RemoteClusters", h
180 }
181 arvcfg.declare_config "RemoteClusters.*.Proxy", Boolean, :remote_hosts_via_dns
182
183 dbcfg = ConfigLoader.new
184
185 dbcfg.declare_config "PostgreSQL.ConnectionPool", Integer, :pool
186 dbcfg.declare_config "PostgreSQL.Connection.host", String, :host
187 dbcfg.declare_config "PostgreSQL.Connection.port", String, :port
188 dbcfg.declare_config "PostgreSQL.Connection.user", String, :username
189 dbcfg.declare_config "PostgreSQL.Connection.password", String, :password
190 dbcfg.declare_config "PostgreSQL.Connection.dbname", String, :database
191 dbcfg.declare_config "PostgreSQL.Connection.template", String, :template
192 dbcfg.declare_config "PostgreSQL.Connection.encoding", String, :encoding
193
194 application_config = {}
195 %w(application.default application).each do |cfgfile|
196   path = "#{::Rails.root.to_s}/config/#{cfgfile}.yml"
197   confs = ConfigLoader.load(path, erb: true)
198   # Ignore empty YAML file:
199   next if confs == false
200   application_config.deep_merge!(confs['common'] || {})
201   application_config.deep_merge!(confs[::Rails.env.to_s] || {})
202 end
203
204 db_config = {}
205 path = "#{::Rails.root.to_s}/config/database.yml"
206 if !ENV['ARVADOS_CONFIG_NOLEGACY'] && File.exist?(path)
207   db_config = ConfigLoader.load(path, erb: true)
208 end
209
210 $remaining_config = arvcfg.migrate_config(application_config, $arvados_config)
211 dbcfg.migrate_config(db_config[::Rails.env.to_s] || {}, $arvados_config)
212
213 if application_config[:auto_activate_users_from]
214   application_config[:auto_activate_users_from].each do |cluster|
215     if $arvados_config.RemoteClusters[cluster]
216       $arvados_config.RemoteClusters[cluster]["ActivateUsers"] = true
217     end
218   end
219 end
220
221 if application_config[:host] || application_config[:port] || application_config[:scheme]
222   if !application_config[:host] || application_config[:host].empty?
223     raise "Must set 'host' when setting 'port' or 'scheme'"
224   end
225   $arvados_config.Services["Controller"]["ExternalURL"] = URI((application_config[:scheme] || "https")+"://"+application_config[:host]+
226                                                               (if application_config[:port] then ":#{application_config[:port]}" else "" end))
227 end
228
229 # Checks for wrongly typed configuration items, coerces properties
230 # into correct types (such as Duration), and optionally raise error
231 # for essential configuration that can't be empty.
232 arvcfg.coercion_and_check $arvados_config_defaults, check_nonempty: false
233 arvcfg.coercion_and_check $arvados_config_global, check_nonempty: false
234 arvcfg.coercion_and_check $arvados_config, check_nonempty: true
235 dbcfg.coercion_and_check $arvados_config, check_nonempty: true
236
237 # * $arvados_config_defaults is the defaults
238 # * $arvados_config_global is $arvados_config_defaults merged with the contents of /etc/arvados/config.yml
239 # These are used by the rake config: tasks
240 #
241 # * $arvados_config is $arvados_config_global merged with the migrated contents of application.yml
242 # This is what actually gets copied into the Rails configuration object.
243
244 if $arvados_config["Collections"]["DefaultTrashLifetime"] < 86400.seconds then
245   raise "default_trash_lifetime is %d, must be at least 86400" % Rails.configuration.Collections.DefaultTrashLifetime
246 end
247
248 #
249 # Special case for test database where there's no database.yml,
250 # because the Arvados config.yml doesn't have a concept of multiple
251 # rails environments.
252 #
253 if ::Rails.env.to_s == "test" && db_config["test"].nil?
254   $arvados_config["PostgreSQL"]["Connection"]["dbname"] = "arvados_test"
255 end
256 if ::Rails.env.to_s == "test"
257   # Use template0 when creating a new database. Avoids
258   # character-encoding/collation problems.
259   $arvados_config["PostgreSQL"]["Connection"]["template"] = "template0"
260 end
261
262 if $arvados_config["PostgreSQL"]["Connection"]["password"].empty?
263   raise "Database password is empty, PostgreSQL section is: #{$arvados_config["PostgreSQL"]}"
264 end
265
266 dbhost = $arvados_config["PostgreSQL"]["Connection"]["host"]
267 if $arvados_config["PostgreSQL"]["Connection"]["port"] != 0
268   dbhost += ":#{$arvados_config["PostgreSQL"]["Connection"]["port"]}"
269 end
270
271 #
272 # If DATABASE_URL is set, then ActiveRecord won't error out if database.yml doesn't exist.
273 #
274 # For config migration, we've previously populated the PostgreSQL
275 # section of the config from database.yml
276 #
277 ENV["DATABASE_URL"] = "postgresql://#{$arvados_config["PostgreSQL"]["Connection"]["user"]}:"+
278                       "#{$arvados_config["PostgreSQL"]["Connection"]["password"]}@"+
279                       "#{dbhost}/#{$arvados_config["PostgreSQL"]["Connection"]["dbname"]}?"+
280                       "template=#{$arvados_config["PostgreSQL"]["Connection"]["template"]}&"+
281                       "encoding=#{$arvados_config["PostgreSQL"]["Connection"]["client_encoding"]}&"+
282                       "pool=#{$arvados_config["PostgreSQL"]["ConnectionPool"]}"
283
284 Server::Application.configure do
285   # Copy into the Rails config object.  This also turns Hash into
286   # OrderedOptions so that application code can use
287   # Rails.configuration.API.Blah instead of
288   # Rails.configuration.API["Blah"]
289   ConfigLoader.copy_into_config $arvados_config, config
290   ConfigLoader.copy_into_config $remaining_config, config
291   secrets.secret_key_base = $arvados_config["API"]["RailsSessionSecretToken"]
292 end