bf27f6ff99104879da00019bd09bd7f975fbfd74
[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_SLOTS = 64
17
18   @@dns_server_conf_dir = Rails.configuration.dns_server_conf_dir
19   @@dns_server_conf_template = Rails.configuration.dns_server_conf_template
20   @@dns_server_reload_command = Rails.configuration.dns_server_reload_command
21   @@uuid_prefix = Rails.configuration.uuid_prefix
22   @@domain = Rails.configuration.compute_node_domain rescue `hostname --domain`.strip
23   @@nameservers = Rails.configuration.compute_node_nameservers
24
25   api_accessible :user, :extend => :common do |t|
26     t.add :hostname
27     t.add :domain
28     t.add :ip_address
29     t.add :last_ping_at
30     t.add :slot_number
31     t.add :status
32     t.add :api_job_uuid, as: :job_uuid
33     t.add :crunch_worker_state
34     t.add :properties
35   end
36   api_accessible :superuser, :extend => :user do |t|
37     t.add :first_ping_at
38     t.add :info
39     t.add lambda { |x| @@nameservers }, :as => :nameservers
40   end
41
42   def domain
43     super || @@domain
44   end
45
46   def api_job_uuid
47     job_readable ? job_uuid : nil
48   end
49
50   def crunch_worker_state
51     return 'down' if slot_number.nil?
52     case self.info.andand['slurm_state']
53     when 'alloc', 'comp'
54       'busy'
55     when 'idle'
56       'idle'
57     else
58       'down'
59     end
60   end
61
62   def status
63     if !self.last_ping_at
64       if db_current_time - self.created_at > 5.minutes
65         'startup-fail'
66       else
67         'pending'
68       end
69     elsif db_current_time - self.last_ping_at > 1.hours
70       'missing'
71     else
72       'running'
73     end
74   end
75
76   def ping(o)
77     raise "must have :ip and :ping_secret" unless o[:ip] and o[:ping_secret]
78
79     if o[:ping_secret] != self.info['ping_secret']
80       logger.info "Ping: secret mismatch: received \"#{o[:ping_secret]}\" != \"#{self.info['ping_secret']}\""
81       raise ArvadosModel::UnauthorizedError.new("Incorrect ping_secret")
82     end
83
84     current_time = db_current_time
85     self.last_ping_at = current_time
86
87     @bypass_arvados_authorization = true
88
89     # Record IP address
90     if self.ip_address.nil?
91       logger.info "#{self.uuid} ip_address= #{o[:ip]}"
92       self.ip_address = o[:ip]
93       self.first_ping_at = current_time
94     end
95
96     # Record instance ID if not already known
97     if o[:ec2_instance_id]
98       if !self.info['ec2_instance_id']
99         self.info['ec2_instance_id'] = o[:ec2_instance_id]
100       elsif self.info['ec2_instance_id'] != o[:ec2_instance_id]
101         logger.debug "Multiple nodes have credentials for #{self.uuid}"
102         raise "#{self.uuid} is already running at #{self.info['ec2_instance_id']} so rejecting ping from #{o[:ec2_instance_id]}"
103       end
104     end
105
106     # Assign hostname
107     if self.slot_number.nil?
108       try_slot = 0
109       begin
110         self.slot_number = try_slot
111         begin
112           self.save!
113           break
114         rescue ActiveRecord::RecordNotUnique
115           try_slot += 1
116         end
117         raise "No available node slots" if try_slot == MAX_SLOTS
118       end while true
119       self.hostname = self.class.hostname_for_slot(self.slot_number)
120     end
121
122     # Record other basic stats
123     ['total_cpu_cores', 'total_ram_mb', 'total_scratch_mb'].each do |key|
124       if value = (o[key] or o[key.to_sym])
125         self.properties[key] = value.to_i
126       else
127         self.properties.delete(key)
128       end
129     end
130
131     save!
132   end
133
134   protected
135
136   def ensure_ping_secret
137     self.info['ping_secret'] ||= rand(2**256).to_s(36)
138   end
139
140   def dns_server_update
141     if self.hostname_changed? or self.ip_address_changed?
142       if not self.ip_address.nil?
143         stale_conflicting_nodes = Node.where('id != ? and ip_address = ? and last_ping_at < ?',self.id,self.ip_address,10.minutes.ago)
144         if not stale_conflicting_nodes.empty?
145           # One or more stale compute node records have the same IP address as the new node.
146           # Clear the ip_address field on the stale nodes.
147           stale_conflicting_nodes.each do |stale_node|
148             stale_node.ip_address = nil
149             stale_node.save!
150           end
151         end
152       end
153       if self.hostname and self.ip_address
154         self.class.dns_server_update(self.hostname, self.ip_address)
155       end
156     end
157   end
158
159   def self.dns_server_update(hostname, ip_address)
160     return unless @@dns_server_conf_dir and @@dns_server_conf_template
161     ptr_domain = ip_address.
162       split('.').reverse.join('.').concat('.in-addr.arpa')
163     hostfile = File.join @@dns_server_conf_dir, "#{hostname}.conf"
164
165     begin
166       template = IO.read(@@dns_server_conf_template)
167     rescue => e
168       STDERR.puts "Unable to read dns_server_conf_template #{@@dns_server_conf_template}: #{e.message}"
169       return
170     end
171
172     populated = template % {hostname:hostname, uuid_prefix:@@uuid_prefix, ip_address:ip_address, ptr_domain:ptr_domain}
173
174     begin
175       File.open hostfile, 'w' do |f|
176         f.puts populated
177       end
178     rescue => e
179       STDERR.puts "Unable to write #{hostfile}: #{e.message}"
180       return
181     end
182     File.open(File.join(@@dns_server_conf_dir, 'restart.txt'), 'w') do |f|
183       # this will trigger a dns server restart
184       f.puts @@dns_server_reload_command
185     end
186   end
187
188   def self.hostname_for_slot(slot_number)
189     "compute#{slot_number}"
190   end
191
192   # At startup, make sure all DNS entries exist.  Otherwise, slurmctld
193   # will refuse to start.
194   if @@dns_server_conf_dir and @@dns_server_conf_template
195     (0..MAX_SLOTS-1).each do |slot_number|
196       hostname = hostname_for_slot(slot_number)
197       hostfile = File.join @@dns_server_conf_dir, "#{hostname}.conf"
198       if !File.exists? hostfile
199         n = Node.where(:slot_number => slot_number).first
200         if n.nil? or n.ip_address.nil?
201           dns_server_update(hostname, '127.40.4.0')
202         else
203           dns_server_update(hostname, n.ip_address)
204         end
205       end
206     end
207   end
208
209   def permission_to_update
210     @bypass_arvados_authorization or super
211   end
212
213   def permission_to_create
214     current_user and current_user.is_admin
215   end
216 end