dn42-scripts/scripts/dhcp

111 lines
2.9 KiB
Ruby
Executable File

#!/usr/bin/env ruby
require_relative "utils"
require "optparse"
class DhcpRegistry < Registry
def add_lease(name, macaddress, ipv4, ipv6)
data["network"][name] ||= {}
host = data["network"][name]
host["macaddress"] = macaddress
host["ipv4"] = ipv4 if ipv4
host["ipv6"] = ipv6 if ipv6
end
def remove_lease(name)
if data["network"].delete(name).nil?
die "no such lease name #{name} in registry.json"
end
end
def update_leases
template_path = Pathname.new(File.expand_path("../../templates", __FILE__))
dhcp_template = Template.new(template_path.join("dhcp.conf.erb"))
static_leases = data["network"].select do |name, data|
data["mac"] && (data["ipv4"] || data["ipv6"])
end.map do |name, data|
TemplateContext.new(data.merge(name: name))
end
dhcp_path = Pathname.new(File.expand_path("../../dhcp.peers.conf", __FILE__))
File.open(dhcp_path, "w+").write(dhcp_template.render(leases: static_leases))
reload_dhcp
end
def reload_dhcp
command = try(data, "host", "reload_command")
if command.nil?
puts "skip to reload dhcpd because reload_command is not defined"
else
sh(command)
end
end
end
GLOBAL_OPTIONS = OptionParser.new do |opts|
opts.banner = "Usage: dhcp [options] [subcommand [options]]"
opts.separator ""
opts.separator <<HELP
Available subcommands:
add [options] NAME MACADDRESS: add dhcp lease
remove [options] NAME: remove dhcp static lease
regenerate: regenerate dhcp configuration
See 'dhcp COMMAND --help' for more information on a specific command.
HELP
end
class Application
def run(args)
GLOBAL_OPTIONS.order!(args)
@registry = DhcpRegistry.new
case command = args.shift
when "add"
add_command
when "remove"
remove_command
when nil
puts(GLOBAL_OPTIONS.help())
exit(0)
when "regenerate" # fall through
else
die "unknown subcommand #{command}"
end
registry.save
registry.update_leases
end
private
def add_command(args)
ipv4, ipv6 = nil, nil
parser = OptionParser.new do |opts|
opts.banner = "Usage: dhcp add [options] NAME MACADDRESS"
opts.on("-4", "--ipv4 ADDRESS", "set fixed ipv4 address") do |address|
ipv4 = address
end
opts.on("-6", "--ipv6 ADDRESS", "set fixed ipv6 address") do |address|
ipv6 = address
end
end.order!(args)
if ARGV.size < 2
$stderr.puts "no enough arguments"
die(parser.help)
end
name, macaddress = args
@registry.add_lease(name, macaddress, ipv4, ipv6)
end
def remove_command(args)
parser = OptionParser.new do |opts|
opts.banner = "Usage: dhcp remove NAME"
end.order!(args)
if args.empty?
$stderr.puts "no enough arguments"
die(parser.help)
end
@registry.remove_lease(args.first)
end
end
Application.new.run(ARGV)