14873: Fixes unit tests.
[arvados.git] / services / api / app / models / node.rb
1 # Copyright (C) The Arvados Authors. All rights reserved.
2 #
3 # SPDX-License-Identifier: AGPL-3.0
4
5 require 'tempfile'
6
7 class Node < ArvadosModel
8   include HasUuid
9   include KindAndEtag
10   include CommonApiTemplate
11
12   # Posgresql JSONB columns should NOT be declared as serialized, Rails 5
13   # already know how to properly treat them.
14
15   before_validation :fill_field_defaults
16   before_validation :ensure_ping_secret
17   after_update :dns_server_update
18
19   # Only a controller can figure out whether or not the current API tokens
20   # have access to the associated Job.  They're expected to set
21   # job_readable=true if the Job UUID can be included in the API response.
22   belongs_to(:job, foreign_key: :job_uuid, primary_key: :uuid)
23   attr_accessor :job_readable
24
25   UNUSED_NODE_IP = '127.40.4.0'
26
27   api_accessible :user, :extend => :common do |t|
28     t.add :hostname
29     t.add :domain
30     t.add :ip_address
31     t.add :last_ping_at
32     t.add :slot_number
33     t.add :status
34     t.add :api_job_uuid, as: :job_uuid
35     t.add :crunch_worker_state
36     t.add :properties
37   end
38   api_accessible :superuser, :extend => :user do |t|
39     t.add :first_ping_at
40     t.add :info
41     t.add lambda { |x| Rails.configuration.compute_node_nameservers }, :as => :nameservers
42   end
43
44   after_initialize do
45     @bypass_arvados_authorization = false
46   end
47
48   def domain
49     super || Rails.configuration.compute_node_domain
50   end
51
52   def api_job_uuid
53     job_readable ? job_uuid : nil
54   end
55
56   def crunch_worker_state
57     return 'down' if slot_number.nil?
58     case self.info.andand['slurm_state']
59     when 'alloc', 'comp', 'mix', 'drng'
60       'busy'
61     when 'idle'
62       'idle'
63     else
64       'down'
65     end
66   end
67
68   def status
69     if !self.last_ping_at
70       if db_current_time - self.created_at > 5.minutes
71         'startup-fail'
72       else
73         'pending'
74       end
75     elsif db_current_time - self.last_ping_at > 1.hours
76       'missing'
77     else
78       'running'
79     end
80   end
81
82   def ping(o)
83     raise "must have :ip and :ping_secret" unless o[:ip] and o[:ping_secret]
84
85     if o[:ping_secret] != self.info['ping_secret']
86       logger.info "Ping: secret mismatch: received \"#{o[:ping_secret]}\" != \"#{self.info['ping_secret']}\""
87       raise ArvadosModel::UnauthorizedError.new("Incorrect ping_secret")
88     end
89
90     current_time = db_current_time
91     self.last_ping_at = current_time
92
93     @bypass_arvados_authorization = true
94
95     # Record IP address
96     if self.ip_address.nil?
97       logger.info "#{self.uuid} ip_address= #{o[:ip]}"
98       self.ip_address = o[:ip]
99       self.first_ping_at = current_time
100     end
101
102     # Record instance ID if not already known
103     if o[:ec2_instance_id]
104       if !self.info['ec2_instance_id']
105         self.info['ec2_instance_id'] = o[:ec2_instance_id]
106       elsif self.info['ec2_instance_id'] != o[:ec2_instance_id]
107         logger.debug "Multiple nodes have credentials for #{self.uuid}"
108         raise "#{self.uuid} is already running at #{self.info['ec2_instance_id']} so rejecting ping from #{o[:ec2_instance_id]}"
109       end
110     end
111
112     assign_slot
113
114     # Record other basic stats
115     ['total_cpu_cores', 'total_ram_mb', 'total_scratch_mb'].each do |key|
116       if value = (o[key] or o[key.to_sym])
117         self.properties[key] = value.to_i
118       else
119         self.properties.delete(key)
120       end
121     end
122
123     save!
124   end
125
126   def assign_slot
127     return if self.slot_number.andand > 0
128     while true
129       self.slot_number = self.class.available_slot_number
130       if self.slot_number.nil?
131         raise "No available node slots"
132       end
133       begin
134         save!
135         return assign_hostname
136       rescue ActiveRecord::RecordNotUnique
137         # try again
138       end
139     end
140   end
141
142   protected
143
144   def fill_field_defaults
145     self.info ||= {}
146     self.properties ||= {}
147   end
148
149   def assign_hostname
150     if self.hostname.nil? and Rails.configuration.assign_node_hostname
151       self.hostname = self.class.hostname_for_slot(self.slot_number)
152     end
153   end
154
155   def self.available_slot_number
156     # Join the sequence 1..max with the nodes table. Return the first
157     # (i.e., smallest) value that doesn't match the slot_number of any
158     # existing node.
159     connection.exec_query('SELECT n FROM generate_series(1, $1) AS slot(n)
160                           LEFT JOIN nodes ON n=slot_number
161                           WHERE slot_number IS NULL
162                           LIMIT 1',
163                           # query label:
164                           'Node.available_slot_number',
165                           # [col_id, val] for $1 vars:
166                           [[nil, Rails.configuration.max_compute_nodes]],
167                          ).rows.first.andand.first
168   end
169
170   def ensure_ping_secret
171     self.info['ping_secret'] ||= rand(2**256).to_s(36)
172   end
173
174   def dns_server_update
175     if ip_address_changed? && ip_address
176       Node.where('id != ? and ip_address = ?',
177                  id, ip_address).each do |stale_node|
178         # One or more(!) stale node records have the same IP address
179         # as the new node. Clear the ip_address field on the stale
180         # nodes. Otherwise, we (via SLURM) might inadvertently connect
181         # to the new node using the old node's hostname.
182         stale_node.update_attributes!(ip_address: nil)
183       end
184     end
185     if hostname_was && hostname_changed?
186       self.class.dns_server_update(hostname_was, UNUSED_NODE_IP)
187     end
188     if hostname && (hostname_changed? || ip_address_changed?)
189       self.class.dns_server_update(hostname, ip_address || UNUSED_NODE_IP)
190     end
191   end
192
193   def self.dns_server_update hostname, ip_address
194     ok = true
195
196     ptr_domain = ip_address.
197       split('.').reverse.join('.').concat('.in-addr.arpa')
198
199     template_vars = {
200       hostname: hostname,
201       uuid_prefix: Rails.configuration.uuid_prefix,
202       ip_address: ip_address,
203       ptr_domain: ptr_domain,
204     }
205
206     if Rails.configuration.dns_server_conf_dir and Rails.configuration.dns_server_conf_template
207       tmpfile = nil
208       begin
209         begin
210           template = IO.read(Rails.configuration.dns_server_conf_template)
211         rescue IOError, SystemCallError => e
212           logger.error "Reading #{Rails.configuration.dns_server_conf_template}: #{e.message}"
213           raise
214         end
215
216         hostfile = File.join Rails.configuration.dns_server_conf_dir, "#{hostname}.conf"
217         Tempfile.open(["#{hostname}-", ".conf.tmp"],
218                                  Rails.configuration.dns_server_conf_dir) do |f|
219           tmpfile = f.path
220           f.puts template % template_vars
221         end
222         File.rename tmpfile, hostfile
223       rescue IOError, SystemCallError => e
224         logger.error "Writing #{hostfile}: #{e.message}"
225         ok = false
226       ensure
227         if tmpfile and File.file? tmpfile
228           # Cleanup remaining temporary file.
229           File.unlink tmpfile
230         end
231       end
232     end
233
234     if Rails.configuration.dns_server_update_command
235       cmd = Rails.configuration.dns_server_update_command % template_vars
236       if not system cmd
237         logger.error "dns_server_update_command #{cmd.inspect} failed: #{$?}"
238         ok = false
239       end
240     end
241
242     if Rails.configuration.dns_server_conf_dir and Rails.configuration.dns_server_reload_command
243       restartfile = File.join(Rails.configuration.dns_server_conf_dir, 'restart.txt')
244       begin
245         File.open(restartfile, 'w') do |f|
246           # Typically, this is used to trigger a dns server restart
247           f.puts Rails.configuration.dns_server_reload_command
248         end
249       rescue IOError, SystemCallError => e
250         logger.error "Unable to write #{restartfile}: #{e.message}"
251         ok = false
252       end
253     end
254
255     ok
256   end
257
258   def self.hostname_for_slot(slot_number)
259     config = Rails.configuration.assign_node_hostname
260
261     return nil if !config
262
263     sprintf(config, {:slot_number => slot_number})
264   end
265
266   # At startup, make sure all DNS entries exist.  Otherwise, slurmctld
267   # will refuse to start.
268   if Rails.configuration.dns_server_conf_dir and Rails.configuration.dns_server_conf_template and Rails.configuration.assign_node_hostname
269     (0..Rails.configuration.max_compute_nodes-1).each do |slot_number|
270       hostname = hostname_for_slot(slot_number)
271       hostfile = File.join Rails.configuration.dns_server_conf_dir, "#{hostname}.conf"
272       if !File.exist? hostfile
273         n = Node.where(:slot_number => slot_number).first
274         if n.nil? or n.ip_address.nil?
275           dns_server_update(hostname, UNUSED_NODE_IP)
276         else
277           dns_server_update(hostname, n.ip_address)
278         end
279       end
280     end
281   end
282
283   def permission_to_update
284     @bypass_arvados_authorization or super
285   end
286
287   def permission_to_create
288     current_user and current_user.is_admin
289   end
290 end