From 33523addebba4c9f790851638f904b9e85da73b3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Chris=20Schl=C3=A4pfer?= Date: Fri, 13 Oct 2023 19:16:18 +0200 Subject: [PATCH] Cleanup --- src/Api/Admin.php | 104 ++-- src/Controller/Admin.php | 5 +- src/ProxmoxAuthentication.php | 22 +- src/ProxmoxIPAM.php | 9 +- src/ProxmoxServer.php | 135 ++++-- src/ProxmoxTemplates.php | 77 +-- src/ProxmoxVM.php | 37 +- src/Service.php | 331 +++++-------- .../mod_serviceproxmox_config.html.twig | 448 +++++++++--------- .../mod_serviceproxmox_index.html.twig | 69 ++- .../mod_serviceproxmox_ipam.html.twig | 136 +++--- ..._serviceproxmox_ipam_client_vlan.html.twig | 6 +- .../mod_serviceproxmox_ipam_iprange.html.twig | 13 +- .../mod_serviceproxmox_settings.html.twig | 60 +-- .../mod_serviceproxmox_storage.html.twig | 144 +++--- .../mod_serviceproxmox_templates.html.twig | 305 ++++++------ ...od_serviceproxmox_templates_qemu.html.twig | 129 ++--- src/migrations/0.0.6.sql | 19 - src/migrations/0.0.7.sql | 84 ---- src/migrations/0.0.8.sql | 38 -- src/migrations/{0.0.5.sql => 0.1.0.sql} | 101 ++-- tests/Serviceproxmox/Api/AdminTest.php | 51 -- tests/Serviceproxmox/ServiceTest.php | 13 +- 23 files changed, 995 insertions(+), 1341 deletions(-) delete mode 100755 src/migrations/0.0.6.sql delete mode 100644 src/migrations/0.0.7.sql delete mode 100755 src/migrations/0.0.8.sql rename src/migrations/{0.0.5.sql => 0.1.0.sql} (77%) diff --git a/src/Api/Admin.php b/src/Api/Admin.php index 127c010..e3eec93 100644 --- a/src/Api/Admin.php +++ b/src/Api/Admin.php @@ -176,7 +176,6 @@ public function storage_get_list() 'free' => $storage->free, 'percent_used' => ($storage->size == 0 || $storage->used == 0 || $storage->free == 0) ? 0 : round($storage->used / $storage->size * 100, 2), ); - } return $storages_grouped; } @@ -358,7 +357,6 @@ public function get_lxc_config_template() // Function to enable qemu template public function vm_config_template_enable($data) { - error_log("vm_config_template_enable: " . $data['id']); $vm_config_template = $this->di['db']->getExistingModelById('service_proxmox_vm_config_template', $data['id'], 'VM Config Template not found'); $vm_config_template->state = 'active'; $this->di['db']->store($vm_config_template); @@ -368,7 +366,6 @@ public function vm_config_template_enable($data) // Function to disable qemu template public function vm_config_template_disable($data) { - error_log("vm_config_template_disable: " . $data['id']); $vm_config_template = $this->di['db']->getExistingModelById('service_proxmox_vm_config_template', $data['id'], 'VM Config Template not found'); $vm_config_template->state = 'inactive'; $this->di['db']->store($vm_config_template); @@ -411,7 +408,7 @@ public function server_create($data) if ($server) { throw new \Box_Exception('Server already exists'); } - + $server = $this->di['db']->dispense('service_proxmox_server'); $server->name = $data['name']; $server->group = $data['group']; @@ -433,22 +430,15 @@ public function server_create($data) $server->root_password = $data['root_password']; $server->tokenname = ''; $server->tokenvalue = ''; - $this->di['db']->store($server); - $this->getService()->test_connection($server); } else { $server->root_user = ''; $server->root_password = ''; $server->tokenname = $data['tokenname']; $server->tokenvalue = $data['tokenvalue']; - $this->di['db']->store($server); - } - - // Validate server by testing connection - - - + $this->di['db']->store($server); + $this->getService()->test_connection($server); return true; } @@ -525,7 +515,7 @@ public function server_update($data) $server->cpu_cores = $data['cpu_cores']; $server->ram = $data['ram']; $server->root_user = $data['root_user']; - $server->root_password = $data['root_password']; + $server->root_password = $data['root_password']; $server->tokenname = $data['tokenname']; $server->config = $data['config']; $server->active = $data['active']; @@ -654,9 +644,8 @@ public function get_hardware_data($server_id) $server->ram_allocated += $value['maxmem']; } $this->di['db']->store($server); - $qemu_templates = $service->getQemuTemplates($server); - error_log('qemu_templates: ' . print_r($qemu_templates, true)); - foreach ($qemu_templates as $key => $value) { + $qemu_vms = $service->getQemuVMs($server); + foreach ($qemu_vms as $key => $value) { // check if $value['template'] exists, and if it's content is 1 if (!empty($value['template'])) { if ($value['template'] == 1) { @@ -676,7 +665,6 @@ public function get_hardware_data($server_id) $template->updated_at = date('Y-m-d H:i:s'); $stored = $this->di['db']->store($template); - error_log('template saved: ' . print_r($stored, true)); } } } @@ -859,19 +847,14 @@ public function storage_update($data) // Retrieve associated storage $storage = $this->di['db']->findOne('service_proxmox_storage', 'id=:id', array(':id' => $data['storageid'])); - - // $data['storageTypeTags']; contains an array of tags like this: Array([0] => ssd,hdd,sdf) - // This needs to be split up and stored as valid json in the storage table - error_log('storageTypeTags: ' . print_r($data['storageTypeTags'], true)); - // Assuming you have $data['storagetype'] populated + $storageType = $data['storagetype']; $tagArray = []; foreach ($data['storageTypeTags'] as $tag) { $splitTags = explode(',', $tag); - $tagArray = array_merge($tagArray, $splitTags); // Flat array of tags + $tagArray = array_merge($tagArray, $splitTags); } - - // for every tag in the tagArray, save the id to the error_log + $jsonArray = []; foreach ($tagArray as $tagId) { // Fetch the tag details from DB @@ -879,7 +862,7 @@ public function storage_update($data) ':id' => $tagId, ':type' => $storageType ]); - + if ($tag_from_db) { $jsonArray[] = [ 'id' => $tag_from_db->id, @@ -889,7 +872,7 @@ public function storage_update($data) error_log("No DB entry found for tagId: $tagId and type: $storageType"); } } - + $jsonString = json_encode($jsonArray); $storage->storageclass = $jsonString; $this->di['db']->store($storage); @@ -1032,7 +1015,6 @@ public function service_add_tag($data) { $added_tag = $this->getService()->save_tag($data); return $added_tag; - } /** @@ -1043,7 +1025,6 @@ public function service_add_tag($data) public function service_get_tags_by_storage($data) { $output = $this->getService()->get_tags_by_storage($data); - error_log("service_get_tags_by_storage: " . print_r($output, true)); return $output; } @@ -1054,7 +1035,6 @@ public function service_get_tags_by_storage($data) */ public function vm_config_template_get($data) { - error_log("vm_config_template_get"); $vm_config_template = $this->di['db']->findOne('service_proxmox_vm_config_template', 'id=:id', array(':id' => $data['id'])); if (!$vm_config_template) { throw new \Box_Exception('VM template not found'); @@ -1084,30 +1064,30 @@ public function vm_config_template_get($data) * @return array */ - public function vm_config_template_get_storages($data) - { - $vm_config_template = $this->di['db']->find('service_proxmox_vm_storage_template', 'template_id=:id', array(':id' => $data['id'])); - - // Replace the storage_type with the name of the tag - foreach ($vm_config_template as $key => $value) { - $storage_tag_ids = explode(',', json_decode($value->storage_type)); // Split the IDs - $tagNames = []; - - foreach ($storage_tag_ids as $tagId) { - $tag = $this->di['db']->findOne('service_proxmox_tag', 'id=:id', array(':id' => $tagId)); - if ($tag) { - $tagNames[] = $tag->name; - } else { - error_log("No DB entry found for tagId: $tagId"); - } - } - - // Combine all the tag names into a single string - $vm_config_template[$key]->storage_type = implode(', ', $tagNames); - } - - return $vm_config_template; - } + public function vm_config_template_get_storages($data) + { + $vm_config_template = $this->di['db']->find('service_proxmox_vm_storage_template', 'template_id=:id', array(':id' => $data['id'])); + + // Replace the storage_type with the name of the tag + foreach ($vm_config_template as $key => $value) { + $storage_tag_ids = explode(',', json_decode($value->storage_type)); // Split the IDs + $tagNames = []; + + foreach ($storage_tag_ids as $tagId) { + $tag = $this->di['db']->findOne('service_proxmox_tag', 'id=:id', array(':id' => $tagId)); + if ($tag) { + $tagNames[] = $tag->name; + } else { + error_log("No DB entry found for tagId: $tagId"); + } + } + + // Combine all the tag names into a single string + $vm_config_template[$key]->storage_type = implode(', ', $tagNames); + } + + return $vm_config_template; + } /** * Function to delete vm config template storage @@ -1255,7 +1235,6 @@ public function vm_template_update($data) ); $this->di['validator']->checkRequiredParamsForArray($required, $data); - error_log("vm_template_update: " . print_r($data, true)); // Retrieve associated vm_config_template $vm_config_template = $this->di['db']->findOne('service_proxmox_vm_config_template', 'id=:id', array(':id' => $data['id'])); @@ -1578,10 +1557,10 @@ public function client_vlan_delete($data) { $required = array( 'id' => 'ID is missing', - ); + ); $this->di['validator']->checkRequiredParamsForArray($required, $data); - + $client_network = $this->di['db']->findOne('service_proxmox_client_vlan', 'id = ?', [$data['id']]); $this->di['db']->trash($client_network); $this->di['logger']->info('Delete Client Network %s', $data['id']); @@ -1650,4 +1629,13 @@ public function get_module_version() return $config['version']; } + /** + * Returns the salt value from the configuration. + * + * @return string The salt value. + */ + private function _getSalt() + { + return $this->di['config']['salt']; + } } // EOF \ No newline at end of file diff --git a/src/Controller/Admin.php b/src/Controller/Admin.php index fe0a1b9..471e412 100644 --- a/src/Controller/Admin.php +++ b/src/Controller/Admin.php @@ -109,7 +109,7 @@ public function register(\Box_App &$app): void * @param \Box_App $app * @return string */ - public function get_index(\Box_App $app):string + public function get_index(\Box_App $app): string { $this->di['is_admin_logged']; return $app->render('mod_serviceproxmox_index'); @@ -121,7 +121,7 @@ public function get_index(\Box_App $app):string * @param \Box_App $app * @return string */ - public function get_templates(\Box_App $app):string + public function get_templates(\Box_App $app): string { return $app->render('mod_serviceproxmox_templates'); } @@ -253,7 +253,6 @@ public function get_lxc_config_template(\Box_App $app, $id): string */ public function get_vm_config_template(\Box_App $app, $id): string { - error_log("Controller get_vm_config_template"); $api = $this->di['api_admin']; $vm_config_template = $api->Serviceproxmox_vm_config_template_get(array('id' => $id)); return $app->render('mod_serviceproxmox_templates_qemu', array('vm_config_template' => $vm_config_template)); diff --git a/src/ProxmoxAuthentication.php b/src/ProxmoxAuthentication.php index 39e0538..aa6e0a6 100644 --- a/src/ProxmoxAuthentication.php +++ b/src/ProxmoxAuthentication.php @@ -38,10 +38,7 @@ trait ProxmoxAuthentication */ public function prepare_pve_setup($server) { - $config = $this->di['mod_config']('Serviceproxmox'); - $serveraccess = $this->find_access($server); - $proxmox = new \PVE2APIClient\PVE2_API($serveraccess, $server->root_user, $server->realm, $server->root_password, port: $server->port, tokenid: $server->tokenname, tokensecret: $server->tokenvalue, debug: $config['pmx_debug_logging']); - + $proxmox = $this->getProxmoxInstance($server); // Attempt to log in to the server using the API if (!$proxmox->login()) { throw new \Box_Exception("Failed to log in to the proxmox server. Check username & password and try again."); @@ -87,7 +84,7 @@ public function prepare_pve_setup($server) default: throw new \Box_Exception("More than one group found"); break; - } + } // Validate if there already is a user and token for fossbilling $users = $proxmox->get("/access/users"); @@ -107,7 +104,7 @@ public function prepare_pve_setup($server) $proxmox->post("/access/users", array('userid' => $userid, 'password' => $this->di['tools'], 'enable' => 1, 'comment' => 'fossbilling user', 'groups' => $groupid)); /* @phpstan-ignore-line */ // Create a token for the new user - $token = $proxmox->post("/access/users/" . $userid . "/token/fb_access", array()); /* @phpstan-ignore-line Proxmox is set, otherwise code errors out */ + $token = $proxmox->post("/access/users/" . $userid . "/token/fb_access", array()); /* @phpstan-ignore-line Proxmox is set, otherwise code errors out */ // Check if the token was created successfully if ($token) { @@ -120,7 +117,7 @@ public function prepare_pve_setup($server) break; case 1: // Create a token for the existing user - $token = $proxmox->post("/access/users/" . $userid . "/token/fb_access", array());/* @phpstan-ignore-line Proxmox is set, otherwise code errors out */ + $token = $proxmox->post("/access/users/" . $userid . "/token/fb_access", array());/* @phpstan-ignore-line Proxmox is set, otherwise code errors out */ if ($token) { $server->tokenname = $token['full-tokenid']; $server->tokenvalue = $token['value']; @@ -173,7 +170,7 @@ public function prepare_pve_setup($server) } } return $this->test_access($server); - } + } return false; } @@ -187,10 +184,7 @@ public function prepare_pve_setup($server) */ public function test_access($server) { - $config = $this->di['mod_config']('Serviceproxmox'); - $serveraccess = $this->find_access($server); - $proxmox = new \PVE2APIClient\PVE2_API($serveraccess, $server->root_user, $server->realm, $server->root_password, port: $server->port, tokenid: $server->tokenname, tokensecret: $server->tokenvalue, debug: $config['pmx_debug_logging']); - + $proxmox = $this->getProxmoxInstance($server); // Attempt to log in to the server using the API if (!$proxmox->login()) { throw new \Box_Exception("Failed to connect to the server. testpmx"); @@ -237,9 +231,7 @@ public function create_client_user($server, $client) $clientuser = $this->di['db']->dispense('service_proxmox_users'); $clientuser->client_id = $client->id; $this->di['db']->store($clientuser); - $serveraccess = $this->find_access($server); - $config = $this->di['mod_config']('Serviceproxmox'); - $proxmox = new \PVE2APIClient\PVE2_API($serveraccess, $server->root_user, $server->realm, $server->root_password, port: $server->port, tokenid: $server->tokenname, tokensecret: $server->tokenvalue, debug: $config['pmx_debug_logging']); + $proxmox = $this->getProxmoxInstance($server); if (!$proxmox->login()) { throw new \Box_Exception("Failed to connect to the server. create_client_user"); } diff --git a/src/ProxmoxIPAM.php b/src/ProxmoxIPAM.php index 1b0012f..93f0d89 100644 --- a/src/ProxmoxIPAM.php +++ b/src/ProxmoxIPAM.php @@ -66,14 +66,12 @@ public function get_vlans() return $vlans; } - - } - /* ################################################################################################### */ - /* ################################### Manage PVE Network ######################################### */ - /* ################################################################################################### */ +/* ################################################################################################### */ +/* ################################### Manage PVE Network ######################################### */ +/* ################################################################################################### */ /** @@ -83,5 +81,4 @@ public function get_vlans() */ trait ProxmoxNetwork { - } diff --git a/src/ProxmoxServer.php b/src/ProxmoxServer.php index 51f3ee4..e2f7975 100644 --- a/src/ProxmoxServer.php +++ b/src/ProxmoxServer.php @@ -28,15 +28,19 @@ trait ProxmoxServer /* ################################################################################################### */ - /* - Test connection - */ + + /** + * Test the connection to the Proxmox server. + * + * @param object $server The server object containing login information. + * + * @return bool Returns true if the connection is successful, otherwise throws an exception. + * + * @throws \Box_Exception If login information is missing or incorrect, or if the connection fails. + */ public function test_connection($server) { - // Test if login - $serveraccess = $this->find_access($server); - $config = $this->di['mod_config']('Serviceproxmox'); - $proxmox = new \PVE2APIClient\PVE2_API($serveraccess, $server->root_user, $server->realm, $server->root_password, port: $server->port, tokenid: $server->tokenname, tokensecret: $server->tokenvalue,debug: $config['pmx_debug_logging']); + $proxmox = $this->getProxmoxInstance($server); // check if tokenname and tokenvalue contain values by checking their content if (empty($server->tokenname) || empty($server->tokenvalue)) { if (!empty($server->root_user) && !empty($server->root_password)) { @@ -58,15 +62,22 @@ public function test_connection($server) } } - /* - Validate token access and setup - */ + + /** + * This function tests the token connection to the Proxmox server. + * It checks if the tokenname and tokenvalue contain values by checking their content. + * If they are empty, it throws an exception. + * If the login with token is successful, it retrieves the permissions and checks for 'Realm.AllocateUser' permission. + * If the permission is not found, it throws an exception. + * It also validates if there already is a group for fossbilling and checks if the groupid is the same as the id of the token. + * + * @param object $server The server object containing the tokenname and tokenvalue. + * @return bool Returns true if the token connection is successful. + * @throws \Box_Exception Throws an exception if the token access fails, the connection to the server fails, or the token does not have 'Realm.AllocateUser' permission. + */ public function test_token_connection($server) { - // Test if login - $serveraccess = $this->find_access($server); - $config = $this->di['mod_config']('Serviceproxmox'); - $proxmox = new \PVE2APIClient\PVE2_API($serveraccess, $server->root_user, $server->realm, $server->root_password, port: $server->port, tokenid: $server->tokenname, tokensecret: $server->tokenvalue,debug: $config['pmx_debug_logging']); + $proxmox = $this->getProxmoxInstance($server); // check if tokenname and tokenvalue contain values by checking their content if (empty($server->tokenname) || empty($server->tokenvalue)) { throw new \Box_Exception("Token Access Failed: No tokenname or tokenvalue provided"); @@ -96,13 +107,12 @@ public function test_token_connection($server) } // check if groupid is the same as the id of the token (fb_1234@pve!fb_access) $fb_token_instanceid = explode('@', $server->tokenname)[1]; - + if ($group['groupid'] == $server->tokenname) { $foundgroups += 1; $groupid = $group['groupid']; } - } return true; } else { @@ -112,8 +122,13 @@ public function test_token_connection($server) - /* Find best Server - */ + + /** + * Finds an empty server with the best CPU and RAM usage ratio based on the given product's group and filling. + * + * @param object $product The product to find an empty server for. + * @return int|null The ID of the server with the best CPU and RAM usage ratio, or null if no server is found. + */ public function find_empty($product) { $productconfig = json_decode($product->config, 1); @@ -126,11 +141,9 @@ public function find_empty($product) $ram_overprovion_percent = $config['ram_overprovisioning']; $avoid_overprovision = $config['avoid_overprovision']; - // Retrieve only non-full active servers sorted by ratio. - // priority is given to servers with the largest difference between ram and used ram - // if avoid_overprovision is set to true, servers with a ratio of >1 are ignored + $servers = $this->di['db']->find('service_proxmox_server', ['status' => 'active']); - //echo ""; + $server = null; $server_ratio = 0; // use values from database to calculate ratio and store the server id, cpu and ram usage ratio if it's better than the previous one @@ -164,9 +177,15 @@ public function find_empty($product) return $server; } - /* - Find access to server (hostname, ipv4, ipv6) - */ + /** + * Find the access of the server based on its hostname, IPv4 or IPv6 address. + * + * @param object $server The server object containing hostname, IPv4 and/or IPv6 address. + * + * @return string The hostname, IPv4 or IPv6 address of the server. + * + * @throws \Box_Exception If no hostname, IPv4 or IPv6 address is found for the server. + */ public function find_access($server) { if (!empty($server->hostname)) { @@ -180,16 +199,16 @@ public function find_access($server) } } - /* - Find server hardware usage information "getHardwareData" - */ + /** + * Returns hardware data for a given server. + * + * @param object $server The server object. + * @return array The hardware data. + * @throws \Box_Exception If failed to connect to the server. + */ public function getHardwareData($server) { - // Retrieve associated server - $serveraccess = $this->find_access($server); - $config = $this->di['mod_config']('Serviceproxmox'); - $proxmox = new \PVE2APIClient\PVE2_API($serveraccess, $server->root_user, $server->realm, $server->root_password, port: $server->port, tokenid: $server->tokenname, tokensecret: $server->tokenvalue,debug: $config['pmx_debug_logging']); - + $proxmox = $this->getProxmoxInstance($server); if ($proxmox->login()) { error_log("ProxmoxServer.php: getHardwareData: Login successful"); $hardware = $proxmox->get("/nodes/" . $server->name . "/status"); @@ -199,12 +218,16 @@ public function getHardwareData($server) } } + /** + * Returns storage data for a given server. + * + * @param object $server The server object. + * @return array The storage data. + * @throws \Box_Exception If failed to connect to the server. + */ public function getStorageData($server) { - // Retrieve associated server - $serveraccess = $this->find_access($server); - $config = $this->di['mod_config']('Serviceproxmox'); - $proxmox = new \PVE2APIClient\PVE2_API($serveraccess, $server->root_user, $server->realm, $server->root_password, port: $server->port, tokenid: $server->tokenname, tokensecret: $server->tokenvalue,debug: $config['pmx_debug_logging']); + $proxmox = $this->getProxmoxInstance($server); if ($proxmox->login()) { $storage = $proxmox->get("/nodes/" . $server->name . "/storage"); return $storage; @@ -213,13 +236,16 @@ public function getStorageData($server) } } - // function to get all assigned cpu_cores and ram on a server (used to find free resources) + /** + * Returns assigned resources for a given server. + * + * @param object $server The server object. + * @return array The assigned resources. + * @throws \Box_Exception If failed to connect to the server. + */ public function getAssignedResources($server) { - // Retrieve associated server - $serveraccess = $this->find_access($server); - $config = $this->di['mod_config']('Serviceproxmox'); - $proxmox = new \PVE2APIClient\PVE2_API($serveraccess, $server->root_user, $server->realm, $server->root_password, port: $server->port, tokenid: $server->tokenname, tokensecret: $server->tokenvalue,debug: $config['pmx_debug_logging']); + $proxmox = $this->getProxmoxInstance($server); if ($proxmox->login()) { $assigned_resources = $proxmox->get("/nodes/" . $server->name . "/qemu"); return $assigned_resources; @@ -228,14 +254,17 @@ public function getAssignedResources($server) } } - // function to get available appliances from a server + /** + * Returns available appliances. + * + * @return array The available appliances. + * @throws \Box_Exception If failed to connect to the server. + */ public function getAvailableAppliances() { $server = $this->di['db']->getExistingModelById('service_proxmox_server', 1, 'Server not found'); - $serveraccess = $this->find_access($server); - $config = $this->di['mod_config']('Serviceproxmox'); - $proxmox = new \PVE2APIClient\PVE2_API($serveraccess, $server->root_user, $server->realm, $server->root_password, port: $server->port, tokenid: $server->tokenname, tokensecret: $server->tokenvalue,debug: $config['pmx_debug_logging']); + $proxmox = $this->getProxmoxInstance($server); if ($proxmox->login()) { $appliances = $proxmox->get("/nodes/" . $server->name . "/aplinfo"); return $appliances; @@ -244,12 +273,16 @@ public function getAvailableAppliances() } } - // function to get available template vms from a server - public function getQemuTemplates($server) + /** + * Returns an array of QEMU virtual machines for the given Proxmox server. + * + * @param object $server The server object containing the server name. + * @return array An array of QEMU virtual machines. + * @throws \Box_Exception If failed to connect to the server. + */ + public function getQemuVMs($server) { - $serveraccess = $this->find_access($server); - $config = $this->di['mod_config']('Serviceproxmox'); - $proxmox = new \PVE2APIClient\PVE2_API($serveraccess, $server->root_user, $server->realm, $server->root_password, port: $server->port, tokenid: $server->tokenname, tokensecret: $server->tokenvalue,debug: $config['pmx_debug_logging']); + $proxmox = $this->getProxmoxInstance($server); if ($proxmox->login()) { $templates = $proxmox->get("/nodes/" . $server->name . "/qemu"); return $templates; diff --git a/src/ProxmoxTemplates.php b/src/ProxmoxTemplates.php index b1b7141..723f21e 100644 --- a/src/ProxmoxTemplates.php +++ b/src/ProxmoxTemplates.php @@ -27,27 +27,35 @@ trait ProxmoxTemplates /* #################################### VM Template Mgmt ########################################### */ /* ################################################################################################### */ - // Function that gets all the VM templates and returns them as an array + /** + * Returns an array of all VM templates. + * + * @return array + */ public function get_vmtemplates() { - // get all the VM templates from the service_proxmox_vm_config_template table $templates = $this->di['db']->findAll('service_proxmox_vm_config_template'); return $templates; } - - // Function that gets all the LXC templates and returns them as an array + /** + * Returns an array of all LXC templates. + * + * @return array + */ public function get_lxctemplates() { - // get all the LXC templates from the service_proxmox_lxc_config_template table $templates = $this->di['db']->findAll('service_proxmox_lxc_config_template'); return $templates; } - // Function that gets all qemu templates and returns them as an array + /** + * Returns an array of all QEMU templates, with the server name for each template. + * + * @return array + */ public function get_qemutemplates() { - // get all the qemu templates from the service_proxmox_qemu_template table $qemu_templates = $this->di['db']->findAll('service_proxmox_qemu_template'); // Get server name for each template foreach ($qemu_templates as $qemu_template) { @@ -57,38 +65,50 @@ public function get_qemutemplates() return $qemu_templates; } - // Function that gets a vm config template by id + /** + * Get the virtual machine configuration template by ID. + * + * @param int $id The ID of the template to retrieve. + * @return Model The virtual machine configuration template. + */ public function get_vmconfig($id) { - // get the vm config template from the service_proxmox_vm_config_template table $template = $this->di['db']->getExistingModelById('service_proxmox_vm_config_template', $id); return $template; } - // Function that gets a lxc config template by id + /** + * Get the Linux container configuration template by ID. + * + * @param int $id The ID of the template to retrieve. + * @return Model The Linux container configuration template. + */ public function get_lxc_conftempl($id) { - // get the lxc config template from the service_proxmox_lxc_config_template table $template = $this->di['db']->getExistingModelById('service_proxmox_lxc_config_template', $id); return $template; } - - - // function to get tags for type + /** + * Get all tags of a certain type. + * + * @param array $data An array containing the type of tags to retrieve. + * @return array An array of tags of the specified type. + */ public function get_tags($data) { - // get list of tags for input type $tags = $this->di['db']->find('service_proxmox_tag', 'type=:type', array(':type' => $data['type'])); - // return tags return $tags; } - // function to save tags for type + /** + * Saves a tag to the database, creating it if it doesn't already exist. + * + * @param array $data An array containing the tag type and name. + * @return object The tag that was just created or the tag that already exists. + */ public function save_tag($data) { - // $data contains 'type' and 'tag' - // search if the tag already exists $tag_exists = $this->di['db']->findOne('service_proxmox_tag', 'type=:type AND name=:name', array(':type' => $data['type'], ':name' => $data['tag'])); // and if not create it @@ -103,27 +123,24 @@ public function save_tag($data) // return the tag that already exists return $tag_exists; } - - // Function to return tags for storage (stored in service_proxmox_storage->storageclass) ($data contains storageid) + /** + * Gets the tags associated with a given storage ID. + * + * @param array $data An array containing the storage ID. + * @return mixed An array of tags or an empty string if the storage has no tags. + */ public function get_tags_by_storage($data) { - // get storageclass for storage - // log to debug.log - error_log('get_tags_by_storage: ' . $data['storageid']); $storage = $this->di['db']->findOne('service_proxmox_storage', 'id=:id', array(':id' => $data['storageid'])); - // return tags (saved in json format in $storage->storageclass) (F.ex ["ssd","hdd"]) - // as well as the service_proxmox_tag id for each tag so there is a key value pair with id and name. - // check if $storage->storageclass is not empty + if (empty($storage->storageclass)) { - // if empty return empty array + // if empty return empty string $tags = ""; } else { $tags = json_decode($storage->storageclass, true); } return $tags; - - } } diff --git a/src/ProxmoxVM.php b/src/ProxmoxVM.php index 18fc019..0d9c01b 100644 --- a/src/ProxmoxVM.php +++ b/src/ProxmoxVM.php @@ -89,15 +89,9 @@ public function delete($order, $model) $product = $this->di['db']->load('product', $order->product_id); $product_config = json_decode($product->config, 1); - - // Retrieve associated server $server = $this->di['db']->findOne('service_proxmox_server', 'id=:id', array(':id' => $model->server_id)); - // Connect to YNH API - $serveraccess = $this->find_access($server); - $config = $this->di['mod_config']('Serviceproxmox'); - $proxmox = new \PVE2APIClient\PVE2_API($serveraccess, $server->root_user, $server->realm, $server->root_password, port: $server->port, tokenid: $server->tokenname, tokensecret: $server->tokenvalue,debug: $config['pmx_debug_logging']); - + $proxmox = $this->getProxmoxInstance($server); if ($proxmox->login()) { $proxmox->post("/nodes/" . $model->node . "/" . $product_config['virt'] . "/" . $model->vmid . "/status/shutdown", array()); $status = $proxmox->get("/nodes/" . $model->node . "/" . $product_config['virt'] . "/" . $model->vmid . "/status/current"); @@ -135,15 +129,10 @@ public function vm_info($order, $service) $product = $this->di['db']->load('product', $order->product_id); $product_config = json_decode($product->config, 1); $client = $this->di['db']->load('client', $order->client_id); - - // Retrieve associated server $server = $this->di['db']->findOne('service_proxmox_server', 'id=:id', array(':id' => $service->server_id)); $clientuser = $this->di['db']->findOne('service_proxmox_users', 'server_id = ? and client_id = ?', array($server->id, $client->id)); - // Test if login - $serveraccess = $this->find_access($server); - $config = $this->di['mod_config']('Serviceproxmox'); - $proxmox = new \PVE2APIClient\PVE2_API($serveraccess, $server->root_user, $server->realm, $server->root_password, port: $server->port, tokenid: $clientuser->admin_tokenname, tokensecret: $clientuser->admin_tokenvalue,debug: $config['pmx_debug_logging']); + $proxmox = $this->getProxmoxInstance($server); if ($proxmox->get_version()) { $status = $proxmox->get("/nodes/" . $server->name . "/" . $product_config['virt'] . "/" . $service->vmid . "/status/current"); // VM monitoring? @@ -166,14 +155,10 @@ public function vm_reboot($order, $service) $product_config = json_decode($product->config, 1); $client = $this->di['db']->load('client', $order->client_id); - // Retrieve associated server $server = $this->di['db']->findOne('service_proxmox_server', 'id=:id', array(':id' => $service->server_id)); $clientuser = $this->di['db']->findOne('service_proxmox_users', 'server_id = ? and client_id = ?', array($server->id, $client->id)); - // Test if login - $serveraccess = $this->find_access($server); - $config = $this->di['mod_config']('Serviceproxmox'); - $proxmox = new \PVE2APIClient\PVE2_API($serveraccess, $server->root_user, $server->realm, $server->root_password, port: $server->port, tokenid: $clientuser->admin_tokenname, tokensecret: $clientuser->admin_tokenvalue,debug: $config['pmx_debug_logging']); + $proxmox = $this->getProxmoxInstance($server); if ($proxmox->login()) { $proxmox->post("/nodes/" . $server->name . "/" . $product_config['virt'] . "/" . $service->vmid . "/status/shutdown", array()); $status = $proxmox->get("/nodes/" . $server->name . "/" . $product_config['virt'] . "/" . $service->vmid . "/status/current"); @@ -213,15 +198,10 @@ public function vm_start($order, $service) $product = $this->di['db']->load('product', $order->product_id); $product_config = json_decode($product->config, 1); $client = $this->di['db']->load('client', $order->client_id); - // Retrieve associated server - // Retrieve associated server $server = $this->di['db']->findOne('service_proxmox_server', 'id=:id', array(':id' => $service->server_id)); $clientuser = $this->di['db']->findOne('service_proxmox_users', 'server_id = ? and client_id = ?', array($server->id, $client->id)); - // Test if login - $serveraccess = $this->find_access($server); - $config = $this->di['mod_config']('Serviceproxmox'); - $proxmox = new \PVE2APIClient\PVE2_API($serveraccess, $server->root_user, $server->realm, $server->root_password, port: $server->port, tokenid: $clientuser->admin_tokenname, tokensecret: $clientuser->admin_tokenvalue,debug: $config['pmx_debug_logging']); + $proxmox = $this->getProxmoxInstance($server); if ($proxmox->login()) { $proxmox->post("/nodes/" . $server->name . "/" . $product_config['virt'] . "/" . $service->vmid . "/status/start", array()); return true; @@ -238,16 +218,10 @@ public function vm_shutdown($order, $service) $product = $this->di['db']->load('product', $order->product_id); $product_config = json_decode($product->config, 1); $client = $this->di['db']->load('client', $order->client_id); - // Retrieve associated server $server = $this->di['db']->findOne('service_proxmox_server', 'id=:id', array(':id' => $service->server_id)); - // Test if login - // find service access for server $clientuser = $this->di['db']->findOne('service_proxmox_users', 'server_id = ? and client_id = ?', array($server->id, $client->id)); - //echo "D: ".var_dump($order); - $serveraccess = $this->find_access($server); - $config = $this->di['mod_config']('Serviceproxmox'); - $proxmox = new \PVE2APIClient\PVE2_API($serveraccess, $server->root_user, $server->realm, $server->root_password, port: $server->port, tokenid: $clientuser->admin_tokenname, tokensecret: $clientuser->admin_tokenvalue,debug: $config['pmx_debug_logging']); + $proxmox = $this->getProxmoxInstance($server); if ($proxmox->login()) { $settings = array( 'forceStop' => true @@ -259,5 +233,4 @@ public function vm_shutdown($order, $service) throw new \Box_Exception("Login to Proxmox Host failed."); } } - } diff --git a/src/Service.php b/src/Service.php index bf598ad..14f4e66 100644 --- a/src/Service.php +++ b/src/Service.php @@ -33,22 +33,56 @@ class Service implements \FOSSBilling\InjectionAwareInterface { protected $di; - + private $pdo; public function setDi(\Pimple\Container|null $di): void { $this->di = $di; } - - public function getDi(): ?\Pimple\Container - { - return $this->di; - } + + public function getDi(): ?\Pimple\Container + { + return $this->di; + } use ProxmoxAuthentication; use ProxmoxServer; use ProxmoxVM; use ProxmoxTemplates; use ProxmoxIPAM; + + /** + * Returns a PDO instance for the database connection. + * + * @return PDO The PDO instance. + */ + private function getPdo(): PDO + { + if (!$this->pdo) { + // Get db config + $db_user = $this->di['config']['db']['user']; + $db_password = $this->di['config']['db']['password']; + $db_name = $this->di['config']['db']['name']; + + // Create PDO instance + $this->pdo = new PDO('mysql:host=localhost;dbname=' . $db_name, $db_user, $db_password); + $this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); + } + + return $this->pdo; + } + + + /** + * Fetches all tables in the database that start with 'service_proxmox'. + * + * @return array An array of table names. + */ + private function fetchServiceProxmoxTables(): array + { + $pdo = $this->getPdo(); + $stmt = $pdo->query("SHOW TABLES LIKE 'service_proxmox%'"); + return $stmt->fetchAll(PDO::FETCH_COLUMN); + } /** * Method to install module. In most cases you will provide your own * database table or tables to store extension related data. @@ -68,10 +102,7 @@ public function install(): bool // check if there is a sqldump backup with "uninstall" in it's name in the pmxconfig folder, if so, restore it $filesystem = new Filesystem(); - // list content of pmxconfig folder using symfony finder $finder = new Finder(); - - // check if pmxconfig folder exists if (!$filesystem->exists(PATH_ROOT . '/pmxconfig')) { $filesystem->mkdir(PATH_ROOT . '/pmxconfig'); } @@ -102,16 +133,10 @@ public function install(): bool $dump_version = str_replace('-- Proxmox module version: ', '', $version_line); $dump = str_replace($version_line . "\n", '', $dump); - // Get db config - $db_user = $this->di['config']['db']['user']; - $db_password = $this->di['config']['db']['password']; - $db_name = $this->di['config']['db']['name']; try { - // Create PDO instance - $pdo = new PDO('mysql:host=localhost;dbname=' . $db_name, $db_user, $db_password); - $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); - + // Retrieve PDO instance + $pdo = $this->getPdo(); // If version number in dump is smaller than current version number, restore dump and run upgrade function if ($dump_version < $version) { // Split the dump into an array by each sql command @@ -189,15 +214,10 @@ public function install(): bool error_log('PDO Exception: ' . $e->getMessage()); exit(1); } - - - // Create table for vm } - // add default values to module config table: - // cpu_overprovisioning, ram_overprovisioning, storage_overprovisioning, avoid_overprovision, no_overprovision, use_auth_tokens - // example: $extensionService->setConfig(['ext' => 'mod_massmailer', 'limit' => '2', 'interval' => '10', 'test_client_id' => 1]); + $extensionService = $this->di['mod_service']('extension'); - $extensionService->setConfig(['ext' => 'mod_serviceproxmox', 'cpu_overprovisioning' => '1', 'ram_overprovisioning' => '1', 'storage_overprovisioning' => '1', 'avoid_overprovision' => '0', 'no_overprovision' => '1', 'use_auth_tokens' => '1']); + $extensionService->setConfig(['ext' => 'mod_serviceproxmox', 'cpu_overprovisioning' => '1', 'ram_overprovisioning' => '1', 'storage_overprovisioning' => '1', 'avoid_overprovision' => '0', 'no_overprovision' => '1', 'use_auth_tokens' => '1', 'pmx_debug_logging' =>'0']); return true; @@ -212,29 +232,13 @@ public function install(): bool */ public function uninstall(): bool { - $this->pmxdbbackup('uninstall'); - $this->di['db']->exec("DROP TABLE IF EXISTS `service_proxmox`"); - $this->di['db']->exec("DROP TABLE IF EXISTS `service_proxmox_server`"); - $this->di['db']->exec("DROP TABLE IF EXISTS `service_proxmox_users`"); - $this->di['db']->exec("DROP TABLE IF EXISTS `service_proxmox_storage`"); - $this->di['db']->exec("DROP TABLE IF EXISTS `service_proxmox_templates`"); - $this->di['db']->exec("DROP TABLE IF EXISTS `service_proxmox_vms`"); - $this->di['db']->exec("DROP TABLE IF EXISTS `service_proxmox_vm_config_template`"); - $this->di['db']->exec("DROP TABLE IF EXISTS `service_proxmox_vm_storage_template`"); - $this->di['db']->exec("DROP TABLE IF EXISTS `service_proxmox_vm_network_template`"); - $this->di['db']->exec("DROP TABLE IF EXISTS `service_proxmox_lxc_appliance`"); - $this->di['db']->exec("DROP TABLE IF EXISTS `service_proxmox_storageclass`"); - $this->di['db']->exec("DROP TABLE IF EXISTS `service_proxmox_client_network`"); - $this->di['db']->exec("DROP TABLE IF EXISTS `service_proxmox_ip_networks`"); - $this->di['db']->exec("DROP TABLE IF EXISTS `service_proxmox_ip_range`"); - $this->di['db']->exec("DROP TABLE IF EXISTS `service_proxmox_client_vlan`"); - $this->di['db']->exec("DROP TABLE IF EXISTS `service_proxmox_lxc_config_template`"); - $this->di['db']->exec("DROP TABLE IF EXISTS `service_proxmox_lxc_network_template`"); - $this->di['db']->exec("DROP TABLE IF EXISTS `service_proxmox_lxc_storage_template`"); - $this->di['db']->exec("DROP TABLE IF EXISTS `service_proxmox_qemu_template`"); - $this->di['db']->exec("DROP TABLE IF EXISTS `service_proxmox_ipam_settings`"); - $this->di['db']->exec("DROP TABLE IF EXISTS `service_proxmox_ipadress`"); + // Retrieve PDO instance + $pdo = $this->getPdo(); + $tables = $this->fetchServiceProxmoxTables(); + foreach ($tables as $table) { + $pdo->exec("DROP TABLE IF EXISTS `$table`"); + } return true; } @@ -258,56 +262,45 @@ public function upgrade($previous_version): bool return version_compare(basename($a, '.sql'), basename($b, '.sql')); }); - // Get db config - $db_user = $this->di['config']['db']['user']; - $db_password = $this->di['config']['db']['password']; - $db_name = $this->di['config']['db']['name']; - - // Create PDO instance - $pdo = new PDO('mysql:host=localhost;dbname=' . $db_name, $db_user, $db_password); - $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); + // Retrieve PDO instance + $pdo = $this->getPdo(); foreach ($migrations as $migration) { // get version from filename - // log to debug.log - error_log('found migration: ' . $migration); + error_log('Found migration: ' . $migration); $filename = basename($migration, '.sql'); $version = str_replace('_', '.', $filename); - // check if version is between previous and current version - error_log('version: ' . $version . ' previous_version: ' . $previous_version . ' current_version: ' . $current_version); - - // Apply migration if version is larger than previous version and smaller or equal to current version - error_log('version_compare: ' . version_compare($version, $previous_version, '>') . ' version_compare2: ' . version_compare($version, $current_version, '<=')); - if (version_compare($version, $previous_version, '>') && version_compare($version, $current_version, '<=')) { - error_log('applying migration: ' . $migration); + error_log('Applying migration: ' . $migration); // run migration $migration_sql = file_get_contents($migration); $pdo->exec($migration_sql); + } else { + error_log('Skipping migration: ' . $migration); } } return true; } - /** - * Method to update module. When you release new version to - * extensions.fossbilling.org then this method will be called - * after the new files are placed. - * - * @param array $manifest - information about the new module version - * - * @return bool - * - * @throws \Box_Exception - */ - public function update(array $manifest): bool - { - // throw new \Box_Exception("Throw exception to terminate module update process with a message", array(), 125); - return true; - } + /** + * Method to update module. When you release new version to + * extensions.fossbilling.org then this method will be called + * after the new files are placed. + * + * @param array $manifest - information about the new module version + * + * @return bool + * + * @throws \Box_Exception + */ + public function update(array $manifest): bool + { + // throw new \Box_Exception("Throw exception to terminate module update process with a message", array(), 125); + return true; + } @@ -324,24 +317,7 @@ public function check_db_migration() // read current module version from manifest.json $manifest = json_decode(file_get_contents(__DIR__ . '/manifest.json'), true); $current_version = $manifest['version']; - $tables = array( - 'service_proxmox_server', - 'service_proxmox', - 'service_proxmox_users', - 'service_proxmox_storageclass', - 'service_proxmox_storage', - 'service_proxmox_lxc_appliance', - 'service_proxmox_vm_config_template', - 'service_proxmox_vm_storage_template', - 'service_proxmox_vm_network_template', - 'service_proxmox_lxc_config_template', - 'service_proxmox_lxc_storage_template', - 'service_proxmox_lxc_network_template', - 'service_proxmox_qemu_template', - 'service_proxmox_client_vlan', - 'service_proxmox_ip_range' - - ); + $tables = $this->fetchServiceProxmoxTables(); foreach ($tables as $table) { $sql = "SELECT table_comment FROM INFORMATION_SCHEMA.TABLES WHERE table_schema='" . DB_NAME . "' AND table_name='" . $table . "'"; /* @phpstan-ignore-line */ @@ -349,7 +325,6 @@ public function check_db_migration() $row = $result->fetch(); // check if version is the same as current version if ($row['table_comment'] != $current_version) { - // if not, throw error to inform user about inconsistent database status throw new \Box_Exception('Database migration is not up to date. Please run the database migration script.'); } } @@ -369,47 +344,20 @@ public function pmxdbbackup($data) $filesystem = new Filesystem(); $filesystem->mkdir([PATH_ROOT . '/pmxconfig'], 0750); } catch (IOException $e) { - error_log($e->getMessage()); + error_log('An error occurred while creating backup directory at ' . $e->getMessage()); throw new \Box_Exception('Unable to create directory pmxconfig'); } - // create filename with timestamp - // check if $data is 'uninstall' or 'backup' + if ($data == 'uninstall') { $filename = '/pmxconfig/proxmox_uninstall_' . date('Y-m-d_H-i-s') . '.sql'; } else { $filename = '/pmxconfig/proxmox_backup_' . date('Y-m-d_H-i-s') . '.sql'; } - // get db config - $db_user = $this->di['config']['db']['user']; - $db_password = $this->di['config']['db']['password']; - $db_name = $this->di['config']['db']['name']; try { - // create PDO instance - $pdo = new PDO('mysql:host=localhost;dbname=' . $db_name, $db_user, $db_password); - - // List of tables to backup - $tables = array( - 'service_proxmox_server', - 'service_proxmox', - 'service_proxmox_users', - 'service_proxmox_storage', - 'service_proxmox_lxc_appliance', - 'service_proxmox_vm_config_template', - 'service_proxmox_vm_storage_template', - 'service_proxmox_vm_network_template', - 'service_proxmox_lxc_config_template', - 'service_proxmox_lxc_storage_template', - 'service_proxmox_lxc_network_template', - 'service_proxmox_qemu_template', - 'service_proxmox_client_vlan', - 'service_proxmox_ip_range', - 'service_proxmox_ipadress',/* - 'service_proxmox_ipam_settings' */ - ); - - // Initialize backup variable + $pdo = $this->getPdo(); + $tables = $tables = $this->fetchServiceProxmoxTables(); $backup = ''; // Loop through tables and create SQL statement @@ -444,62 +392,7 @@ public function pmxdbbackup($data) $handle = fopen(PATH_ROOT . $filename, 'w+'); fwrite($handle, $backup); fclose($handle); - // create PDO instance - $pdo = new PDO('mysql:host=localhost;dbname=' . $db_name, $db_user, $db_password); - - // List of tables to backup - $tables = array( - 'service_proxmox_server', - 'service_proxmox', - 'service_proxmox_users', - 'service_proxmox_storage', - 'service_proxmox_lxc_appliance', - 'service_proxmox_vm_config_template', - 'service_proxmox_vm_storage_template', - 'service_proxmox_vm_network_template', - 'service_proxmox_lxc_config_template', - 'service_proxmox_lxc_storage_template', - 'service_proxmox_lxc_network_template', - 'service_proxmox_qemu_template', - 'service_proxmox_client_vlan', - 'service_proxmox_ip_range' - ); - - // Initialize backup variable - $backup = ''; - - // Loop through tables and create SQL statement - foreach ($tables as $table) { - $result = $pdo->query('SELECT * FROM ' . $table); - $num_fields = $result->columnCount(); - - $backup .= 'DROP TABLE IF EXISTS ' . $table . ';'; - $row2 = $pdo->query('SHOW CREATE TABLE ' . $table)->fetch(PDO::FETCH_NUM); - $backup .= "\n\n" . $row2[1] . ";\n\n"; - - while ($row = $result->fetch(PDO::FETCH_NUM)) { - $backup .= 'INSERT INTO ' . $table . ' VALUES('; - for ($j = 0; $j < $num_fields; $j++) { - $row[$j] = addslashes($row[$j]); - $row[$j] = preg_replace("/\n/", "\\n", $row[$j]); - if (isset($row[$j])) { - $backup .= '"' . $row[$j] . '"'; - } else { - $backup .= '""'; - } - if ($j < ($num_fields - 1)) { - $backup .= ','; - } - } - $backup .= ");\n"; - } - $backup .= "\n\n\n"; - } - // Save to file - $handle = fopen(PATH_ROOT . $filename, 'w+'); - fwrite($handle, $backup); - fclose($handle); } catch (\Box_Exception $e) { throw new \Box_Exception('Error during backup process: ' . $e->getMessage()); } @@ -546,40 +439,29 @@ public function pmxbackuplist() /** * Method to restore Proxmox tables from backup - * It's a bit destructive, as it will drop & overwrite all existing tables + * It's a destructive operation, as it will drop & overwrite all existing tables * * @param string $data - filename of backup * @return bool */ public function pmxbackuprestore($data) { - // get filename from $data and see if it exists using finder $manifest = json_decode(file_get_contents(__DIR__ . '/manifest.json'), true); $version = $manifest['version']; - //if the file exists, restore it $dump = file_get_contents(PATH_ROOT . '/pmxconfig/' . $data['backup']); - // check if dump is not empty if (!empty($dump)) { - // check version number in first line of dump format: - // -- Proxmox module version: 0.0.5 - // get first line of dump $version_line = strtok($dump, "\n"); - // get version number from line $dump_version = str_replace('-- Proxmox module version: ', '', $version_line); $dump = str_replace($version_line . "\n", '', $dump); - // if version number in dump is smaller than current version number, restore dump and run upgrade function if ($dump_version == $version) { - // get db config $db_user = $this->di['config']['db']['user']; $db_password = $this->di['config']['db']['password']; $db_name = $this->di['config']['db']['name']; try { // create PDO instance - $pdo = new PDO('mysql:host=localhost;dbname=' . $db_name, $db_user, $db_password); - $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); - + $pdo = $this->getPdo(); // split the dump into an array by each sql command $query_array = explode(";", $dump); @@ -645,10 +527,7 @@ public function create($order) $model->created_at = date('Y-m-d H:i:s'); $model->updated_at = date('Y-m-d H:i:s'); - // Find suitable server and save it to service_proxmox $model->server_id = $this->find_empty($product); - // Retrieve server info - $this->di['db']->store($model); return $model; @@ -686,7 +565,7 @@ public function activate($order, $model) // find client permissions for server $clientuser = $this->di['db']->findOne('service_proxmox_users', 'server_id = ? and client_id = ?', array($server->id, $client->id)); $config = $this->di['mod_config']('Serviceproxmox'); - $proxmox = new \PVE2APIClient\PVE2_API($serveraccess, $server->root_user, $server->realm, $server->root_password, port: $server->port, tokenid: $clientuser->admin_tokenname, tokensecret: $clientuser->admin_tokenvalue,debug: $config['pmx_debug_logging']); + $proxmox = new \PVE2APIClient\PVE2_API($serveraccess, $server->root_user, $server->realm, $server->root_password, port: $server->port, tokenid: $clientuser->admin_tokenname, tokensecret: $clientuser->admin_tokenvalue, debug: $config['pmx_debug_logging']); // Create Proxmox VM if ($proxmox->login()) { @@ -707,7 +586,7 @@ public function activate($order, $model) $description = 'Service package ' . $model->id . ' belonging to client id: ' . $client->id; if ($product_config['clone'] == true) { - $clone = '/' . $product_config['cloneid'] . '/clone'; // Define the route for cloning + $clone = '/' . $product_config['cloneid'] . '/clone'; $container_settings = array( 'newid' => $vmid, 'name' => $model->username, @@ -718,8 +597,8 @@ public function activate($order, $model) if ($product_config['virt'] == 'qemu') { $container_settings = array( 'vmid' => $vmid, - 'name' => 'vm' . $vmid, // Hostname to define - 'node' => $server->name, // Node to create the VM on + 'name' => 'vm' . $vmid, + 'node' => $server->name, 'description' => $description, 'storage' => $product_config['storage'], 'memory' => $product_config['memory'], @@ -736,7 +615,7 @@ public function activate($order, $model) } else { $container_settings = array( 'vmid' => $vmid, - 'hostname' => 'vm' . $vmid, // Hostname to define + 'hostname' => 'vm' . $vmid, 'description' => $description, 'storage' => $product_config['storage'], 'memory' => $product_config['memory'], @@ -744,7 +623,7 @@ public function activate($order, $model) 'password' => $proxmoxuser_password, 'net0' => $product_config['network'] ); - // Storage to do for LXC + // TODO: Storage for LXC } } @@ -752,7 +631,6 @@ public function activate($order, $model) $vmurl = "/nodes/" . $server->name . "/" . $product_config['virt'] . $clone; $vmcreate = $proxmox->post($vmurl, $container_settings); - //echo "Debug:\n " . var_dump($vmcreate) . "\n \n"; if ($vmcreate) { // Start the vm @@ -818,7 +696,12 @@ public function toApiArray($model) ); } - // function to get novnc_appjs file + /** + * Retrieves the novnc appjs file from a Proxmox server. + * + * @param array $data An array containing the version of the appjs file to retrieve. + * @return object The contents of the appjs file. + */ public function get_novnc_appjs($data) { // get list of servers @@ -831,7 +714,6 @@ public function get_novnc_appjs($data) // build url $url = "https://$hostname:8006/novnc/" . $data; //$data['ver']; - // get file using symphony http client // set options $client = $this->getHttpClient()->withOptions([ 'verify_peer' => false, @@ -839,18 +721,29 @@ public function get_novnc_appjs($data) 'timeout' => 60, ]); $result = $client->request('GET', $url); - //echo ""; // return file return $result; } + /** + * Returns an instance of the Symfony HttpClient. + * + * @return \Symfony\Component\HttpClient\HttpClient + */ public function getHttpClient() { return \Symfony\Component\HttpClient\HttpClient::create(); } - + + /** + * Validates custom form data against a product's form fields. + * TODO: This needs to be fixes / changed + * @param array &$data The form data to validate. + * @param array $product The product containing the form fields to validate against. + * @throws \Box_Exception If a required field is missing or a read-only field is modified. + */ public function validateCustomForm(array &$data, array $product) { if ($product['form_id']) { @@ -874,4 +767,20 @@ public function validateCustomForm(array &$data, array $product) } } } + /** + * Returns the salt value from the configuration. + * + * @return string The salt value. + */ + private function _getSalt() + { + return $this->di['config']['salt']; + } + + private function getProxmoxInstance($server) + { + $serveraccess = $this->find_access($server); + $config = $this->di['mod_config']('Serviceproxmox'); + return new \PVE2APIClient\PVE2_API($serveraccess, $server->root_user, $server->realm, $server->root_password, port: $server->port, tokenid: $server->tokenname, tokensecret: $server->tokenvalue, debug: $config['pmx_debug_logging']); + } } diff --git a/src/html_admin/mod_serviceproxmox_config.html.twig b/src/html_admin/mod_serviceproxmox_config.html.twig index 29600fd..f49c652 100644 --- a/src/html_admin/mod_serviceproxmox_config.html.twig +++ b/src/html_admin/mod_serviceproxmox_config.html.twig @@ -1,248 +1,232 @@
- - -
-

