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