lib/process/daemon/listen.rb



# Copyright, 2016, by Samuel G. D. Williams. <http://www.codeotaku.com>
# 
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
# 
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
# 
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.

module Process
	class Daemon
		# Access incoming file descriptors from daemons started by systemd.
		class Listen
			LISTEN_PID = 'LISTEN_PID'
			LISTEN_FDS = 'LISTEN_FDS'
			LISTEN_FDNAMES = 'LISTEN_FDNAMES'
			
			FD_START = 3
			SEPERATOR = ':'
			
			def self.set_close_at_exec(fd)
				fd.fcntl(Fcntl::F_SETFD, Fcntl::FD_CLOEXEC) if defined? Fcntl::F_SETFD
			end
			
			def self.open(fd)
				set_close_at_exec(fd)
				
				return IO.for_fd(fd)
			end
			
			# Returns a Array or Hash of file descriptors. If LISTEN_FDNAMES is set, a Hash is returned which includes key => value pairs for named file descriptors.
			def self.file_descriptors(env = ENV)
				pid, fds, names = env.values_at(LISTEN_PID, LISTEN_FDS, LISTEN_FDNAMES)
				
				# Are the PIDs valid for this process?
				unless pid and Integer(pid) == Process.pid
					return nil
				end
				
				files = Integer(fds).times.collect do |i|
					self.open(FD_START + i)
				end
				
				if names
					names = names.split(SEPARATOR, -1)
				end
				
				self.new(files, names)
			end
			
			def initialize(files, names)
				@files = files
				@names = names
				
				@named = {}
				@unnamed = []
				
				@names.each_with_index do |name, index|
					if name
						@named[name] = @files[index]
					else
						@unnamed << @files[index]
					end
				end
			end
			
			attr :files
			attr :names
			
			attr :named
			attr :unnamed
		end
	end
end