summaryrefslogtreecommitdiff
path: root/lib/chef/data_collector/resource_report.rb
blob: 1793fe2c9d53051ad24979aa20fb06e1fc621c9c (plain)
1
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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
#
# Author:: Adam Leff (<adamleff@chef.io>)
# Author:: Ryan Cragun (<ryan@chef.io>)
#
# Copyright:: Copyright 2012-2016, Chef Software Inc.
# License:: Apache License, Version 2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

class Chef
  class DataCollector
    class ResourceReport

      attr_reader :action, :current_resource, :elapsed_time, :new_resource, :status
      attr_accessor :conditional, :exception

      def initialize(new_resource, action, current_resource = nil)
        @new_resource     = new_resource
        @action           = action
        @current_resource = current_resource
      end

      def skipped(conditional)
        @status      = "skipped"
        @conditional = conditional
      end

      def updated
        @status = "updated"
      end

      def failed(exception)
        @current_resource = nil
        @status           = "failed"
        @exception        = exception
      end

      def up_to_date
        @status = "up-to-date"
      end

      def finish
        @elapsed_time = new_resource.elapsed_time
      end

      def to_hash
        hash = {
          "type"     => new_resource.resource_name.to_sym,
          "name"     => new_resource.name.to_s,
          "id"       => new_resource.identity.to_s,
          "after"    => new_resource.state_for_resource_reporter,
          "before"   => current_resource ? current_resource.state_for_resource_reporter : {},
          "duration" => (elapsed_time * 1000).to_i.to_s,
          "delta"    => new_resource.respond_to?(:diff) ? new_resource.diff : "",
          "result"   => action.to_s,
          "status"   => status,
        }

        if new_resource.cookbook_name
          hash["cookbook_name"]    = new_resource.cookbook_name
          hash["cookbook_version"] = new_resource.cookbook_version.version
        end

        hash["conditional"]   = conditional.to_text if status == "skipped"
        hash["error_message"] = exception.message unless exception.nil?

        hash
      end
      alias :to_h :to_hash
      alias :for_json :to_hash
    end
  end
end