/**
 *  Add the performance counter subscriptions to the specified role. A list of
 * roles may be passed in using an array
 * 
 * @global type $manager
 * @global type $perf_counters
 * @param Mixed $role - (String|Array)
 */
function add_perf_counters($role)
{
    global $manager, $perf_counters;
    //var_dump($role);
    if (is_array($role)) {
        // recursive
        foreach ($role as $r) {
            add_perf_counters($r);
        }
    }
    $configuration = $manager->getConfigurationForRoleInstance($role);
    foreach ($perf_counters as $c) {
        $configuration->DataSources->PerformanceCounters->addSubscription($c, PERF_IN_SEC);
    }
    $configuration->DataSources->OverallQuotaInMB = 10;
    $configuration->DataSources->PerformanceCounters->BufferQuotaInMB = 10;
    $configuration->DataSources->PerformanceCounters->ScheduledTransferPeriodInMinutes = 1;
    $manager->setConfigurationForRoleInstance($role, $configuration);
}
 /* 
  $req_free_cpu = 70; // lowest % of free cpu allowed
  $free_cpu = round(100 - $avg['cpu']);//round((1 - ($avg / ($num_current_roles * 100)) * 100);
  $lower_threshold = 90; // % cpu free before removing an instance
  echo "\n - Free CPU: $free_cpu";
  echo "\n - Required Free CPU: $req_free_cpu";
  echo "\n - Role Removal when % CPU free: $lower_threshold";
  echo "\n - Number of running 'WebRole': $num_current_roles";
 */
 // Check to see if any process is already running. If so then we cannot change role counts
 $timer->mark('start_get_op_status');
 $status = $client->getOperationStatus($lastRequestId);
 $timer->mark('stop_get_op_status');
 $timer->mark('start_update_perf_sub');
 // Update instance configuration to add performance metric subscriptions
 add_perf_counters(find_role_instances_by_name('WebRole'));
 $timer->mark('stop_update_perf_sub');
 if ($status->Status != 'InProgress') {
     // Nothing found. Try updating the instance counts
     if ($avg['avg_connections_per_role'] > 120 && $num_current_roles < MAX_WEBROLES) {
         // Too many connections to handle. Scale out
         $timer->mark('start_add_instance');
         echo "\n - LOAD HIGH! Creating new role";
         $client->setInstanceCountBySlot(AZURE_ROLE_END, 'production', 'WebRole', $num_current_roles + 5);
         $lastRequestId = $client->getLastRequestId();
         $timer->mark('stop_add_instance');
     } else {
         if ($avg['avg_connections_per_role'] < 20 && $num_current_roles > MIN_WEBROLES) {
             echo "\n - Low load. Removing role";
             $timer->mark('start_remove_instance');
             $client->setInstanceCountBySlot(AZURE_ROLE_END, 'production', 'WebRole', $num_current_roles - 1);