summaryrefslogtreecommitdiff
path: root/lib/chef/provider/cron.rb
blob: c017c9d691afbd008a388ca680daaf8323aab189 (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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
#
# Author:: Bryan McLellan (btm@loftninjas.org)
# Copyright:: Copyright (c) 2009 Bryan McLellan
# 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.
#

require 'chef/log'
require 'chef/mixin/command'
require 'chef/provider'

class Chef
  class Provider
    class Cron < Chef::Provider
      include Chef::Mixin::ShellOut

      SPECIAL_TIME_VALUES = [:reboot, :yearly, :annually, :monthly, :weekly, :daily, :midnight, :hourly]
      CRON_ATTRIBUTES = [:minute, :hour, :day, :month, :weekday, :time, :command, :mailto, :path, :shell, :home, :environment]
      WEEKDAY_SYMBOLS = [:sunday, :monday, :tuesday, :wednesday, :thursday, :friday, :saturday]

      CRON_PATTERN = /\A([-0-9*,\/]+)\s([-0-9*,\/]+)\s([-0-9*,\/]+)\s([-0-9*,\/]+|[a-zA-Z]{3})\s([-0-9*,\/]+|[a-zA-Z]{3})\s(.*)/
      SPECIAL_PATTERN = /\A(@(#{SPECIAL_TIME_VALUES.join('|')}))\s(.*)/
      ENV_PATTERN = /\A(\S+)=(\S*)/

      def initialize(new_resource, run_context)
        super(new_resource, run_context)
        @cron_exists = false
        @cron_empty = false
      end
      attr_accessor :cron_exists, :cron_empty

      def whyrun_supported?
        true
      end

      def load_current_resource
        crontab_lines = []
        @current_resource = Chef::Resource::Cron.new(@new_resource.name)
        @current_resource.user(@new_resource.user(determine_user))
        @cron_exists = false
        if crontab = read_crontab
          cron_found = false
          crontab.each_line do |line|
            case line.chomp
            when "# Chef Name: #{@new_resource.name}"
              Chef::Log.debug("Found cron '#{@new_resource.name}'")
              cron_found = true
              @cron_exists = true
              next
            when ENV_PATTERN
              set_environment_var($1, $2) if cron_found
              next
            when SPECIAL_PATTERN
              if cron_found
                @current_resource.time($2.to_sym)
                @current_resource.command($3)
                cron_found=false
              end
            when CRON_PATTERN
              if cron_found
                @current_resource.minute($1)
                @current_resource.hour($2)
                @current_resource.day($3)
                @current_resource.month($4)
                @current_resource.weekday($5)
                @current_resource.command($6)
                cron_found=false
              end
              next
            else
              cron_found=false # We've got a Chef comment with no following crontab line
              next
            end
          end
          Chef::Log.debug("Cron '#{@new_resource.name}' not found") unless @cron_exists
        else
          Chef::Log.debug("Cron empty for '#{@new_resource.user}'")
          @cron_empty = true
        end

        @current_resource
      end

      def cron_different?
        CRON_ATTRIBUTES.any? do |cron_var|
          @new_resource.send(cron_var) != @current_resource.send(cron_var)
        end
      end

      def action_create
        crontab = String.new
        newcron = String.new
        cron_found = false

        newcron = get_crontab_entry

        if @cron_exists
          unless cron_different?
            Chef::Log.debug("Skipping existing cron entry '#{@new_resource.name}'")
            return
          end
          read_crontab.each_line do |line|
            case line.chomp
            when "# Chef Name: #{@new_resource.name}"
              cron_found = true
              next
            when ENV_PATTERN
              crontab << line unless cron_found
              next
            when SPECIAL_PATTERN
              if cron_found
                cron_found = false
                crontab << newcron
                next
              end
            when CRON_PATTERN
              if cron_found
                cron_found = false
                crontab << newcron
                next
              end
            else
              if cron_found # We've got a Chef comment with no following crontab line
                crontab << newcron
                cron_found = false
              end
            end
            crontab << line
          end

          # Handle edge case where the Chef comment is the last line in the current crontab
          crontab << newcron if cron_found

          converge_by("update crontab entry for #{@new_resource}") do
            write_crontab crontab
            Chef::Log.info("#{@new_resource} updated crontab entry")
          end

        else
          crontab = read_crontab unless @cron_empty
          crontab << newcron

          converge_by("add crontab entry for #{@new_resource}") do
            write_crontab crontab
            Chef::Log.info("#{@new_resource} added crontab entry")
          end
        end
      end

      def action_delete
        if @cron_exists
          crontab = String.new
          cron_found = false
          read_crontab.each_line do |line|
            case line.chomp
            when "# Chef Name: #{@new_resource.name}"
              cron_found = true
              next
            when ENV_PATTERN
              next if cron_found
            when SPECIAL_PATTERN
              if cron_found
                cron_found = false
                next
              end
            when CRON_PATTERN
              if cron_found
                cron_found = false
                next
              end
            else
              # We've got a Chef comment with no following crontab line
              cron_found = false
            end
            crontab << line
          end
          description = cron_found ? "remove #{@new_resource.name} from crontab" :
            "save unmodified crontab"
          converge_by(description) do
            write_crontab crontab
            Chef::Log.info("#{@new_resource} deleted crontab entry")
          end
        end
      end

      private

      def root?
        return false if Chef::Platform.windows?
        Process.euid == 0
      end

      def determine_user
        root? ? @new_resource.user : Etc.getpwuid(Process.uid).name
      end

      def set_environment_var(attr_name, attr_value)
        if %w(MAILTO PATH SHELL HOME).include?(attr_name)
          @current_resource.send(attr_name.downcase.to_sym, attr_value)
        else
          @current_resource.environment(@current_resource.environment.merge(attr_name => attr_value))
        end
      end

      def shell_out_crontab(*arguments)
        options = arguments.pop if arguments[-1].is_a?(Hash)
        # A great majority of the "crontab" (the user space binary) implementations
        # will only ever accept the "-u" flag when the user is either root or said
        # user has elevated privileges (effective UID is 0 via "sudo", etc.).
        crontab_cmd = "crontab "
        if root?
          crontab_cmd += "-u #{@new_resource.user} "
        else
          Chef::Log.warn("Not running as root! Will only be able to access cron jobs for user: #{@new_resource.user}")
        end
        crontab_cmd += arguments.join(' ')
        shell_out(crontab_cmd, options)
      end

      def read_crontab
        result = shell_out_crontab('-l')
        status = result.status.exitstatus

        # A non-zero exit code is an indicator of error for majority
        # of "crontab" (the user space binary) implementations,
        # like i.e., vixie-cron, cronie, dcron, fcron, bcron, etc.,
        # and even mcron which returns a whole range of exit codes.
        Chef::Log.debug(result.format_for_exception) if status > 0

        # Besides mcron, probably no other implementation
        # will ever emit exit code greater or equal to two.
        if status > 1
          raise Chef::Exceptions::Cron, "Error determining state of #{@new_resource.name}, exit: #{status}"
        end

        return nil if status > 0
        result.stdout
      end

      def write_crontab(content)
        result = shell_out_crontab('-', input: content)
        status = result.status.exitstatus

        # See note about viable exit codes in the "read_crontab" method.
        if status > 0
          Chef::Log.debug(result.format_for_exception)
          raise Chef::Exceptions::Cron, "Error updating state of #{@new_resource.name}, exit: #{status}"
        end
      end

      def get_crontab_entry
        newcron = ""
        newcron << "# Chef Name: #{new_resource.name}\n"
        [ :mailto, :path, :shell, :home ].each do |v|
          newcron << "#{v.to_s.upcase}=#{@new_resource.send(v)}\n" if @new_resource.send(v)
        end
        @new_resource.environment.each do |name, value|
          newcron << "#{name}=#{value}\n"
        end
        if @new_resource.time
          newcron << "@#{@new_resource.time} #{@new_resource.command}\n"
        else
          newcron << "#{@new_resource.minute} #{@new_resource.hour} #{@new_resource.day} #{@new_resource.month} #{@new_resource.weekday} #{@new_resource.command}\n"
        end
        newcron
      end

      def weekday_in_crontab
        weekday_in_crontab = WEEKDAY_SYMBOLS.index(@new_resource.weekday)
        if weekday_in_crontab.nil?
          @new_resource.weekday
        else
          weekday_in_crontab.to_s
        end
      end
    end
  end
end