Class: Collins::CLI::Modify

Inherits:
Object
  • Object
show all
Includes:
Mixins
Defined in:
lib/collins/cli/modify.rb

Constant Summary collapse

VALID_STATUSES =
["ALLOCATED","CANCELLED","DECOMMISSIONED","INCOMPLETE","MAINTENANCE","NEW","PROVISIONED","PROVISIONING","UNALLOCATED"]
VALID_STATES =

TODO: this shouldnt be hardcoded. we should pull this from the API instead? should elegantly support user-defined states without changing this script

{
  "ALLOCATED" => ["CLAIMED","SPARE","RUNNING_UNMONITORED","UNMONITORED"],
  "MAINTENANCE" => ["AWAITING_REVIEW","HARDWARE_PROBLEM","HW_TESTING","HARDWARE_UPGRADE","IPMI_PROBLEM","MAINT_NOOP","NETWORK_PROBLEM","RELOCATION",'PROVISIONING_PROBLEM'],
  "ANY" => ["RUNNING","STARTING","STOPPING","TERMINATED"],
}
LOG_LEVELS =
Collins::Api::Logging::Severity.constants.map(&:to_s)
OPTIONS_DEFAULTS =
{
  :query_size => 9999,
  :attributes => {},
  :delete_attributes => [],
  :log_level  => 'NOTE',
  :timeout    => 120,
  :config     => nil
}
PROG_NAME =
'collins modify'

Constants included from Mixins

Collins::CLI::Mixins::COLORS, Collins::CLI::Mixins::ERROR, Collins::CLI::Mixins::SUCCESS

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from Mixins

#api_call, #as_query?, #collins, #convert_to_query

Constructor Details

#initializeModify

Returns a new instance of Modify.



29
30
31
32
33
# File 'lib/collins/cli/modify.rb', line 29

def initialize
  @options = OPTIONS_DEFAULTS.clone
  @validated = false
  @parsed = false
end

Instance Attribute Details

#optionsObject (readonly)

Returns the value of attribute options.



27
28
29
# File 'lib/collins/cli/modify.rb', line 27

def options
  @options
end

Instance Method Details

#parse!(argv = ARGV) ⇒ Object



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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
# File 'lib/collins/cli/modify.rb', line 35

