Class: GrafanaSync::Stage

Inherits:
Object
  • Object
show all
Defined in:
lib/grafana_sync/stage.rb

Constant Summary collapse

DASHBOARDS_ROOT =
"dashboards"
FILE_ENCODING =
"UTF-8"
FILE_EXTENSION =
".json"
CREDENTIALS =
File.expand_path("~/.grafana_sync_rc")

Instance Method Summary collapse

Constructor Details

#initialize(stage:, make_folders: false, debug: false, logger: Logger.new(STDERR, level: Logger::INFO)) ⇒ Stage

Returns a new instance of Stage.



18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/grafana_sync/stage.rb', line 18

def initialize(stage:, make_folders: false, debug: false,
               logger: Logger.new(STDERR, level: Logger::INFO))
  @stage_name = stage
  @make_folders = make_folders
  @logger = logger
  HttpLog.configure do |config|
    config.logger = logger
    config.log_connect = false
    config.log_data = debug
    config.log_response = debug
    config.log_benchmark = false
  end

  GrafanaSync.load_config()
  validate_config!
  @base_url = stage_config[:url].chomp("/")
  folder = stage_config[:folder]
  # If there's no folder specified in Grafana dashboard config then it's "General".
  @folder_name = (folder == "General") ? nil : folder
end

Instance Method Details

#diffObject



64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
# File 'lib/grafana_sync/stage.rb', line 64

def diff
  dashboards_to_delete.keys.each do |key|
    puts("--- #{@stage_name}/#{key}")
    puts("+++ /dev/null")
    puts
  end

  dashboards_to_update.keys.sort.each do |key|
    diff_str = Diffy::Diff.new(JSON.pretty_generate(remote_dashboards[key]),
                               JSON.pretty_generate(local_dashboards[key]),
                               context: 3, diff: '-w', include_diff_info: true).to_s(:color)
    unless diff_str.chop.empty?
      puts("--- #{@stage_name}/#{key}")
      puts("+++ local/#{key}")
      puts(diff_str)
    end
  end
end

#pullObject



39
40
41
42
43
44
45
46
47
# File 'lib/grafana_sync/stage.rb', line 39

def pull
  FileUtils.mkdir_p(DASHBOARDS_ROOT)
  FileUtils.rm(dashboard_files)
  remote_dashboards.each do |title, db|
    @logger.info("Saving dashboard '#{title}'")
    IO.write(File.join(DASHBOARDS_ROOT, title+FILE_EXTENSION),
             JSON.pretty_generate(db), encoding: FILE_ENCODING, mode: "w")
  end
end

#pushObject



49
50
51
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/grafana_sync/stage.rb', line 49

def push
  dashboards_to_delete.each do |title, _db|
    @logger.info("Deleting dashboard '#{title}'")
    uid = dashboard_uid(title)
    http_delete("/api/dashboards/uid/#{uid}")
  end

  dashboards_to_update.each do |title, db|
    db["folderId"] = (folder_id or make_folder)
    db["overwrite"] = true
    @logger.info("Updating dashboard '#{title}'")
    http_post("/api/dashboards/db", json: db)
  end
end