Class: DatadogSync

Inherits:
Object
  • Object
show all
Defined in:
lib/datadog_sync/base.rb,
lib/datadog_sync/errors.rb,
lib/datadog_sync/version.rb,
lib/datadog_sync/save_dashboards.rb

Constant Summary collapse

AlreadyExists =
Class.new(RuntimeError)
VERSION =
'0.0.1'

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(api_key, app_key) ⇒ DatadogSync

Returns a new instance of DatadogSync.



4
5
6
# File 'lib/datadog_sync/base.rb', line 4

def initialize(api_key, app_key)
  @dd_client = Dogapi::Client.new(api_key, app_key)
end

Instance Attribute Details

#dd_clientObject (readonly)

Returns the value of attribute dd_client.



2
3
4
# File 'lib/datadog_sync/base.rb', line 2

def dd_client
  @dd_client
end

Instance Method Details

#sanitize_filename(filename) ⇒ Object



8
9
10
# File 'lib/datadog_sync/base.rb', line 8

def sanitize_filename(filename)
  filename.gsub(/[\?\*\/\\]/, "_")
end

#save_dashboards(dashboards_path, title_pattern = "") ⇒ Object



2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/datadog_sync/save_dashboards.rb', line 2

def save_dashboards(dashboards_path, title_pattern="")
  regex = Regexp.new(title_pattern)
  base_path = File.expand_path(dashboards_path)

  if File.file?(base_path)
    raise AlreadyExists, "Provided gashboards path already exists and it's not a directory."
  elsif !File.directory?(base_path)
    puts "Creating directory for dashboards: '#{base_path}'"
    FileUtils.mkdir_p(base_path)
  end

  all_dashes = dd_client.get_dashboards[1]["dashes"]

  puts "Found #{all_dashes.count} dashboards"

  filtered_dashes = all_dashes.select { |dash| dash["title"] =~ regex }
  filtered_dashes_ids = filtered_dashes.collect { |dash| dash["id"] }

  puts "Saving #{filtered_dashes.count} dashboards with pattern /#{title_pattern}/ into '#{base_path}'"

  filtered_dashes_ids.each do |dash_id|
    dash_data = dd_client.get_dashboard(dash_id)[1]["dash"]
    filename = sanitize_filename(dash_data["title"])
    filepath = File.join(base_path, "#{filename}.json")
    File.open(filepath, "wb") do |f|
      f.puts JSON.pretty_generate(dash_data)
    end
  end
end