summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorNoah Kantrowitz <noah@coderanger.net>2017-04-03 11:36:08 -0500
committerNoah Kantrowitz <noah@coderanger.net>2017-04-03 11:36:37 -0500
commite5161b5f9ee4a74dc70d785c955df48ba7882e4e (patch)
treeaa406d417e170f20a626f02a6b3f77d637270594
parent05cf05cb76ae22af9a8466e0226d0092b74c8414 (diff)
downloadohai-e5161b5f9ee4a74dc70d785c955df48ba7882e4e.tar.gz
Freeze all string values coming out of Ohai.
This both helps avoid weird mutation bugs and saves a bit of RAM. Refs https://github.com/chef/chef/issues/4930 Signed-off-by: Noah Kantrowitz <noah@coderanger.net>
-rw-r--r--lib/ohai/system.rb23
-rw-r--r--spec/unit/system_spec.rb4
2 files changed, 27 insertions, 0 deletions
diff --git a/lib/ohai/system.rb b/lib/ohai/system.rb
index e66ba90b..d2a8243a 100644
--- a/lib/ohai/system.rb
+++ b/lib/ohai/system.rb
@@ -107,6 +107,9 @@ module Ohai
Ohai::Log.error("Encountered error while running plugins: #{e.inspect}")
raise
end
+
+ # Freeze all strings.
+ freeze_strings!
end
def have_v6_plugin?(name)
@@ -231,5 +234,25 @@ module Ohai
Ohai::Log.level = Ohai.config[:log_level]
end
end
+
+ # Freeze all string values in @data. This makes them immutable and saves
+ # a bit of RAM.
+ #
+ # @api private
+ # @return [void]
+ def freeze_strings!
+ # Recursive visitor pattern helper.
+ visitor = lambda do |val|
+ case val
+ when Hash
+ val.each_value {|v| visitor.call(v) }
+ when Array
+ val.each {|v| visitor.call(v) }
+ when String
+ val.freeze
+ end
+ end
+ visitor.call(@data)
+ end
end
end
diff --git a/spec/unit/system_spec.rb b/spec/unit/system_spec.rb
index 3bfafcf1..0941b1f0 100644
--- a/spec/unit/system_spec.rb
+++ b/spec/unit/system_spec.rb
@@ -166,6 +166,8 @@ EOF
ohai.all_plugins
expect(ohai.data[:zoo]).to eq("animals")
expect(ohai.data[:park]).to eq("plants")
+ expect(ohai.data[:zoo]).to be_frozen
+ expect(ohai.data[:park]).to be_frozen
end
describe "when using :disabled_plugins" do
@@ -312,6 +314,8 @@ EOF
ohai.all_plugins
expect(ohai.data[:zoo]).to eq("animals")
expect(ohai.data[:park]).to eq("plants")
+ expect(ohai.data[:zoo]).to be_frozen
+ expect(ohai.data[:park]).to be_frozen
end
it "should write an error to Ohai::Log" do