Class: Bosh::Agent::State

Inherits:
Object show all
Defined in:
lib/bosh_agent/state.rb

Instance Method Summary collapse

Constructor Details

#initialize(state_file) ⇒ State

Returns a new instance of State.



14
15
16
17
18
19
# File 'lib/bosh_agent/state.rb', line 14

def initialize(state_file)
  @state_file = state_file
  @lock = Mutex.new
  @data = nil
  read
end

Instance Method Details

#[](key) ⇒ Object

Fetches the state from file (unless it’s been already fetched) and returns the value of a given key.

Parameters:

  • key

    Key that will be looked up in state hash



24
25
26
# File 'lib/bosh_agent/state.rb', line 24

def [](key)
  @lock.synchronize { @data[key] }
end

#ipsObject



32
33
34
35
36
37
38
39
40
41
42
# File 'lib/bosh_agent/state.rb', line 32

def ips
  result = []
  networks = self["networks"] || {}
  return [] unless networks.kind_of?(Hash)

  networks.each_pair do |name, network |
    result << network["ip"] if network["ip"]
  end

  result
end

#readObject

Reads the current agent state from the state file and saves it internally. Empty file is fine but malformed file raises an exception.



46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/bosh_agent/state.rb', line 46

def read
  @lock.synchronize do
    if File.exists?(@state_file)
      state = Psych.load_file(@state_file) || default_state
      unless state.kind_of?(Hash)
        raise_format_error(state)
      end
      @data = state
    else
      @data = default_state
    end
  end

  self
rescue SystemCallError => e
  raise StateError, "Cannot read agent state file `#{@state_file}': #{e}"
rescue Psych::SyntaxError
  raise StateError, "Malformed agent state: #{e}"
end

#to_hashObject



28
29
30
# File 'lib/bosh_agent/state.rb', line 28

def to_hash
  @lock.synchronize { @data.dup }
end

#write(new_state) ⇒ Object

Writes a new agent state into the state file.

Parameters:

  • new_state

    Hash New state



68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
# File 'lib/bosh_agent/state.rb', line 68

def write(new_state)
  unless new_state.is_a?(Hash)
    raise_format_error(new_state)
  end

  @lock.synchronize do
    File.open(@state_file, "w") do |f|
      f.puts(Psych.dump(new_state))
    end
    @data = new_state
  end

  true
rescue SystemCallError, Psych::SyntaxError => e
  raise StateError, "Cannot write agent state file `#{@state_file}': #{e}"
end