#!/usr/bin/env oo-ruby
#--
# Copyright 2010 Red Hat, Inc.
#
# 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.
#++

def usage
  puts <<USAGE
== Synopsis

#{$0}: Reclassify gear processes into cgroups
  This command must be run as root.

== Usage

To reclassify all gear processes not already in the correct group:
#{$0} --with-all-containers

To reclassify a specific gear's processes not already in the correct group:
#{$0} --with-container-uuid UUID

== List of arguments
  -c|--with-container-uuid  gear_uuid   Unique identifier for the gear
  -a|--with-all-containers              Run on all gears
  -d|--debug                            Enable debug mode
  -h|--help                             Print this message

USAGE
  exit 255
end

require 'rubygems'
require 'openshift-origin-node'
opts = GetoptLong.new(
    ["--with-container-uuid", "-c", GetoptLong::REQUIRED_ARGUMENT],
    ["--with-all-containers", "-a", GetoptLong::NO_ARGUMENT],
    ["--debug",               "-d", GetoptLong::NO_ARGUMENT],
    ["--help",                "-?", GetoptLong::NO_ARGUMENT]
)


container_uuid = nil
all_containers = false

begin
  opts.each do |k, v|
    case k
    when '--help'
      usage
    when '--with-container-uuid'
      container_uuid = v
    when '--with-all-containers'
      all_containers = true
    when '--debug'
      $oo_debug = true
    else
      usage
    end
  end
rescue GetoptLong::Error => e
  usage
end

unless all_containers or container_uuid
  usage
end


begin
  errors = {}
  if all_containers
    OpenShift::Runtime::ApplicationContainer.all_uuids.each do |uuid|
      errs = OpenShift::Runtime::Utils::Cgroups.new(uuid).classify_processes
      errors.merge!(errs)
    end
  else
    errs = OpenShift::Runtime::Utils::Cgroups.new(container_uuid.to_s).classify_processes
    errors.merge!(errs)
  end

  if not errors.empty?
    $stderr.puts("Errors classifying processes")
    errors.each do |pid, msg|
      $stderr.puts("    #{pid}: #{msg}")
    end
  end
rescue Exception => e
  $stderr.puts(e.message)
  exit -1
end
exit 0
