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