def parse!(argv = ARGV)
  OptionParser.new do |opts|
    opts.banner = "Usage: #{PROG_NAME} [options]"
    opts.on('-a','--set-attribute attribute:value',String,"Set attribute=value. : between key and value. attribute will be uppercased.") do |x|
      if not x.include? ':'
        puts '--set-attribute requires attribute:value, missing :value'
        puts opts.help
        exit 1
      end
      a,v = x.split(':')
      @options[:attributes][a.upcase.to_sym] = v
    end
    opts.on('-d','--delete-attribute attribute',String,"Delete attribute.") {|v| @options[:delete_attributes] << v.to_sym }
    opts.on('-S','--set-status status[:state]',String,'Set status (and optionally state) to status:state. Requires --reason') do |v|
      status,state = v.split(':')
      @options[:status] = status.upcase if not status.nil? and not status.empty?
      @options[:state] = state.upcase if not state.nil? and not state.empty?
    end
    opts.on('-r','--reason REASON',String,"Reason for changing status/state.") {|v| @options[:reason] = v }
    opts.on('-l','--log MESSAGE',String,"Create a log entry.") do |v|
      @options[:log_message] = v
    end
    opts.on('-L','--level LEVEL',String, LOG_LEVELS + LOG_LEVELS.map(&:downcase),"Set log level. Default level is #{@options[:log_level]}.") do |v|
      @options[:log_level] = v.upcase
    end
    opts.on('-t','--tags TAGS',Array,"Tags to work on, comma separated") {|v| @options[:tags] = v.map(&:to_sym)}
    opts.on('-C','--config CONFIG',String,'Use specific Collins config yaml for Collins::Client') {|v| @options[:config] = v}
    opts.on('-h','--help',"Help") {puts opts ; exit 0}
    opts.separator ""
    opts.separator "Allowed values (uppercase or lowercase is accepted):"
    opts.separator "  Status (-S,--set-status):\n\#{VALID_STATUSES.join(', ')}\n  States (-S,--set-status):\n\#{VALID_STATES.keys.map {|k| \"\#{k} ->\\n      \#{VALID_STATES[k].join(', ')}\"}.join \"\\n    \"}\n  Log levels (-L,--level):\n\#{LOG_LEVELS.join(', ')}\n"
    opts.separator ""
    opts.separator "Examples:"
    opts.separator "  Set an attribute on some hosts:\n\#{PROG_NAME} -t 001234,004567 -a my_attribute:true\n  Delete an attribute on some hosts:\n\#{PROG_NAME} -t 001234,004567 -d my_attribute\n  Delete and add attribute at same time:\n\#{PROG_NAME} -t 001234,004567 -a new_attr:test -d old_attr\n  Set machine into maintenace noop:\n\#{PROG_NAME} -t 001234 -S maintenance:maint_noop -r \"I do what I want\"\n  Set machine back to allocated:\n\#{PROG_NAME} -t 001234 -S allocated:running -r \"Back to allocated\"\n  Set machine back to new without setting state:\n\#{PROG_NAME} -t 001234 -S new -r \"Dunno why you would want this\"\n  Create a log entry:\n\#{PROG_NAME} -t 001234 -l'computers are broken and everything is horrible' -Lwarning\n  Read from stdin:\ncollins find -n develnode | \#{PROG_NAME} -d my_attribute\ncollins find -n develnode -S allocated | \#{PROG_NAME} -a collectd_version:5.2.1-52\necho -e \"001234\\\\n001235\\\\n001236\"| \#{PROG_NAME} -a test_attribute:'hello world'\n"
  end.parse!(argv)
  if options[:tags].nil? or options[:tags].empty?
    # read tags from stdin. first field on the line is the tag
    input = ARGF.readlines
    @options[:tags] = input.map{|l| l.split(/\s+/)[0] rescue nil}.compact.uniq
  end
  @parsed = true
  self
end

#run!Object



123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
# File 'lib/collins/cli/modify.rb', line 123

def run!
  exit_clean = true
  options[:tags].each do |t|
    if options[:log_message]
      exit_clean = api_call("logging #{options[:log_level].downcase} #{options[:log_message].inspect}", :log!, t, options[:log_message], options[:log_level]) && exit_clean
    end
    options[:attributes].each do |k,v|
      exit_clean = api_call("setting #{k}=#{v}", :set_attribute!, t, k, v) && exit_clean
    end
    options[:delete_attributes].each do |k|
      exit_clean = api_call("deleting #{k}", :delete_attribute!, t, k) && exit_clean
    end
    if options[:status]
      exit_clean = api_call("changing status to #{options[:status]}#{options[:state] ? ":#{options[:state]}" : ''}", :set_status!, t, :status => options[:status], :state => options[:state], :reason => options[:reason]) && exit_clean
    end
  end
  exit_clean
end

#validate!Object



105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
# File 'lib/collins/cli/modify.rb', line 105

def validate!
  raise "See --help for #{PROG_NAME} usage" if options[:attributes].empty? and options[:delete_attributes].empty? and options[:status].nil? and options[:log_message].nil?
  raise "You need to provide a --reason when changing asset states!" if not options[:status].nil? and options[:reason].nil?
  #TODO this is never checked because we are making option parser vet our options for levels. Catch OptionParser::InvalidArgument?
  raise "Log level #{options[:log_level]} is invalid! Use one of #{LOG_LEVELS.join(', ')}" unless Collins::Api::Logging::Severity.valid?(options[:log_level])

  # if any statuses or states, validate them against allowed values
  unless options[:status].nil?
    raise "Invalid status #{options[:status]} (Should be in #{VALID_STATUSES.join(', ')})" unless VALID_STATUSES.include? options[:status]
  states_for_status = VALID_STATES["ANY"].concat((VALID_STATES[options[:status]].nil?) ? [] : VALID_STATES[options[:status]])
    raise "State #{options[:state]} doesn't apply to status #{options[:status]} (Should be one of #{states_for_status.join(', ')})" unless options[:state].nil? or states_for_status.include?(options[:state])
  end


  @validated = true
  self
end