Make MAX_SLOTS a configurable parameter, and rename it to max_compute_nodes.
[arvados.git] / services / api / app / models / node.rb
1 class Node < ArvadosModel
2   include HasUuid
3   include KindAndEtag
4   include CommonApiTemplate
5   serialize :info, Hash
6   serialize :properties, Hash
7   before_validation :ensure_ping_secret
8   after_update :dns_server_update
9
10   # Only a controller can figure out whether or not the current API tokens
11   # have access to the associated Job.  They're expected to set
12   # job_readable=true if the Job UUID can be included in the API response.
13   belongs_to(:job, foreign_key: :job_uuid, primary_key: :uuid)
14   attr_accessor :job_readable
15
16   @@max_compute_nodes = Rails.configuration.max_compute_nodes
17   @@dns_server_conf_dir = Rails.configuration.dns_server_conf_dir
18   @@dns_server_conf_template = Rails.configuration.dns_server_conf_template
19   @@dns_server_reload_command = Rails.configuration.dns_server_reload_command
20   @@uuid_prefix = Rails.configuration.uuid_prefix
21   @@domain = Rails.configuration.compute_node_domain rescue `hostname --domain`.strip
22   @@nameservers = Rails.configuration.compute_node_nameservers
23
24   api_accessible :user, :extend => :common do |t|
25     t.add :hostname
26     t.add :domain
27     t.add :ip_address
28     t.add :last_ping_at
29     t.add :slot_number
30     t.add :status
31     t.add :api_job_uuid, as: :job_uuid
32     t.add :crunch_worker_state
33     t.add :properties
34   end
35   api_accessible :superuser, :extend => :user do |t|
36     t.add :first_ping_at
37     t.add :info
38     t.add lambda { |x| @@nameservers }, :as => :nameservers
39   end
40
41   def domain
42     super || @@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'
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 hostname
106     if self.slot_number.nil?
107       try_slot = 0
108       begin
109         self.slot_number = try_slot
110         begin
111           self.save!
112           break
113         rescue ActiveRecord::RecordNotUnique
114           try_slot += 1
115         end
116         raise "No available node slots" if try_slot == @@max_compute_nodes
117       end while true
118       self.hostname = self.class.hostname_for_slot(self.slot_number)
119     end
120
121     # Record other basic stats
122     ['total_cpu_cores', 'total_ram_mb', 'total_scratch_mb'].each do |key|
123       if value = (o[key] or o[key.to_sym])
124         self.properties[key] = value.to_i
125       else
126         self.properties.delete(key)
127       end
128     end
129
130     save!
131   end
132
133   protected
134
135   def ensure_ping_secret
136     self.info['ping_secret'] ||= rand(2**256).to_s(36)
137   end
138
139   def dns_server_update
140     if self.hostname_changed? or self.ip_address_changed?
141       if not self.ip_address.nil?
142         stale_conflicting_nodes = Node.where('id != ? and ip_address = ? and last_ping_at < ?',self.id,self.ip_address,10.minutes.ago)
143         if not stale_conflicting_nodes.empty?
144           # One or more stale compute node records have the same IP address as the new node.
145           # Clear the ip_address field on the stale nodes.
146           stale_conflicting_nodes.each do |stale_node|
147             stale_node.ip_address = nil
148             stale_node.save!
149           end
150         end
151       end
152       if self.hostname and self.ip_address
153         self.class.dns_server_update(self.hostname, self.ip_address)
154       end
155     end
156   end
157
158   def self.dns_server_update(hostname, ip_address)
159     return unless @@dns_server_conf_dir and @@dns_server_conf_template
160     ptr_domain = ip_address.
161       split('.').reverse.join('.').concat('.in-addr.arpa')
162     hostfile = File.join @@dns_server_conf_dir, "#{hostname}.conf"
163
164     begin
165       template = IO.read(@@dns_server_conf_template)
166     rescue => e
167       STDERR.puts "Unable to read dns_server_conf_template #{@@dns_server_conf_template}: #{e.message}"
168       return
169     end
170
171     populated = template % {hostname:hostname, uuid_prefix:@@uuid_prefix, ip_address:ip_address, ptr_domain:ptr_domain}
172
173     begin
174       File.open hostfile, 'w' do |f|
175         f.puts populated
176       end
177     rescue => e
178       STDERR.puts "Unable to write #{hostfile}: #{e.message}"
179       return
180     end
181     File.open(File.join(@@dns_server_conf_dir, 'restart.txt'), 'w') do |f|
182       # this will trigger a dns server restart
183       f.puts @@dns_server_reload_command
184     end
185   end
186
187   def self.hostname_for_slot(slot_number)
188     "compute#{slot_number}"
189   end
190
191   # At startup, make sure all DNS entries exist.  Otherwise, slurmctld
192   # will refuse to start.
193   if @@dns_server_conf_dir and @@dns_server_conf_template
194     (0..@@max_compute_nodes-1).each do |slot_number|
195       hostname = hostname_for_slot(slot_number)
196       hostfile = File.join @@dns_server_conf_dir, "#{hostname}.conf"
197       if !File.exists? hostfile
198         n = Node.where(:slot_number => slot_number).first
199         if n.nil? or n.ip_address.nil?
200           dns_server_update(hostname, '127.40.4.0')
201         else
202           dns_server_update(hostname, n.ip_address)
203         end
204       end
205     end
206   end
207
208   def permission_to_update
209     @bypass_arvados_authorization or super
210   end
211
212   def permission_to_create
213     current_user and current_user.is_admin
214   end
215 end