Module: FluentGem

Defined in:
app/models/fluent_gem.rb

Defined Under Namespace

Classes: GemError

Constant Summary collapse

LIST_CACHE_KEY =
"gem_list".freeze

Class Method Summary collapse

Class Method Details

.detect_td_agent_gemObject



56
57
58
59
60
61
62
63
64
65
66
67
# File 'app/models/fluent_gem.rb', line 56

def detect_td_agent_gem
  # NOTE: td-agent has a command under the /usr/lib{,64}, td-agent2 has under /opt/td-agent
  %W(
    /usr/sbin/td-agent-gem
    /opt/td-agent/embedded/bin/fluent-gem
    /usr/lib/fluent/ruby/bin/fluent-gem
    /usr/lib64/fluent/ruby/bin/fluent-gem
    fluent-gem
  ).find do |path|
    system("which #{path}", out: File::NULL, err: File::NULL)
  end
end

.gemObject



44
45
46
47
48
49
50
51
52
53
54
# File 'app/models/fluent_gem.rb', line 44

def gem
  # Not yet setup any fluentd/td-agent
  return "fluent-gem" unless Fluentd.instance

  # On installed both td-agent and fluentd system, decide which fluent-gem command should be used depend on setup(Fluentd.instance)
  if Fluentd.instance && Fluentd.instance.fluentd?
    "fluent-gem" # maybe `fluent-gem` command is in the $PATH
  else
    detect_td_agent_gem
  end
end

.install(*args) ⇒ Object



7
8
9
# File 'app/models/fluent_gem.rb', line 7

def install(*args)
  run("install", *args)
end

.listObject



15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'app/models/fluent_gem.rb', line 15

def list
  # NOTE: gem list is heavyly used from anywhere in 1 request, if not caching, user experience to be bad
  #       but long living caching causes mismatch with actual status e.g. user install plugin from console (without fluentd-ui)
  #       So our decision is that cache `gem list` in 3 seconds
  Rails.cache.fetch(LIST_CACHE_KEY, expires_in: 3.seconds) do
    last_status = $?
    output = `#{gem} list 2>&1`
    # https://github.com/fluent/fluentd-ui/pull/149#issuecomment-71954588
    # Sometimes, $? wouldn't override with `#{gem} list` but I don't know why..
    if $? && last_status != $? && $?.exitstatus != 0 # NOTE: $? will be nil on CircleCI, so check $? at first
      raise GemError, "failed command: `#{gem} list` output: #{output}"
    end
    output.lines.to_a
  end
end

.run(*args) ⇒ Object



31
32
33
34
35
36
37
38
39
40
41
42
# File 'app/models/fluent_gem.rb', line 31

def run(*args)
  # NOTE: use `fluent-gem` instead of `gem`
  Bundler.with_clean_env do
    # NOTE: this app is under the Bundler, so call `system` in with_clean_env is Bundler jail breaking
    cmd = [gem, *args].compact
    unless system(*cmd)
      raise GemError, "failed command: `#{cmd.join(" ")}`"
    end
    Rails.cache.delete(LIST_CACHE_KEY)
  end
  true
end

.uninstall(*args) ⇒ Object



11
12
13
# File 'app/models/fluent_gem.rb', line 11

def uninstall(*args)
  run("uninstall", *args)
end