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