Class: CommonMob::Shell

Inherits:
Object
  • Object
show all
Defined in:
lib/common_mob/shell.rb

Defined Under Namespace

Classes: ShellResult

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(*args, &block) ⇒ Shell

Returns a new instance of Shell.



28
29
30
31
32
33
34
35
36
37
# File 'lib/common_mob/shell.rb', line 28

def initialize(*args,&block)
  @block = block
  @options = if Hash === args.last then args.pop else {} end

  unless args.empty?
    @options[:cmd] = args
  end

  @options[:stream] = false unless @options.key?(:stream)
end

Instance Attribute Details

#optionsObject (readonly)

Returns the value of attribute options.



26
27
28
# File 'lib/common_mob/shell.rb', line 26

def options
  @options
end

Instance Method Details

#debug(*msg) ⇒ Object



22
23
24
# File 'lib/common_mob/shell.rb', line 22

def debug(*msg)
  AngryMob::Mob.ui.debug "sh: #{msg * ' '}"
end

#executeObject



39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/common_mob/shell.rb', line 39

def execute
  error,out = nil,nil

  rv = popen4(options) {|pid,stdin,stdout,stderr|
    out   = stdout.read
    error = stderr.read
  }
  
  # TODO print as debug

  rv.stderr = error
  rv.stdout = out

  rv
end

#massaged_args(args) ⇒ Object



302
303
304
305
306
307
308
309
310
311
312
# File 'lib/common_mob/shell.rb', line 302

def massaged_args args
  returning(args.dup) do |args_to_print|
    args_to_print[:environment] = e = args[:environment].dup

    %w{LC_ALL GEM_HOME GEM_PATH RUBYOPT BUNDLE_GEMFILE}.each {|env| e.delete(env)}

    args_to_print['cwd'] = args_to_print['cwd'].to_s if args_to_print['cwd']

    args_to_print.delete_if{|k,v| v.blank?}
  end
end

#ok?Boolean

Returns:

  • (Boolean)


59
60
61
# File 'lib/common_mob/shell.rb', line 59

def ok?
  execute.ok?
end

#popen4(args = {}, &b) ⇒ Object

This is taken directly from Chef and then modified to suit the needs of Igor.

This is taken directly from Ara T Howard’s Open4 library, and then modified to suit the needs of Chef. Any bugs here are most likely my own, and not Ara’s.

The original appears in external/open4.rb in its unmodified form.

Thanks Ara!



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
290
291
292
293
294
295
296
297
298
299
300
# File 'lib/common_mob/shell.rb', line 95

