Class: WavefrontCli::Base
- Inherits:
-
Object
- Object
- WavefrontCli::Base
- Includes:
- Wavefront::Validators
- Defined in:
- lib/wavefront-cli/base.rb
Overview
Parent of all the CLI classes. This class uses metaprogramming techniques to try to make adding new CLI commands and sub-commands as simple as possible.
To define a subcommand ‘cmd’, you only need add it to the docopt description in the relevant section, and create a method ‘do_cmd’. The WavefrontCli::Base::dispatch() method will find it, and call it. If your subcommand has multiple words, like ‘delete tag’, your do method would be called do_delete_tag. The do_ methods are able to access the Wavefront SDK object as wf, and all docopt options as options.
Direct Known Subclasses
Alert, CloudIntegration, Dashboard, Event, ExternalLink, MaintenanceWindow, Message, Metric, Proxy, Query, SavedSearch, Source, User, Webhook, Write
Instance Attribute Summary collapse
-
#klass ⇒ Object
Returns the value of attribute klass.
-
#klass_word ⇒ Object
Returns the value of attribute klass_word.
-
#options ⇒ Object
Returns the value of attribute options.
-
#wf ⇒ Object
Returns the value of attribute wf.
Instance Method Summary collapse
- #check_status(status) ⇒ Object
-
#dispatch ⇒ nil
Works out the user’s command by matching any options docopt has set to ‘true’ with any ‘do_’ method in the class.
-
#display(data, method) ⇒ Object
Display a Ruby object as JSON, YAML, or human-readable.
- #do_delete ⇒ Object
- #do_describe ⇒ Object
- #do_import ⇒ Object
-
#do_list ⇒ Object
Below here are common methods.
- #do_tag_add ⇒ Object
- #do_tag_clear ⇒ Object
- #do_tag_delete ⇒ Object
- #do_tag_set ⇒ Object
- #do_tags ⇒ Object
- #do_undelete ⇒ Object
- #do_update ⇒ Object
-
#format_var ⇒ Symbol
To allow a user to default to different output formats for different object, we define a format for each class.
-
#handle_error(method, code) ⇒ Object
This gives us a chance to catch different errors in WavefrontDisplay classes.
- #handle_response(resp, format, method) ⇒ Object
-
#import_to_create(raw) ⇒ Object
Most things will re-import with the POST method if you remove the ID.
-
#initialize(options) ⇒ Base
constructor
A new instance of Base.
- #load_display_class ⇒ Object
-
#load_file(path) ⇒ Hash
Give it a path to a file (as a string) and it will return the contents of that file as a Ruby object.
-
#mk_creds ⇒ Hash
Make a wavefront-sdk credentials object from standard options.
-
#mk_opts ⇒ Hash
Make a common wavefront-sdk options object from standard CLI options.
- #run ⇒ Object
- #validate_id ⇒ Object
- #validate_input ⇒ Object
-
#validate_opts ⇒ Object
There are things we need to have.
- #validate_tags ⇒ Object
- #validator_exception ⇒ Object
-
#validator_method ⇒ Object
We normally validate with a predictable method name.
Constructor Details
#initialize(options) ⇒ Base
Returns a new instance of Base.
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
# File 'lib/wavefront-cli/base.rb', line 28 def initialize() @options = sdk_class = self.class.name.sub(/Cli/, '') @klass_word = sdk_class.split('::').last.downcase validate_input if .include?(:help) && [:help] puts exit 0 end require File.join('wavefront-sdk', @klass_word) @klass = Object.const_get(sdk_class) send(:post_initialize, ) if respond_to?(:post_initialize) end |
Instance Attribute Details
#klass ⇒ Object
Returns the value of attribute klass.
24 25 26 |
# File 'lib/wavefront-cli/base.rb', line 24 def klass @klass end |
#klass_word ⇒ Object
Returns the value of attribute klass_word.
24 25 26 |
# File 'lib/wavefront-cli/base.rb', line 24 def klass_word @klass_word end |
#options ⇒ Object
Returns the value of attribute options.
24 25 26 |
# File 'lib/wavefront-cli/base.rb', line 24 def @options end |
#wf ⇒ Object
Returns the value of attribute wf.
24 25 26 |
# File 'lib/wavefront-cli/base.rb', line 24 def wf @wf end |
Instance Method Details
#check_status(status) ⇒ Object
187 188 189 |
# File 'lib/wavefront-cli/base.rb', line 187 def check_status(status) status.respond_to?(:result) && status.result == 'OK' end |
#dispatch ⇒ nil
Works out the user’s command by matching any options docopt has set to ‘true’ with any ‘do_’ method in the class. Then calls that method, and displays whatever it returns.
126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 |
# File 'lib/wavefront-cli/base.rb', line 126 def dispatch # # Take a list of do_ methods, remove the 'do_' from their name, # and break them into arrays of '_' separated words. # m_list = methods.select { |m| m.to_s.start_with?('do_') }.map do |m| m.to_s.split('_')[1..-1] end # Sort that array of arrays by length, longest first. Then look # through each deconstructed method name and see if the user # supplied an option for each component. Call the first one that # matches. The order will ensure we match "do_delete_tags" before # we match "do_delete". # m_list.sort_by(&:length).reverse.each do |m| if m.reject { |w| [w.to_sym] }.empty? method = (%w(do) + m).join('_') return display(public_send(method), method) end end if respond_to?(:do_default) return display(public_send(:do_default), :do_default) end raise WavefrontCli::Exception::UnhandledCommand end |
#display(data, method) ⇒ Object
Display a Ruby object as JSON, YAML, or human-readable. We provide a default method to format human-readable output, but you can override it by creating your own humanize_command_output method control how its output is handled by setting the response instance variable.
168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 |
# File 'lib/wavefront-cli/base.rb', line 168 def display(data, method) [:status, :response].each do |b| abort "no #{b} block in API response" unless data.respond_to?(b) end unless check_status(data.status) handle_error(method, data.status.code) if format_var == :human abort "API #{data.status.code}: #{data.status.}." end resp = if data.response.respond_to?(:items) data.response.items else data.response end handle_response(resp, format_var, method) end |
#do_delete ⇒ Object
280 281 282 |
# File 'lib/wavefront-cli/base.rb', line 280 def do_delete wf.delete([:'<id>']) end |
#do_describe ⇒ Object
263 264 265 |
# File 'lib/wavefront-cli/base.rb', line 263 def do_describe wf.describe([:'<id>']) end |
#do_import ⇒ Object
267 268 269 270 271 272 273 274 275 276 277 278 |
# File 'lib/wavefront-cli/base.rb', line 267 def do_import raw = load_file([:'<file>']) begin prepped = import_to_create(raw) rescue => e puts e if [:debug] raise 'could not parse input.' end wf.create(prepped) end |
#do_list ⇒ Object
Below here are common methods. Most are used by most classes, but if they don’t match a command described in the docopt text, the dispatcher will never call them. So, there’s no harm inheriting unneeded things. Some classes override them.
259 260 261 |
# File 'lib/wavefront-cli/base.rb', line 259 def do_list wf.list([:offset] || 0, [:limit] || 100) end |
#do_tag_add ⇒ Object
297 298 299 |
# File 'lib/wavefront-cli/base.rb', line 297 def do_tag_add wf.tag_add([:'<id>'], [:'<tag>'].first) end |
#do_tag_clear ⇒ Object
309 310 311 |
# File 'lib/wavefront-cli/base.rb', line 309 def do_tag_clear wf.tag_set([:'<id>'], []) end |
#do_tag_delete ⇒ Object
301 302 303 |
# File 'lib/wavefront-cli/base.rb', line 301 def do_tag_delete wf.tag_delete([:'<id>'], [:'<tag>'].first) end |
#do_tag_set ⇒ Object
305 306 307 |
# File 'lib/wavefront-cli/base.rb', line 305 def do_tag_set wf.tag_set([:'<id>'], [:'<tag>']) end |
#do_tags ⇒ Object
293 294 295 |
# File 'lib/wavefront-cli/base.rb', line 293 def wf.([:'<id>']) end |
#do_undelete ⇒ Object
284 285 286 |
# File 'lib/wavefront-cli/base.rb', line 284 def do_undelete wf.undelete([:'<id>']) end |
#do_update ⇒ Object
288 289 290 291 |
# File 'lib/wavefront-cli/base.rb', line 288 def do_update k, v = [:'<key=value>'].split('=') wf.update([:'<id>'], k => v) end |
#format_var ⇒ Symbol
To allow a user to default to different output formats for different object, we define a format for each class. For instance, alertformat or agentformat. This method returns such a string appropriate for the inheriting class.
113 114 115 116 |
# File 'lib/wavefront-cli/base.rb', line 113 def format_var [:format].to_sym # (self.class.name.split('::').last.downcase + 'format').to_sym end |
#handle_error(method, code) ⇒ Object
This gives us a chance to catch different errors in WavefrontDisplay classes. If nothing catches, them abort.
194 195 196 197 |
# File 'lib/wavefront-cli/base.rb', line 194 def handle_error(method, code) k = load_display_class k.new({}, ).run_error([method, code].join('_')) end |
#handle_response(resp, format, method) ⇒ Object
199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 |
# File 'lib/wavefront-cli/base.rb', line 199 def handle_response(resp, format, method) case format when :json puts resp.to_json when :yaml # We don't want the YAML keys to be symbols. puts JSON.parse(resp.to_json).to_yaml when :ruby p resp when :human k = load_display_class k.new(resp, ).run(method) else raise "Unknown output format '#{format}'." end end |
#import_to_create(raw) ⇒ Object
Most things will re-import with the POST method if you remove the ID.
316 317 318 |
# File 'lib/wavefront-cli/base.rb', line 316 def import_to_create(raw) raw.delete_if { |k, _v| k == 'id' } end |
#load_display_class ⇒ Object
215 216 217 218 |
# File 'lib/wavefront-cli/base.rb', line 215 def load_display_class require_relative File.join('display', klass_word) Object.const_get(klass.name.sub('Wavefront', 'WavefrontDisplay')) end |
#load_file(path) ⇒ Hash
Give it a path to a file (as a string) and it will return the contents of that file as a Ruby object. Automatically detects JSON and YAML. Raises an exception if it doesn’t look like either.
241 242 243 244 245 246 247 248 249 250 251 252 |
# File 'lib/wavefront-cli/base.rb', line 241 def load_file(path) file = Pathname.new(path) raise 'Import file does not exist.' unless file.exist? if file.extname == '.json' JSON.parse(IO.read(file)) elsif file.extname == '.yaml' || file.extname == '.yml' YAML.safe_load(IO.read(file)) else raise 'Unsupported file format.' end end |
#mk_creds ⇒ Hash
Make a wavefront-sdk credentials object from standard options.
91 92 93 |
# File 'lib/wavefront-cli/base.rb', line 91 def mk_creds { token: [:token], endpoint: [:endpoint] } end |
#mk_opts ⇒ Hash
Make a common wavefront-sdk options object from standard CLI options.
100 101 102 103 |
# File 'lib/wavefront-cli/base.rb', line 100 def mk_opts { debug: [:debug], verbose: [:verbose], noop: [:noop] } end |
#run ⇒ Object
45 46 47 48 |
# File 'lib/wavefront-cli/base.rb', line 45 def run @wf = klass.new(mk_creds, mk_opts) dispatch end |
#validate_id ⇒ Object
80 81 82 83 84 |
# File 'lib/wavefront-cli/base.rb', line 80 def validate_id send(validator_method, [:'<id>']) rescue validator_exception abort "'#{[:'<id>']}' is not a valid #{klass_word} ID." end |
#validate_input ⇒ Object
64 65 66 67 68 |
# File 'lib/wavefront-cli/base.rb', line 64 def validate_input validate_id if [:'<id>'] if [:'<tag>'] send(:extra_validation) if respond_to?(:extra_validation) end |
#validate_opts ⇒ Object
There are things we need to have. If we don’t have them, stop the user right now. Also, if we’re in debug mode, print out a hash of options, which can be very useful when doing actual debugging. Some classes may have to override this method. The writer, for instance, uses a proxy and has no token.
226 227 228 229 |
# File 'lib/wavefront-cli/base.rb', line 226 def validate_opts raise 'Please supply an API token.' unless [:token] raise 'Please supply an API endpoint.' unless [:endpoint] end |
#validate_tags ⇒ Object
70 71 72 73 74 75 76 77 78 |
# File 'lib/wavefront-cli/base.rb', line 70 def Array([:'<tag>']).each do |t| begin send(:wf_tag?, t) rescue Wavefront::Exception::InvalidTag abort "'#{t}' is not a valid tag." end end end |
#validator_exception ⇒ Object
58 59 60 61 62 |
# File 'lib/wavefront-cli/base.rb', line 58 def validator_exception Object.const_get( "Wavefront::Exception::Invalid#{klass_word.capitalize}Id" ) end |
#validator_method ⇒ Object
We normally validate with a predictable method name. Alert IDs are validated with #wf_alert_id? etc. If you need to change that, override this method.
54 55 56 |
# File 'lib/wavefront-cli/base.rb', line 54 def validator_method "wf_#{klass_word}_id?".to_sym end |