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