def popen4(args={}, &b)

  cmd = args[:cmd]

 
  # Do we wait for the child process to die before we yield
  # to the block, or after?
  #
  # By default, we are waiting before we yield the block.
  args[:stream] ||= false
  

  args[:user] ||= nil
  unless args[:user].kind_of?(Integer)
    args[:user] = Etc.getpwnam(args[:user]).uid if args[:user]
  end

  args[:group] ||= nil
  unless args[:group].kind_of?(Integer)
    args[:group] = Etc.getgrnam(args[:group]).gid if args[:group]
  end


  args[:environment] ||= {}

  # Default on C locale so parsing commands output can be done
  # independently of the node's default locale.
  # "LC_ALL" could be set to nil, in which case we also must ignore it.
  unless args[:environment].has_key?("LC_ALL")
    args[:environment]["LC_ALL"] = "C"
  end

  unless TrueClass === args[:without_cleaning_bundler]
    args[:environment].update('RUBYOPT' => nil, 'BUNDLE_GEMFILE' => nil, 'GEM_HOME' => nil, 'GEM_PATH' => nil)
  end

  if user = args[:as]
    if (evars = args[:environment].reject {|k,v| v.nil?}.map {|k,v| "#{k}=#{v}"}) && !evars.empty?
      env = "env #{evars.join(' ')}"
    else
      env = ''
    end
    
    cmd = "sudo -H -u #{user} #{env} #{cmd}"
  end

  # debug "running #{cmd} #{massaged_args(args).inspect}"
  
  pwrite, pread, perror, pexception = IO.pipe, IO.pipe, IO.pipe, IO.pipe

  verbose = $VERBOSE
  begin
    $VERBOSE = nil
    pexception.last.fcntl(Fcntl::F_SETFD, Fcntl::FD_CLOEXEC)

    cid = fork {
      pwrite.last.close
      STDIN.reopen pwrite.first
      pwrite.first.close

      pread.first.close
      STDOUT.reopen pread.last
      pread.last.close

      perror.first.close
      STDERR.reopen perror.last
      perror.last.close

      STDOUT.sync = STDERR.sync = true

      if args[:group]
        Process.egid = args[:group]
        Process.gid = args[:group]
      end

      if args[:user]
        Process.euid = args[:user]
        Process.uid = args[:user]
      end

      # Copy the specified environment across to the child's environment.
      # Keys with `nil` values are deleted from the environment.
      args[:environment].each do |key,value|
        if value.nil?
          ENV.delete(key.to_s)
        else
          ENV[key.to_s] = value
        end
      end

      if args[:umask]
        umask = ((args[:umask].respond_to?(:oct) ? args[:umask].oct : args[:umask].to_i) & 007777)
        File.umask(umask)
      end

      if args[:cwd]
        Dir.chdir args[:cwd]
      end
      
      begin
        if cmd.kind_of?(Array)
          exec(*cmd)
        else
          exec(cmd)
        end
        raise 'forty-two' 
      rescue Exception => e
        Marshal.dump(e, pexception.last)
        pexception.last.flush
      end
      pexception.last.close unless (pexception.last.closed?)
      exit!
    }
  ensure
    $VERBOSE = verbose
  end

  [pwrite.first, pread.last, perror.last, pexception.last].each{|fd| fd.close}

  begin
    e = Marshal.load pexception.first
    raise(Exception === e ? e : "unknown failure!")
  rescue EOFError # If we get an EOF error, then the exec was successful
    42
  ensure
    pexception.first.close
  end

  pwrite.last.sync = true

  pi = [pwrite.last, pread.first, perror.first]

  if b 
    begin
      if args[:stream]
        b[cid, *pi]
        ShellResult.new(Process.waitpid2(cid).last, args)
      else
        o = StringIO.new
        e = StringIO.new

        if args[:input]
          pi[0].puts args[:input]
        end

        pi[0].close
        
        stdout = pi[1]
        stderr = pi[2]

        stdout.sync = true
        stderr.sync = true

        stdout.fcntl(Fcntl::F_SETFL, pi[1].fcntl(Fcntl::F_GETFL) | Fcntl::O_NONBLOCK)
        stderr.fcntl(Fcntl::F_SETFL, pi[2].fcntl(Fcntl::F_GETFL) | Fcntl::O_NONBLOCK)
        
        stdout_finished = false
        stderr_finished = false
       
        results = nil

        while !stdout_finished || !stderr_finished
          begin
            channels_to_watch = []
            channels_to_watch << stdout if !stdout_finished
            channels_to_watch << stderr if !stderr_finished
            ready = IO.select(channels_to_watch, nil, nil, 1.0)
          rescue Errno::EAGAIN
            results = Process.waitpid2(cid, Process::WNOHANG)
            if results
              stdout_finished = true
              stderr_finished = true 
            end
          end

          if ready && ready.first.include?(stdout)
            line = results ? stdout.gets(nil) : stdout.gets
            if line
              o.write(line)
            else
              stdout_finished = true
            end
          end
          if ready && ready.first.include?(stderr)
            line = results ? stderr.gets(nil) : stderr.gets
            if line
              e.write(line)
            else
              stderr_finished = true
            end
          end
        end
        results = Process.waitpid2(cid).last unless results
        o.rewind
        e.rewind
        b[cid, pi[0], o, e]

        ShellResult.new(results, args)
      end
    ensure
      pi.each{|fd| fd.close unless fd.closed?}
    end
  else
    [cid, pw.last, pr.first, pe.first]
  end
end

#runObject



55
56
57
# File 'lib/common_mob/shell.rb', line 55

def run
  execute.ensure_ok!
end

#to_sObject



63
64
65
66
67
68
69
70
# File 'lib/common_mob/shell.rb', line 63

def to_s
  result = execute
  if result.ok?
    result.stdout.chomp
  else
    ''
  end
end