Пример #1
0
function create_vm($service_id, $hostname, $template_id)
{
    $service = get_service($service_id);
    if ($service['serverid'] != $service['productserverid']) {
        $service['serverid'] = $service['productserverid'];
    }
    $user = get_onapp_client($service_id);
    $onapp_config = get_onapp_config($service['serverid']);
    if (isset($user['error'])) {
        $vm = new OnApp_VirtualMachine();
        $vm->setErrors($user['error']);
        return $vm;
    }
    $instance = new OnApp_Factory($onapp_config["adress"], $user["email"], $user["password"]);
    if (!$instance->_is_auth) {
        return $instance;
    }
    $vm = $instance->factory('VirtualMachine');
    $tpl = $instance->factory('Template');
    $option = explode(",", $service['configoption4']);
    if (count($option) > 1) {
        $vm->_hypervisor_group_id = $option[1];
    } else {
        $vm->_hypervisor_id = $option[0];
    }
    $option = explode(",", $service['configoption11']);
    if (count($option) > 1) {
        $vm->_data_store_group_primary_id = $option[1];
    }
    $option = explode(",", $service['configoption9']);
    if (count($option) > 1) {
        $vm->_data_store_group_swap_id = $option[1];
    }
    $option10 = explode(",", $service['configoption10']);
    if (!$option10[1]) {
        $option10[1] = '0';
    }
    $memory = $service['configoption3'] + $service['additionalram'];
    $cpus = $service['configoption5'] + $service['additionalcpus'];
    $cpu_shares = $service['configoption7'] + $service['additionalcpushares'];
    $primary_disk_size = $service['configoption11'] + $service['additionaldisksize'];
    $rate_limit = $service['configoption8'] + $service['additionalportspead'];
    $vm->_template_id = isset($service['os']) ? $service['os'] : $template_id;
    $vm->_primary_network_id = $service['configoption6'];
    $vm->_required_virtual_machine_build = $option10[0] == 'on' ? '1' : '0';
    $vm->_required_automatic_backup = $option10[1] == 'on' ? '1' : '0';
    $vm->_hostname = $hostname;
    $vm->_memory = $memory;
    $vm->_cpus = $cpus;
    $vm->_cpu_shares = $cpu_shares;
    $vm->_primary_disk_size = round($primary_disk_size);
    $vm->_swap_disk_size = round($service['configoption9']);
    $vm->_label = $hostname;
    $vm->_remote_access_password = decrypt($service['password']);
    $vm->_initial_root_password = decrypt($service['password']);
    $vm->_required_ip_address_assignment = '1';
    $vm->_rate_limit = $rate_limit;
    $tpl->load($vm->_template_id);
    if ($tpl->_obj->_operating_system == 'windows') {
        $vm->_swap_disk_size = NULL;
    }
    $vm->save();
    if (!is_null($vm->_obj->error)) {
        $vm->error = $vm->_obj->error;
        return $vm;
    } elseif (is_null($vm->_obj->_id)) {
        $vm->error = "Can't create virtual machine for service #" . $service_id;
        return $vm;
    } else {
        $sql_replace = "REPLACE tblonappservices SET\n            service_id = '{$service_id}',\n            vm_id      = '" . $vm->_obj->_id . "',\n            memory     = '{$memory}',\n            cpus       = '{$cpus}',\n            cpu_shares = '{$cpu_shares}',\n            disk_size  = '{$primary_disk_size}';";
        switch ($vm->_obj->_operating_system) {
            case 'linux':
                $username = "******";
                break;
            case 'windows':
                $username = "******";
                break;
        }
        $sql_username_update = "UPDATE tblhosting SET\n            username = '******',\n            server = '" . $service['serverid'] . "'\n        WHERE\n            id = '" . $service['id'] . "';";
        if ($username != "") {
            full_query($sql_username_update);
        }
        if (full_query($sql_replace)) {
            sendmessage('Virtual Machine Created', $service_id);
            //        action_resolveall_ips();
            //        action_resolve all_backups();
        } else {
            $vm->error = "Can't add virtual machine in DB";
            return $vm;
        }
    }
    update_service_ips($service_id);
    return $vm;
}
Пример #2
0
function onapp_UsageUpdate($params)
{
    global $_LANG, $CONFIG;
    error_reporting(E_ERROR);
    ini_set("display_errors", 1);
    //    date_default_timezone_set('UTC');
    $serverid = $params['serverid'];
    $query = "\n        SELECT\n            tblservers.id,\n            tblservers.password,\n            tblservers.hostname,\n            tblservers.ipaddress,\n            tblservers.username,\n            tblhosting.regdate,\n            tblhosting.id as hosting_id,\n            tblhosting.bwusage,\n            tblhosting.domain,\n            tblhosting.bwlimit,\n            tblproducts.servertype,\n            tblhosting.lastupdate,\n            tblhosting.nextinvoicedate,\n            tblhosting.paymentmethod,\n            tblonappservices.vm_id,\n            tblproducts.overagesbwlimit as bwlimit,\n            tblproducts.overagesdisklimit as disklimit,\n            tblproducts.overagesenabled as enabled,\n            tblproducts.configoption10 as configoption10,\n            tblproducts.configoption22 as bandwidthconfigoption,\n            tblproducts.name as packagename,\n            tblproducts.overagesbwprice,\n            tblproducts.tax,\n            tblhostingconfigoptions.optionid,\n            tblupgrades.status as upgrade_status,\n            tblupgrades.paid as upgrade_paid,\n            tblupgrades.id as upgrade_id,\n            tblproductconfigoptionssub.sortorder as additional_bandwidth,\n            tblclients.id as clientid,\n            tblclients.taxexempt,\n            tblclients.state,\n            tblclients.country,\n            tblcurrencies.prefix,\n            tblcurrencies.code,\n            tblcurrencies.rate,\n            tblonappcronhostingdates.account_date\n        FROM\n            tblservers\n    \n        LEFT JOIN\n            tblhosting ON tblhosting.server = tblservers.id\n        LEFT JOIN\n            tblproducts ON tblhosting.packageid = tblproducts.id\n        LEFT JOIN\n            tblonappservices ON tblhosting.id = tblonappservices.service_id\n        LEFT JOIN\n            tblhostingconfigoptions\n            ON tblhostingconfigoptions.relid = tblhosting.id\n            AND tblhostingconfigoptions.configid = tblproducts.configoption22\n        LEFT JOIN\n            tblproductconfigoptionssub\n            ON\n            tblhostingconfigoptions.optionid = tblproductconfigoptionssub.id\n        LEFT JOIN\n            tblupgrades\n            ON tblupgrades.newvalue = tblhostingconfigoptions.optionid\n            AND tblupgrades.id = (SELECT MAX( id ) FROM tblupgrades WHERE\n            newvalue = tblhostingconfigoptions.optionid )\n        LEFT JOIN \n            tblclients ON tblhosting.userid = tblclients.id\n        LEFT JOIN\n            tblcurrencies ON tblcurrencies.id = tblclients.currency\n        LEFT JOIN\n            tblonappcronhostingdates ON tblonappcronhostingdates.hosting_id = tblhosting.id\n\n        WHERE\n           tblservers.id = {$serverid} AND\n           tblproducts.servertype = 'onapp' AND\n           tblproducts.overagesenabled = 1 AND\n           tblonappservices.vm_id != ''\n    ";
    $result = full_query($query);
    if (!$result || mysql_num_rows($result) < 1) {
        return;
    }
    $duedate = date('Ymd', time() + $GLOBALS['CONFIG']['CreateInvoiceDaysBefore'] * 86400);
    $today = date('Y-m-d H:i:s');
    $enddate = $today;
    $i = 0;
    while ($products = mysql_fetch_assoc($result)) {
        if ($products['account_date']) {
            $invoicedate = date('Y-m-d', strtotime($products['account_date']) + 31 * 24 * 60 * 60);
            $startdate = $products['account_date'];
        } else {
            $invoicedate = getAccountDate($products['regdate']);
            $time = strtotime($invoicedate) - 2678400;
            $startdate = date('Y-m-d H:00:00', $time);
        }
        $onapp = new OnApp_Factory($products['hostname'] ? $products['hostname'] : $products['ipaddress'], $products['username'], decrypt($products['password']));
        if ($onapp->getErrorsAsArray()) {
            // Debug
            echo '<b>Get OnApp Version Permission Error: </b>' . implode(PHP_EOL, $onapp->getErrorsAsArray()) . '. Skipping' . PHP_EOL;
            continue;
        }
        $network_interface = $onapp->factory('VirtualMachine_NetworkInterface');
        if (!$products['vm_id']) {
            // Debug
            echo 'virtual_machine_id is empty. Skipping' . PHP_EOL;
            continue;
        }
        $network_interfaces = $network_interface->getList($products['vm_id']);
        if ($network_interface->getErrorsAsArray()) {
            // Debug
            echo '<b>Network Interface Get List Error : </b>' . implode(PHP_EOL, $network_interface->getErrorsAsArray()) . '. Skipping' . PHP_EOL;
            continue;
        }
        $usage = $onapp->factory('VirtualMachine_NetworkInterface_Usage', true);
        $url_args = array('period[startdate]' => $startdate, 'period[enddate]' => $enddate);
        foreach ($network_interfaces as $interface) {
            $usage_stats[$i][$interface->_id] = $usage->getList($interface->_virtual_machine_id, $interface->_id, $url_args);
        }
        $traffic = 0;
        foreach ($usage_stats[$i] as $interface) {
            foreach ($interface as $bandwidth) {
                $traffic += $bandwidth->_data_sent;
                $traffic += $bandwidth->_data_received;
            }
        }
        $traffic = $traffic / 1024;
        // Count bandwidth limit + upgrades if needed
        $bandwidth_limit = $products['optionid'] && $products['additional_bandwidth'] && $products['upgrade_status'] == 'Completed' && $products['upgrade_paid'] == 'Y' ? $products['bwlimit'] + $products['additional_bandwidth'] : $products['bwlimit'];
        if (date('Y-m-d') == $invoicedate) {
            // debug
            echo 'Payment Day' . PHP_EOL;
            if ($traffic > $bandwidth_limit && !$params['extracall']) {
                // debug
                echo 'Called by the main cron' . PHP_EOL;
                echo 'Update cron dates' . PHP_EOL;
                $query = "REPLACE INTO\n                              tblonappcronhostingdates\n                              ( hosting_id, account_date )\n                          VALUES ( {$products['hosting_id']}, '" . $enddate . "'  )\n                ";
                $result = full_query($query);
                if (!$result) {
                    // debug
                    echo 'cron date REPLACE error ' . mysql_error() . PHP_EOL;
                }
                /// Generating Invoice ///
                /////////////////////////
                // debug
                echo 'Generating Invoice' . PHP_EOL;
                $sql = 'SELECT username FROM tbladmins LIMIT 1';
                $res = full_query($sql);
                $admin = mysql_fetch_assoc($res);
                $taxed = empty($products['taxexempt']) && $CONFIG['TaxEnabled'];
                if ($taxed) {
                    // debug
                    echo 'taxed invoice' . PHP_EOL;
                    $taxrate = getTaxRate(1, $products['state'], $products['country']);
                    $taxrate = $taxrate['rate'];
                } else {
                    $taxrate = '';
                }
                $amount = round(($traffic - $bandwidth_limit) * $products['overagesbwprice'] * $products['rate'], 2);
                $description = $products['packagename'] . ' - ' . $products['domain'] . ' ( ' . $startdate . ' / ' . $enddate . ' )' . PHP_EOL . $_LANG['onappbwusage'] . ' - ' . $traffic . ' MB' . PHP_EOL . $_LANG['onappbwlimit'] . ' - ' . $bandwidth_limit . ' MB' . PHP_EOL . $_LANG['onappbwoverages'] . ' - ' . ($traffic - $bandwidth_limit) . ' MB' . PHP_EOL . $_LANG['onapppriceformbbwoverages'] . ' - ' . $products['prefix'] . round($products['rate'] * $products['overagesbwprice'], 2) . ' ' . $products['code'] . PHP_EOL;
                $data = array('userid' => $products['clientid'], 'date' => $today, 'duedate' => $duedate, 'paymentmethod' => $products['paymentmethod'], 'taxrate' => $taxrate, 'sendinvoice' => true, 'itemdescription1' => $description, 'itemamount1' => $amount, 'itemtaxed1' => $taxed);
                // debug
                print '<pre>';
                print_r($data);
                echo PHP_EOL;
                $result = localAPI('CreateInvoice', $data, $admin);
                if ($result['result'] != 'success') {
                    // debug
                    echo 'Following error occurred: ' . $result['result'] . PHP_EOL;
                }
                // Generating Invoice End //
                ///////////////////////////
            }
            if (!$params['extracall']) {
                // debug
                echo 'Reset bwusage to 0' . PHP_EOL;
                $traffic = 0;
            }
        }
        $results[] = array('bwusage' => $traffic, 'disklimit' => $products['disklimit'], 'bwlimit' => $bandwidth_limit, 'domain' => $products['domain']);
        /// Debug block ///
        //////////////////
        print '<pre>';
        print_r($products);
        echo PHP_EOL;
        echo 'today  => ' . $today . PHP_EOL;
        echo 'regdate  => ' . $products['regdate'] . PHP_EOL;
        echo 'invoicedate  => ' . $invoicedate . PHP_EOL;
        echo 'startdate  => ' . $startdate . PHP_EOL;
        echo 'enddate  => ' . $enddate . PHP_EOL;
        echo 'bwlimit  (' . $products['bwlimit'] . ') + ';
        echo 'additional bwlimit (' . $products['additional_bandwidth'] . ') = ';
        echo $bandwidth_limit . PHP_EOL . PHP_EOL;
        echo 'Updating bwusage => ' . PHP_EOL;
        print '<pre>';
        print_r($results);
        echo '************************************************' . PHP_EOL . PHP_EOL;
        /// Debug block END ///
        //////////////////////
        $i++;
    }
    // Updating Usage Overages
    foreach ($results as $domain => $values) {
        update_query("tblhosting", array("disklimit" => $values['disklimit'], "bwusage" => $values['bwusage'], "bwlimit" => $values['bwlimit'], "lastupdate" => $today), array("server" => $serverid, "domain" => $values['domain']));
    }
}
Пример #3
0
/**
 * Show virtual machine details
 */
