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