Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

cpu % threads are not friendly with configurable options like quantity/ slider bar!!! #18

Closed
ZeltronModz opened this issue Jun 17, 2024 · 1 comment

Comments

@ZeltronModz
Copy link

ZeltronModz commented Jun 17, 2024

When using a configurable option like a quantity or slider bar, for example cpu|CPU Threads ! and the user only selects 2 threads
this will in put 2% and not 200%, this is of course a issue and makes it unpractical.

ive created logic to mitigate this issue, and im sharing it today hopefully for it to be implemented in future updates so i dont have to consistently apply this on every update. <3

function pterosync_CreateAccount(array $params)
{
    try {
        PteroSyncInstance::get()->service_id = $params['serviceid'];
        $ports = pteroSyncGetOption($params, 'ports_ranges');
        $ports = json_decode($ports, true);
        if (!empty($ports) && !is_array($ports)) {
            throw new Exception('Failed to create server because ports is not in valid json format.');
        }
        $serverId = pteroSyncGetServer($params);
        if ($serverId) throw new Exception('Failed to create server because it is already created.');
        $customFieldId = pteroSyncGetCustomFiledId($params);

        $userResult = PteroSyncInstance::get()->getPterodactylUser($params, [
            'username' => pteroSyncGetOption($params, 'username', pteroSyncGenerateUsername()),
            'id' => $params['clientsdetails']['client_id'],
            'email' => $params['clientsdetails']['email'],
            'firstname' => $params['clientsdetails']['firstname'],
            'lastname' => $params['clientsdetails']['lastname'],
        ]);

        if ($userResult['status_code'] === 200 || $userResult['status_code'] === 201) {
            $userId = $userResult['attributes']['id'];
        } else {
            throw new Exception('Failed to create user, received error code: ' . $userResult['status_code'] . '. Enable module debug log for more info.');
        }

        $nestId = pteroSyncGetOption($params, 'nest_id');
        $eggId = pteroSyncGetOption($params, 'egg_id');

        $eggData = pteroSyncApplicationApi($params, 'nests/' . $nestId . '/eggs/' . $eggId . '?include=variables');
        if ($eggData['status_code'] !== 200) throw new Exception('Failed to get egg data, received error code: ' . $eggData['status_code'] . '. Enable module debug log for more info.');

        $environment = [];
        $default_variables = pteroSyncGetOption($params, 'default_variables');
        $default_variables = json_decode($default_variables, true);
        foreach ($eggData['attributes']['relationships']['variables']['data'] as $key => $val) {
            $attr = $val['attributes'];
            $var = $attr['env_variable'];
            $default = $attr['default_value'];
            $friendlyName = pteroSyncGetOption($params, $attr['name']);
            $envName = pteroSyncGetOption($params, $attr['env_variable']);

            if (isset($friendlyName)) {
                $environment[$var] = $friendlyName;
            } elseif (isset($envName)) {
                $environment[$var] = $envName;
            } elseif (isset($default_variables[$var]) && !in_array($default_variables[$var], PteroSyncInstance::get()->dynamic_variables)) {
                $environment[$var] = $default_variables[$var];
            } else {
                $environment[$var] = $default;
            }
        }

        if ($default_variables) {
            foreach ($default_variables as $default_variable => $default_variable_value) {
                if (in_array($default_variable_value, PteroSyncInstance::get()->dynamic_variables)) {
                    PteroSyncInstance::get()->dynamic_environment_array[$default_variable] = $default_variable_value;
                }
            }
        }

        $name = pteroSyncGetOption($params, 'server_name', pteroSyncGenerateUsername() . '_' . $params['serviceid']);
        [$memory, $swap, $disk] = pteroSyncGetMemorySwapAndDisck($params);

        $io = pteroSyncGetOption($params, 'io');
        $cpu = pteroSyncGetOption($params, 'cpu');
        $cpu = $cpu * 100; // Multiply the CPU value by 100

        $location_id = pteroSyncGetOption($params, 'location_id');
        $dedicated_ip = (bool)pteroSyncGetOption($params, 'dedicated_ip');

        PteroSyncInstance::get()->server_port_offset = pteroSyncGetOption($params, 'server_port_offset');

        $port_range = explode(',', $ports['SERVER_PORT'] ?? '');
        if (count($port_range) == 0) {
            $port_range = [];
        }
        $image = pteroSyncGetOption($params, 'image', $eggData['attributes']['docker_image']);
        $startup = pteroSyncGetOption($params, 'startup', $eggData['attributes']['startup']);
        $databases = pteroSyncGetOption($params, 'databases');
        $maximumAllocations = pteroSyncGetOption($params, 'allocations');
        $backups = pteroSyncGetOption($params, 'backups');
        $oom_disabled = (bool)pteroSyncGetOption($params, 'oom_disabled');
        $split_limit = pteroSyncGetOption($params, 'split_limit');

        $serverData = [
            'name' => $name,
            'user' => (int)$userId,
            'nest' => (int)$nestId,
            'egg' => (int)$eggId,
            'docker_image' => $image,
            'startup' => $startup,
            'oom_disabled' => $oom_disabled,
            'limits' => [
                'memory' => (int)$memory,
                'swap' => (int)$swap,
                'io' => (int)$io,
                'cpu' => (int)$cpu, // Use the updated CPU value
                'disk' => (int)$disk,
            ],
            'feature_limits' => [
                'databases' => $databases ? (int)$databases : null,
                'allocations' => (int)$maximumAllocations,
                'backups' => (int)$backups,
                'split_limit' => (int)$split_limit,
            ],
            'deploy' => [
                'locations' => [(int)$location_id],
                'dedicated_ip' => $dedicated_ip,
                'port_range' => $port_range,
            ],
            'environment' => $environment,
            'start_on_completion' => true,
            'external_id' => (string)$params['serviceid'],
        ];

        $server = pteroSyncApplicationApi($params, 'servers?include=allocations', $serverData, 'POST');

        if ($server['status_code'] === 400) throw new Exception('Couldn\'t find any nodes satisfying the request.');
        if ($server['status_code'] !== 201) throw new Exception('Failed to create the server, received the error code: ' . $server['status_code'] . '. Enable module debug log for more info.');

        $serverId = $server['attributes']['id'];
        $_SERVER_ID = $server['attributes']['uuid'];
        $_SERVER_IP = '';
        $_SERVER_PORT = '';
        $serverAllocations = $server['attributes']['relationships']['allocations']['data'];
        $allocation = $server['attributes']['allocation'];
        pteroSync_getServerIPAndPort($_SERVER_IP, $_SERVER_PORT, $serverAllocations, $allocation);
        $_SERVER_PORT_ID = $serverAllocations[0]['attributes']['id'];

        $serverNode = $server['attributes']['node'];
        $node_path = 'nodes/' . $serverNode . '/allocations';
        $foundPorts = [];
        $variables = [];
        $ips = [];
        $nodeAllocations = [];
        if ($ports) {
            $nodeAllocations = pteroSyncGetNodeAllocations($params, $node_path);
            $variables = pteroSyncProcessAllocations($eggData, $ports, $_SERVER_PORT);
        }

        if (!$variables) {
            pteroSyncLog('VARIABLES', 'No variables founds.', $ports);
        }

        if (!$nodeAllocations) {
            pteroSyncLog('NODE ALLOCATIONS', 'Node allocations not found.', [$node_path]);
        }

        while ($variables && $nodeAllocations) {
            $ips = pteroSyncMakeIParray($nodeAllocations);
            $foundPorts = pteroSyncfindPorts($ports, $_SERVER_PORT, $_SERVER_IP, $variables, $ips);
            if ($foundPorts) {
                break;
            }
            if (PteroSyncInstance::get()->fetching) {
                $nodeAllocations = pteroSyncGetNodeAllocations($params, $node_path);
            } else {
                break;
            }
        }

        if (!$foundPorts && $variables && $nodeAllocations) {
            pteroSyncLog('Ports not founds', 'Ports not founds.', [
                'results' => PteroSyncInstance::get()->fetchedResults,
                'variables' => $variables
            ]);
        }

        if ($foundPorts) {
            $allocationArray['allocation'] = $_SERVER_PORT_ID;
            //if we have set SERVER_PORT that mean we have new server port and we need to remove the given allocation and add new allocation.
            if (isset($foundPorts['SERVER_PORT'])) {
                $allocationArray['allocation'] = $foundPorts['SERVER_PORT']['id'];
                $allocationArray['remove_allocations'] = [$_SERVER_PORT_ID];
            }

            $environment = [];
            $additional = [];
            foreach ($foundPorts as $key => $var) {
                $environment[$key] = "" . $var['port'] . "";
                $additional[] = $var['id'];
                $maximumAllocations++;
            }

            if (PteroSyncInstance::get()->getDynamicEnvironmentArray()) {
                PteroSyncInstance::get()->addFileLog(PteroSyncInstance::get()->getDynamicEnvironmentArray(), 'Setting Dynamic Environment');
                foreach (PteroSyncInstance::get()->getDynamicEnvironmentArray() as $environmentName => $variableName) {
                    if (isset($environment[$variableName])) {
                        $environment[$environmentName] = $environment[$variableName];
                    }
                }
            }
            if (isset($environment['SERVER_PORT'])) {
                unset($environment['SERVER_PORT']);
            }
            $allocationArray['add_allocations'] = $additional;

            $updateResult = pteroSyncApplicationApi($params, 'servers/' . $serverId . '/build?include=allocations', array_merge([
                'memory' => (int)$memory,
                'swap' => (int)$swap,
                'io' => (int)$io,
                'cpu' => (int)$cpu,
                'disk' => (int)$disk,
                'oom_disabled' => $oom_disabled,
                'feature_limits' => [
                    'databases' => (int)$databases,
                    'allocations' => (int)$maximumAllocations,
                    'backups' => (int)$backups,
                    'split_limit' => (int)$split_limit,
                ],
            ], $allocationArray), 'PATCH');

            if ($updateResult['status_code'] !== 200) throw new Exception('Failed to update build of the server, received error code: ' . $updateResult['status_code'] . '. Enable module debug log for more info.');


            $allocation = $updateResult['attributes']['allocation'];
            $newServerAllocations = $updateResult['attributes']['relationships']['allocations']['data'];
            pteroSync_getServerIPAndPort($_SERVER_IP, $_SERVER_PORT, $newServerAllocations, $allocation);
            pteroSyncApplicationApi($params, 'servers/' . $serverId . '/startup', [
                'startup' => $server['attributes']['container']['environment']['STARTUP'],
                'egg' => $server['attributes']['egg'],
                'image' => $server['attributes']['container']['image'],
                'environment' => array_merge($serverData['environment'], $environment),
                'skip_scripts' => false,
            ], 'PATCH');

        }


        unset($params['password']);
        pteroSync_updateServerDomain($_SERVER_IP, $_SERVER_PORT, $params);
        pteroSyncUpdateCustomFiled($params, $customFieldId, $_SERVER_ID);
        Capsule::table('tblhosting')->where('id', $params['serviceid'])->update([
            'username' => '',
            'password' => '',
        ]);

    } catch (Exception $err) {
        return $err->getMessage();
    }
    return 'success';
}
@wohahobg
Copy link
Owner

wohahobg commented Jul 2, 2024

Hey somehow i have not seen this one.

I will review it when I have a bit more time.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants