Merge branch 'master' into 2871-preload-objects
[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   before_validation :ensure_ping_secret
7   after_update :dnsmasq_update
8
9   MAX_SLOTS = 64
10
11   @@confdir = Rails.configuration.dnsmasq_conf_dir
12   @@domain = Rails.configuration.compute_node_domain rescue `hostname --domain`.strip
13   @@nameservers = Rails.configuration.compute_node_nameservers
14
15   api_accessible :user, :extend => :common do |t|
16     t.add :hostname
17     t.add :domain
18     t.add :ip_address
19     t.add :last_ping_at
20     t.add :slot_number
21     t.add :status
22     t.add :crunch_worker_state
23   end
24   api_accessible :superuser, :extend => :user do |t|
25     t.add :first_ping_at
26     t.add :info
27     t.add lambda { |x| @@nameservers }, :as => :nameservers
28   end
29
30   def info
31     @info ||= Hash.new
32     super
33   end
34
35   def domain
36     super || @@domain
37   end
38
39   def crunch_worker_state
40     case self.info.andand['slurm_state']
41     when 'alloc', 'comp'
42       'busy'
43     when 'idle'
44       'idle'
45     else
46       'down'
47     end
48   end
49
50   def status
51     if !self.last_ping_at
52       if Time.now - self.created_at > 5.minutes
53         'startup-fail'
54       else
55         'pending'
56       end
57     elsif Time.now - self.last_ping_at > 1.hours
58       'missing'
59     else
60       'running'
61     end
62   end
63
64   def ping(o)
65     raise "must have :ip and :ping_secret" unless o[:ip] and o[:ping_secret]
66
67     if o[:ping_secret] != self.info['ping_secret']
68       logger.info "Ping: secret mismatch: received \"#{o[:ping_secret]}\" != \"#{self.info['ping_secret']}\""
69       raise ArvadosModel::UnauthorizedError.new("Incorrect ping_secret")
70     end
71     self.last_ping_at = Time.now
72
73     @bypass_arvados_authorization = true
74
75     # Record IP address
76     if self.ip_address.nil?
77       logger.info "#{self.uuid} ip_address= #{o[:ip]}"
78       self.ip_address = o[:ip]
79       self.first_ping_at = Time.now
80     end
81
82     # Record instance ID if not already known
83     if o[:ec2_instance_id]
84       if !self.info['ec2_instance_id']
85         self.info['ec2_instance_id'] = o[:ec2_instance_id]
86         if (Rails.configuration.compute_node_ec2_tag_enable rescue true)
87           tag_cmd = ("ec2-create-tags #{o[:ec2_instance_id]} " +
88                      "--tag 'Name=#{self.uuid}'")
89           `#{tag_cmd}`
90         end
91       elsif self.info['ec2_instance_id'] != o[:ec2_instance_id]
92         logger.debug "Multiple nodes have credentials for #{self.uuid}"
93         raise "#{self.uuid} is already running at #{self.info['ec2_instance_id']} so rejecting ping from #{o[:ec2_instance_id]}"
94       end
95     end
96
97     # Assign hostname
98     if self.slot_number.nil?
99       try_slot = 0
100       begin
101         self.slot_number = try_slot
102         begin
103           self.save!
104           break
105         rescue ActiveRecord::RecordNotUnique
106           try_slot += 1
107         end
108         raise "No available node slots" if try_slot == MAX_SLOTS
109       end while true
110       self.hostname = self.class.hostname_for_slot(self.slot_number)
111       if info['ec2_instance_id']
112         if (Rails.configuration.compute_node_ec2_tag_enable rescue true)
113           `ec2-create-tags #{self.info['ec2_instance_id']} --tag 'hostname=#{self.hostname}'`
114         end
115       end
116     end
117
118     # Record other basic stats
119     ['total_cpu_cores', 'total_ram_mb', 'total_scratch_mb'].each do |key|
120       if value = (o[key] or o[key.to_sym])
121         self.info[key] = value
122       else
123         self.info.delete(key)
124       end
125     end
126
127     save!
128   end
129
130   def start!(ping_url_method)
131     ensure_permission_to_save
132     ping_url = ping_url_method.call({ id: self.uuid, ping_secret: self.info['ping_secret'] })
133     if (Rails.configuration.compute_node_ec2run_args and
134         Rails.configuration.compute_node_ami)
135       ec2_args = ["--user-data '#{ping_url}'",
136                   "-t c1.xlarge -n 1",
137                   Rails.configuration.compute_node_ec2run_args,
138                   Rails.configuration.compute_node_ami
139                  ]
140       ec2run_cmd = ["ec2-run-instances",
141                     "--client-token", self.uuid,
142                     ec2_args].flatten.join(' ')
143       ec2spot_cmd = ["ec2-request-spot-instances",
144                      "-p #{Rails.configuration.compute_node_spot_bid} --type one-time",
145                      ec2_args].flatten.join(' ')
146     else
147       ec2run_cmd = ''
148       ec2spot_cmd = ''
149     end
150     self.info['ec2_run_command'] = ec2run_cmd
151     self.info['ec2_spot_command'] = ec2spot_cmd
152     self.info['ec2_start_command'] = ec2spot_cmd
153     logger.info "#{self.uuid} ec2_start_command= #{ec2spot_cmd.inspect}"
154     result = `#{ec2spot_cmd} 2>&1`
155     self.info['ec2_start_result'] = result
156     logger.info "#{self.uuid} ec2_start_result= #{result.inspect}"
157     result.match(/INSTANCE\s*(i-[0-9a-f]+)/) do |m|
158       instance_id = m[1]
159       self.info['ec2_instance_id'] = instance_id
160       if (Rails.configuration.compute_node_ec2_tag_enable rescue true)
161         `ec2-create-tags #{instance_id} --tag 'Name=#{self.uuid}'`
162       end
163     end
164     result.match(/SPOTINSTANCEREQUEST\s*(sir-[0-9a-f]+)/) do |m|
165       sir_id = m[1]
166       self.info['ec2_sir_id'] = sir_id
167       if (Rails.configuration.compute_node_ec2_tag_enable rescue true)
168         `ec2-create-tags #{sir_id} --tag 'Name=#{self.uuid}'`
169       end
170     end
171     self.save!
172   end
173
174   protected
175
176   def ensure_ping_secret
177     self.info['ping_secret'] ||= rand(2**256).to_s(36)
178   end
179
180   def dnsmasq_update
181     if self.hostname_changed? or self.ip_address_changed?
182       if self.hostname and self.ip_address
183         self.class.dnsmasq_update(self.hostname, self.ip_address)
184       end
185     end
186   end
187
188   def self.dnsmasq_update(hostname, ip_address)
189     return unless @@confdir
190     ptr_domain = ip_address.
191       split('.').reverse.join('.').concat('.in-addr.arpa')
192     hostfile = File.join @@confdir, hostname
193     File.open hostfile, 'w' do |f|
194       f.puts "address=/#{hostname}/#{ip_address}"
195       f.puts "address=/#{hostname}.#{@@domain}/#{ip_address}" if @@domain
196       f.puts "ptr-record=#{ptr_domain},#{hostname}"
197     end
198     File.open(File.join(@@confdir, 'restart.txt'), 'w') do |f|
199       # this should trigger a dnsmasq restart
200     end
201   end
202
203   def self.hostname_for_slot(slot_number)
204     "compute#{slot_number}"
205   end
206
207   # At startup, make sure all DNS entries exist.  Otherwise, slurmctld
208   # will refuse to start.
209   if @@confdir and
210       !File.exists? (File.join(@@confdir, hostname_for_slot(MAX_SLOTS-1)))
211     (0..MAX_SLOTS-1).each do |slot_number|
212       hostname = hostname_for_slot(slot_number)
213       hostfile = File.join @@confdir, hostname
214       if !File.exists? hostfile
215         dnsmasq_update(hostname, '127.40.4.0')
216       end
217     end
218   end
219
220   def permission_to_update
221     @bypass_arvados_authorization or super
222   end
223
224   def permission_to_create
225     current_user and current_user.is_admin
226   end
227 end