function showproduct()
{
    global $_ONAPPVARS, $_LANG;
    // Geting transaction by Ajax request //
    ///////////////////////////////////////
    if (isset($_GET['transactionid'])) {
        if ($_GET['type'] != 'Transaction') {
            exit;
        }
        $user = get_onapp_client($_ONAPPVARS['id']);
        $onapp_config = get_onapp_config($_ONAPPVARS['service']['serverid']);
        $onapp = new OnApp_Factory($onapp_config["adress"], $user["email"], $user["password"]);
        $transaction = $onapp->factory('Transaction', true);
        $_transaction = $transaction->load($_GET['transactionid']);
        $transaction_js['output'] = $_transaction->_log_output;
        $transaction_js = json_encode($transaction_js);
        ob_end_clean();
        exit($transaction_js);
    }
    // End Geting transaction by Ajax request //
    ///////////////////////////////////////////
    $onapp_config = get_onapp_config($_ONAPPVARS['service']['serverid']);
    if (!is_null($_ONAPPVARS['vm']->error)) {
        $_ONAPPVARS['error'] = is_array($_ONAPPVARS['vm']->error) ? implode('.<br>', $_ONAPPVARS['vm']->error) : $_ONAPPVARS['vm']->error;
        clientareaproducts();
    } elseif (is_null($_ONAPPVARS['vm']->_id)) {
        $_ONAPPVARS['error'] = sprintf($_LANG["onappvmnotfoundonserver"], $_ONAPPVARS['service']['vmid'], $onapp_config["adress"]);
        showcreateproduct();
    } else {
        $network = get_vm_interface($_ONAPPVARS['id']);
        // Getting log info //
        /////////////////////
        $user = get_onapp_client($_ONAPPVARS['id']);
        $onapp_config = get_onapp_config($_ONAPPVARS['service']['serverid']);
        $onapp = new OnApp_Factory($onapp_config["adress"], $user["email"], $user["password"]);
        $log = $onapp->factory('Log', true);
        $url_args = array('q' => $_ONAPPVARS['vm']->_obj->_identifier);
        $logs = $log->getList($url_args);
        foreach ($logs as $item) {
            $log_items[$item->_id]['target_type'] = $item->_target_type;
            $log_items[$item->_id]['target_id'] = $item->_target_id;
            $log_items[$item->_id]['created_at'] = str_replace('T', ' ', substr($item->_created_at, 0, 16));
            $log_items[$item->_id]['updated_at'] = $item->_updated_at;
            $log_items[$item->_id]['status'] = $item->_status;
            $log_items[$item->_id]['action'] = $item->_action;
        }
        $log_items = array_slice($log_items, 0, 15, true);
        // End Getting Log Info //
        /////////////////////////
        show_template("onapp/clientareaoverview", array('virtualmachine' => $_ONAPPVARS['vm']->_obj, 'id' => $_ONAPPVARS['id'], 'error' => isset($_ONAPPVARS['error']) ? $_ONAPPVARS['error'] : NULL, 'configoptionsupgrade' => $_ONAPPVARS['service']['configoptionsupgrade'], 'rate_limit' => $network->_rate_limit, 'vm_logs' => $log_items));
    }
}
Пример #4
0
 private function getAPIVersion()
 {
     $obj = new OnApp_Factory($this->server->address, $this->server->user, $this->server->pass);
     $apiVersion = (string) $obj->getAPIVersion();
     return $apiVersion;
 }