- {{ 'General Settings' | trans }} -

-
-
-
- -
-
- - -
-
- - -
-
-
-
- - {% set groups = admin.serviceproxmox_server_groups() %} -
- -
-
-
- -
- -
-
-
- -
-
- - -
-
- - -
-
-
-
-
-

- {{ 'Product Settings' | trans }} -

-
-
-
- -
-
- - -
-
- - -
-
-
- {% set lxc_templates = admin.serviceproxmox_service_get_lxctemplates() %} - {% set vm_templates = admin.serviceproxmox_service_get_vmtemplates() %} - {% set qemu_templates = admin.serviceproxmox_service_get_qemutemplates() %} -
- -
- -
-
-
- -
- -
-
-
- -
- -
-
- + + +
+

+ {{ 'General Settings' | trans }} +

+
+
+
+ +
+
+ + +
+
+ + +
+
+
+
+ + {% set groups = admin.serviceproxmox_server_groups() %} +
+ +
+
+
+ +
+ +
+
+
+ +
+
+ + +
+
+ + +
+
+
+
+
+

+ {{ 'Product Settings' | trans }} +

+
+
+
+ +
+
+ + +
+
+ + +
+
+
+ {% set lxc_templates = admin.serviceproxmox_service_get_lxctemplates() %} + {% set vm_templates = admin.serviceproxmox_service_get_vmtemplates() %} + {% set qemu_templates = admin.serviceproxmox_service_get_qemutemplates() %} +
+ +
+ +
+
+
+ +
+ +
+
+
+ +
+ +
+
+ -
+
{% block js %} {% endblock %} - \ No newline at end of file diff --git a/src/html_admin/mod_serviceproxmox_index.html.twig b/src/html_admin/mod_serviceproxmox_index.html.twig index 7f8d043..01accd0 100644 --- a/src/html_admin/mod_serviceproxmox_index.html.twig +++ b/src/html_admin/mod_serviceproxmox_index.html.twig @@ -581,45 +581,38 @@ } - > + + var username = document.getElementById("username"); + var token = document.getElementById("token"); + + username.addEventListener("click", function() { + document.getElementsByName("user_name_field")[0].hidden = false; + document.getElementsByName("password_field")[0].hidden = false; + document.getElementsByName("token_name_field")[0].hidden = true; + document.getElementsByName("token_value_field")[0].hidden = true; + }); + + token.addEventListener("click", function() { + document.getElementsByName("user_name_field")[0].hidden = true; + document.getElementsByName("password_field")[0].hidden = true; + document.getElementsByName("token_name_field")[0].hidden = false; + document.getElementsByName("token_value_field")[0].hidden = false; + }); + {% endblock %} diff --git a/src/html_admin/mod_serviceproxmox_ipam.html.twig b/src/html_admin/mod_serviceproxmox_ipam.html.twig index e804fb8..a72055a 100644 --- a/src/html_admin/mod_serviceproxmox_ipam.html.twig +++ b/src/html_admin/mod_serviceproxmox_ipam.html.twig @@ -522,62 +522,62 @@ {% block js %} {% endblock %} diff --git a/src/html_admin/mod_serviceproxmox_ipam_client_vlan.html.twig b/src/html_admin/mod_serviceproxmox_ipam_client_vlan.html.twig index 2e193d0..d88cfa3 100644 --- a/src/html_admin/mod_serviceproxmox_ipam_client_vlan.html.twig +++ b/src/html_admin/mod_serviceproxmox_ipam_client_vlan.html.twig @@ -55,8 +55,8 @@ - {% endblock %} - {% block js %} +{% endblock %} +{% block js %} - {% endblock %} +{% endblock %} \ No newline at end of file diff --git a/src/html_admin/mod_serviceproxmox_ipam_iprange.html.twig b/src/html_admin/mod_serviceproxmox_ipam_iprange.html.twig index 62d3ad9..f05543e 100644 --- a/src/html_admin/mod_serviceproxmox_ipam_iprange.html.twig +++ b/src/html_admin/mod_serviceproxmox_ipam_iprange.html.twig @@ -76,8 +76,8 @@ - {% endblock %} - {% block js %} +{% endblock %} +{% block js %} - {% endblock %} - - \ No newline at end of file +{% endblock %} \ No newline at end of file diff --git a/src/html_admin/mod_serviceproxmox_settings.html.twig b/src/html_admin/mod_serviceproxmox_settings.html.twig index 6f1b75a..669c7cd 100644 --- a/src/html_admin/mod_serviceproxmox_settings.html.twig +++ b/src/html_admin/mod_serviceproxmox_settings.html.twig @@ -269,56 +269,42 @@ {% block js %} {% endblock %} diff --git a/src/html_admin/mod_serviceproxmox_storage.html.twig b/src/html_admin/mod_serviceproxmox_storage.html.twig index d40c022..7f63833 100644 --- a/src/html_admin/mod_serviceproxmox_storage.html.twig +++ b/src/html_admin/mod_serviceproxmox_storage.html.twig @@ -99,93 +99,89 @@ {% block js %} diff --git a/src/html_admin/mod_serviceproxmox_templates.html.twig b/src/html_admin/mod_serviceproxmox_templates.html.twig index 3fc6684..a1bd8a5 100644 --- a/src/html_admin/mod_serviceproxmox_templates.html.twig +++ b/src/html_admin/mod_serviceproxmox_templates.html.twig @@ -98,7 +98,6 @@ {{ template.name }} - - {% if template.state == 'draft' %} {% set statusClass = 'badge bg-secondary' %} {% elseif template.state == 'active' %} @@ -216,8 +215,6 @@ - -
@@ -231,9 +228,7 @@ - {% set os_list = admin.serviceproxmox_os_get_list() %} -
{% for bios in bios_list %} @@ -546,8 +539,6 @@ - -
@@ -117,9 +115,7 @@ - {% set os_list = admin.serviceproxmox_os_get_list() %} -
{% for bios in bios_list %} @@ -404,26 +398,26 @@ const templateId = templateIdElem.value; API.admin.post( - 'serviceproxmox/vm_config_template_get_storages', - { id: templateId }, + 'serviceproxmox/vm_config_template_get_storages', { + id: templateId + }, populateTable, handleError ); } - - + function deleteStorage(storageId) { API.admin.post( - 'serviceproxmox/vm_config_template_delete_storage', - { id: storageId }, + 'serviceproxmox/vm_config_template_delete_storage', { + id: storageId + }, () => { - updateStorageTable(); // Update the table after deletion + updateStorageTable(); }, handleError ); } - - + function populateTable(response) { const tableBody = document.getElementById("template-storage-list"); tableBody.innerHTML = ''; @@ -434,7 +428,6 @@ row.id = "template-storage-list-row-" + storageData.id; tableBody.appendChild(row); - // Append empty cell to match table header. row.appendChild(document.createElement("td")); appendCellToRow(row, storageData.id, "storage-name", storageData.storage_type); @@ -460,9 +453,8 @@ const button = document.createElement("a"); button.className = "btn btn-icon"; - // If the actionType is "delete", attach an event to handle the deletion. if (actionType === "delete") { - button.href = "javascript:void(0)"; // Make sure the link doesn't navigate anywhere + button.href = "javascript:void(0)"; button.addEventListener('click', function(event) { event.preventDefault(); deleteStorage(storageId); @@ -476,7 +468,7 @@ const img = document.createElement("img"); img.className = "icon"; img.src = `assets/icons/${actionType}.svg`; - img.alt = `${actionType} icon`; // For accessibility + img.alt = `${actionType} icon`; button.appendChild(img); } @@ -484,37 +476,30 @@ console.error("API Error:", error); } - document.getElementById('add-storage-btn').addEventListener('click', function() { - // Save the storage configuration saveStorage(); }); - - // function to save storage configuration - function saveStorage(){ - - //prepare the data for the ajax call: template id in the hidden input with id vm_config_template_id + + function saveStorage() { + var template_id_v = document.getElementById('vm_config_template_id'); - // storage size from the input with name=storage_size, not id var storage_size_v = document.getElementById('storage_size'); - //storage controller from the select named controller var storage_controller_v = document.getElementById('controller'); - // storage type tags from the input with id storageTypeTags var storage_type_tags_v = document.getElementById('storageTypeTags'); - - // Build the data for the API call - var data = { template_id: template_id_v.value, storage_size: storage_size_v.value, storage_controller: storage_controller_v.value, storage_type_tags: storage_type_tags_v.value }; - // Call the API - - API.admin.post('serviceproxmox/vm_config_template_storage_create', data , (response) => { + + var data = { + template_id: template_id_v.value, + storage_size: storage_size_v.value, + storage_controller: storage_controller_v.value, + storage_type_tags: storage_type_tags_v.value + }; + + API.admin.post('serviceproxmox/vm_config_template_storage_create', data, (response) => { updateStorageTable() }, (response) => { - // Handle error - console.log(response); + console.log('Error occurred while saving storage: ' + response); }); - - - + } $(document).ready(function() { var Type = "storage"; @@ -522,56 +507,44 @@ plugins: ['remove_button'], create: true, delimiter: ',', - // Add more options and settings as needed }); - + getTagsForType(Type, function(options) { - // Add options to the TomSelect instance select.addOption(options); }); updateStorageTable(); - + $('#slide-toggle').on('change', function() { - $('.help-section').toggleClass('d-none'); - - if ($('#slide-toggle').prop('checked')) { - // Slide toggle is ON - $('#toggle-label').text('Hide help'); - } else { - // Slide toggle is OFF - $('#toggle-label').text('Show help'); - } - }); + $('.help-section').toggleClass('d-none'); + + if ($('#slide-toggle').prop('checked')) { + $('#toggle-label').text('Hide help'); + } else { + $('#toggle-label').text('Show help'); + } + }); }); + function getTagsForType(Type, callback) { - // Create the AJAX request var options = []; - $.ajax({ - url: '/index.php?_url=/api/admin/serviceproxmox/service_get_tags', - method: 'POST', - data: { - type: Type, - CSRFToken: '{{ CSRFToken }}' - }, - success: function(response) { - for (var key in response.result) { - if (response.result.hasOwnProperty(key)) { - var option = { - value: response.result[key].id, - text: response.result[key].name - }; - options.push(option); - } + API.admin.post("serviceproxmox/service_get_tags", { + type: Type + }, function(response) { + for (var key in response) { + if (response.hasOwnProperty(key)) { + var option = { + value: response[key].id, + text: response[key].name + }; + options.push(option); } - // Call the callback function with the options array - callback(options); - }, - error: function(xhr, status, error) { - callback(options); } - }); + callback(options); + }, function(error) { + console.log('Error occurred while getting tags: ' + error); + callback(options); + }, false); } - {% endblock %} \ No newline at end of file diff --git a/src/migrations/0.0.6.sql b/src/migrations/0.0.6.sql deleted file mode 100755 index 5beae37..0000000 --- a/src/migrations/0.0.6.sql +++ /dev/null @@ -1,19 +0,0 @@ --- -------------------------------------------------------- --- increment all tables to 0.0.6 --- -------------------------------------------------------- -ALTER TABLE `service_proxmox_server` COMMENT = '0.0.6'; -ALTER TABLE `service_proxmox` COMMENT = '0.0.6'; -ALTER TABLE `service_proxmox_users` COMMENT = '0.0.6'; -ALTER TABLE `service_proxmox_storageclass` COMMENT = '0.0.6'; -ALTER TABLE `service_proxmox_storage` COMMENT = '0.0.6'; -ALTER TABLE `service_proxmox_lxc_appliance` COMMENT = '0.0.6'; -ALTER TABLE `service_proxmox_vm_config_template` COMMENT = '0.0.6'; -ALTER TABLE `service_proxmox_vm_storage_template` COMMENT = '0.0.6'; -ALTER TABLE `service_proxmox_vm_network_template` COMMENT = '0.0.6'; -ALTER TABLE `service_proxmox_lxc_config_template` COMMENT = '0.0.6'; -ALTER TABLE `service_proxmox_lxc_storage_template` COMMENT = '0.0.6'; -ALTER TABLE `service_proxmox_lxc_network_template` COMMENT = '0.0.6'; -ALTER TABLE `service_proxmox_qemu_template` COMMENT = '0.0.6'; -ALTER TABLE `service_proxmox_client_vlan` COMMENT = '0.0.6'; -ALTER TABLE `service_proxmox_ip_range` COMMENT = '0.0.6'; --- -------------------------------------------------------- \ No newline at end of file diff --git a/src/migrations/0.0.7.sql b/src/migrations/0.0.7.sql deleted file mode 100644 index 6b3d8d8..0000000 --- a/src/migrations/0.0.7.sql +++ /dev/null @@ -1,84 +0,0 @@ --- Migration: 0.0.7 --- -------------------------------------------------------- --- Add new table for ipam settings --- -------------------------------------------------------- --- Fields: Minimum Network size (default 24), Maximum Network size (default 23), DNS Server 1, DNS Server 2 --- -------------------------------------------------------- -CREATE TABLE IF NOT EXISTS `service_proxmox_ipam_settings` ( - `id` int(11) NOT NULL AUTO_INCREMENT, - `min_network_size` int(11) NOT NULL DEFAULT '24', - `max_network_size` int(11) NOT NULL DEFAULT '23', - `dns_server_1` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '', - `dns_server_2` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '', - `use_proxmox_sdn` tinyint(1) NOT NULL DEFAULT '0', - PRIMARY KEY (`id`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; - --- -------------------------------------------------------- --- Add new table for ip adresses --- -------------------------------------------------------- --- Fields: IP address, ip range, dedicated, gateway, vlan - -CREATE TABLE IF NOT EXISTS `service_proxmox_ipadress` ( - `id` int(11) NOT NULL AUTO_INCREMENT, - `ip` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, - `ip_range_id` int(11) NOT NULL, - `dedicated` tinyint(1) NOT NULL DEFAULT '0', - `gateway` tinyint(1) NOT NULL DEFAULT '0', - `vlan` int(11) NOT NULL DEFAULT '0', - PRIMARY KEY (`id`), - KEY `ip_range_id` (`ip_range_id`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; - --- -------------------------------------------------------- --- alter service_proxmox_qemu_template to add auto increment to id, and add vmid field after id --- -------------------------------------------------------- -ALTER TABLE `service_proxmox_qemu_template` CHANGE `id` `id` INT(11) NOT NULL AUTO_INCREMENT; -ALTER TABLE `service_proxmox_qemu_template` ADD `vmid` INT(11) NOT NULL AFTER `id`; - --- -------------------------------------------------------- --- alter service_proxmox_ip_range to add network field after gateway --- -------------------------------------------------------- -ALTER TABLE `service_proxmox_ip_range` ADD `network` VARCHAR(255) NOT NULL AFTER `gateway`; - --- -------------------------------------------------------- --- alter service_proxmox_vm_config_template to add state field after id --- -------------------------------------------------------- -ALTER TABLE `service_proxmox_vm_config_template` ADD `state` VARCHAR(255) NOT NULL AFTER `id`; --- -------------------------------------------------------- --- insert state "draft" for all existing templates - -UPDATE `service_proxmox_vm_config_template` SET `state` = 'draft'; - --- -------------------------------------------------------- --- add new table for tags and tag relations --- -------------------------------------------------------- -CREATE TABLE IF NOT EXISTS `service_proxmox_tag` ( - `id` int(11) NOT NULL AUTO_INCREMENT, - `type` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, - `name` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, - PRIMARY KEY (`id`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; - --- -------------------------------------------------------- --- increment all tables to 0.0.7 --- -------------------------------------------------------- -ALTER TABLE `service_proxmox_server` COMMENT = '0.0.7'; -ALTER TABLE `service_proxmox` COMMENT = '0.0.7'; -ALTER TABLE `service_proxmox_users` COMMENT = '0.0.7'; -ALTER TABLE `service_proxmox_storageclass` COMMENT = '0.0.7'; -ALTER TABLE `service_proxmox_storage` COMMENT = '0.0.7'; -ALTER TABLE `service_proxmox_lxc_appliance` COMMENT = '0.0.7'; -ALTER TABLE `service_proxmox_vm_config_template` COMMENT = '0.0.7'; -ALTER TABLE `service_proxmox_vm_storage_template` COMMENT = '0.0.7'; -ALTER TABLE `service_proxmox_vm_network_template` COMMENT = '0.0.7'; -ALTER TABLE `service_proxmox_lxc_config_template` COMMENT = '0.0.7'; -ALTER TABLE `service_proxmox_lxc_storage_template` COMMENT = '0.0.7'; -ALTER TABLE `service_proxmox_lxc_network_template` COMMENT = '0.0.7'; -ALTER TABLE `service_proxmox_qemu_template` COMMENT = '0.0.7'; -ALTER TABLE `service_proxmox_client_vlan` COMMENT = '0.0.7'; -ALTER TABLE `service_proxmox_ip_range` COMMENT = '0.0.7'; -ALTER TABLE `service_proxmox_ipam_settings` COMMENT = '0.0.7'; -ALTER TABLE `service_proxmox_ipadress` COMMENT = '0.0.7'; -ALTER TABLE `service_proxmox_tag` COMMENT = '0.0.7'; --- -------------------------------------------------------- \ No newline at end of file diff --git a/src/migrations/0.0.8.sql b/src/migrations/0.0.8.sql deleted file mode 100755 index 459cdff..0000000 --- a/src/migrations/0.0.8.sql +++ /dev/null @@ -1,38 +0,0 @@ --- -------------------------------------------------------- --- alter service_storage_proxmox to change storageclass from VARCHAR to text --- -------------------------------------------------------- -ALTER TABLE `service_proxmox_storage` CHANGE `storageclass` `storageclass` TEXT DEFAULT NULL; - --- -------------------------------------------------------- --- alter `service_proxmox_vm_storage_template` so `format` is called `controller` --- -------------------------------------------------------- -ALTER TABLE `service_proxmox_vm_storage_template` CHANGE `format` `controller` VARCHAR(255) DEFAULT NULL; - - --- -------------------------------------------------------- --- increment all tables to 0.0.8 --- -------------------------------------------------------- -ALTER TABLE `service_proxmox_server` COMMENT = '0.0.8'; -ALTER TABLE `service_proxmox` COMMENT = '0.0.8'; -ALTER TABLE `service_proxmox_users` COMMENT = '0.0.8'; -ALTER TABLE `service_proxmox_storageclass` COMMENT = '0.0.8'; -ALTER TABLE `service_proxmox_storage` COMMENT = '0.0.8'; -ALTER TABLE `service_proxmox_lxc_appliance` COMMENT = '0.0.8'; -ALTER TABLE `service_proxmox_vm_config_template` COMMENT = '0.0.8'; -ALTER TABLE `service_proxmox_vm_storage_template` COMMENT = '0.0.8'; -ALTER TABLE `service_proxmox_vm_network_template` COMMENT = '0.0.8'; -ALTER TABLE `service_proxmox_lxc_config_template` COMMENT = '0.0.8'; -ALTER TABLE `service_proxmox_lxc_storage_template` COMMENT = '0.0.8'; -ALTER TABLE `service_proxmox_lxc_network_template` COMMENT = '0.0.8'; -ALTER TABLE `service_proxmox_qemu_template` COMMENT = '0.0.8'; -ALTER TABLE `service_proxmox_client_vlan` COMMENT = '0.0.8'; -ALTER TABLE `service_proxmox_ip_range` COMMENT = '0.0.8'; -ALTER TABLE `service_proxmox_ipam_settings` COMMENT = '0.0.8'; -ALTER TABLE `service_proxmox_ipadress` COMMENT = '0.0.8'; -ALTER TABLE `service_proxmox_tag` COMMENT = '0.0.8'; --- -------------------------------------------------------- - --- -------------------------------------------------------- --- drop table service_proxmox_storageclass --- -------------------------------------------------------- -DROP TABLE IF EXISTS `service_proxmox_storageclass`; \ No newline at end of file diff --git a/src/migrations/0.0.5.sql b/src/migrations/0.1.0.sql similarity index 77% rename from src/migrations/0.0.5.sql rename to src/migrations/0.1.0.sql index 769062e..09b6e1e 100755 --- a/src/migrations/0.0.5.sql +++ b/src/migrations/0.1.0.sql @@ -1,7 +1,8 @@ --- Migration: 0.0.5 --- Initial Migration for Proxmox Server Module - +-- Migration: 0.1.0 +-- Initial Migration for Proxmox Server Module v 0.1.0. +-- -------------------------------------------------------- +-- Table for storing proxmox server information -- -------------------------------------------------------- CREATE TABLE IF NOT EXISTS `service_proxmox_server` ( `id` bigint(20) NOT NULL AUTO_INCREMENT, @@ -27,6 +28,8 @@ CREATE TABLE IF NOT EXISTS `service_proxmox_server` ( PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1; +-- -------------------------------------------------------- +-- Table for storing proxmox service information -- -------------------------------------------------------- CREATE TABLE IF NOT EXISTS `service_proxmox` ( `id` bigint(20) NOT NULL AUTO_INCREMENT, @@ -51,6 +54,8 @@ CREATE TABLE IF NOT EXISTS `service_proxmox` ( ) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1; +-- -------------------------------------------------------- +-- Table for storing proxmox user information -- -------------------------------------------------------- CREATE TABLE IF NOT EXISTS `service_proxmox_users` ( `id` bigint(20) NOT NULL AUTO_INCREMENT, @@ -67,14 +72,8 @@ CREATE TABLE IF NOT EXISTS `service_proxmox_users` ( KEY `server_id_idx` (`server_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1; - -- -------------------------------------------------------- -CREATE TABLE IF NOT EXISTS `service_proxmox_storageclass` ( - `id` bigint(20) NOT NULL AUTO_INCREMENT, - `storageclass` varchar(35) DEFAULT NULL, - PRIMARY KEY (`id`) - ) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1; - +-- Table for storing proxmox storage information -- -------------------------------------------------------- CREATE TABLE IF NOT EXISTS `service_proxmox_storage` ( `id` bigint(20) NOT NULL AUTO_INCREMENT, @@ -83,15 +82,16 @@ CREATE TABLE IF NOT EXISTS `service_proxmox_storage` ( `type` varchar(255) DEFAULT NULL, `content` varchar(255) DEFAULT NULL, `active` bigint(20) DEFAULT NULL, - `storageclass` varchar(35) DEFAULT NULL, + `storageclass` TEXT DEFAULT NULL, `size` bigint(20) DEFAULT NULL, `used` bigint(20) DEFAULT NULL, `free` bigint(20) DEFAULT NULL, PRIMARY KEY (`id`), - UNIQUE KEY `server_storage_unique` (`server_id`, `storage`) + UNIQUE KEY `server_storage_unique` (`server_id`, `storage`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1; - +-- -------------------------------------------------------- +-- Table for storing proxmox lxc appliance information -- -------------------------------------------------------- CREATE TABLE IF NOT EXISTS `service_proxmox_lxc_appliance` ( `id` bigint(20) NOT NULL AUTO_INCREMENT, @@ -99,7 +99,6 @@ CREATE TABLE IF NOT EXISTS `service_proxmox_lxc_appliance` ( `type` varchar(255) DEFAULT NULL, `package` varchar(255) DEFAULT NULL, `section` varchar(255) DEFAULT NULL, - `location` varchar(255) DEFAULT NULL, `headline` varchar(255) DEFAULT NULL, `os` varchar(255) DEFAULT NULL, @@ -114,8 +113,12 @@ CREATE TABLE IF NOT EXISTS `service_proxmox_lxc_appliance` ( UNIQUE KEY `sha512sum_idx` (`sha512sum`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1; +-- -------------------------------------------------------- +-- Table for storing vm configuration templates +-- -------------------------------------------------------- CREATE TABLE IF NOT EXISTS `service_proxmox_vm_config_template` ( `id` bigint(20) NOT NULL AUTO_INCREMENT, + `state` VARCHAR(255) NOT NULL, `name` varchar(255) DEFAULT NULL, `description` varchar(255) DEFAULT NULL, `cores` bigint(20) DEFAULT NULL, @@ -132,14 +135,14 @@ CREATE TABLE IF NOT EXISTS `service_proxmox_vm_config_template` ( ) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1; -- -------------------------------------------------------- --- Create vm storage template table +-- Table for storing vm template storage information -- -------------------------------------------------------- CREATE TABLE IF NOT EXISTS `service_proxmox_vm_storage_template` ( `id` bigint(20) NOT NULL AUTO_INCREMENT, `template_id` bigint(20) DEFAULT NULL, `storage_type` varchar(255) DEFAULT NULL, `size` bigint(20) DEFAULT NULL, - `format` varchar(255) DEFAULT NULL, + `controller` VARCHAR(255) DEFAULT NULL, `created_at` varchar(35) DEFAULT NULL, `updated_at` varchar(35) DEFAULT NULL, PRIMARY KEY (`id`), @@ -148,7 +151,7 @@ CREATE TABLE IF NOT EXISTS `service_proxmox_vm_storage_template` ( -- -------------------------------------------------------- --- Create vm network template table +-- Table for storing vm template network information -- -------------------------------------------------------- CREATE TABLE IF NOT EXISTS `service_proxmox_vm_network_template` ( `id` bigint(20) NOT NULL AUTO_INCREMENT, @@ -166,7 +169,11 @@ CREATE TABLE IF NOT EXISTS `service_proxmox_vm_network_template` ( KEY `template_id_idx` (`template_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1; - CREATE TABLE IF NOT EXISTS `service_proxmox_lxc_config_template` ( + +-- -------------------------------------------------------- +-- Table for storing lxc template information +-- -------------------------------------------------------- +CREATE TABLE IF NOT EXISTS `service_proxmox_lxc_config_template` ( `id` bigint(20) NOT NULL AUTO_INCREMENT, `template_id` bigint(20) DEFAULT NULL, `name` varchar(255) DEFAULT NULL, @@ -183,7 +190,7 @@ CREATE TABLE IF NOT EXISTS `service_proxmox_vm_network_template` ( ) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1; -- -------------------------------------------------------- --- add lxc storage template table with a foreign key to service_proxmox_lxc_template +-- Table for storing lxc template storage information -- -------------------------------------------------------- CREATE TABLE IF NOT EXISTS `service_proxmox_lxc_storage_template` ( `id` bigint(20) NOT NULL AUTO_INCREMENT, @@ -198,7 +205,7 @@ CREATE TABLE IF NOT EXISTS `service_proxmox_lxc_storage_template` ( ) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1; -- -------------------------------------------------------- --- add lxc network template table with a foreign key to service_proxmox_lxc_template +-- Table for storing lxc template network information -- -------------------------------------------------------- CREATE TABLE IF NOT EXISTS `service_proxmox_lxc_network_template` ( `id` bigint(20) NOT NULL AUTO_INCREMENT, @@ -215,8 +222,7 @@ CREATE TABLE IF NOT EXISTS `service_proxmox_lxc_network_template` ( PRIMARY KEY (`id`), KEY `template_id_idx` (`template_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1; --- -------------------------------------------------------- --- New Table: service_proxmox_client_vlan + -- -------------------------------------------------------- -- Table to store client vlans -- -------------------------------------------------------- @@ -231,8 +237,6 @@ CREATE TABLE IF NOT EXISTS `service_proxmox_client_vlan` ( KEY `client_id_idx` (`client_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1; --- -------------------------------------------------------- --- New Table: service_proxmox_ip_range -- -------------------------------------------------------- -- Table to store ip networks -- -------------------------------------------------------- @@ -240,6 +244,7 @@ CREATE TABLE IF NOT EXISTS `service_proxmox_ip_range` ( `id` bigint(20) NOT NULL AUTO_INCREMENT, `cidr` varchar(255) DEFAULT NULL, `gateway` varchar(255) DEFAULT NULL, + `network` VARCHAR(255) NOT NULL, `broadcast` varchar(255) DEFAULT NULL, `type` varchar(255) DEFAULT NULL, `created_at` varchar(35) DEFAULT NULL, @@ -247,12 +252,12 @@ CREATE TABLE IF NOT EXISTS `service_proxmox_ip_range` ( PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1; - - --- add template vm table for storing information about qemu_template VMs +-- -------------------------------------------------------- +-- Table to qemu template VMs -- -------------------------------------------------------- CREATE TABLE IF NOT EXISTS `service_proxmox_qemu_template` ( - `id` bigint(20) NOT NULL, + `id` bigint(20) NOT NULL AUTO_INCREMENT, + `vmid` INT(11) NOT NULL, `server_id` bigint(20) DEFAULT NULL, `name` varchar(255) DEFAULT NULL, `created_at` varchar(35) DEFAULT NULL, @@ -261,5 +266,43 @@ CREATE TABLE IF NOT EXISTS `service_proxmox_qemu_template` ( KEY `id_idx` (`id`), UNIQUE KEY `vmid_server_id_idx` (`id`, `server_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1; + +-- -------------------------------------------------------- +-- Table to store ipam settings +-- -------------------------------------------------------- +CREATE TABLE IF NOT EXISTS `service_proxmox_ipam_settings` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `min_network_size` int(11) NOT NULL DEFAULT '24', + `max_network_size` int(11) NOT NULL DEFAULT '23', + `dns_server_1` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '', + `dns_server_2` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '', + `use_proxmox_sdn` tinyint(1) NOT NULL DEFAULT '0', + PRIMARY KEY (`id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; + +-- -------------------------------------------------------- +-- Add new table for individual ip adresses +-- -------------------------------------------------------- +CREATE TABLE IF NOT EXISTS `service_proxmox_ipadress` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `ip` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, + `ip_range_id` int(11) NOT NULL, + `dedicated` tinyint(1) NOT NULL DEFAULT '0', + `gateway` tinyint(1) NOT NULL DEFAULT '0', + `vlan` int(11) NOT NULL DEFAULT '0', + PRIMARY KEY (`id`), + KEY `ip_range_id` (`ip_range_id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; + +-- -------------------------------------------------------- +-- Add new table for the tagging system +-- -------------------------------------------------------- +CREATE TABLE IF NOT EXISTS `service_proxmox_tag` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `type` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, + `name` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, + PRIMARY KEY (`id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; + -- -------------------------------------------------------- -COMMIT; +COMMIT; \ No newline at end of file diff --git a/tests/Serviceproxmox/Api/AdminTest.php b/tests/Serviceproxmox/Api/AdminTest.php index 01c9936..ecdbbce 100644 --- a/tests/Serviceproxmox/Api/AdminTest.php +++ b/tests/Serviceproxmox/Api/AdminTest.php @@ -25,55 +25,4 @@ public function testgetDi() $this->assertEquals($di, $getDi); } - public function testServerGetList() - { - // Mocking the service_proxmox_server model - $serverModel = new \RedBeanPHP\SimpleModel(); - $serverModel->loadBean(new \DummyBean()); - $serverModel->id = 1; - $serverModel->ram = 4096; // 4GB in MB - $serverModel->cpu_cores = 4; - $serverModel->group = 'testGroup'; - - // Mocking the service_proxmox model - $proxmoxModel = new \RedBeanPHP\SimpleModel(); - $proxmoxModel->loadBean(new \DummyBean()); - $proxmoxModel->server_id = 1; - $proxmoxModel->cpu_cores = 2; - $proxmoxModel->ram = 20480; // 20GB in MB - - // Mocking the database - $dbMock = $this->getMockBuilder('\Box_Database')->getMock(); - $dbMock->expects($this->at(0)) - ->method('find') - ->with('service_proxmox_server') - ->will($this->returnValue([$serverModel])); - $dbMock->expects($this->at(1)) - ->method('find') - ->with('service_proxmox', 'server_id=:id', array(':id' => $serverModel->id)) - ->will($this->returnValue([$proxmoxModel])); - - // Mocking mod_config - $config = [ - 'cpu_overprovisioning' => 50, // Example value - 'ram_overprovisioning' => 50 // Example value - ]; - $modConfigMock = $this->getMockBuilder('\Box_ModConfig')->getMock(); - $modConfigMock->expects($this->once()) - ->method('get') - ->with('Serviceproxmox') - ->will($this->returnValue($config)); - - $di = new \Pimple\Container(); - $di['db'] = $dbMock; - $di['mod_config'] = $modConfigMock; - - $this->api->setDi($di); - $this->api->setService($serviceMock); - - $result = $this->api->server_get_list(array()); - $this->assertIsArray($result); - } - - } diff --git a/tests/Serviceproxmox/ServiceTest.php b/tests/Serviceproxmox/ServiceTest.php index 45e4d90..9beb782 100644 --- a/tests/Serviceproxmox/ServiceTest.php +++ b/tests/Serviceproxmox/ServiceTest.php @@ -72,16 +72,5 @@ public function test_create() $this->assertInstanceOf('\RedBeanPHP\SimpleModel', $result); $this->assertEquals($orderModel->client_id, $result->client_id); $this->assertEquals(1, $result->server_id); // Asserting the server ID is set correctly - } - - public function testGetHttpClient() - { - // Call the method - $httpClient = $this->getHttpClient(); - - // Assert that the returned object is an instance of the expected HttpClient - $this->assertInstanceOf(\Symfony\Component\HttpClient\HttpClient::class, $httpClient); - } - - + } }