list_processes

in chefctl/src/chefctl.rb [463:544]


      def list_processes(command, exclude = nil, parents = false,
                         same_nsid = true)
        check_nsid = same_nsid
        exclude ||= []
        procs = []

        
        
        
        
        begin
          out = shell_output('ps -e -o pid,pidns,command 2>/dev/null')
          out.lines.each do |l|
            fields = l.split
            procs << {
              :pid => fields[0].to_i,
              :nsid => fields[1],
              :command => fields[2..fields.length].join(' '),
            }
          end
        rescue Mixlib::ShellOut::ShellCommandFailed
          check_nsid = false
          out = shell_output('ps -e -o pid,command')
          out.lines.each do |l|
            fields = l.split
            procs << {
              :pid => fields[0].to_i,
              :nsid => nil,
              :command => fields[1..fields.length].join(' '),
            }
          end
        end

        
        case command
        when String
          procs.select! { |p| p[:command].include?(command) }
        when Regexp
          procs.select! { |p| command =~ p[:command] }
        end

        
        exclude.each do |b|
          procs.reject! { |p| b =~ p[:command] }
        end

        
        unless parents
          ppids = parent_group(Process.pid)
          procs.reject! { |p| ppids.include?(p[:pid]) }
        end

        
        
        
        nsid_f = "/proc/#{Process.pid}/ns/pid"
        if File.exist?(nsid_f) && check_nsid
          pid_ns = File.readlink(nsid_f)
          r = /pid:\[(\d*)\]/.match(pid_ns)
          if r
            procs.select! do |p|
              x = p[:nsid] == '-' || r[1] == p[:nsid]
              unless x
                Chefctl.logger.debug(
                  "Ignoring (#{p[:pid]},#{p[:command].inspect}) since it's " +
                  "in a different namespace #{p[:nsid]}",
                )
              end
              x
            end
          else
            Chefctl.logger.error(
              "Uh oh. I couldn't figure out my own pid nsid: #{pid_ns.inspect}",
            )
          end
        else
          Chefctl.logger.debug('Not checking for process namespaces.')
        end

        return procs
      end