Пример #5
0
/**
 *
 * Upgrade resources
 * 
 * @return void
 */
function _action()
{
    if (!defined('ONAPP_WRAPPER_INIT')) {
        define('ONAPP_WRAPPER_INIT', dirname(__FILE__) . '/../wrapper/OnAppInit.php');
    }
    if (file_exists(ONAPP_WRAPPER_INIT)) {
        require_once ONAPP_WRAPPER_INIT;
    }
    $query = "\n        SELECT\n            tblupgrades.id as upgrade_id,\n            tblproductconfigoptionssub.configid,\n            SUBSTRING_INDEX( tblupgrades.originalvalue,  '=', 1 ) as _configid,\n            tblproductconfigoptionssub.sortorder as additional_value,\n            tblproducts.configoption12 as ram_configid,\n            tblproducts.configoption13 as cpu_cores_configid,\n            tblproducts.configoption14 as cpu_priority_configid,\n            tblproducts.configoption15 as primary_disk_size_configid,\n            tblproducts.configoption16 as ipaddress_configid,\n            tblproducts.configoption6  as primary_network_id,\n            tblproducts.configoption19 as template_configid,\n            tblproducts.configoption20 as port_speed_configid,\n            tblproducts.configoption22 as bandwidth_configid,\n            tblproducts.configoption2 as product_template_ids,\n            tblproducts.configoption3 as product_ram,\n            tblproducts.configoption5 as product_cpu_cores,\n            tblproducts.configoption7 as product_cpu_priority,\n            tblproducts.configoption11 as product_primary_disk_size,\n            tblproducts.configoption8 as product_port_speed,\n            tblproducts.configoption18 as product_ip_addresses,\n            tblproducts.overagesbwlimit as product_bandwidth,\n            tblproducts.name as product_name,\n            tblhosting.id as hosting_id,\n            tblupgrades.newvalue as additional_value_slider,\n            tblonappservices.*,\n            tblservers.ipaddress,\n            tblservers.hostname,\n            tblservers.username,\n            tblservers.password\n        FROM\n            tblupgrades\n        LEFT JOIN\n            tblproductconfigoptionssub ON\n            tblproductconfigoptionssub.id = tblupgrades.newvalue\n        LEFT JOIN\n            tblhosting ON tblhosting.id = tblupgrades.relid\n        LEFT JOIN\n            tblproducts ON tblproducts.id = tblhosting.packageid\n        LEFT JOIN\n            tblonappservices ON tblonappservices.service_id = tblhosting.id\n        LEFT JOIN\n            tblservers ON tblhosting.server = tblservers.id\n        WHERE\n            tblupgrades.id IN ( " . implode(',', $_SESSION['upgradeids']) . " )\n            AND tblservers.type = 'onapp'\n            AND tblupgrades.paid = 'Y'\n    ";
    // AND tblupgrades.status != 'Completed' couldn't be used because of own cycle...
    $result = full_query($query);
    if (!$result || mysql_num_rows($result) < 1) {
        return;
    }
    while ($row = mysql_fetch_assoc($result)) {
        // Debug block
        //        print('<pre>');
        //        print_r($row); echo '<hr />'. PHP_EOL;
        $configurableoptions_labels = array('_memory' => $row['ram_configid'], '_cpus' => $row['cpu_cores_configid'], '_cpu_shares' => $row['cpu_priority_configid'], '_primary_disk_size' => $row['primary_disk_size_configid'], 'ipaddresses' => $row['ipaddress_configid'], '_template_id' => $row['template_configid'], '_rate_limit' => $row['port_speed_configid'], 'bandwidth' => $row['bandwidth_configid']);
        $configurableoptions_product_values = array('_memory' => $row['product_ram'], '_cpus' => $row['product_cpu_cores'], '_cpu_shares' => $row['product_cpu_priority'], '_primary_disk_size' => $row['product_primary_disk_size'], 'ipaddresses' => $row['product_ip_addresses'], '_template_id' => $row['product_template_ids'], '_rate_limit' => $row['product_port_speed'], 'bandwidth' => $row['product_bandwidth']);
        if (!count($configurableoptions_labels) == count(array_unique($configurableoptions_labels))) {
            return 'Wrong configurable options settings in ' . product_name . 'product';
        }
        // IF configurableoption type "Quantity"
        if (is_null($row['additional_value']) && is_null($row['configid'])) {
            $row['additional_value'] = $row['additional_value_slider'];
            $row['configid'] = $row['_configid'];
        }
        $resource_label = array_search($row['configid'], $configurableoptions_labels);
        if ($resource_label != '_template_id') {
            $vm_resource[$resource_label] = $row['additional_value'] + $configurableoptions_product_values[$resource_label];
        } elseif ($resource_label == '_template_id') {
            $vm_resource[$resource_label] = $row['additional_value'];
        }
        $ipaddress = $row['ipaddress'];
        $hostname = $row['hostname'];
        $username = $row['username'];
        $password = $row['password'];
        $vm_id = $row['vm_id'];
        $hosting_id = $row['hosting_id'];
        $primary_network_id = $row['primary_network_id'];
    }
    // Debug block
    //    print('<pre>VM_RESOURCE:');
    //    print_r($vm_resource);
    $onapp = new OnApp_Factory($hostname ? $hostname : $ipaddress, $username, decrypt($password));
    $vm = $onapp->factory('VirtualMachine', true);
    foreach ($vm_resource as $label => $value) {
        if ($label == 'bandwidth') {
            $update_bandwidth = $value;
        }
        if ($label == '_template_id') {
            $rebuild_vm = true;
            $template_id = $value;
        }
        if ($label == '_rate_limit') {
            $rate_limit = $value;
        }
        if ($label == '_primary_disk_size') {
            $primary_disk_size = $value;
        }
        if ($label == 'ipaddresses') {
            $ipaddresses_number = $value;
        }
        if ($label != '_template_id' && $label != 'bandwidth' && $label != '_rate_limit' && $label != '_primary_disk_size' && $label != 'ipaddresses') {
            $vm->{$label} = $value;
        }
    }
    // Edit VM resourses RAM, cpus, cpu_shares //
    ////////////////////////////////////////////
    $vm->_id = $vm_id;
    // Debug block
    //    print('VM_Object:<pre>');
    //    print_r($vm);
    if (isset($vm->_cpu_shares) || isset($vm->_primary_disk_size) || isset($vm->_memory) || isset($vm->_cpus)) {
        $vm->save();
    }
    // Edit VM resourses RAM, cpus, cpu_shares //
    ////////////////////////////////////////////
    // Upgrade / Downgrade Primary Disk size //
    //////////////////////////////////////////
    if (isset($primary_disk_size)) {
        $vm_disk = $onapp->factory('Disk', true);
        $vm_disks = $vm_disk->getList($vm_id);
        foreach ($vm_disks as $disk) {
            if ($disk->_primary) {
                $disk_id = $disk->_id;
            }
        }
        $vm_disk->_id = $disk_id;
        $vm_disk->_disk_size = $primary_disk_size;
        $vm_disk->save();
    }
    // End Upgrade / Downgrade Primary disk size //
    //////////////////////////////////////////////
    // Upgrade / Downgrade Rate Limit //
    ///////////////////////////////////
    if (isset($rate_limit)) {
        $vm_interface = $onapp->factory('VirtualMachine_NetworkInterface');
        $vm_interfaces = $vm_interface->getList($vm_id);
        foreach ($vm_interfaces as $interface) {
            if ($interface->_primary) {
                $interface_id = $interface->_id;
            }
        }
        $vm_interface->_id = $interface_id;
        $vm_interface->_rate_limit = $rate_limit;
        $vm_interface->save();
        if (!isset($template_id)) {
            $vm->rebuild_network();
        }
    }
    // End Upgrade / Downgrade Rate Limit //
    ///////////////////////////////////////
    // Upgrade / Downgrade Bandwidth Limit //
    ////////////////////////////////////////
    if ($update_bandwidth) {
        $query = "\n            UPDATE\n                tblhosting\n            SET\n                bwlimit    = '{$update_bandwidth}'\n            WHERE\n                id = '{$hosting_id}'";
        $result = full_query($query);
    }
    // End Upgrade / Downgrade Bandwidth  Limit //
    /////////////////////////////////////////////
    // Upgrade / Downgrade Ipaddresses //
    ////////////////////////////////////
    if (isset($ipaddresses_number)) {
        $vm_obj = $onapp->factory('VirtualMachine');
        $vm = $vm_obj->load($vm_id);
        $vm_ipaddresses_number = count($vm->_ip_addresses);
        $ipaddresses_to_add = $ipaddresses_number - $vm_ipaddresses_number;
        if ($ipaddresses_to_add > 0) {
            $ip_address_obj = $onapp->factory('IpAddress');
            $vm_network_interface = $onapp->factory('VirtualMachine_NetworkInterface');
            $vm_network_interfaces = $vm_network_interface->getList($vm_id);
            foreach ($vm_network_interfaces as $interface) {
                if ($interface->_primary) {
                    $primary_interface_id = $interface->_id;
                }
            }
            for ($i = 0; $i < $ipaddresses_to_add; $i++) {
                $ip_addresses_list = $ip_address_obj->getList($primary_network_id);
                foreach ($ip_addresses_list as $ip) {
                    if ($ip->_free) {
                        $free_ip = $ip->_id;
                        break;
                    }
                }
                if ($free_ip && isset($primary_interface_id)) {
                    $ip_address_join = $onapp->factory('VirtualMachine_IpAddressJoin', true);
                    $ip_address_join->_virtual_machine_id = $vm_id;
                    $ip_address_join->_network_interface_id = $primary_interface_id;
                    $ip_address_join->_ip_address_id = $free_ip;
                    $ip_address_join->save();
                    if ($ip_address_join->_id) {
                        $query = "\n                            INSERT INTO\n                                tblonappips ( serviceid, ipid, isbase )\n                            VALUES\n                                ( {$hosting_id}, {$free_ip}, '0')\n                        ";
                        $result = full_query($query);
                    }
                }
                $free_ip = null;
            }
        }
        $vm_obj = $onapp->factory('VirtualMachine');
        $vm = $vm_obj->load($vm_id);
        foreach ($vm->_ip_addresses as $ip) {
            $ips .= $ip->_address . '\\n';
        }
        $query = "UPDATE  tblhosting SET assignedips = '{$ips}' WHERE id = '{$hosting_id}'";
        $result = full_query($query);
    }
    // End Upgrade / Downgrade Ipaddresses //
    ////////////////////////////////////////
    // Upgrade / Downgrade template //
    /////////////////////////////////
    if (isset($rebuild_vm) && $index == 0) {
        $_vm = $onapp->factory('VirtualMachine', true);
        $vm = $_vm->load($vm_id);
        if ($vm->_template_id != $template_id) {
            $_vm->_id = $vm_id;
            $_vm->_required_startup = '1';
            $_vm->_template_id = $template_id;
            $_vm->build();
        }
    }
    // End Upgrade / Downgrade Template //
    /////////////////////////////////////
}