Class: Xlogin::CLI

Inherits:
Object
  • Object
show all
Defined in:
lib/xlogin/cli.rb

Constant Summary collapse

DEFAULT_INVENTORY_FILE =
File.join(ENV['HOME'], '.xloginrc')
DEFAULT_TEMPLATE_DIR =
File.join(ENV['HOME'], '.xlogin.d')

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.getopts(args) ⇒ Object



21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/xlogin/cli.rb', line 21

def self.getopts(args)
  config = OpenStruct.new(
    jobs: 1,
    task: [:tty, nil],
    assume_yes:   false,
    inventory:    DEFAULT_INVENTORY_FILE,
    template_dir: DEFAULT_TEMPLATE_DIR,
  )

  parser = OptionParser.new
  parser.banner  = "#{File.basename($0)} HOST_PATTERN [Options]"
  parser.version = Xlogin::VERSION

  parser.on('-i PATH',        '--inventory',    String, 'The PATH to the inventory file (default: $HOME/.xloginrc).') { |v| config.inventory    = v }
  parser.on('-T PATH',        '--template',     String, 'The PATH to the template dir (default: $HOME/.xlogin.d).')   { |v| config.template_dir = v }
  parser.on('-L [DIRECTORY]', '--log-dir',      String, 'The PATH to the log dir (default: $PWD).')                   { |v| config.logdir = v || '.' }

  parser.on('-l', '--list', TrueClass, 'List the inventory.')     { |v| config.task = [:list, nil] }
  parser.on('-t', '--tty',  TrueClass, 'Allocate a pseudo-tty.')  { |v| config.task = [:tty,  nil] }
  parser.on('-e COMMAND', '--exec', 'Execute commands and quit.') { |v| config.task = [:exec, v] }

  parser.on('-j NUM', '--jobs', Integer, 'The NUM of jobs to execute in parallel(default: 1).') { |v| config.jobs = v }
  parser.on('-E',     '--enable',     TrueClass, 'Try to gain enable priviledge.')              { |v| config.enable = v }
  parser.on('-y',     '--assume-yes', TrueClass, 'Automatically answer yes to prompts.')        { |v| config.assume_yes = v }

  parser.parse!(args)
  Xlogin.configure do
    assume_yes(true)
    source(File.expand_path(config.inventory, ENV['PWD']))
    template(File.expand_path(config.template_dir, ENV['PWD']))
  end

  config.hosts = Xlogin.list(*args)
  raise "No host found: `#{args.join(', ')}`" if config.hosts.empty?

  return config
rescue => e
  $stderr.puts e, '', parser
  exit 1
end

.run(args = ARGV) ⇒ Object



15
16
17
18
19
# File 'lib/xlogin/cli.rb', line 15

def self.run(args = ARGV)
  config = getopts(args)
  client = Xlogin::CLI.new
  client.method(config.task.first).call(config)
end

Instance Method Details

#exec(config) ⇒ Object



86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
# File 'lib/xlogin/cli.rb', line 86

def exec(config)
  Signal.trap(:INT) { exit 0 }

  max_width = config.hosts.map { |e| e[:name].length }.max
  Parallel.map(config.hosts, in_threads: config.jobs) do |hostinfo|
    session = nil
    error   = nil

    begin
      buffer   = StringIO.new

      loggers  = []
      loggers << ((config.jobs > 1)? buffer : $stdout)
      loggers << File.expand_path(File.join(config.logdir, "#{hostinfo[:name]}.log"), ENV['PWD']) if config.logdir

      session = Xlogin.get(hostinfo.merge(log: loggers))
      session.enable(hostinfo[:enable]) if config.enable && hostinfo[:enable]

      command_lines = ['', *config.task.last.to_s.split(';').map(&:strip)]
      command_lines.each { |line| session.cmd(line) }
    rescue => err
      error = err
    end

    if config.jobs > 1
      prefix = "#{hostinfo[:name].to_s.ljust(max_width)} |"
      output = buffer.string.lines.map { |line| prefix + line.chomp.gsub("\r", '') + "\n" }.join
      $stdout.print output
      $stderr.print prefix + "[Error] #{error}\n" if error
    else
      $stderr.print "[Error] #{error}\n" if error
    end

    session
  end
end

#list(config) ⇒ Object



62
63
64
# File 'lib/xlogin/cli.rb', line 62

def list(config)
  $stdout.puts config.hosts.map { |e| e[:name] }.sort.uniq
end

#tty(config) ⇒ Object



66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
# File 'lib/xlogin/cli.rb', line 66

def tty(config)
  Signal.trap(:INT) { exit 0 }

  config.hosts.each do |hostinfo|
    unless config.hosts.size == 1
      case resp = Readline.readline(">> #{hostinfo[:name]}(Y/n)? ", false).strip
      when /^y(es)?$/i, ''
      when /^n(o)?$/i then next
      else redo
      end
    end

    $stdout.puts "Trying #{hostinfo[:name]}...", "Escape character is '^]'."
    tty_config = OpenStruct.new(config.to_h.merge(jobs: 1, hosts: [hostinfo]))

    session, _ = exec(tty_config)
    session.interact!
  end
end