# frozen_string_literal: true module Hotwired class CLI require "slop" require_relative "../hotwired" class HotwiredError < StandardError; end class NoConfig < HotwiredError; end MAX_DELETE = 1 # 脚本调度函数入口 def run # 检查 CLI 是否携带相关参数 if @opts[:poll] Log.debug "Start hotwired with specify #{@opts[:poll]}" Hotwired.new(cidr: @opts[:poll]).run elsif @opts[:remove] Log.debug "Start hotwired remove job" remove_records @opts[:remove] elsif @opts["purge-old"] Log.debug "Start hotwired purge-old job" remove_old @opts["purge-old"] else # 缺省的执行方式 Log.debug "Start hotwired with default params!" Hotwired.new.run end end # 类对象实例化入口函数 def initialize args, @opts = opts_parse @arg = args.shift CFG.debug = true if @opts[:debug] raise NoConfig, "edit ~/.config/hotwired/config" if CONFIG.create end # 解析命令行脚本接收参数 def opts_parse opts = Slop.parse do |o| # banner "Usage: hotwired [options] [argument]" o.on "-h", "--help", "show usage" do puts o exit end o.bool "-d", "--debug", "Debugging on" o.string "-p", "--poll", "Poll CIDR [argument]" o.bool "-r", "--remove", "Remove [argument] from DB" o.string "-m", "--max-delete", "Maximum number to delete, default #{MAX_DELETE}" o.bool "-o", "--purge-old", "Remove records order than [argument] days" o.bool "-s", "--simulate", "Simulate, do not change DB" end [opts.arguments, opts] end # 删除表记录 def remove_records(name) Log.warn "Remove record #{name}" DB.new delete_records DB::Device.filter(Sequel.like(:ptr, "%#{name}%")).all end # 删除历史数据 【 N*天之前 】 def remove_old(days) Log.warn "Remove #{days} days ago data" old = (Time.now.utc - days.to_i * 24 * 60 * 60) DB.new delete_records DB::Device.filter { :last_seen < old }.all end # 删除某些主机数据:接收数组对象 def delete_records(devs) Log.debug "delete_records #{devs.size}" max_del = @opts["max-delete"] ? @opts["max-delete"] : MAX_DELETE # 判断当前表已有数据条目和期望删除条目是否匹配 if devs.size > max_del.to_i puts "Too many matching devices:" devs.each do |dev| puts " %s (%s)" % [dev.ptr, dev.ip] end puts "Be more specific" else puts "Deleting records:" devs.each do |dev| puts " %s (%s)" % [dev.ptr, dev.ip] dev.delete unless @opts[:simulate] end end end end end