diff --git a/.gitignore b/.gitignore index 1b6d5405b..0d20b6487 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1 @@ *.pyc -containerization diff --git a/backup/migrations/0001_initial.py b/backup/migrations/0001_initial.py deleted file mode 100644 index 971731f5a..000000000 --- a/backup/migrations/0001_initial.py +++ /dev/null @@ -1,70 +0,0 @@ -# -*- coding: utf-8 -*- -# Generated by Django 1.11 on 2019-01-07 12:43 -from __future__ import unicode_literals - -from django.db import migrations, models - - -class Migration(migrations.Migration): - - initial = True - - dependencies = [ - ] - - operations = [ - migrations.CreateModel( - name='DBUsers', - fields=[ - ('host', models.CharField(db_column='Host', max_length=60, primary_key=True, serialize=False)), - ('user', models.CharField(db_column='User', max_length=16)), - ('password', models.CharField(db_column='Password', max_length=41)), - ('select_priv', models.CharField(db_column='Select_priv', max_length=1)), - ('insert_priv', models.CharField(db_column='Insert_priv', max_length=1)), - ('update_priv', models.CharField(db_column='Update_priv', max_length=1)), - ('delete_priv', models.CharField(db_column='Delete_priv', max_length=1)), - ('create_priv', models.CharField(db_column='Create_priv', max_length=1)), - ('drop_priv', models.CharField(db_column='Drop_priv', max_length=1)), - ('reload_priv', models.CharField(db_column='Reload_priv', max_length=1)), - ('shutdown_priv', models.CharField(db_column='Shutdown_priv', max_length=1)), - ('process_priv', models.CharField(db_column='Process_priv', max_length=1)), - ('file_priv', models.CharField(db_column='File_priv', max_length=1)), - ('grant_priv', models.CharField(db_column='Grant_priv', max_length=1)), - ('references_priv', models.CharField(db_column='References_priv', max_length=1)), - ('index_priv', models.CharField(db_column='Index_priv', max_length=1)), - ('alter_priv', models.CharField(db_column='Alter_priv', max_length=1)), - ('show_db_priv', models.CharField(db_column='Show_db_priv', max_length=1)), - ('super_priv', models.CharField(db_column='Super_priv', max_length=1)), - ('create_tmp_table_priv', models.CharField(db_column='Create_tmp_table_priv', max_length=1)), - ('lock_tables_priv', models.CharField(db_column='Lock_tables_priv', max_length=1)), - ('execute_priv', models.CharField(db_column='Execute_priv', max_length=1)), - ('repl_slave_priv', models.CharField(db_column='Repl_slave_priv', max_length=1)), - ('repl_client_priv', models.CharField(db_column='Repl_client_priv', max_length=1)), - ('create_view_priv', models.CharField(db_column='Create_view_priv', max_length=1)), - ('show_view_priv', models.CharField(db_column='Show_view_priv', max_length=1)), - ('create_routine_priv', models.CharField(db_column='Create_routine_priv', max_length=1)), - ('alter_routine_priv', models.CharField(db_column='Alter_routine_priv', max_length=1)), - ('create_user_priv', models.CharField(db_column='Create_user_priv', max_length=1)), - ('event_priv', models.CharField(db_column='Event_priv', max_length=1)), - ('trigger_priv', models.CharField(db_column='Trigger_priv', max_length=1)), - ('create_tablespace_priv', models.CharField(db_column='Create_tablespace_priv', max_length=1)), - ('ssl_type', models.CharField(max_length=9)), - ('ssl_cipher', models.TextField()), - ('x509_issuer', models.TextField()), - ('x509_subject', models.TextField()), - ('max_questions', models.IntegerField()), - ('max_updates', models.IntegerField()), - ('max_connections', models.IntegerField()), - ('max_user_connections', models.IntegerField()), - ('plugin', models.CharField(max_length=64)), - ('authentication_string', models.TextField()), - ], - options={ - 'db_table': 'user', - }, - ), - migrations.AlterUniqueTogether( - name='dbusers', - unique_together=set([('host', 'user')]), - ), - ] diff --git a/baseTemplate/migrations/0001_initial.py b/baseTemplate/migrations/0001_initial.py deleted file mode 100644 index 8a21783bb..000000000 --- a/baseTemplate/migrations/0001_initial.py +++ /dev/null @@ -1,24 +0,0 @@ -# -*- coding: utf-8 -*- -# Generated by Django 1.11 on 2019-01-07 12:43 -from __future__ import unicode_literals - -from django.db import migrations, models - - -class Migration(migrations.Migration): - - initial = True - - dependencies = [ - ] - - operations = [ - migrations.CreateModel( - name='version', - fields=[ - ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), - ('currentVersion', models.CharField(max_length=50)), - ('build', models.IntegerField()), - ], - ), - ] diff --git a/bin/activate b/bin/activate deleted file mode 100644 index b47274181..000000000 --- a/bin/activate +++ /dev/null @@ -1,78 +0,0 @@ -# This file must be used with "source bin/activate" *from bash* -# you cannot run it directly - -deactivate () { - unset -f pydoc >/dev/null 2>&1 - - # reset old environment variables - # ! [ -z ${VAR+_} ] returns true if VAR is declared at all - if ! [ -z "${_OLD_VIRTUAL_PATH+_}" ] ; then - PATH="$_OLD_VIRTUAL_PATH" - export PATH - unset _OLD_VIRTUAL_PATH - fi - if ! [ -z "${_OLD_VIRTUAL_PYTHONHOME+_}" ] ; then - PYTHONHOME="$_OLD_VIRTUAL_PYTHONHOME" - export PYTHONHOME - unset _OLD_VIRTUAL_PYTHONHOME - fi - - # This should detect bash and zsh, which have a hash command that must - # be called to get it to forget past commands. Without forgetting - # past commands the $PATH changes we made may not be respected - if [ -n "${BASH-}" ] || [ -n "${ZSH_VERSION-}" ] ; then - hash -r 2>/dev/null - fi - - if ! [ -z "${_OLD_VIRTUAL_PS1+_}" ] ; then - PS1="$_OLD_VIRTUAL_PS1" - export PS1 - unset _OLD_VIRTUAL_PS1 - fi - - unset VIRTUAL_ENV - if [ ! "${1-}" = "nondestructive" ] ; then - # Self destruct! - unset -f deactivate - fi -} - -# unset irrelevant variables -deactivate nondestructive - -VIRTUAL_ENV="/usr/local/CyberCP" -export VIRTUAL_ENV - -_OLD_VIRTUAL_PATH="$PATH" -PATH="$VIRTUAL_ENV/bin:$PATH" -export PATH - -# unset PYTHONHOME if set -if ! [ -z "${PYTHONHOME+_}" ] ; then - _OLD_VIRTUAL_PYTHONHOME="$PYTHONHOME" - unset PYTHONHOME -fi - -if [ -z "${VIRTUAL_ENV_DISABLE_PROMPT-}" ] ; then - _OLD_VIRTUAL_PS1="$PS1" - if [ "x" != x ] ; then - PS1="$PS1" - else - PS1="(`basename \"$VIRTUAL_ENV\"`) $PS1" - fi - export PS1 -fi - -# Make sure to unalias pydoc if it's already there -alias pydoc 2>/dev/null >/dev/null && unalias pydoc - -pydoc () { - python -m pydoc "$@" -} - -# This should detect bash and zsh, which have a hash command that must -# be called to get it to forget past commands. Without forgetting -# past commands the $PATH changes we made may not be respected -if [ -n "${BASH-}" ] || [ -n "${ZSH_VERSION-}" ] ; then - hash -r 2>/dev/null -fi diff --git a/bin/activate.csh b/bin/activate.csh deleted file mode 100644 index 309134216..000000000 --- a/bin/activate.csh +++ /dev/null @@ -1,42 +0,0 @@ -# This file must be used with "source bin/activate.csh" *from csh*. -# You cannot run it directly. -# Created by Davide Di Blasi . - -set newline='\ -' - -alias deactivate 'test $?_OLD_VIRTUAL_PATH != 0 && setenv PATH "$_OLD_VIRTUAL_PATH:q" && unset _OLD_VIRTUAL_PATH; rehash; test $?_OLD_VIRTUAL_PROMPT != 0 && set prompt="$_OLD_VIRTUAL_PROMPT:q" && unset _OLD_VIRTUAL_PROMPT; unsetenv VIRTUAL_ENV; test "\!:*" != "nondestructive" && unalias deactivate && unalias pydoc' - -# Unset irrelevant variables. -deactivate nondestructive - -setenv VIRTUAL_ENV "/usr/local/CyberCP" - -set _OLD_VIRTUAL_PATH="$PATH:q" -setenv PATH "$VIRTUAL_ENV:q/bin:$PATH:q" - - - -if ("" != "") then - set env_name = "" -else - set env_name = "$VIRTUAL_ENV:t:q" -endif - -# Could be in a non-interactive environment, -# in which case, $prompt is undefined and we wouldn't -# care about the prompt anyway. -if ( $?prompt ) then - set _OLD_VIRTUAL_PROMPT="$prompt:q" -if ( "$prompt:q" =~ *"$newline:q"* ) then - : -else - set prompt = "[$env_name:q] $prompt:q" -endif -endif - -unset env_name - -alias pydoc python -m pydoc - -rehash diff --git a/bin/activate.fish b/bin/activate.fish deleted file mode 100644 index 326f0aa31..000000000 --- a/bin/activate.fish +++ /dev/null @@ -1,76 +0,0 @@ -# This file must be used using `source bin/activate.fish` *within a running fish ( http://fishshell.com ) session*. -# Do not run it directly. - -function deactivate -d 'Exit virtualenv mode and return to the normal environment.' - # reset old environment variables - if test -n "$_OLD_VIRTUAL_PATH" - set -gx PATH $_OLD_VIRTUAL_PATH - set -e _OLD_VIRTUAL_PATH - end - - if test -n "$_OLD_VIRTUAL_PYTHONHOME" - set -gx PYTHONHOME $_OLD_VIRTUAL_PYTHONHOME - set -e _OLD_VIRTUAL_PYTHONHOME - end - - if test -n "$_OLD_FISH_PROMPT_OVERRIDE" - # Set an empty local `$fish_function_path` to allow the removal of `fish_prompt` using `functions -e`. - set -l fish_function_path - - # Erase virtualenv's `fish_prompt` and restore the original. - functions -e fish_prompt - functions -c _old_fish_prompt fish_prompt - functions -e _old_fish_prompt - set -e _OLD_FISH_PROMPT_OVERRIDE - end - - set -e VIRTUAL_ENV - - if test "$argv[1]" != 'nondestructive' - # Self-destruct! - functions -e pydoc - functions -e deactivate - end -end - -# Unset irrelevant variables. -deactivate nondestructive - -set -gx VIRTUAL_ENV "/usr/local/CyberCP" - -set -gx _OLD_VIRTUAL_PATH $PATH -set -gx PATH "$VIRTUAL_ENV/bin" $PATH - -# Unset `$PYTHONHOME` if set. -if set -q PYTHONHOME - set -gx _OLD_VIRTUAL_PYTHONHOME $PYTHONHOME - set -e PYTHONHOME -end - -function pydoc - python -m pydoc $argv -end - -if test -z "$VIRTUAL_ENV_DISABLE_PROMPT" - # Copy the current `fish_prompt` function as `_old_fish_prompt`. - functions -c fish_prompt _old_fish_prompt - - function fish_prompt - # Save the current $status, for fish_prompts that display it. - set -l old_status $status - - # Prompt override provided? - # If not, just prepend the environment name. - if test -n "" - printf '%s%s' "" (set_color normal) - else - printf '%s(%s) ' (set_color normal) (basename "$VIRTUAL_ENV") - end - - # Restore the original $status - echo "exit $old_status" | source - _old_fish_prompt - end - - set -gx _OLD_FISH_PROMPT_OVERRIDE "$VIRTUAL_ENV" -end diff --git a/bin/activate.ps1 b/bin/activate.ps1 deleted file mode 100644 index 89dbec6cc..000000000 --- a/bin/activate.ps1 +++ /dev/null @@ -1,150 +0,0 @@ -# This file must be dot sourced from PoSh; you cannot run it -# directly. Do this: . ./activate.ps1 - -# FIXME: clean up unused vars. -$script:THIS_PATH = $myinvocation.mycommand.path -$script:BASE_DIR = split-path (resolve-path "$THIS_PATH/..") -Parent -$script:DIR_NAME = split-path $BASE_DIR -Leaf - -function global:deactivate ( [switch] $NonDestructive ){ - - if ( test-path variable:_OLD_VIRTUAL_PATH ) { - $env:PATH = $variable:_OLD_VIRTUAL_PATH - remove-variable "_OLD_VIRTUAL_PATH" -scope global - } - - if ( test-path function:_old_virtual_prompt ) { - $function:prompt = $function:_old_virtual_prompt - remove-item function:\_old_virtual_prompt - } - - if ($env:VIRTUAL_ENV) { - $old_env = split-path $env:VIRTUAL_ENV -leaf - remove-item env:VIRTUAL_ENV -erroraction silentlycontinue - } - - if ( !$NonDestructive ) { - # Self destruct! - remove-item function:deactivate - } -} - -# unset irrelevant variables -deactivate -nondestructive - -$VIRTUAL_ENV = $BASE_DIR -$env:VIRTUAL_ENV = $VIRTUAL_ENV - -$global:_OLD_VIRTUAL_PATH = $env:PATH -$env:PATH = "$env:VIRTUAL_ENV/bin:" + $env:PATH -if (! $env:VIRTUAL_ENV_DISABLE_PROMPT) { - function global:_old_virtual_prompt { "" } - $function:_old_virtual_prompt = $function:prompt - function global:prompt { - # Add a prefix to the current prompt, but don't discard it. - write-host "($(split-path $env:VIRTUAL_ENV -leaf)) " -nonewline - & $function:_old_virtual_prompt - } -} - -# SIG # Begin signature block -# MIISeAYJKoZIhvcNAQcCoIISaTCCEmUCAQExCzAJBgUrDgMCGgUAMGkGCisGAQQB -# gjcCAQSgWzBZMDQGCisGAQQBgjcCAR4wJgIDAQAABBAfzDtgWUsITrck0sYpfvNR -# AgEAAgEAAgEAAgEAAgEAMCEwCQYFKw4DAhoFAAQUS5reBwSg3zOUwhXf2jPChZzf -# yPmggg6tMIIGcDCCBFigAwIBAgIBJDANBgkqhkiG9w0BAQUFADB9MQswCQYDVQQG -# EwJJTDEWMBQGA1UEChMNU3RhcnRDb20gTHRkLjErMCkGA1UECxMiU2VjdXJlIERp -# Z2l0YWwgQ2VydGlmaWNhdGUgU2lnbmluZzEpMCcGA1UEAxMgU3RhcnRDb20gQ2Vy -# dGlmaWNhdGlvbiBBdXRob3JpdHkwHhcNMDcxMDI0MjIwMTQ2WhcNMTcxMDI0MjIw -# MTQ2WjCBjDELMAkGA1UEBhMCSUwxFjAUBgNVBAoTDVN0YXJ0Q29tIEx0ZC4xKzAp -# BgNVBAsTIlNlY3VyZSBEaWdpdGFsIENlcnRpZmljYXRlIFNpZ25pbmcxODA2BgNV -# BAMTL1N0YXJ0Q29tIENsYXNzIDIgUHJpbWFyeSBJbnRlcm1lZGlhdGUgT2JqZWN0 -# IENBMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAyiOLIjUemqAbPJ1J -# 0D8MlzgWKbr4fYlbRVjvhHDtfhFN6RQxq0PjTQxRgWzwFQNKJCdU5ftKoM5N4YSj -# Id6ZNavcSa6/McVnhDAQm+8H3HWoD030NVOxbjgD/Ih3HaV3/z9159nnvyxQEckR -# ZfpJB2Kfk6aHqW3JnSvRe+XVZSufDVCe/vtxGSEwKCaNrsLc9pboUoYIC3oyzWoU -# TZ65+c0H4paR8c8eK/mC914mBo6N0dQ512/bkSdaeY9YaQpGtW/h/W/FkbQRT3sC -# pttLVlIjnkuY4r9+zvqhToPjxcfDYEf+XD8VGkAqle8Aa8hQ+M1qGdQjAye8OzbV -# uUOw7wIDAQABo4IB6TCCAeUwDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMC -# AQYwHQYDVR0OBBYEFNBOD0CZbLhLGW87KLjg44gHNKq3MB8GA1UdIwQYMBaAFE4L -# 7xqkQFulF2mHMMo0aEPQQa7yMD0GCCsGAQUFBwEBBDEwLzAtBggrBgEFBQcwAoYh -# aHR0cDovL3d3dy5zdGFydHNzbC5jb20vc2ZzY2EuY3J0MFsGA1UdHwRUMFIwJ6Al -# oCOGIWh0dHA6Ly93d3cuc3RhcnRzc2wuY29tL3Nmc2NhLmNybDAnoCWgI4YhaHR0 -# cDovL2NybC5zdGFydHNzbC5jb20vc2ZzY2EuY3JsMIGABgNVHSAEeTB3MHUGCysG -# AQQBgbU3AQIBMGYwLgYIKwYBBQUHAgEWImh0dHA6Ly93d3cuc3RhcnRzc2wuY29t -# L3BvbGljeS5wZGYwNAYIKwYBBQUHAgEWKGh0dHA6Ly93d3cuc3RhcnRzc2wuY29t -# L2ludGVybWVkaWF0ZS5wZGYwEQYJYIZIAYb4QgEBBAQDAgABMFAGCWCGSAGG+EIB -# DQRDFkFTdGFydENvbSBDbGFzcyAyIFByaW1hcnkgSW50ZXJtZWRpYXRlIE9iamVj -# dCBTaWduaW5nIENlcnRpZmljYXRlczANBgkqhkiG9w0BAQUFAAOCAgEAcnMLA3Va -# N4OIE9l4QT5OEtZy5PByBit3oHiqQpgVEQo7DHRsjXD5H/IyTivpMikaaeRxIv95 -# baRd4hoUcMwDj4JIjC3WA9FoNFV31SMljEZa66G8RQECdMSSufgfDYu1XQ+cUKxh -# D3EtLGGcFGjjML7EQv2Iol741rEsycXwIXcryxeiMbU2TPi7X3elbwQMc4JFlJ4B -# y9FhBzuZB1DV2sN2irGVbC3G/1+S2doPDjL1CaElwRa/T0qkq2vvPxUgryAoCppU -# FKViw5yoGYC+z1GaesWWiP1eFKAL0wI7IgSvLzU3y1Vp7vsYaxOVBqZtebFTWRHt -# XjCsFrrQBngt0d33QbQRI5mwgzEp7XJ9xu5d6RVWM4TPRUsd+DDZpBHm9mszvi9g -# VFb2ZG7qRRXCSqys4+u/NLBPbXi/m/lU00cODQTlC/euwjk9HQtRrXQ/zqsBJS6U -# J+eLGw1qOfj+HVBl/ZQpfoLk7IoWlRQvRL1s7oirEaqPZUIWY/grXq9r6jDKAp3L -# ZdKQpPOnnogtqlU4f7/kLjEJhrrc98mrOWmVMK/BuFRAfQ5oDUMnVmCzAzLMjKfG -# cVW/iMew41yfhgKbwpfzm3LBr1Zv+pEBgcgW6onRLSAn3XHM0eNtz+AkxH6rRf6B -# 2mYhLEEGLapH8R1AMAo4BbVFOZR5kXcMCwowggg1MIIHHaADAgECAgIEuDANBgkq -# hkiG9w0BAQUFADCBjDELMAkGA1UEBhMCSUwxFjAUBgNVBAoTDVN0YXJ0Q29tIEx0 -# ZC4xKzApBgNVBAsTIlNlY3VyZSBEaWdpdGFsIENlcnRpZmljYXRlIFNpZ25pbmcx -# ODA2BgNVBAMTL1N0YXJ0Q29tIENsYXNzIDIgUHJpbWFyeSBJbnRlcm1lZGlhdGUg -# T2JqZWN0IENBMB4XDTExMTIwMzE1MzQxOVoXDTEzMTIwMzE0NTgwN1owgYwxIDAe -# BgNVBA0TFzU4MTc5Ni1HaDd4Zkp4a3hRU0lPNEUwMQswCQYDVQQGEwJERTEPMA0G -# A1UECBMGQmVybGluMQ8wDQYDVQQHEwZCZXJsaW4xFjAUBgNVBAMTDUphbm5pcyBM -# ZWlkZWwxITAfBgkqhkiG9w0BCQEWEmphbm5pc0BsZWlkZWwuaW5mbzCCAiIwDQYJ -# KoZIhvcNAQEBBQADggIPADCCAgoCggIBAMcPeABYdN7nPq/AkZ/EkyUBGx/l2Yui -# Lfm8ZdLG0ulMb/kQL3fRY7sUjYPyn9S6PhqqlFnNoGHJvbbReCdUC9SIQYmOEjEA -# raHfb7MZU10NjO4U2DdGucj2zuO5tYxKizizOJF0e4yRQZVxpUGdvkW/+GLjCNK5 -# L7mIv3Z1dagxDKHYZT74HXiS4VFUwHF1k36CwfM2vsetdm46bdgSwV+BCMmZICYT -# IJAS9UQHD7kP4rik3bFWjUx08NtYYFAVOd/HwBnemUmJe4j3IhZHr0k1+eDG8hDH -# KVvPgLJIoEjC4iMFk5GWsg5z2ngk0LLu3JZMtckHsnnmBPHQK8a3opUNd8hdMNJx -# gOwKjQt2JZSGUdIEFCKVDqj0FmdnDMPfwy+FNRtpBMl1sz78dUFhSrnM0D8NXrqa -# 4rG+2FoOXlmm1rb6AFtpjAKksHRpYcPk2DPGWp/1sWB+dUQkS3gOmwFzyqeTuXpT -# 0juqd3iAxOGx1VRFQ1VHLLf3AzV4wljBau26I+tu7iXxesVucSdsdQu293jwc2kN -# xK2JyHCoZH+RyytrwS0qw8t7rMOukU9gwP8mn3X6mgWlVUODMcHTULjSiCEtvyZ/ -# aafcwjUbt4ReEcnmuZtWIha86MTCX7U7e+cnpWG4sIHPnvVTaz9rm8RyBkIxtFCB -# nQ3FnoQgyxeJAgMBAAGjggOdMIIDmTAJBgNVHRMEAjAAMA4GA1UdDwEB/wQEAwIH -# gDAuBgNVHSUBAf8EJDAiBggrBgEFBQcDAwYKKwYBBAGCNwIBFQYKKwYBBAGCNwoD -# DTAdBgNVHQ4EFgQUWyCgrIWo8Ifvvm1/YTQIeMU9nc8wHwYDVR0jBBgwFoAU0E4P -# QJlsuEsZbzsouODjiAc0qrcwggIhBgNVHSAEggIYMIICFDCCAhAGCysGAQQBgbU3 -# AQICMIIB/zAuBggrBgEFBQcCARYiaHR0cDovL3d3dy5zdGFydHNzbC5jb20vcG9s -# aWN5LnBkZjA0BggrBgEFBQcCARYoaHR0cDovL3d3dy5zdGFydHNzbC5jb20vaW50 -# ZXJtZWRpYXRlLnBkZjCB9wYIKwYBBQUHAgIwgeowJxYgU3RhcnRDb20gQ2VydGlm -# aWNhdGlvbiBBdXRob3JpdHkwAwIBARqBvlRoaXMgY2VydGlmaWNhdGUgd2FzIGlz -# c3VlZCBhY2NvcmRpbmcgdG8gdGhlIENsYXNzIDIgVmFsaWRhdGlvbiByZXF1aXJl -# bWVudHMgb2YgdGhlIFN0YXJ0Q29tIENBIHBvbGljeSwgcmVsaWFuY2Ugb25seSBm -# b3IgdGhlIGludGVuZGVkIHB1cnBvc2UgaW4gY29tcGxpYW5jZSBvZiB0aGUgcmVs -# eWluZyBwYXJ0eSBvYmxpZ2F0aW9ucy4wgZwGCCsGAQUFBwICMIGPMCcWIFN0YXJ0 -# Q29tIENlcnRpZmljYXRpb24gQXV0aG9yaXR5MAMCAQIaZExpYWJpbGl0eSBhbmQg -# d2FycmFudGllcyBhcmUgbGltaXRlZCEgU2VlIHNlY3Rpb24gIkxlZ2FsIGFuZCBM -# aW1pdGF0aW9ucyIgb2YgdGhlIFN0YXJ0Q29tIENBIHBvbGljeS4wNgYDVR0fBC8w -# LTAroCmgJ4YlaHR0cDovL2NybC5zdGFydHNzbC5jb20vY3J0YzItY3JsLmNybDCB -# iQYIKwYBBQUHAQEEfTB7MDcGCCsGAQUFBzABhitodHRwOi8vb2NzcC5zdGFydHNz -# bC5jb20vc3ViL2NsYXNzMi9jb2RlL2NhMEAGCCsGAQUFBzAChjRodHRwOi8vYWlh -# LnN0YXJ0c3NsLmNvbS9jZXJ0cy9zdWIuY2xhc3MyLmNvZGUuY2EuY3J0MCMGA1Ud -# EgQcMBqGGGh0dHA6Ly93d3cuc3RhcnRzc2wuY29tLzANBgkqhkiG9w0BAQUFAAOC -# AQEAhrzEV6zwoEtKjnFRhCsjwiPykVpo5Eiye77Ve801rQDiRKgSCCiW6g3HqedL -# OtaSs65Sj2pm3Viea4KR0TECLcbCTgsdaHqw2x1yXwWBQWZEaV6EB05lIwfr94P1 -# SFpV43zkuc+bbmA3+CRK45LOcCNH5Tqq7VGTCAK5iM7tvHwFlbQRl+I6VEL2mjpF -# NsuRjDOVrv/9qw/a22YJ9R7Y1D0vUSs3IqZx2KMUaYDP7H2mSRxJO2nADQZBtriF -# gTyfD3lYV12MlIi5CQwe3QC6DrrfSMP33i5Wa/OFJiQ27WPxmScYVhiqozpImFT4 -# PU9goiBv9RKXdgTmZE1PN0NQ5jGCAzUwggMxAgEBMIGTMIGMMQswCQYDVQQGEwJJ -# TDEWMBQGA1UEChMNU3RhcnRDb20gTHRkLjErMCkGA1UECxMiU2VjdXJlIERpZ2l0 -# YWwgQ2VydGlmaWNhdGUgU2lnbmluZzE4MDYGA1UEAxMvU3RhcnRDb20gQ2xhc3Mg -# MiBQcmltYXJ5IEludGVybWVkaWF0ZSBPYmplY3QgQ0ECAgS4MAkGBSsOAwIaBQCg -# eDAYBgorBgEEAYI3AgEMMQowCKACgAChAoAAMBkGCSqGSIb3DQEJAzEMBgorBgEE -# AYI3AgEEMBwGCisGAQQBgjcCAQsxDjAMBgorBgEEAYI3AgEVMCMGCSqGSIb3DQEJ -# BDEWBBRVGw0FDSiaIi38dWteRUAg/9Pr6DANBgkqhkiG9w0BAQEFAASCAgCInvOZ -# FdaNFzbf6trmFDZKMojyx3UjKMCqNjHVBbuKY0qXwFC/ElYDV1ShJ2CBZbdurydO -# OQ6cIQ0KREOCwmX/xB49IlLHHUxNhEkVv7HGU3EKAFf9IBt9Yr7jikiR9cjIsfHK -# 4cjkoKJL7g28yEpLLkHt1eo37f1Ga9lDWEa5Zq3U5yX+IwXhrUBm1h8Xr033FhTR -# VEpuSz6LHtbrL/zgJnCzJ2ahjtJoYevdcWiNXffosJHFaSfYDDbiNsPRDH/1avmb -# 5j/7BhP8BcBaR6Fp8tFbNGIcWHHGcjqLMnTc4w13b7b4pDhypqElBa4+lCmwdvv9 -# GydYtRgPz8GHeoBoKj30YBlMzRIfFYaIFGIC4Ai3UEXkuH9TxYohVbGm/W0Kl4Lb -# RJ1FwiVcLcTOJdgNId2vQvKc+jtNrjcg5SP9h2v/C4aTx8tyc6tE3TOPh2f9b8DL -# S+SbVArJpuJqrPTxDDoO1QNjTgLcdVYeZDE+r/NjaGZ6cMSd8db3EaG3ijD/0bud -# SItbm/OlNVbQOFRR76D+ZNgPcU5iNZ3bmvQQIg6aSB9MHUpIE/SeCkNl9YeVk1/1 -# GFULgNMRmIYP4KLvu9ylh5Gu3hvD5VNhH6+FlXANwFy07uXks5uF8mfZVxVCnodG -# xkNCx+6PsrA5Z7WP4pXcmYnMn97npP/Q9EHJWw== -# SIG # End signature block diff --git a/bin/activate_this.py b/bin/activate_this.py deleted file mode 100644 index 444d3fd35..000000000 --- a/bin/activate_this.py +++ /dev/null @@ -1,36 +0,0 @@ -"""By using execfile(this_file, dict(__file__=this_file)) you will -activate this virtualenv environment. - -This can be used when you must use an existing Python interpreter, not -the virtualenv bin/python -""" - -try: - __file__ -except NameError: - raise AssertionError( - "You must run this like execfile('path/to/activate_this.py', dict(__file__='path/to/activate_this.py'))" - ) -import os -import site -import sys - -old_os_path = os.environ.get("PATH", "") -os.environ["PATH"] = os.path.dirname(os.path.abspath(__file__)) + os.pathsep + old_os_path -base = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) -if sys.platform == "win32": - site_packages = os.path.join(base, "Lib", "site-packages") -else: - site_packages = os.path.join(base, "lib", "python%s" % sys.version[:3], "site-packages") -prev_sys_path = list(sys.path) - -site.addsitedir(site_packages) -sys.real_prefix = sys.prefix -sys.prefix = base -# Move the added items to the front of the path: -new_sys_path = [] -for item in list(sys.path): - if item not in prev_sys_path: - new_sys_path.append(item) - sys.path.remove(item) -sys.path[:0] = new_sys_path diff --git a/bin/certbot b/bin/certbot deleted file mode 100755 index edc76445f..000000000 --- a/bin/certbot +++ /dev/null @@ -1,11 +0,0 @@ -#!/usr/local/CyberCP/bin/python2 - -# -*- coding: utf-8 -*- -import re -import sys - -from certbot.main import main - -if __name__ == '__main__': - sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0]) - sys.exit(main()) diff --git a/bin/chardetect b/bin/chardetect deleted file mode 100755 index 2369c4ac5..000000000 --- a/bin/chardetect +++ /dev/null @@ -1,11 +0,0 @@ -#!/usr/local/CyberCP/bin/python2 - -# -*- coding: utf-8 -*- -import re -import sys - -from chardet.cli.chardetect import main - -if __name__ == '__main__': - sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0]) - sys.exit(main()) diff --git a/bin/django-admin b/bin/django-admin deleted file mode 100755 index ff74a0dce..000000000 --- a/bin/django-admin +++ /dev/null @@ -1,11 +0,0 @@ -#!/usr/local/CyberCP/bin/python2 - -# -*- coding: utf-8 -*- -import re -import sys - -from django.core.management import execute_from_command_line - -if __name__ == '__main__': - sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0]) - sys.exit(execute_from_command_line()) diff --git a/bin/django-admin.py b/bin/django-admin.py deleted file mode 100755 index f9b4fc90d..000000000 --- a/bin/django-admin.py +++ /dev/null @@ -1,5 +0,0 @@ -#!/usr/local/CyberCP/bin/python2 -from django.core import management - -if __name__ == "__main__": - management.execute_from_command_line() diff --git a/bin/easy_install b/bin/easy_install deleted file mode 100755 index a9a19fade..000000000 --- a/bin/easy_install +++ /dev/null @@ -1,11 +0,0 @@ -#!/usr/local/CyberCP/bin/python2 - -# -*- coding: utf-8 -*- -import re -import sys - -from setuptools.command.easy_install import main - -if __name__ == '__main__': - sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0]) - sys.exit(main()) diff --git a/bin/easy_install-2.7 b/bin/easy_install-2.7 deleted file mode 100755 index a9a19fade..000000000 --- a/bin/easy_install-2.7 +++ /dev/null @@ -1,11 +0,0 @@ -#!/usr/local/CyberCP/bin/python2 - -# -*- coding: utf-8 -*- -import re -import sys - -from setuptools.command.easy_install import main - -if __name__ == '__main__': - sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0]) - sys.exit(main()) diff --git a/bin/futurize b/bin/futurize deleted file mode 100755 index 9ea6944cd..000000000 --- a/bin/futurize +++ /dev/null @@ -1,11 +0,0 @@ -#!/usr/local/CyberCP/bin/python2 - -# -*- coding: utf-8 -*- -import re -import sys - -from libfuturize.main import main - -if __name__ == '__main__': - sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0]) - sys.exit(main()) diff --git a/bin/gunicorn b/bin/gunicorn deleted file mode 100755 index 807a18079..000000000 --- a/bin/gunicorn +++ /dev/null @@ -1,11 +0,0 @@ -#!/usr/local/CyberCP/bin/python2 - -# -*- coding: utf-8 -*- -import re -import sys - -from gunicorn.app.wsgiapp import run - -if __name__ == '__main__': - sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0]) - sys.exit(run()) diff --git a/bin/gunicorn_paster b/bin/gunicorn_paster deleted file mode 100755 index 6849ab396..000000000 --- a/bin/gunicorn_paster +++ /dev/null @@ -1,11 +0,0 @@ -#!/usr/local/CyberCP/bin/python2 - -# -*- coding: utf-8 -*- -import re -import sys - -from gunicorn.app.pasterapp import run - -if __name__ == '__main__': - sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0]) - sys.exit(run()) diff --git a/bin/jsonpointer b/bin/jsonpointer deleted file mode 100755 index 54cc7b622..000000000 --- a/bin/jsonpointer +++ /dev/null @@ -1,46 +0,0 @@ -#!/home/stefan/work/python-json-patch/venv/bin/python -# -*- coding: utf-8 -*- - -from __future__ import print_function - -import sys -import os.path -import json -import jsonpointer -import argparse - - -parser = argparse.ArgumentParser( - description='Resolve a JSON pointer on JSON files') -parser.add_argument('POINTER', type=argparse.FileType('r'), - help='File containing a JSON pointer expression') -parser.add_argument('FILE', type=argparse.FileType('r'), nargs='+', - help='Files for which the pointer should be resolved') -parser.add_argument('--indent', type=int, default=None, - help='Indent output by n spaces') -parser.add_argument('-v', '--version', action='version', - version='%(prog)s ' + jsonpointer.__version__) - - -def main(): - try: - resolve_files() - except KeyboardInterrupt: - sys.exit(1) - - -def resolve_files(): - """ Resolve a JSON pointer on JSON files """ - args = parser.parse_args() - ptr = json.load(args.POINTER) - for f in args.FILE: - doc = json.load(f) - try: - result = jsonpointer.resolve_pointer(doc, ptr) - print(json.dumps(result, indent=args.indent)) - except jsonpointer.JsonPointerException as e: - print('Could not resolve pointer: %s' % str(e), file=sys.stderr) - - -if __name__ == "__main__": - main() diff --git a/bin/jws b/bin/jws deleted file mode 100755 index a0cd269ad..000000000 --- a/bin/jws +++ /dev/null @@ -1,11 +0,0 @@ -#!/usr/local/CyberCP/bin/python2 - -# -*- coding: utf-8 -*- -import re -import sys - -from josepy.jws import CLI - -if __name__ == '__main__': - sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0]) - sys.exit(CLI.run()) diff --git a/bin/miniterm.py b/bin/miniterm.py deleted file mode 100755 index fba0565b4..000000000 --- a/bin/miniterm.py +++ /dev/null @@ -1,645 +0,0 @@ -#!/usr/local/CyberCP/bin/python2 - -# Very simple serial terminal -# (C)2002-2011 Chris Liechti - -# Input characters are sent directly (only LF -> CR/LF/CRLF translation is -# done), received characters are displayed as is (or escaped trough pythons -# repr, useful for debug purposes) - - -import sys, os, serial, threading - -EXITCHARCTER = '\x1d' # GS/CTRL+] -MENUCHARACTER = '\x14' # Menu: CTRL+T - - -def key_description(character): - """generate a readable description for a key""" - ascii_code = ord(character) - if ascii_code < 32: - return 'Ctrl+%c' % (ord('@') + ascii_code) - else: - return repr(character) - - -# help text, starts with blank line! it's a function so that the current values -# for the shortcut keys is used and not the value at program start -def get_help_text(): - return """ ---- pySerial (%(version)s) - miniterm - help ---- ---- %(exit)-8s Exit program ---- %(menu)-8s Menu escape key, followed by: ---- Menu keys: ---- %(itself)-7s Send the menu character itself to remote ---- %(exchar)-7s Send the exit character itself to remote ---- %(info)-7s Show info ---- %(upload)-7s Upload file (prompt will be shown) ---- Toggles: ---- %(rts)-7s RTS %(echo)-7s local echo ---- %(dtr)-7s DTR %(break)-7s BREAK ---- %(lfm)-7s line feed %(repr)-7s Cycle repr mode ---- ---- Port settings (%(menu)s followed by the following): ---- p change port ---- 7 8 set data bits ---- n e o s m change parity (None, Even, Odd, Space, Mark) ---- 1 2 3 set stop bits (1, 2, 1.5) ---- b change baud rate ---- x X disable/enable software flow control ---- r R disable/enable hardware flow control -""" % { - 'version': getattr(serial, 'VERSION', 'unknown version'), - 'exit': key_description(EXITCHARCTER), - 'menu': key_description(MENUCHARACTER), - 'rts': key_description('\x12'), - 'repr': key_description('\x01'), - 'dtr': key_description('\x04'), - 'lfm': key_description('\x0c'), - 'break': key_description('\x02'), - 'echo': key_description('\x05'), - 'info': key_description('\x09'), - 'upload': key_description('\x15'), - 'itself': key_description(MENUCHARACTER), - 'exchar': key_description(EXITCHARCTER), -} - -if sys.version_info >= (3, 0): - def character(b): - return b.decode('latin1') -else: - def character(b): - return b - -# first choose a platform dependant way to read single characters from the console -global console - -if os.name == 'nt': - import msvcrt - class Console(object): - def __init__(self): - pass - - def setup(self): - pass # Do nothing for 'nt' - - def cleanup(self): - pass # Do nothing for 'nt' - - def getkey(self): - while True: - z = msvcrt.getch() - if z == '\0' or z == '\xe0': # functions keys, ignore - msvcrt.getch() - else: - if z == '\r': - return '\n' - return z - - console = Console() - -elif os.name == 'posix': - import termios, sys, os - class Console(object): - def __init__(self): - self.fd = sys.stdin.fileno() - - def setup(self): - self.old = termios.tcgetattr(self.fd) - new = termios.tcgetattr(self.fd) - new[3] = new[3] & ~termios.ICANON & ~termios.ECHO & ~termios.ISIG - new[6][termios.VMIN] = 1 - new[6][termios.VTIME] = 0 - termios.tcsetattr(self.fd, termios.TCSANOW, new) - - def getkey(self): - c = os.read(self.fd, 1) - return c - - def cleanup(self): - termios.tcsetattr(self.fd, termios.TCSAFLUSH, self.old) - - console = Console() - - def cleanup_console(): - console.cleanup() - - console.setup() - sys.exitfunc = cleanup_console # terminal modes have to be restored on exit... - -else: - raise NotImplementedError("Sorry no implementation for your platform (%s) available." % sys.platform) - - -CONVERT_CRLF = 2 -CONVERT_CR = 1 -CONVERT_LF = 0 -NEWLINE_CONVERISON_MAP = ('\n', '\r', '\r\n') -LF_MODES = ('LF', 'CR', 'CR/LF') - -REPR_MODES = ('raw', 'some control', 'all control', 'hex') - -class Miniterm(object): - def __init__(self, port, baudrate, parity, rtscts, xonxoff, echo=False, convert_outgoing=CONVERT_CRLF, repr_mode=0): - try: - self.serial = serial.serial_for_url(port, baudrate, parity=parity, rtscts=rtscts, xonxoff=xonxoff, timeout=1) - except AttributeError: - # happens when the installed pyserial is older than 2.5. use the - # Serial class directly then. - self.serial = serial.Serial(port, baudrate, parity=parity, rtscts=rtscts, xonxoff=xonxoff, timeout=1) - self.echo = echo - self.repr_mode = repr_mode - self.convert_outgoing = convert_outgoing - self.newline = NEWLINE_CONVERISON_MAP[self.convert_outgoing] - self.dtr_state = True - self.rts_state = True - self.break_state = False - - def _start_reader(self): - """Start reader thread""" - self._reader_alive = True - # start serial->console thread - self.receiver_thread = threading.Thread(target=self.reader) - self.receiver_thread.setDaemon(True) - self.receiver_thread.start() - - def _stop_reader(self): - """Stop reader thread only, wait for clean exit of thread""" - self._reader_alive = False - self.receiver_thread.join() - - - def start(self): - self.alive = True - self._start_reader() - # enter console->serial loop - self.transmitter_thread = threading.Thread(target=self.writer) - self.transmitter_thread.setDaemon(True) - self.transmitter_thread.start() - - def stop(self): - self.alive = False - - def join(self, transmit_only=False): - self.transmitter_thread.join() - if not transmit_only: - self.receiver_thread.join() - - def dump_port_settings(self): - sys.stderr.write("\n--- Settings: %s %s,%s,%s,%s\n" % ( - self.serial.portstr, - self.serial.baudrate, - self.serial.bytesize, - self.serial.parity, - self.serial.stopbits)) - sys.stderr.write('--- RTS: %-8s DTR: %-8s BREAK: %-8s\n' % ( - (self.rts_state and 'active' or 'inactive'), - (self.dtr_state and 'active' or 'inactive'), - (self.break_state and 'active' or 'inactive'))) - try: - sys.stderr.write('--- CTS: %-8s DSR: %-8s RI: %-8s CD: %-8s\n' % ( - (self.serial.getCTS() and 'active' or 'inactive'), - (self.serial.getDSR() and 'active' or 'inactive'), - (self.serial.getRI() and 'active' or 'inactive'), - (self.serial.getCD() and 'active' or 'inactive'))) - except serial.SerialException: - # on RFC 2217 ports it can happen to no modem state notification was - # yet received. ignore this error. - pass - sys.stderr.write('--- software flow control: %s\n' % (self.serial.xonxoff and 'active' or 'inactive')) - sys.stderr.write('--- hardware flow control: %s\n' % (self.serial.rtscts and 'active' or 'inactive')) - sys.stderr.write('--- data escaping: %s linefeed: %s\n' % ( - REPR_MODES[self.repr_mode], - LF_MODES[self.convert_outgoing])) - - def reader(self): - """loop and copy serial->console""" - try: - while self.alive and self._reader_alive: - data = character(self.serial.read(1)) - - if self.repr_mode == 0: - # direct output, just have to care about newline setting - if data == '\r' and self.convert_outgoing == CONVERT_CR: - sys.stdout.write('\n') - else: - sys.stdout.write(data) - elif self.repr_mode == 1: - # escape non-printable, let pass newlines - if self.convert_outgoing == CONVERT_CRLF and data in '\r\n': - if data == '\n': - sys.stdout.write('\n') - elif data == '\r': - pass - elif data == '\n' and self.convert_outgoing == CONVERT_LF: - sys.stdout.write('\n') - elif data == '\r' and self.convert_outgoing == CONVERT_CR: - sys.stdout.write('\n') - else: - sys.stdout.write(repr(data)[1:-1]) - elif self.repr_mode == 2: - # escape all non-printable, including newline - sys.stdout.write(repr(data)[1:-1]) - elif self.repr_mode == 3: - # escape everything (hexdump) - for c in data: - sys.stdout.write("%s " % c.encode('hex')) - sys.stdout.flush() - except serial.SerialException, e: - self.alive = False - # would be nice if the console reader could be interruptted at this - # point... - raise - - - def writer(self): - """\ - Loop and copy console->serial until EXITCHARCTER character is - found. When MENUCHARACTER is found, interpret the next key - locally. - """ - menu_active = False - try: - while self.alive: - try: - b = console.getkey() - except KeyboardInterrupt: - b = serial.to_bytes([3]) - c = character(b) - if menu_active: - if c == MENUCHARACTER or c == EXITCHARCTER: # Menu character again/exit char -> send itself - self.serial.write(b) # send character - if self.echo: - sys.stdout.write(c) - elif c == '\x15': # CTRL+U -> upload file - sys.stderr.write('\n--- File to upload: ') - sys.stderr.flush() - console.cleanup() - filename = sys.stdin.readline().rstrip('\r\n') - if filename: - try: - file = open(filename, 'r') - sys.stderr.write('--- Sending file %s ---\n' % filename) - while True: - line = file.readline().rstrip('\r\n') - if not line: - break - self.serial.write(line) - self.serial.write('\r\n') - # Wait for output buffer to drain. - self.serial.flush() - sys.stderr.write('.') # Progress indicator. - sys.stderr.write('\n--- File %s sent ---\n' % filename) - except IOError, e: - sys.stderr.write('--- ERROR opening file %s: %s ---\n' % (filename, e)) - console.setup() - elif c in '\x08hH?': # CTRL+H, h, H, ? -> Show help - sys.stderr.write(get_help_text()) - elif c == '\x12': # CTRL+R -> Toggle RTS - self.rts_state = not self.rts_state - self.serial.setRTS(self.rts_state) - sys.stderr.write('--- RTS %s ---\n' % (self.rts_state and 'active' or 'inactive')) - elif c == '\x04': # CTRL+D -> Toggle DTR - self.dtr_state = not self.dtr_state - self.serial.setDTR(self.dtr_state) - sys.stderr.write('--- DTR %s ---\n' % (self.dtr_state and 'active' or 'inactive')) - elif c == '\x02': # CTRL+B -> toggle BREAK condition - self.break_state = not self.break_state - self.serial.setBreak(self.break_state) - sys.stderr.write('--- BREAK %s ---\n' % (self.break_state and 'active' or 'inactive')) - elif c == '\x05': # CTRL+E -> toggle local echo - self.echo = not self.echo - sys.stderr.write('--- local echo %s ---\n' % (self.echo and 'active' or 'inactive')) - elif c == '\x09': # CTRL+I -> info - self.dump_port_settings() - elif c == '\x01': # CTRL+A -> cycle escape mode - self.repr_mode += 1 - if self.repr_mode > 3: - self.repr_mode = 0 - sys.stderr.write('--- escape data: %s ---\n' % ( - REPR_MODES[self.repr_mode], - )) - elif c == '\x0c': # CTRL+L -> cycle linefeed mode - self.convert_outgoing += 1 - if self.convert_outgoing > 2: - self.convert_outgoing = 0 - self.newline = NEWLINE_CONVERISON_MAP[self.convert_outgoing] - sys.stderr.write('--- line feed %s ---\n' % ( - LF_MODES[self.convert_outgoing], - )) - elif c in 'pP': # P -> change port - sys.stderr.write('\n--- Enter port name: ') - sys.stderr.flush() - console.cleanup() - try: - port = sys.stdin.readline().strip() - except KeyboardInterrupt: - port = None - console.setup() - if port and port != self.serial.port: - # reader thread needs to be shut down - self._stop_reader() - # save settings - settings = self.serial.getSettingsDict() - try: - try: - new_serial = serial.serial_for_url(port, do_not_open=True) - except AttributeError: - # happens when the installed pyserial is older than 2.5. use the - # Serial class directly then. - new_serial = serial.Serial() - new_serial.port = port - # restore settings and open - new_serial.applySettingsDict(settings) - new_serial.open() - new_serial.setRTS(self.rts_state) - new_serial.setDTR(self.dtr_state) - new_serial.setBreak(self.break_state) - except Exception, e: - sys.stderr.write('--- ERROR opening new port: %s ---\n' % (e,)) - new_serial.close() - else: - self.serial.close() - self.serial = new_serial - sys.stderr.write('--- Port changed to: %s ---\n' % (self.serial.port,)) - # and restart the reader thread - self._start_reader() - elif c in 'bB': # B -> change baudrate - sys.stderr.write('\n--- Baudrate: ') - sys.stderr.flush() - console.cleanup() - backup = self.serial.baudrate - try: - self.serial.baudrate = int(sys.stdin.readline().strip()) - except ValueError, e: - sys.stderr.write('--- ERROR setting baudrate: %s ---\n' % (e,)) - self.serial.baudrate = backup - else: - self.dump_port_settings() - console.setup() - elif c == '8': # 8 -> change to 8 bits - self.serial.bytesize = serial.EIGHTBITS - self.dump_port_settings() - elif c == '7': # 7 -> change to 8 bits - self.serial.bytesize = serial.SEVENBITS - self.dump_port_settings() - elif c in 'eE': # E -> change to even parity - self.serial.parity = serial.PARITY_EVEN - self.dump_port_settings() - elif c in 'oO': # O -> change to odd parity - self.serial.parity = serial.PARITY_ODD - self.dump_port_settings() - elif c in 'mM': # M -> change to mark parity - self.serial.parity = serial.PARITY_MARK - self.dump_port_settings() - elif c in 'sS': # S -> change to space parity - self.serial.parity = serial.PARITY_SPACE - self.dump_port_settings() - elif c in 'nN': # N -> change to no parity - self.serial.parity = serial.PARITY_NONE - self.dump_port_settings() - elif c == '1': # 1 -> change to 1 stop bits - self.serial.stopbits = serial.STOPBITS_ONE - self.dump_port_settings() - elif c == '2': # 2 -> change to 2 stop bits - self.serial.stopbits = serial.STOPBITS_TWO - self.dump_port_settings() - elif c == '3': # 3 -> change to 1.5 stop bits - self.serial.stopbits = serial.STOPBITS_ONE_POINT_FIVE - self.dump_port_settings() - elif c in 'xX': # X -> change software flow control - self.serial.xonxoff = (c == 'X') - self.dump_port_settings() - elif c in 'rR': # R -> change hardware flow control - self.serial.rtscts = (c == 'R') - self.dump_port_settings() - else: - sys.stderr.write('--- unknown menu character %s --\n' % key_description(c)) - menu_active = False - elif c == MENUCHARACTER: # next char will be for menu - menu_active = True - elif c == EXITCHARCTER: - self.stop() - break # exit app - elif c == '\n': - self.serial.write(self.newline) # send newline character(s) - if self.echo: - sys.stdout.write(c) # local echo is a real newline in any case - sys.stdout.flush() - else: - self.serial.write(b) # send byte - if self.echo: - sys.stdout.write(c) - sys.stdout.flush() - except: - self.alive = False - raise - -def main(): - import optparse - - parser = optparse.OptionParser( - usage = "%prog [options] [port [baudrate]]", - description = "Miniterm - A simple terminal program for the serial port." - ) - - parser.add_option("-p", "--port", - dest = "port", - help = "port, a number or a device name. (deprecated option, use parameter instead)", - default = None - ) - - parser.add_option("-b", "--baud", - dest = "baudrate", - action = "store", - type = 'int', - help = "set baud rate, default %default", - default = 9600 - ) - - parser.add_option("--parity", - dest = "parity", - action = "store", - help = "set parity, one of [N, E, O, S, M], default=N", - default = 'N' - ) - - parser.add_option("-e", "--echo", - dest = "echo", - action = "store_true", - help = "enable local echo (default off)", - default = False - ) - - parser.add_option("--rtscts", - dest = "rtscts", - action = "store_true", - help = "enable RTS/CTS flow control (default off)", - default = False - ) - - parser.add_option("--xonxoff", - dest = "xonxoff", - action = "store_true", - help = "enable software flow control (default off)", - default = False - ) - - parser.add_option("--cr", - dest = "cr", - action = "store_true", - help = "do not send CR+LF, send CR only", - default = False - ) - - parser.add_option("--lf", - dest = "lf", - action = "store_true", - help = "do not send CR+LF, send LF only", - default = False - ) - - parser.add_option("-D", "--debug", - dest = "repr_mode", - action = "count", - help = """debug received data (escape non-printable chars) ---debug can be given multiple times: -0: just print what is received -1: escape non-printable characters, do newlines as unusual -2: escape non-printable characters, newlines too -3: hex dump everything""", - default = 0 - ) - - parser.add_option("--rts", - dest = "rts_state", - action = "store", - type = 'int', - help = "set initial RTS line state (possible values: 0, 1)", - default = None - ) - - parser.add_option("--dtr", - dest = "dtr_state", - action = "store", - type = 'int', - help = "set initial DTR line state (possible values: 0, 1)", - default = None - ) - - parser.add_option("-q", "--quiet", - dest = "quiet", - action = "store_true", - help = "suppress non error messages", - default = False - ) - - parser.add_option("--exit-char", - dest = "exit_char", - action = "store", - type = 'int', - help = "ASCII code of special character that is used to exit the application", - default = 0x1d - ) - - parser.add_option("--menu-char", - dest = "menu_char", - action = "store", - type = 'int', - help = "ASCII code of special character that is used to control miniterm (menu)", - default = 0x14 - ) - - (options, args) = parser.parse_args() - - options.parity = options.parity.upper() - if options.parity not in 'NEOSM': - parser.error("invalid parity") - - if options.cr and options.lf: - parser.error("only one of --cr or --lf can be specified") - - if options.menu_char == options.exit_char: - parser.error('--exit-char can not be the same as --menu-char') - - global EXITCHARCTER, MENUCHARACTER - EXITCHARCTER = chr(options.exit_char) - MENUCHARACTER = chr(options.menu_char) - - port = options.port - baudrate = options.baudrate - if args: - if options.port is not None: - parser.error("no arguments are allowed, options only when --port is given") - port = args.pop(0) - if args: - try: - baudrate = int(args[0]) - except ValueError: - parser.error("baud rate must be a number, not %r" % args[0]) - args.pop(0) - if args: - parser.error("too many arguments") - else: - if port is None: port = 0 - - convert_outgoing = CONVERT_CRLF - if options.cr: - convert_outgoing = CONVERT_CR - elif options.lf: - convert_outgoing = CONVERT_LF - - try: - miniterm = Miniterm( - port, - baudrate, - options.parity, - rtscts=options.rtscts, - xonxoff=options.xonxoff, - echo=options.echo, - convert_outgoing=convert_outgoing, - repr_mode=options.repr_mode, - ) - except serial.SerialException, e: - sys.stderr.write("could not open port %r: %s\n" % (port, e)) - sys.exit(1) - - if not options.quiet: - sys.stderr.write('--- Miniterm on %s: %d,%s,%s,%s ---\n' % ( - miniterm.serial.portstr, - miniterm.serial.baudrate, - miniterm.serial.bytesize, - miniterm.serial.parity, - miniterm.serial.stopbits, - )) - sys.stderr.write('--- Quit: %s | Menu: %s | Help: %s followed by %s ---\n' % ( - key_description(EXITCHARCTER), - key_description(MENUCHARACTER), - key_description(MENUCHARACTER), - key_description('\x08'), - )) - - if options.dtr_state is not None: - if not options.quiet: - sys.stderr.write('--- forcing DTR %s\n' % (options.dtr_state and 'active' or 'inactive')) - miniterm.serial.setDTR(options.dtr_state) - miniterm.dtr_state = options.dtr_state - if options.rts_state is not None: - if not options.quiet: - sys.stderr.write('--- forcing RTS %s\n' % (options.rts_state and 'active' or 'inactive')) - miniterm.serial.setRTS(options.rts_state) - miniterm.rts_state = options.rts_state - - miniterm.start() - try: - miniterm.join(True) - except KeyboardInterrupt: - pass - if not options.quiet: - sys.stderr.write("\n--- exit ---\n") - miniterm.join() - - -if __name__ == '__main__': - main() diff --git a/bin/pasteurize b/bin/pasteurize deleted file mode 100755 index 27b4b0932..000000000 --- a/bin/pasteurize +++ /dev/null @@ -1,11 +0,0 @@ -#!/usr/local/CyberCP/bin/python2 - -# -*- coding: utf-8 -*- -import re -import sys - -from libpasteurize.main import main - -if __name__ == '__main__': - sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0]) - sys.exit(main()) diff --git a/bin/pbr b/bin/pbr deleted file mode 100755 index 0c58f1e9c..000000000 --- a/bin/pbr +++ /dev/null @@ -1,11 +0,0 @@ -#!/usr/local/CyberCP/bin/python2 - -# -*- coding: utf-8 -*- -import re -import sys - -from pbr.cmd.main import main - -if __name__ == '__main__': - sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0]) - sys.exit(main()) diff --git a/bin/pip b/bin/pip deleted file mode 100755 index 930b1e5a2..000000000 --- a/bin/pip +++ /dev/null @@ -1,11 +0,0 @@ -#!/usr/local/CyberCP/bin/python2 - -# -*- coding: utf-8 -*- -import re -import sys - -from pip._internal import main - -if __name__ == '__main__': - sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0]) - sys.exit(main()) diff --git a/bin/pip2 b/bin/pip2 deleted file mode 100755 index 930b1e5a2..000000000 --- a/bin/pip2 +++ /dev/null @@ -1,11 +0,0 @@ -#!/usr/local/CyberCP/bin/python2 - -# -*- coding: utf-8 -*- -import re -import sys - -from pip._internal import main - -if __name__ == '__main__': - sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0]) - sys.exit(main()) diff --git a/bin/pip2.7 b/bin/pip2.7 deleted file mode 100755 index 930b1e5a2..000000000 --- a/bin/pip2.7 +++ /dev/null @@ -1,11 +0,0 @@ -#!/usr/local/CyberCP/bin/python2 - -# -*- coding: utf-8 -*- -import re -import sys - -from pip._internal import main - -if __name__ == '__main__': - sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0]) - sys.exit(main()) diff --git a/bin/pybabel b/bin/pybabel deleted file mode 100755 index 516f5eaae..000000000 --- a/bin/pybabel +++ /dev/null @@ -1,11 +0,0 @@ -#!/usr/local/CyberCP/bin/python2 - -# -*- coding: utf-8 -*- -import re -import sys - -from babel.messages.frontend import main - -if __name__ == '__main__': - sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0]) - sys.exit(main()) diff --git a/bin/python b/bin/python deleted file mode 120000 index 551ab2685..000000000 --- a/bin/python +++ /dev/null @@ -1 +0,0 @@ -python2 \ No newline at end of file diff --git a/bin/python-config b/bin/python-config deleted file mode 100755 index 4a59544fe..000000000 --- a/bin/python-config +++ /dev/null @@ -1,78 +0,0 @@ -#!/usr/local/CyberCP/bin/python - -import sys -import getopt -import sysconfig - -valid_opts = ['prefix', 'exec-prefix', 'includes', 'libs', 'cflags', - 'ldflags', 'help'] - -if sys.version_info >= (3, 2): - valid_opts.insert(-1, 'extension-suffix') - valid_opts.append('abiflags') -if sys.version_info >= (3, 3): - valid_opts.append('configdir') - - -def exit_with_usage(code=1): - sys.stderr.write("Usage: {0} [{1}]\n".format( - sys.argv[0], '|'.join('--'+opt for opt in valid_opts))) - sys.exit(code) - -try: - opts, args = getopt.getopt(sys.argv[1:], '', valid_opts) -except getopt.error: - exit_with_usage() - -if not opts: - exit_with_usage() - -pyver = sysconfig.get_config_var('VERSION') -getvar = sysconfig.get_config_var - -opt_flags = [flag for (flag, val) in opts] - -if '--help' in opt_flags: - exit_with_usage(code=0) - -for opt in opt_flags: - if opt == '--prefix': - print(sysconfig.get_config_var('prefix')) - - elif opt == '--exec-prefix': - print(sysconfig.get_config_var('exec_prefix')) - - elif opt in ('--includes', '--cflags'): - flags = ['-I' + sysconfig.get_path('include'), - '-I' + sysconfig.get_path('platinclude')] - if opt == '--cflags': - flags.extend(getvar('CFLAGS').split()) - print(' '.join(flags)) - - elif opt in ('--libs', '--ldflags'): - abiflags = getattr(sys, 'abiflags', '') - libs = ['-lpython' + pyver + abiflags] - libs += getvar('LIBS').split() - libs += getvar('SYSLIBS').split() - # add the prefix/lib/pythonX.Y/config dir, but only if there is no - # shared library in prefix/lib/. - if opt == '--ldflags': - if not getvar('Py_ENABLE_SHARED'): - libs.insert(0, '-L' + getvar('LIBPL')) - if not getvar('PYTHONFRAMEWORK'): - libs.extend(getvar('LINKFORSHARED').split()) - print(' '.join(libs)) - - elif opt == '--extension-suffix': - ext_suffix = sysconfig.get_config_var('EXT_SUFFIX') - if ext_suffix is None: - ext_suffix = sysconfig.get_config_var('SO') - print(ext_suffix) - - elif opt == '--abiflags': - if not getattr(sys, 'abiflags', None): - exit_with_usage() - print(sys.abiflags) - - elif opt == '--configdir': - print(sysconfig.get_config_var('LIBPL')) diff --git a/bin/python2 b/bin/python2 deleted file mode 100755 index c6b219710..000000000 Binary files a/bin/python2 and /dev/null differ diff --git a/bin/python2.7 b/bin/python2.7 deleted file mode 120000 index 551ab2685..000000000 --- a/bin/python2.7 +++ /dev/null @@ -1 +0,0 @@ -python2 \ No newline at end of file diff --git a/bin/tldextract b/bin/tldextract deleted file mode 100755 index 764b8134b..000000000 --- a/bin/tldextract +++ /dev/null @@ -1,11 +0,0 @@ -#!/usr/local/CyberCP/bin/python2 - -# -*- coding: utf-8 -*- -import re -import sys - -from tldextract.cli import main - -if __name__ == '__main__': - sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0]) - sys.exit(main()) diff --git a/bin/wheel b/bin/wheel deleted file mode 100755 index 87e36339a..000000000 --- a/bin/wheel +++ /dev/null @@ -1,11 +0,0 @@ -#!/usr/local/CyberCP/bin/python2 - -# -*- coding: utf-8 -*- -import re -import sys - -from wheel.cli import main - -if __name__ == '__main__': - sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0]) - sys.exit(main()) diff --git a/containerization/__init__.py b/containerization/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/containerization/admin.py b/containerization/admin.py new file mode 100644 index 000000000..13be29d96 --- /dev/null +++ b/containerization/admin.py @@ -0,0 +1,6 @@ +# -*- coding: utf-8 -*- +from __future__ import unicode_literals + +from django.contrib import admin + +# Register your models here. diff --git a/containerization/apps.py b/containerization/apps.py new file mode 100644 index 000000000..466ee5897 --- /dev/null +++ b/containerization/apps.py @@ -0,0 +1,8 @@ +# -*- coding: utf-8 -*- +from __future__ import unicode_literals + +from django.apps import AppConfig + + +class ContainerizationConfig(AppConfig): + name = 'containerization' diff --git a/containerization/container.py b/containerization/container.py new file mode 100755 index 000000000..f4186b2b1 --- /dev/null +++ b/containerization/container.py @@ -0,0 +1,99 @@ +#!/usr/local/CyberCP/bin/python2 +import os +import os.path +import sys +import django +sys.path.append('/usr/local/CyberCP') +os.environ.setdefault("DJANGO_SETTINGS_MODULE", "CyberCP.settings") +#django.setup() +import plogical.CyberCPLogFileWriter as logging +import argparse +import subprocess +import shlex +from plogical.processUtilities import ProcessUtilities +from xml.etree import ElementTree + +class Container: + packages = ['talksho'] + users = ['5001'] + + @staticmethod + def listAll(): + try: + counter = 0 + length = len(Container.users) + for items in Container.users: + if (counter + 1) == length: + print items + ' ' + Container.packages[counter] + else: + print items + ' ' + Container.packages[counter] + ' ' + counter = counter + 1 + + except BaseException, msg: + logging.CyberCPLogFileWriter.writeToFile(str(msg)) + + @staticmethod + def listPackages(): + try: + counter = 0 + length = len(Container.users) + for items in Container.packages: + if (counter + 1) == length: + print items + else: + print items + '\n' + counter = counter + 1 + + except BaseException, msg: + logging.CyberCPLogFileWriter.writeToFile(str(msg)) + + @staticmethod + def userIDPackage(user): + try: + counter = 0 + for items in Container.users: + if items == user: + print Container.packages[counter] + return + counter = counter + 1 + except BaseException, msg: + logging.CyberCPLogFileWriter.writeToFile(str(msg)) + + @staticmethod + def packageForUser(package): + try: + counter = 0 + for items in Container.packages: + if items == package: + print Container.users[counter] + return + counter = counter + 1 + except BaseException, msg: + logging.CyberCPLogFileWriter.writeToFile(str(msg)) + +def main(): + + parser = argparse.ArgumentParser(description='CyberPanel Container Manager') + parser.add_argument('--userid', help='User ID') + parser.add_argument('--package', help='Package') + parser.add_argument('--list-all', help='List all users/packages.', action='store_true') + parser.add_argument('--list-packages', help='List all packages.', action='store_true') + + + args = vars(parser.parse_args()) + + if args['userid']: + Container.userIDPackage(args['userid']) + elif args['package']: + Container.packageForUser(args['package']) + elif args['list_all']: + Container.listAll() + elif args['list_packages']: + Container.listPackages() + + + + +if __name__ == "__main__": + main() + diff --git a/containerization/containerManager.py b/containerization/containerManager.py new file mode 100644 index 000000000..bfff8322c --- /dev/null +++ b/containerization/containerManager.py @@ -0,0 +1,195 @@ +from django.shortcuts import render +from plogical.processUtilities import ProcessUtilities +import threading as multi +from plogical.acl import ACLManager +from plogical.mailUtilities import mailUtilities +import plogical.CyberCPLogFileWriter as logging +from serverStatus.serverStatusUtil import ServerStatusUtil +import os, stat + + +class ContainerManager(multi.Thread): + defaultConf = """group {groupName}{ + cpu { + cpu.cfs_quota_us = {cfs_quota_us}; + cpu.cfs_period_us = {cfs_period_us}; + } + memory { + memory.limit_in_bytes = {memory}m; + } + blkio { + blkio.throttle.read_bps_device = "{major}:{minor} {io}"; + blkio.throttle.write_bps_device = "{major}:{minor} {io}"; + blkio.throttle.read_iops_device = "{major}:{minor} {iops}"; + blkio.throttle.write_iops_device = "{major}:{minor} {iops}"; + } + net_cls + { + net_cls.classid = 0x10{net_cls}; + } +}""" + + def __init__(self, request=None, templateName=None, function=None, data=None): + multi.Thread.__init__(self) + self.request = request + self.templateName = templateName + self.function = function + self.data = data + + def run(self): + try: + if self.function == 'submitContainerInstall': + self.submitContainerInstall() + elif self.function == 'addTrafficController': + self.addTrafficController() + elif self.function == 'removeLimits': + self.removeLimits() + except BaseException, msg: + logging.CyberCPLogFileWriter.writeToFile(str(msg) + ' [ContainerManager.run]') + + @staticmethod + def fetchHexValue(count): + hexValue = format(count, '02x') + + if len(hexValue) == 1: + return '000' + hexValue + elif len(hexValue) == 2: + return '00' + hexValue + elif len(hexValue) == 3: + return '0' + hexValue + elif len(hexValue) == 3: + return hexValue + + @staticmethod + def prepConf(groupName, cfs_quota_us, cfs_period_us, memory, io, iops, net_cls): + try: + dev = os.stat('/')[stat.ST_DEV] + major = str(os.major(dev)) + minor = str(0) + finalIO = str(int(io) * 1024 * 1024) + + ioConf = ContainerManager.defaultConf.replace('{groupName}', groupName) + ioConf = ioConf.replace('{cfs_quota_us}', cfs_quota_us) + ioConf = ioConf.replace('{cfs_period_us}', cfs_period_us) + ioConf = ioConf.replace('{memory}', memory) + ioConf = ioConf.replace('{major}', major) + ioConf = ioConf.replace('{minor}', minor) + ioConf = ioConf.replace('{io}', finalIO) + ioConf = ioConf.replace('{iops}', str(iops)) + ioConf = ioConf.replace('{net_cls}', str(net_cls)) + + return ioConf + except BaseException, msg: + logging.CyberCPLogFileWriter.writeToFile(str(msg)) + return 0 + + def renderC(self): + + userID = self.request.session['userID'] + currentACL = ACLManager.loadedACL(userID) + + if currentACL['admin'] == 1: + pass + else: + return ACLManager.loadError() + + data = {} + data['OLS'] = 0 + data['notInstalled'] = 0 + + if ProcessUtilities.decideServer() == ProcessUtilities.OLS: + data['OLS'] = 1 + data['notInstalled'] = 0 + return render(self.request, 'containerization/notAvailable.html', data) + elif not ProcessUtilities.containerCheck(): + data['OLS'] = 0 + data['notInstalled'] = 1 + return render(self.request, 'containerization/notAvailable.html', data) + else: + if self.data == None: + self.data = {} + self.data['OLS'] = 0 + self.data['notInstalled'] = 0 + return render(self.request, self.templateName, self.data) + + def submitContainerInstall(self): + try: + userID = self.request.session['userID'] + currentACL = ACLManager.loadedACL(userID) + + if currentACL['admin'] == 1: + pass + else: + logging.CyberCPLogFileWriter.statusWriter(ServerStatusUtil.lswsInstallStatusPath, + 'Not authorized to install container packages. [404].', + 1) + return 0 + + mailUtilities.checkHome() + + statusFile = open(ServerStatusUtil.lswsInstallStatusPath, 'w') + + logging.CyberCPLogFileWriter.statusWriter(ServerStatusUtil.lswsInstallStatusPath, + "Starting Packages Installation..\n", 1) + + command = 'sudo yum install -y libcgroup-tools' + ServerStatusUtil.executioner(command, statusFile) + + command = 'sudo systemctl enable cgconfig' + ServerStatusUtil.executioner(command, statusFile) + + command = 'sudo systemctl enable cgred' + ServerStatusUtil.executioner(command, statusFile) + + logging.CyberCPLogFileWriter.statusWriter(ServerStatusUtil.lswsInstallStatusPath, + "Packages successfully installed.[200]\n", 1) + + except BaseException, msg: + logging.CyberCPLogFileWriter.statusWriter(ServerStatusUtil.lswsInstallStatusPath, str(msg) + ' [404].', 1) + + def restartServices(self): + command = 'sudo systemctl restart cgconfig' + ProcessUtilities.executioner(command) + + command = 'sudo systemctl restart cgred' + ProcessUtilities.executioner(command) + + def addTrafficController(self): + command = 'sudo tc qdisc add dev eth0 root handle 10: htb default 1000' + #logging.CyberCPLogFileWriter.writeToFile(command) + ProcessUtilities.executioner(command) + + try: + command = 'sudo tc class del dev eth0 classid 10:' + str(self.data['classID']) + # logging.CyberCPLogFileWriter.writeToFile(command) + ProcessUtilities.executioner(command) + except: + pass + + command = 'sudo tc class add dev eth0 parent 10: classid 10:1000 htb rate 100mbit' + #logging.CyberCPLogFileWriter.writeToFile(command) + ProcessUtilities.executioner(command) + + command = 'sudo tc class add dev eth0 parent 10: classid 10:' + str(self.data['classID']) + ' htb rate ' + str(self.data['rateLimit']) + #logging.CyberCPLogFileWriter.writeToFile(command) + ProcessUtilities.executioner(command) + + #if str(self.data['classID']) == '1': + # command = 'sudo tc filter add dev eth0 parent 10: protocol ip prio 10 handle 1: cgroup' + #else: + # command = 'sudo tc filter add dev eth0 parent 10:' + str( + # self.data['classID']) + ' protocol ip prio 10 handle 1: cgroup' + + command = 'sudo tc filter add dev eth0 parent 10: protocol ip prio 10 handle 1: cgroup' + #logging.CyberCPLogFileWriter.writeToFile(command) + ProcessUtilities.executioner(command) + + self.restartServices() + + def removeLimits(self): + command = 'sudo tc class del dev eth0 classid 10:' + str(self.data['classID']) + #logging.CyberCPLogFileWriter.writeToFile(command) + ProcessUtilities.executioner(command) + + self.restartServices() + diff --git a/containerization/migrations/__init__.py b/containerization/migrations/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/containerization/models.py b/containerization/models.py new file mode 100644 index 000000000..28111e839 --- /dev/null +++ b/containerization/models.py @@ -0,0 +1,16 @@ +# -*- coding: utf-8 -*- +from __future__ import unicode_literals + +from django.db import models +from websiteFunctions.models import Websites +# Create your models here. + +class ContainerLimits(models.Model): + owner = models.ForeignKey(Websites, on_delete=models.PROTECT) + cpuPers = models.CharField(max_length=10) + IO = models.CharField(max_length=10) + IOPS = models.CharField(max_length=10) + memory = models.CharField(max_length=10) + networkSpeed = models.CharField(max_length=10) + networkHexValue = models.CharField(max_length=10) + enforce = models.IntegerField(default=0) diff --git a/containerization/static/containerization/containerization.js b/containerization/static/containerization/containerization.js new file mode 100644 index 000000000..f0fad7a03 --- /dev/null +++ b/containerization/static/containerization/containerization.js @@ -0,0 +1,646 @@ +app.controller('installContainer', function ($scope, $http, $timeout, $window) { + $scope.installDockerStatus = true; + $scope.installBoxGen = true; + $scope.dockerInstallBTN = false; + + $scope.submitContainerInstall = function () { + + $scope.installDockerStatus = false; + $scope.installBoxGen = true; + $scope.dockerInstallBTN = true; + + url = "/container/submitContainerInstall"; + + var data = {}; + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + $scope.cyberPanelLoading = true; + if (response.data.status === 1) { + $scope.installBoxGen = false; + getRequestStatus(); + } + else { + new PNotify({ + title: 'Operation Failed!', + text: response.data.error_message, + type: 'error' + }); + } + + } + + function cantLoadInitialDatas(response) { + $scope.cyberPanelLoading = true; + new PNotify({ + title: 'Operation Failed!', + text: 'Could not connect to server, please refresh this page', + type: 'error' + }); + } + + }; + function getRequestStatus() { + $scope.cyberPanelLoading = false; + + url = "/serverstatus/switchTOLSWSStatus"; + + var data = {}; + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + if (response.data.abort === 0) { + $scope.requestData = response.data.requestStatus; + $timeout(getRequestStatus, 1000); + } + else { + // Notifications + $scope.cyberPanelLoading = true; + $timeout.cancel(); + $scope.requestData = response.data.requestStatus; + if (response.data.installed === 1) { + $timeout(function () { + $window.location.reload(); + }, 3000); + } + + } + } + + function cantLoadInitialDatas(response) { + $scope.cyberPanelLoading = true; + new PNotify({ + title: 'Operation Failed!', + text: 'Could not connect to server, please refresh this page', + type: 'error' + }); + + + } + + } +}); + + +app.controller('websiteContainerLimit', function ($scope, $http, $timeout, $window) { + + + // Get CPU Usage of User + + var cpu = []; + var dataset; + var totalPoints = 100; + var updateInterval = 1000; + var now = new Date().getTime(); + + var options = { + series: { + lines: { + lineWidth: 1.2 + }, + bars: { + align: "center", + fillColor: {colors: [{opacity: 1}, {opacity: 1}]}, + barWidth: 500, + lineWidth: 1 + } + }, + xaxis: { + mode: "time", + tickSize: [5, "second"], + tickFormatter: function (v, axis) { + var date = new Date(v); + + if (date.getSeconds() % 20 == 0) { + var hours = date.getHours() < 10 ? "0" + date.getHours() : date.getHours(); + var minutes = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes(); + var seconds = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds(); + + return hours + ":" + minutes + ":" + seconds; + } else { + return ""; + } + }, + axisLabel: "Time", + axisLabelUseCanvas: true, + axisLabelFontSizePixels: 12, + axisLabelFontFamily: 'Verdana, Arial', + axisLabelPadding: 10 + }, + yaxes: [ + { + min: 0, + max: 100, + tickSize: 5, + tickFormatter: function (v, axis) { + if (v % 10 == 0) { + return v + "%"; + } else { + return ""; + } + }, + axisLabel: "CPU loading", + axisLabelUseCanvas: true, + axisLabelFontSizePixels: 12, + axisLabelFontFamily: 'Verdana, Arial', + axisLabelPadding: 6 + }, { + max: 5120, + position: "right", + axisLabel: "Disk", + axisLabelUseCanvas: true, + axisLabelFontSizePixels: 12, + axisLabelFontFamily: 'Verdana, Arial', + axisLabelPadding: 6 + } + ], + legend: { + noColumns: 0, + position: "nw" + }, + grid: { + backgroundColor: {colors: ["#ffffff", "#EDF5FF"]} + } + }; + + function initData() { + for (var i = 0; i < totalPoints; i++) { + var temp = [now += updateInterval, 0]; + + cpu.push(temp); + } + } + + function GetData() { + + var data = { + domain: $("#domain").text() + }; + $.ajaxSetup({cache: false}); + + $.ajax({ + url: "/container/getUsageData", + dataType: 'json', + success: update, + type: "POST", + contentType: "application/json", + data: JSON.stringify(data), // Our valid JSON string + error: function () { + setTimeout(GetData, updateInterval); + } + }); + } + + var temp; + + function update(_data) { + cpu.shift(); + + now += updateInterval; + + temp = [now, _data.cpu]; + cpu.push(temp); + + + dataset = [ + {label: "CPU:" + _data.cpu + "%", data: cpu, lines: {fill: true, lineWidth: 1.2}, color: "#00FF00"} + ]; + + $.plot($("#flot-placeholder1"), dataset, options); + setTimeout(GetData, updateInterval); + } + + // Memory Usage of User + + var memory = []; + var datasetMemory; + var totalPointsMemory = 100; + var updateIntervalMemory = 1000; + var nowMemory = new Date().getTime(); + + var optionsMemory = { + series: { + lines: { + lineWidth: 1.2 + }, + bars: { + align: "center", + fillColor: {colors: [{opacity: 1}, {opacity: 1}]}, + barWidth: 500, + lineWidth: 1 + } + }, + xaxis: { + mode: "time", + tickSize: [5, "second"], + tickFormatter: function (v, axis) { + var date = new Date(v); + + if (date.getSeconds() % 20 == 0) { + var hours = date.getHours() < 10 ? "0" + date.getHours() : date.getHours(); + var minutes = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes(); + var seconds = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds(); + + return hours + ":" + minutes + ":" + seconds; + } else { + return ""; + } + }, + axisLabel: "Time", + axisLabelUseCanvas: true, + axisLabelFontSizePixels: 12, + axisLabelFontFamily: 'Verdana, Arial', + axisLabelPadding: 10 + }, + yaxes: [ + { + min: 0, + max: $scope.memory, + tickSize: 5, + tickFormatter: function (v, axis) { + if (v % 10 == 0) { + return v + "MB"; + } else { + return ""; + } + }, + axisLabel: "CPU loading", + axisLabelUseCanvas: true, + axisLabelFontSizePixels: 12, + axisLabelFontFamily: 'Verdana, Arial', + axisLabelPadding: 6 + }, { + max: 5120, + position: "right", + axisLabel: "Disk", + axisLabelUseCanvas: true, + axisLabelFontSizePixels: 12, + axisLabelFontFamily: 'Verdana, Arial', + axisLabelPadding: 6 + } + ], + legend: { + noColumns: 0, + position: "nw" + }, + grid: { + backgroundColor: {colors: ["#ffffff", "#EDF5FF"]} + } + }; + + function initDataMemory() { + for (var i = 0; i < totalPointsMemory; i++) { + var temp = [nowMemory += updateIntervalMemory, 0]; + + memory.push(temp); + } + } + + function GetDataMemory() { + + var data = { + domain: $("#domain").text(), + type: 'memory' + }; + $.ajaxSetup({cache: false}); + + $.ajax({ + url: "/container/getUsageData", + dataType: 'json', + success: updateMemory, + type: "POST", + contentType: "application/json", + data: JSON.stringify(data), // Our valid JSON string + error: function () { + setTimeout(GetDataMemory, updateIntervalMemory); + } + }); + } + + var tempMemory; + + function updateMemory(_data) { + memory.shift(); + + nowMemory += updateIntervalMemory; + + tempMemory = [nowMemory, _data.memory]; + memory.push(tempMemory); + + + datasetMemory = [ + { + label: "Memory:" + _data.memory + "MB", + data: memory, + lines: {fill: true, lineWidth: 1.2}, + color: "#00FF00" + } + ]; + + $.plot($("#memoryUsage"), datasetMemory, optionsMemory); + setTimeout(GetDataMemory, updateIntervalMemory); + } + + // Disk Usage + + var readRate = [], writeRate = []; + var datasetDisk; + var totalPointsDisk = 100; + var updateIntervalDisk = 5000; + var now = new Date().getTime(); + + var optionsDisk = { + series: { + lines: { + lineWidth: 1.2 + }, + bars: { + align: "center", + fillColor: {colors: [{opacity: 1}, {opacity: 1}]}, + barWidth: 500, + lineWidth: 1 + } + }, + xaxis: { + mode: "time", + tickSize: [30, "second"], + tickFormatter: function (v, axis) { + var date = new Date(v); + + if (date.getSeconds() % 20 == 0) { + var hours = date.getHours() < 10 ? "0" + date.getHours() : date.getHours(); + var minutes = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes(); + var seconds = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds(); + + return hours + ":" + minutes + ":" + seconds; + } else { + return ""; + } + }, + axisLabel: "Time", + axisLabelUseCanvas: true, + axisLabelFontSizePixels: 12, + axisLabelFontFamily: 'Verdana, Arial', + axisLabelPadding: 10 + }, + yaxes: [ + { + min: 0, + max: $scope.networkSpeed, + tickSize: 5, + tickFormatter: function (v, axis) { + if (v % 10 == 0) { + return v + "mb/sec"; + } else { + return ""; + } + }, + axisLabel: "CPU loading", + axisLabelUseCanvas: true, + axisLabelFontSizePixels: 12, + axisLabelFontFamily: 'Verdana, Arial', + axisLabelPadding: 6 + }, { + max: 5120, + position: "right", + axisLabel: "Disk", + axisLabelUseCanvas: true, + axisLabelFontSizePixels: 12, + axisLabelFontFamily: 'Verdana, Arial', + axisLabelPadding: 6 + } + ], + legend: { + noColumns: 0, + position: "nw" + }, + grid: { + backgroundColor: {colors: ["#ffffff", "#EDF5FF"]} + } + }; + + function initDataDisk() { + for (var i = 0; i < totalPointsDisk; i++) { + var temp = [now += updateIntervalDisk, 0]; + + readRate.push(temp); + writeRate.push(temp); + } + } + + function GetDataDisk() { + + var data = { + domain: $("#domain").text(), + type: 'io' + }; + + $.ajaxSetup({cache: false}); + + $.ajax({ + url: "/container/getUsageData", + dataType: 'json', + success: updateDisk, + type: "POST", + contentType: "application/json", + data: JSON.stringify(data), // Our valid JSON string + error: function () { + setTimeout(GetDataMemory, updateIntervalMemory); + } + }); + } + + var tempDisk; + + function updateDisk(_data) { + readRate.shift(); + writeRate.shift(); + + now += updateIntervalDisk; + + tempDisk = [now, _data.readRate]; + readRate.push(tempDisk); + + tempDisk = [now, _data.readRate]; + writeRate.push(tempDisk); + + datasetDisk = [ + {label: "Read IO/s " + _data.readRate + " mb/s ", data: readRate, lines: {fill: true, lineWidth: 1.2}, color: "#00FF00"}, + {label: "Write IO/s " + _data.writeRate + " mb/s ", data: writeRate, lines: {lineWidth: 1.2}, color: "#FF0000"} + ]; + + $.plot($("#diskUsage"), datasetDisk, optionsDisk); + setTimeout(GetDataDisk, updateIntervalDisk); + } + + + $(document).ready(function () { + initDataDisk(); + + datasetDisk = [ + {label: "Read IO/s: ", data: readRate, lines: {fill: true, lineWidth: 1.2}, color: "#00FF00"}, + {label: "Write IO/s: ", data: writeRate, color: "#0044FF", bars: {show: true}, yaxis: 2} + ]; + + $.plot($("#diskUsage"), datasetDisk, optionsDisk); + setTimeout(GetDataDisk, updateIntervalDisk); + }); + + //// + + $scope.cyberPanelLoading = true; + $scope.limitsInfoBox = true; + + $scope.fetchWebsiteLimits = function () { + + $scope.cyberPanelLoading = false; + + url = "/container/fetchWebsiteLimits"; + + var data = { + 'domain': $("#domain").text() + }; + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + $scope.cyberPanelLoading = true; + if (response.data.status === 1) { + $scope.cpuPers = response.data.cpuPers; + $scope.IO = response.data.IO; + $scope.IOPS = response.data.IOPS; + $scope.memory = response.data.memory; + $scope.networkSpeed = response.data.networkSpeed; + + if (response.data.enforce === 0) { + $scope.limitsInfoBox = false; + } else { + $scope.limitsInfoBox = true; + } + + + // Report Memory Usage + + initDataMemory(); + + datasetMemory = [ + {label: "Memory", data: memory, lines: {fill: true, lineWidth: 1.2}, color: "#00FF00"} + ]; + + $.plot($("#memoryUsage"), datasetMemory, optionsMemory); + setTimeout(GetDataMemory, updateIntervalMemory); + + // Report CPU Usage + + initData(); + + dataset = [ + {label: "CPU", data: cpu, lines: {fill: true, lineWidth: 1.2}, color: "#00FF00"} + ]; + + $.plot($("#flot-placeholder1"), dataset, options); + setTimeout(GetData, updateInterval); + } + else { + new PNotify({ + title: 'Operation Failed!', + text: response.data.error_message, + type: 'error' + }); + } + } + + function cantLoadInitialDatas(response) { + $scope.cyberPanelLoading = true; + new PNotify({ + title: 'Operation Failed!', + text: 'Could not connect to server, please refresh this page', + type: 'error' + }); + } + + }; + $scope.fetchWebsiteLimits(); + + $scope.saveWebsiteLimits = function () { + + $scope.cyberPanelLoading = false; + + url = "/container/saveWebsiteLimits"; + + var data = { + 'domain': $("#domain").text(), + 'cpuPers': $scope.cpuPers, + 'IO': $scope.IO, + 'IOPS': $scope.IOPS, + 'memory': $scope.memory, + 'networkSpeed': $scope.networkSpeedBox, + 'networkHandle': $scope.networkHandle, + 'enforce': $scope.enforce + }; + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + $scope.cyberPanelLoading = true; + if (response.data.status === 1) { + new PNotify({ + title: 'Success', + text: 'Changes successfully applied.', + type: 'success' + }); + $scope.fetchWebsiteLimits(); + } + else { + new PNotify({ + title: 'Operation Failed!', + text: response.data.error_message, + type: 'error' + }); + } + } + + function cantLoadInitialDatas(response) { + $scope.cyberPanelLoading = true; + new PNotify({ + title: 'Operation Failed!', + text: 'Could not connect to server, please refresh this page', + type: 'error' + }); + } + + }; + + +}); \ No newline at end of file diff --git a/containerization/templates/containerization/listWebsites.html b/containerization/templates/containerization/listWebsites.html new file mode 100644 index 000000000..a3efd4d9c --- /dev/null +++ b/containerization/templates/containerization/listWebsites.html @@ -0,0 +1,87 @@ +{% extends "baseTemplate/index.html" %} +{% load i18n %} +{% block title %}{% trans "Limits - CyberPanel" %}{% endblock %} +{% block content %} + + {% load static %} + {% get_current_language as LANGUAGE_CODE %} + + + +
+ +
+

{% trans "List Websites" %}

+

{% trans "Launch and set limits for the websites." %}

+
+ +
+
+

+ {% trans "Websites" %} +

+
+ + + + + + + + + + + + + + + + + + + + + + + + + + +
DomainLaunchIP AddressPackageOwnerStateEmail
+
+ +
+

{% trans "Cannot list websites. Error message:" %} {$ errorMessage $}

+
+ +
+ +
+ + + + +
+ + +
+ +
+
+
+ +
+ + + +{% endblock %} \ No newline at end of file diff --git a/containerization/templates/containerization/notAvailable.html b/containerization/templates/containerization/notAvailable.html new file mode 100644 index 000000000..e23d2f13a --- /dev/null +++ b/containerization/templates/containerization/notAvailable.html @@ -0,0 +1,67 @@ +{% extends "baseTemplate/index.html" %} +{% load i18n %} +{% block title %}{% trans "Not available - CyberPanel" %}{% endblock %} +{% block content %} + + {% load static %} + {% get_current_language as LANGUAGE_CODE %} + + + +
+
+

{% trans "Not available" %}

+

{% trans "CyberPanel Ent is required for Containerization." %}

+
+ + {% if OLS %} + +
+
+
+

{% trans "Containerization is only available on CyberPanel Ent. " %} Click + Here {% trans " for conversion details." %}

+
+
+
+ + {% elif notInstalled %} + +
+
+

+ {% trans "Install Packages" %} +

+
+ +

{% trans "Required packages are not installed on this server. Please proceed to installation." %}

+ + +
+ +
+
+
+ +
+
+
+
+ + + +
+ + +
+
+
+ + {% endif %} + +
+{% endblock %} + diff --git a/containerization/templates/containerization/websiteContainerLimit.html b/containerization/templates/containerization/websiteContainerLimit.html new file mode 100644 index 000000000..e54cec1ed --- /dev/null +++ b/containerization/templates/containerization/websiteContainerLimit.html @@ -0,0 +1,186 @@ +{% extends "baseTemplate/index.html" %} +{% load i18n %} +{% block title %}{{ domain }}{% trans " limits - CyberPanel" %}{% endblock %} +{% block content %} + + {% load static %} + {% get_current_language as LANGUAGE_CODE %} + + + +
+ +
+

{% trans "Limits/Usage" %}

+

{% trans "Set limits and view usage for " %} {{ domain }}

+
+ + + +
+
+

{% trans "Limits are not being inforced, click Edit Limits to inforace the limits." %}

+
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
{% trans 'Limit' %}{% trans 'Value' %}
{% trans 'CPU Percentage' %}{$ cpuPers $}%
{% trans 'Memory' %}{$ memory $}MB
{% trans 'I/O' %}{$ IO $}MB/sec
{% trans 'IOPS' %}{$ IOPS $}
{% trans 'Network Speed' %}{$ networkSpeed $}
+ + +
+
+

+ {% trans "CPU Usage of" %} {{ domain }} +

+
+
+ +
+
+
+

+ {% trans "Memory Usage of" %} {{ domain }} +

+
+
+ +
+
+
+

+ {% trans "Disk Usage of" %} {{ domain }} +

+
+
+ +
+
+
+ +
+ + + +{% endblock %} \ No newline at end of file diff --git a/containerization/tests.py b/containerization/tests.py new file mode 100644 index 000000000..5982e6bcd --- /dev/null +++ b/containerization/tests.py @@ -0,0 +1,6 @@ +# -*- coding: utf-8 -*- +from __future__ import unicode_literals + +from django.test import TestCase + +# Create your tests here. diff --git a/containerization/urls.py b/containerization/urls.py new file mode 100644 index 000000000..6fb3ac761 --- /dev/null +++ b/containerization/urls.py @@ -0,0 +1,11 @@ +from django.conf.urls import url +import views + +urlpatterns = [ + url(r'^$', views.cHome, name='cHome'), + url(r'^submitContainerInstall$', views.submitContainerInstall, name='submitContainerInstall'), + url(r'^manage/(?P(.*))$', views.websiteContainerLimit, name='websiteContainerLimit'), + url(r'^fetchWebsiteLimits$', views.fetchWebsiteLimits, name='fetchWebsiteLimits'), + url(r'^saveWebsiteLimits$', views.saveWebsiteLimits, name='saveWebsiteLimits'), + url(r'^getUsageData$', views.getUsageData, name='getUsageData'), +] \ No newline at end of file diff --git a/containerization/views.py b/containerization/views.py new file mode 100644 index 000000000..b30a57087 --- /dev/null +++ b/containerization/views.py @@ -0,0 +1,350 @@ +# -*- coding: utf-8 -*- +from __future__ import unicode_literals + +from django.shortcuts import HttpResponse, redirect +from loginSystem.views import loadLoginPage +from containerManager import ContainerManager +import json +from websiteFunctions.models import Websites +from .models import ContainerLimits +from random import randint +from plogical.processUtilities import ProcessUtilities +import os +import subprocess, shlex +import multiprocessing +from plogical.httpProc import httpProc +from plogical.CyberCPLogFileWriter import CyberCPLogFileWriter as logging +from plogical.acl import ACLManager +# Create your views here. + +def cHome(request): + try: + templateName = 'containerization/listWebsites.html' + c = ContainerManager(request, templateName) + return c.renderC() + except KeyError: + return redirect(loadLoginPage) + +def submitContainerInstall(request): + try: + + userID = request.session['userID'] + currentACL = ACLManager.loadedACL(userID) + + if currentACL['admin'] == 1: + pass + else: + return ACLManager.loadErrorJson() + + c = ContainerManager(request, None, 'submitContainerInstall') + c.start() + + data_ret = {'status': 1, 'error_message': 'None'} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + except BaseException, msg: + data_ret = {'status': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + +def websiteContainerLimit(request, domain): + try: + templateName = 'containerization/websiteContainerLimit.html' + data = {} + data['domain'] = domain + c = ContainerManager(request, templateName, None, data) + return c.renderC() + except KeyError: + return redirect(loadLoginPage) + +def fetchWebsiteLimits(request): + try: + + userID = request.session['userID'] + currentACL = ACLManager.loadedACL(userID) + + if currentACL['admin'] == 1: + pass + else: + return ACLManager.loadErrorJson() + + data = json.loads(request.body) + domain = data['domain'] + website = Websites.objects.get(domain=domain) + + try: + websiteLimits = ContainerLimits.objects.get(owner=website) + except: + confPathTemp = "/home/cyberpanel/" + str(randint(1000, 9999)) + confPath = '/etc/cgconfig.d/' + domain + count = ContainerLimits.objects.all().count() + 1 + hexValue = ContainerManager.fetchHexValue(count) + cfs_quota_us = multiprocessing.cpu_count() * 10000 + finalContent = ContainerManager.prepConf(website.externalApp, str(cfs_quota_us), str(100000), str(356), 1, 1024, hexValue) + + if finalContent == 0: + return httpProc.AJAX(0, 'Please check CyberPanel main log file.') + + + writeToFile = open(confPathTemp, 'w') + writeToFile.write(finalContent) + writeToFile.close() + + command = 'sudo mv ' + confPathTemp + ' ' + confPath + ProcessUtilities.executioner(command) + + try: + os.remove(confPathTemp) + except: + pass + + websiteLimits = ContainerLimits(owner=website, cpuPers='10', IO='1', IOPS='1024', memory='300', networkSpeed='1mbit', networkHexValue=hexValue) + websiteLimits.save() + + finalData = {} + finalData['status'] = 1 + finalData['cpuPers'] = int(websiteLimits.cpuPers) + finalData['IO'] = int(websiteLimits.IO) + finalData['IOPS'] = int(websiteLimits.IOPS) + finalData['memory'] = int(websiteLimits.memory) + finalData['networkSpeed'] = websiteLimits.networkSpeed + + if websiteLimits.enforce == 1: + finalData['enforce'] = 1 + else: + finalData['enforce'] = 0 + + json_data = json.dumps(finalData) + return HttpResponse(json_data) + + except BaseException, msg: + data_ret = {'status': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + +def saveWebsiteLimits(request): + try: + + userID = request.session['userID'] + currentACL = ACLManager.loadedACL(userID) + + if currentACL['admin'] == 1: + pass + else: + return ACLManager.loadErrorJson() + + data = json.loads(request.body) + domain = data['domain'] + cpuPers = data['cpuPers'] + IO = data['IO'] + IOPS = data['IOPS'] + memory = data['memory'] + networkSpeed = data['networkSpeed'] + networkHandle = data['networkHandle'] + + try: + enforce = data['enforce'] + except: + enforce = False + + if cpuPers > 100: + return httpProc.AJAX(0, 'CPU Percentage can not be greater then 100%') + + website = Websites.objects.get(domain=domain) + websiteLimits = ContainerLimits.objects.get(owner=website) + + + if enforce == True: + if websiteLimits.enforce == 0: + + cgrulesTemp = "/home/cyberpanel/" + str(randint(1000, 9999)) + cgrules = '/etc/cgrules.conf' + enforceString = '{} cpu,memory,blkio,net_cls {}/\n'.format(website.externalApp, website.externalApp) + + cgrulesData = subprocess.check_output(shlex.split('sudo cat /etc/cgrules.conf')).splitlines() + + writeToFile = open(cgrulesTemp, 'w') + + for items in cgrulesData: + writeToFile.writelines(items + '\n') + + writeToFile.writelines(enforceString) + writeToFile.close() + + command = 'sudo mv ' + cgrulesTemp + ' ' + cgrules + ProcessUtilities.executioner(command) + + try: + os.remove(cgrulesTemp) + except: + pass + + websiteLimits.enforce = 1 + + ## Main Conf File + + confPathTemp = "/home/cyberpanel/" + str(randint(1000, 9999)) + confPath = '/etc/cgconfig.d/' + domain + cfs_quota_us = multiprocessing.cpu_count() * 1000 + finalContent = ContainerManager.prepConf(website.externalApp, str(cpuPers * cfs_quota_us), str(100000), + str(memory), IO, IOPS, websiteLimits.networkHexValue) + + if finalContent == 0: + return httpProc.AJAX(0, 'Please check CyberPanel main log file.') + + writeToFile = open(confPathTemp, 'w') + writeToFile.write(finalContent) + writeToFile.close() + + command = 'sudo mv ' + confPathTemp + ' ' + confPath + ProcessUtilities.executioner(command) + + try: + os.remove(confPathTemp) + except: + pass + + ## Add Traffic Control / Restart Services + + additionalArgs = {} + additionalArgs['classID'] = websiteLimits.id + additionalArgs['rateLimit'] = str(networkSpeed) + networkHandle + + c = ContainerManager(None, None, 'addTrafficController', additionalArgs) + c.start() + else: + websiteLimits.enforce = 0 + + cgrulesTemp = "/home/cyberpanel/" + str(randint(1000, 9999)) + cgrules = '/etc/cgrules.conf' + + cgrulesData = subprocess.check_output(shlex.split('sudo cat /etc/cgrules.conf')).splitlines() + + writeToFile = open(cgrulesTemp, 'w') + + for items in cgrulesData: + if items.find(website.externalApp) > -1: + continue + writeToFile.writelines(items + '\n') + + writeToFile.close() + + command = 'sudo mv ' + cgrulesTemp + ' ' + cgrules + ProcessUtilities.executioner(command) + + confPath = '/etc/cgconfig.d/' + domain + + command = 'sudo rm ' + confPath + ProcessUtilities.executioner(command) + + ## Not needed, to be removed later + + additionalArgs = {} + additionalArgs['classID'] = websiteLimits.id + + c = ContainerManager(None, None, 'removeLimits', additionalArgs) + c.start() + + try: + os.remove(cgrulesTemp) + except: + pass + + + + websiteLimits.cpuPers = str(cpuPers) + websiteLimits.memory = str(memory) + websiteLimits.IO = str(IO) + websiteLimits.IOPS = str(IOPS) + websiteLimits.networkSpeed = str(networkSpeed) + str(networkHandle) + websiteLimits.save() + + finalData = {} + finalData['status'] = 1 + json_data = json.dumps(finalData) + return HttpResponse(json_data) + + except BaseException, msg: + data_ret = {'status': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + +def getUsageData(request): + try: + + userID = request.session['userID'] + currentACL = ACLManager.loadedACL(userID) + + if currentACL['admin'] == 1: + pass + else: + return ACLManager.loadErrorJson() + + data = json.loads(request.body) + domain = data['domain'] + website = Websites.objects.get(domain=domain) + + try: + type = data['type'] + finalData = {} + + try: + if type == 'memory': + + command = 'sudo cat /sys/fs/cgroup/memory/' + website.externalApp + '/memory.usage_in_bytes' + output = str(subprocess.check_output(command, shell=True)) + finalData['memory'] = int(float(output)/float(1024 * 1024)) + + elif type == 'io': + + path = '/home/cyberpanel/' + website.externalApp + blkioPath = path + '/blkio' + + if not os.path.exists(path): + os.mkdir(path) + + command = 'sudo cat /sys/fs/cgroup/blkio/' + website.externalApp + '/blkio.throttle.io_service_bytes' + output = subprocess.check_output(command, shell=True).splitlines() + + readCurrent = output[0].split(' ')[2] + writeCurrent = output[1].split(' ')[2] + + if os.path.exists(blkioPath): + + old = open(blkioPath, 'r').read() + oldRead = float(old.split(',')[0]) + oldWrite = float(old.split(',')[1]) + + finalData['readRate'] = int((float(readCurrent) - oldRead)/float(65536000)) + finalData['writeRate'] = int((float(writeCurrent) - oldWrite) / float(65536000)) + + else: + finalData['readRate'] = 0 + finalData['writeRate'] = 0 + + writeToFile = open(blkioPath, 'w') + writeToFile.write(readCurrent + ',' + writeCurrent) + writeToFile.close() + + except: + finalData['memory'] = '0' + finalData['readRate'] = 0 + finalData['writeRate'] = 0 + except: + command = "sudo top -b -n 1 -u " + website.externalApp + " | awk 'NR>7 { sum += $9; } END { print sum; }'" + output = str(subprocess.check_output(command, shell=True)) + + finalData = {} + if len(output) == 0: + finalData['cpu'] = '0' + else: + finalData['cpu'] = str(float(output)/float(multiprocessing.cpu_count())) + + final_json = json.dumps(finalData) + return HttpResponse(final_json) + + except BaseException, msg: + data_ret = {'status': 0, 'error_message': str(msg), 'cpu': 0, 'memory':0} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) \ No newline at end of file diff --git a/databases/migrations/0001_initial.py b/databases/migrations/0001_initial.py deleted file mode 100644 index ac622d14b..000000000 --- a/databases/migrations/0001_initial.py +++ /dev/null @@ -1,27 +0,0 @@ -# -*- coding: utf-8 -*- -# Generated by Django 1.11 on 2019-01-07 12:43 -from __future__ import unicode_literals - -from django.db import migrations, models -import django.db.models.deletion - - -class Migration(migrations.Migration): - - initial = True - - dependencies = [ - ('websiteFunctions', '0001_initial'), - ] - - operations = [ - migrations.CreateModel( - name='Databases', - fields=[ - ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), - ('dbName', models.CharField(max_length=50, unique=True)), - ('dbUser', models.CharField(max_length=50, unique=True)), - ('website', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='websiteFunctions.Websites')), - ], - ), - ] diff --git a/dns/migrations/0001_initial.py b/dns/migrations/0001_initial.py deleted file mode 100644 index 91824de73..000000000 --- a/dns/migrations/0001_initial.py +++ /dev/null @@ -1,125 +0,0 @@ -# -*- coding: utf-8 -*- -# Generated by Django 1.11 on 2019-01-07 12:43 -from __future__ import unicode_literals - -from django.db import migrations, models -import django.db.models.deletion - - -class Migration(migrations.Migration): - - initial = True - - dependencies = [ - ('loginSystem', '0001_initial'), - ] - - operations = [ - migrations.CreateModel( - name='Comments', - fields=[ - ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), - ('domain_id', models.IntegerField()), - ('name', models.CharField(max_length=255)), - ('type', models.CharField(max_length=10)), - ('modified_at', models.IntegerField()), - ('account', models.CharField(max_length=40)), - ('comment', models.CharField(max_length=64000)), - ], - options={ - 'db_table': 'comments', - }, - ), - migrations.CreateModel( - name='Cryptokeys', - fields=[ - ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), - ('domain_id', models.IntegerField()), - ('flags', models.IntegerField()), - ('active', models.IntegerField(blank=True, null=True)), - ('content', models.TextField(blank=True, null=True)), - ], - options={ - 'db_table': 'cryptokeys', - }, - ), - migrations.CreateModel( - name='Domainmetadata', - fields=[ - ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), - ('domain_id', models.IntegerField()), - ('kind', models.CharField(blank=True, max_length=32, null=True)), - ('content', models.TextField(blank=True, null=True)), - ], - options={ - 'db_table': 'domainmetadata', - }, - ), - migrations.CreateModel( - name='Domains', - fields=[ - ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), - ('name', models.CharField(max_length=255, unique=True)), - ('master', models.CharField(blank=True, max_length=128, null=True)), - ('last_check', models.IntegerField(blank=True, null=True)), - ('type', models.CharField(max_length=6)), - ('notified_serial', models.IntegerField(blank=True, null=True)), - ('account', models.CharField(blank=True, max_length=40, null=True)), - ('admin', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='loginSystem.Administrator')), - ], - options={ - 'db_table': 'domains', - }, - ), - migrations.CreateModel( - name='Records', - fields=[ - ('id', models.BigAutoField(primary_key=True, serialize=False)), - ('domain_id', models.IntegerField(blank=True, null=True)), - ('name', models.CharField(blank=True, max_length=255, null=True)), - ('type', models.CharField(blank=True, max_length=10, null=True)), - ('content', models.CharField(blank=True, max_length=64000, null=True)), - ('ttl', models.IntegerField(blank=True, null=True)), - ('prio', models.IntegerField(blank=True, null=True)), - ('change_date', models.IntegerField(blank=True, null=True)), - ('disabled', models.IntegerField(blank=True, null=True)), - ('ordername', models.CharField(blank=True, max_length=255, null=True)), - ('auth', models.IntegerField(blank=True, null=True)), - ('domainOwner', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='dns.Domains')), - ], - options={ - 'db_table': 'records', - }, - ), - migrations.CreateModel( - name='Supermasters', - fields=[ - ('ip', models.CharField(max_length=64, primary_key=True, serialize=False)), - ('nameserver', models.CharField(max_length=255)), - ('account', models.CharField(max_length=40)), - ], - options={ - 'db_table': 'supermasters', - }, - ), - migrations.CreateModel( - name='Tsigkeys', - fields=[ - ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), - ('name', models.CharField(blank=True, max_length=255, null=True)), - ('algorithm', models.CharField(blank=True, max_length=50, null=True)), - ('secret', models.CharField(blank=True, max_length=255, null=True)), - ], - options={ - 'db_table': 'tsigkeys', - }, - ), - migrations.AlterUniqueTogether( - name='tsigkeys', - unique_together=set([('name', 'algorithm')]), - ), - migrations.AlterUniqueTogether( - name='supermasters', - unique_together=set([('ip', 'nameserver')]), - ), - ] diff --git a/dockerManager/static/dockerManager/dockerManager.js b/dockerManager/static/dockerManager/dockerManager.js deleted file mode 100644 index e77e55ed6..000000000 --- a/dockerManager/static/dockerManager/dockerManager.js +++ /dev/null @@ -1,1180 +0,0 @@ -app.controller('installDocker', function ($scope, $http, $timeout, $window) { - $scope.installDockerStatus = true; - $scope.installBoxGen = true; - $scope.dockerInstallBTN = false; - - $scope.installDocker = function () { - - $scope.installDockerStatus = false; - $scope.installBoxGen = true; - $scope.dockerInstallBTN = true; - - url = "/docker/installDocker"; - - var data = {}; - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - - function ListInitialDatas(response) { - $scope.cyberPanelLoading = true; - if (response.data.status === 1) { - $scope.installBoxGen = false; - getRequestStatus(); - } - else { - new PNotify({ - title: 'Operation Failed!', - text: response.data.error_message, - type: 'error' - }); - } - - } - - function cantLoadInitialDatas(response) { - $scope.cyberPanelLoading = true; - new PNotify({ - title: 'Operation Failed!', - text: 'Could not connect to server, please refresh this page', - type: 'error' - }); - } - - }; - - function getRequestStatus() { - $scope.cyberPanelLoading = false; - - url = "/serverstatus/switchTOLSWSStatus"; - - var data = {}; - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - - function ListInitialDatas(response) { - if (response.data.abort === 0) { - $scope.requestData = response.data.requestStatus; - $timeout(getRequestStatus, 1000); - } - else { - // Notifications - $scope.cyberPanelLoading = true; - $timeout.cancel(); - $scope.requestData = response.data.requestStatus; - if (response.data.installed === 1) { - $timeout(function () { - $window.location.reload(); - }, 3000); - } - - } - } - - function cantLoadInitialDatas(response) { - $scope.cyberPanelLoading = true; - new PNotify({ - title: 'Operation Failed!', - text: 'Could not connect to server, please refresh this page', - type: 'error' - }); - - - } - - } -}); - -/* Java script code for docker management */ -var delayTimer = null; - -app.controller('dockerImages', function ($scope) { - $scope.tagList = []; - $scope.imageTag = {}; -}); - -/* Java script code to install Container */ - -app.controller('runContainer', function ($scope, $http) { - $scope.containerCreationLoading = true; - $scope.installationDetailsForm = false; - $scope.installationProgress = true; - $scope.errorMessageBox = true; - $scope.success = true; - $scope.couldNotConnect = true; - $scope.goBackDisable = true; - - $scope.volList = {}; - $scope.volListNumber = 0; - $scope.addVolField = function () { - $scope.volList[$scope.volListNumber] = {'dest': '', 'src': ''}; - $scope.volListNumber = $scope.volListNumber + 1; - console.log($scope.volList) - }; - $scope.removeVolField = function () { - delete $scope.volList[$scope.volListNumber - 1]; - $scope.volListNumber = $scope.volListNumber - 1; - }; - - $scope.addEnvField = function () { - var countEnv = Object.keys($scope.envList).length; - $scope.envList[countEnv + 1] = {'name': '', 'value': ''}; - }; - - var statusFile; - - $scope.createContainer = function () { - - $scope.containerCreationLoading = true; - $scope.installationDetailsForm = true; - $scope.installationProgress = false; - $scope.errorMessageBox = true; - $scope.success = true; - $scope.couldNotConnect = true; - $scope.goBackDisable = true; - - $scope.currentStatus = "Starting creation.."; - - url = "/docker/submitContainerCreation"; - - var name = $scope.name; - var tag = $scope.tag; - var memory = $scope.memory; - var dockerOwner = $scope.dockerOwner; - var image = $scope.image; - var numberOfEnv = Object.keys($scope.envList).length; - - var data = { - name: name, - tag: tag, - memory: memory, - dockerOwner: dockerOwner, - image: image, - envList: $scope.envList, - volList: $scope.volList - - }; - - $.each($scope.portType, function (port, protocol) { - data[port + "/" + protocol] = $scope.eport[port]; - }); - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - - function ListInitialDatas(response) { - - if (response.data.createContainerStatus === 1) { - $scope.currentStatus = "Successful. Redirecting..."; - window.location.href = "/docker/view/" + $scope.name - } - else { - - $scope.containerCreationLoading = true; - $scope.installationDetailsForm = true; - $scope.installationProgress = false; - $scope.errorMessageBox = false; - $scope.success = true; - $scope.couldNotConnect = true; - $scope.goBackDisable = false; - - $scope.errorMessage = response.data.error_message; - } - - - } - - function cantLoadInitialDatas(response) { - - $scope.containerCreationLoading = true; - $scope.installationDetailsForm = true; - $scope.installationProgress = false; - $scope.errorMessageBox = true; - $scope.success = true; - $scope.couldNotConnect = false; - $scope.goBackDisable = false; - - } - }; - $scope.goBack = function () { - $scope.containerCreationLoading = true; - $scope.installationDetailsForm = false; - $scope.installationProgress = true; - $scope.errorMessageBox = true; - $scope.success = true; - $scope.couldNotConnect = true; - $scope.goBackDisable = true; - $("#installProgress").css("width", "0%"); - }; - -}); - -/* Javascript code for listing containers */ - - -app.controller('listContainers', function ($scope, $http) { - $scope.activeLog = ""; - $scope.assignActive = ""; - - $scope.assignContainer = function (name) { - $("#assign").modal("show"); - $scope.assignActive = name; - }; - - $scope.submitAssignContainer = function () { - url = "/docker/assignContainer"; - - var data = {name: $scope.assignActive, admin: $scope.dockerOwner}; - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - $http.post(url, data, config).then(ListInitialData, cantLoadInitialData); - - function ListInitialData(response) { - - if (response.data.assignContainerStatus === 1) { - new PNotify({ - title: 'Container assigned successfully', - type: 'success' - }); - window.location.href = '/docker/listContainers'; - } - else { - new PNotify({ - title: 'Unable to complete request', - text: response.data.error_message, - type: 'error' - }); - } - $("#assign").modal("hide"); - } - - function cantLoadInitialData(response) { - console.log("not good"); - new PNotify({ - title: 'Unable to complete request', - type: 'error' - }); - $("#assign").modal("hide"); - } - }; - - $scope.delContainer = function (name, unlisted=false) { - (new PNotify({ - title: 'Confirmation Needed', - text: 'Are you sure?', - icon: 'fa fa-question-circle', - hide: false, - confirm: { - confirm: true - }, - buttons: { - closer: false, - sticker: false - }, - history: { - history: false - } - })).get().on('pnotify.confirm', function () { - $('#imageLoading').show(); - url = "/docker/delContainer"; - - var data = {name: name, unlisted: unlisted}; - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - $http.post(url, data, config).then(ListInitialData, cantLoadInitialData); - - - function ListInitialData(response) { - console.log(response); - - if (response.data.delContainerStatus === 1) { - location.reload(); - } - else if (response.data.delContainerStatus === 2) { - (new PNotify({ - title: response.data.error_message, - text: 'Delete anyway?', - icon: 'fa fa-question-circle', - hide: false, - confirm: { - confirm: true - }, - buttons: { - closer: false, - sticker: false - }, - history: { - history: false - } - })).get().on('pnotify.confirm', function () { - url = "/docker/delContainer"; - - var data = {name: name, unlisted: unlisted, force: 1}; - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - $http.post(url, data, config).then(ListInitialData, cantLoadInitialData); - - - function ListInitialData(response) { - if (response.data.delContainerStatus === 1) { - location.reload(); - } - else { - $("#listFail").fadeIn(); - $scope.errorMessage = response.data.error_message; - } - $('#imageLoading').hide(); - } - - function cantLoadInitialData(response) { - $('#imageLoading').hide(); - } - }) - } - else { - $("#listFail").fadeIn(); - $scope.errorMessage = response.data.error_message; - } - $('#imageLoading').hide(); - } - - function cantLoadInitialData(response) { - $('#imageLoading').hide(); - } - }) - } - - $scope.showLog = function (name, refresh = false) { - $scope.logs = ""; - if (refresh === false) { - $('#logs').modal('show'); - $scope.activeLog = name; - } - else { - name = $scope.activeLog; - } - $scope.logs = "Loading..."; - - url = "/docker/getContainerLogs"; - - var data = {name: name}; - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - $http.post(url, data, config).then(ListInitialData, cantLoadInitialData); - - - function ListInitialData(response) { - console.log(response); - - if (response.data.containerLogStatus === 1) { - $scope.logs = response.data.containerLog; - } - else { - new PNotify({ - title: 'Unable to complete request', - text: response.data.error_message, - type: 'error' - }); - - } - } - - function cantLoadInitialData(response) { - new PNotify({ - title: 'Unable to complete request', - type: 'error' - }); - } - }; - - url = "/docker/getContainerList"; - - var data = {page: 1}; - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - $http.post(url, data, config).then(ListInitialData, cantLoadInitialData); - - - function ListInitialData(response) { - console.log(response); - - if (response.data.listContainerStatus === 1) { - - var finalData = JSON.parse(response.data.data); - $scope.ContainerList = finalData; - console.log($scope.ContainerList); - $("#listFail").hide(); - } - else { - $("#listFail").fadeIn(); - $scope.errorMessage = response.data.error_message; - - } - } - - function cantLoadInitialData(response) { - console.log("not good"); - } - - - $scope.getFurtherContainersFromDB = function (pageNumber) { - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - var data = {page: pageNumber}; - - - dataurl = "/docker/getContainerList"; - - $http.post(dataurl, data, config).then(ListInitialData, cantLoadInitialData); - - - function ListInitialData(response) { - if (response.data.listContainerStatus === 1) { - - var finalData = JSON.parse(response.data.data); - $scope.ContainerList = finalData; - $("#listFail").hide(); - } - else { - $("#listFail").fadeIn(); - $scope.errorMessage = response.data.error_message; - console.log(response.data); - - } - } - - function cantLoadInitialData(response) { - console.log("not good"); - } - - - }; -}); - -/* Java script code for containerr home page */ - -app.controller('viewContainer', function ($scope, $http) { - $scope.cName = ""; - $scope.status = ""; - $scope.savingSettings = false; - $scope.loadingTop = false; - - $scope.recreate = function () { - (new PNotify({ - title: 'Confirmation Needed', - text: 'Are you sure?', - icon: 'fa fa-question-circle', - hide: false, - confirm: { - confirm: true - }, - buttons: { - closer: false, - sticker: false - }, - history: { - history: false - } - })).get().on('pnotify.confirm', function () { - $('#infoLoading').show(); - - url = "/docker/recreateContainer"; - var data = {name: $scope.cName}; - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - $http.post(url, data, config).then(ListInitialData, cantLoadInitialData); - function ListInitialData(response) { - if (response.data.recreateContainerStatus === 1) { - new PNotify({ - title: 'Action completed!', - text: 'Redirecting...', - type: 'success' - }); - location.reload(); - } - else { - new PNotify({ - title: 'Unable to complete request', - text: response.data.error_message, - type: 'error' - }); - - } - $('#infoLoading').hide(); - } - - function cantLoadInitialData(response) { - PNotify.error({ - title: 'Unable to complete request', - text: "Problem in connecting to server" - }); - $('#actionLoading').hide(); - } - }) - } - - $scope.addEnvField = function () { - var countEnv = Object.keys($scope.envList).length; - $scope.envList[countEnv + 1] = {'name': '', 'value': ''}; - } - - $scope.showTop = function () { - $scope.topHead = []; - $scope.topProcesses = []; - $scope.loadingTop = true; - $("#processes").modal("show"); - - url = "/docker/getContainerTop"; - var data = {name: $scope.cName}; - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - $http.post(url, data, config).then(ListInitialData, cantLoadInitialData); - function ListInitialData(response) { - if (response.data.containerTopStatus === 1) { - $scope.topHead = response.data.processes.Titles; - $scope.topProcesses = response.data.processes.Processes; - } - else { - new PNotify({ - title: 'Unable to complete request', - text: response.data.error_message, - type: 'error' - }); - - } - $scope.loadingTop = false; - } - - function cantLoadInitialData(response) { - PNotify.error({ - title: 'Unable to complete request', - text: "Problem in connecting to server" - }); - $scope.loadingTop = false; - } - - } - - $scope.cRemove = function () { - (new PNotify({ - title: 'Confirmation Needed', - text: 'Are you sure?', - icon: 'fa fa-question-circle', - hide: false, - confirm: { - confirm: true - }, - buttons: { - closer: false, - sticker: false - }, - history: { - history: false - } - })).get().on('pnotify.confirm', function () { - $('#actionLoading').show(); - - url = "/docker/delContainer"; - var data = {name: $scope.cName, unlisted: false}; - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - $http.post(url, data, config).then(ListInitialData, cantLoadInitialData); - function ListInitialData(response) { - if (response.data.delContainerStatus === 1) { - new PNotify({ - title: 'Container deleted!', - text: 'Redirecting...', - type: 'success' - }); - window.location.href = '/docker/listContainers'; - } - else { - new PNotify({ - title: 'Unable to complete request', - text: response.data.error_message, - type: 'error' - }); - } - $('#actionLoading').hide(); - } - - function cantLoadInitialData(response) { - PNotify.error({ - title: 'Unable to complete request', - text: "Problem in connecting to server" - }); - $('#actionLoading').hide(); - } - }) - } - - $scope.refreshStatus = function () { - url = "/docker/getContainerStatus"; - var data = {name: $scope.cName}; - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - $http.post(url, data, config).then(ListInitialData, cantLoadInitialData); - function ListInitialData(response) { - if (response.data.containerStatus === 1) { - console.log(response.data.status); - $scope.status = response.data.status; - } - else { - new PNotify({ - title: 'Unable to complete request', - text: response.data.error_message, - type: 'error' - }); - - } - } - - function cantLoadInitialData(response) { - PNotify.error({ - title: 'Unable to complete request', - text: "Problem in connecting to server" - }); - } - - }; - - $scope.addVolField = function () { - $scope.volList[$scope.volListNumber] = {'dest': '', 'src': ''}; - $scope.volListNumber = $scope.volListNumber + 1; - }; - $scope.removeVolField = function () { - delete $scope.volList[$scope.volListNumber - 1]; - $scope.volListNumber = $scope.volListNumber - 1; - }; - - $scope.saveSettings = function () { - $('#containerSettingLoading').show(); - url = "/docker/saveContainerSettings"; - $scope.savingSettings = true; - - var data = { - name: $scope.cName, - memory: $scope.memory, - startOnReboot: $scope.startOnReboot, - envConfirmation: $scope.envConfirmation, - envList: $scope.envList, - volList: $scope.volList - }; - - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - $http.post(url, data, config).then(ListInitialData, cantLoadInitialData); - function ListInitialData(response) { - if (response.data.saveSettingsStatus === 1) { - if ($scope.envConfirmation) { - new PNotify({ - title: 'Done. Redirecting...', - type: 'success' - }); - location.reload(); - } - else { - new PNotify({ - title: 'Settings Saved', - type: 'success' - }); - } - } - else { - new PNotify({ - title: 'Unable to complete request', - text: response.data.error_message, - type: 'error' - }); - - } - $('#containerSettingLoading').hide(); - $scope.savingSettings = false; - } - - function cantLoadInitialData(response) { - new PNotify({ - title: 'Unable to complete request', - text: "Problem in connecting to server", - type: 'error' - }); - $('#containerSettingLoading').hide(); - $scope.savingSettings = false; - } - - if ($scope.startOnReboot === true) { - $scope.rPolicy = "Yes"; - } - else { - $scope.rPolicy = "No"; - } - - } - - $scope.cAction = function (action) { - $('#actionLoading').show(); - console.log($scope.cName) - url = "/docker/doContainerAction"; - var data = {name: $scope.cName, action: action}; - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - $http.post(url, data, config).then(ListInitialData, cantLoadInitialData); - - - function ListInitialData(response) { - console.log(response); - - if (response.data.containerActionStatus === 1) { - new PNotify({ - title: 'Success!', - text: 'Action completed', - type: 'success' - }); - $scope.status = response.data.status; - $scope.refreshStatus() - } - else { - new PNotify({ - title: 'Unable to complete request', - text: response.data.error_message, - type: 'error' - }); - - } - $('#actionLoading').hide(); - } - - function cantLoadInitialData(response) { - PNotify.error({ - title: 'Unable to complete request', - text: "Problem in connecting to server" - }); - $('#actionLoading').hide(); - } - - } - - $scope.loadLogs = function (name) { - $scope.logs = "Loading..."; - - url = "/docker/getContainerLogs"; - - var data = {name: name}; - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - $http.post(url, data, config).then(ListInitialData, cantLoadInitialData); - - - function ListInitialData(response) { - console.log(response); - - if (response.data.containerLogStatus === 1) { - $scope.logs = response.data.containerLog; - } - else { - $scope.logs = response.data.error_message; - - } - } - - function cantLoadInitialData(response) { - console.log("not good"); - $scope.logs = "Error loading log"; - } - } - -}); - - -/* Java script code for docker image management */ -app.controller('manageImages', function ($scope, $http) { - $scope.tagList = []; - $scope.showingSearch = false; - $("#searchResult").hide(); - - $scope.pullImage = function (image, tag) { - function ListInitialDatas(response) { - if (response.data.installImageStatus === 1) { - new PNotify({ - title: 'Image pulled successfully', - text: 'Reloading...', - type: 'success' - }); - location.reload() - } - else { - new PNotify({ - title: 'Failed to complete request', - text: response.data.error_message, - type: 'error' - }); - } - - $('#imageLoading').hide(); - - } - - function cantLoadInitialDatas(response) { - $('#imageLoading').hide(); - new PNotify({ - title: 'Failed to complete request', - type: 'error' - }); - } - - if (image && tag) { - $('#imageLoading').show(); - - url = "/docker/installImage"; - var data = { - image: image, - tag: tag - }; - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - } - else { - new PNotify({ - title: 'Unable to complete request', - text: 'Please select a tag', - type: 'info' - }); - } - - } - - $scope.searchImages = function () { - console.log($scope.searchString); - if (!$scope.searchString) { - $("#searchResult").hide(); - } - else { - $("#searchResult").show(); - } - clearTimeout(delayTimer); - delayTimer = setTimeout(function () { - $('#imageLoading').show(); - - url = "/docker/searchImage"; - var data = { - string: $scope.searchString - }; - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - function ListInitialDatas(response) { - if (response.data.searchImageStatus === 1) { - $scope.images = response.data.matches; - console.log($scope.images) - } - else { - new PNotify({ - title: 'Failed to complete request', - text: response.data.error, - type: 'error' - }); - } - - $('#imageLoading').hide(); - - } - - function cantLoadInitialDatas(response) { - $('#imageLoading').hide(); - new PNotify({ - title: 'Failed to complete request', - type: 'error' - }); - } - }, 500); - } - - function populateTagList(image, page) { - $('imageLoading').show(); - url = "/docker/getTags" - var data = { - image: image, - page: page + 1 - }; - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - $http.post(url, data, config).then(ListInitialData, cantLoadInitialData); - - - function ListInitialData(response) { - - if (response.data.getTagsStatus === 1) { - $scope.tagList[image].splice(-1, 1); - $scope.tagList[image] = $scope.tagList[image].concat(response.data.list); - - if (response.data.next != null) { - $scope.tagList[image].push("Load more"); - } - } - else { - new PNotify({ - title: 'Unable to complete request', - text: response.data.error_message, - type: 'error' - }); - } - $('#imageLoading').hide(); - } - - function cantLoadInitialData(response) { - new PNotify({ - title: 'Unable to complete request', - text: response.data.error_message, - type: 'error' - }); - $('#imageLoading').hide(); - } - } - - $scope.runContainer = function (image) { - $("#errorMessage").hide(); - if ($scope.imageTag[image] !== undefined) { - $("#imageList").css("pointer-events", "none"); - } - else { - $("#errorMessage").show(); - $scope.errorMessage = "Please select a tag"; - } - } - - $scope.loadTags = function (event) { - var pagesloaded = $(event.target).data('pageloaded'); - var image = event.target.id; - - if (!pagesloaded) { - $scope.tagList[image] = ['Loading...']; - $(event.target).data('pageloaded', 1); - - populateTagList(image, pagesloaded); -// $("#"+image+" option:selected").prop("selected", false); - } - } - - $scope.selectTag = function () { - var image = event.target.id; - var selectedTag = $('#' + image).find(":selected").text(); - - if (selectedTag == 'Load more') { - var pagesloaded = $(event.target).data('pageloaded'); - $(event.target).data('pageloaded', pagesloaded + 1); - - populateTagList(image, pagesloaded); - } - } - - $scope.getHistory = function (counter) { - $('#imageLoading').show(); - var name = $("#" + counter).val() - - url = "/docker/getImageHistory"; - - var data = {name: name}; - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - $http.post(url, data, config).then(ListInitialData, cantLoadInitialData); - - - function ListInitialData(response) { - console.log(response); - - if (response.data.imageHistoryStatus === 1) { - $('#history').modal('show'); - $scope.historyList = response.data.history; - } - else { - new PNotify({ - title: 'Unable to complete request', - text: response.data.error_message, - type: 'error' - }); - } - $('#imageLoading').hide(); - } - - function cantLoadInitialData(response) { - new PNotify({ - title: 'Unable to complete request', - text: response.data.error_message, - type: 'error' - }); - $('#imageLoading').hide(); - } - } - - $scope.rmImage = function (counter) { - - (new PNotify({ - title: 'Confirmation Needed', - text: 'Are you sure?', - icon: 'fa fa-question-circle', - hide: false, - confirm: { - confirm: true - }, - buttons: { - closer: false, - sticker: false - }, - history: { - history: false - } - })).get().on('pnotify.confirm', function () { - $('#imageLoading').show(); - - if (counter == '0') { - var name = 0; - } - else { - var name = $("#" + counter).val() - } - - url = "/docker/removeImage"; - - var data = {name: name}; - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - $http.post(url, data, config).then(ListInitialData, cantLoadInitialData); - - - function ListInitialData(response) { - console.log(response); - - if (response.data.removeImageStatus === 1) { - new PNotify({ - title: 'Image(s) removed', - type: 'success' - }); - window.location.href = "/docker/manageImages"; - } - else { - new PNotify({ - title: 'Unable to complete request', - text: response.data.error_message, - type: 'error' - }); - } - $('#imageLoading').hide(); - } - - function cantLoadInitialData(response) { - new PNotify({ - title: 'Unable to complete request', - text: response.data.error_message, - type: 'error' - }); - $('#imageLoading').hide(); - } - - }) - } -}); \ No newline at end of file diff --git a/dockerManager/templates/dockerManager/runContainer.html b/dockerManager/templates/dockerManager/runContainer.html deleted file mode 100644 index fde7d81d5..000000000 --- a/dockerManager/templates/dockerManager/runContainer.html +++ /dev/null @@ -1,197 +0,0 @@ -{% extends "baseTemplate/index.html" %} -{% load i18n %} -{% block title %}{% trans "Run new container - CyberPanel" %}{% endblock %} -{% block content %} - -{% load static %} -{% get_current_language as LANGUAGE_CODE %} - - -
-
-

{% trans "Run Container" %}

-

{% trans "Modify parameters for your new container" %}

-
- - -
-
-

- {% trans "Container Details" %} -

-
- - -
- -
- -
- -
-
- -
- -
- -
-
- -
- -
- -
-
- -
- -
- -
-
- - -
- -
- -
-
MB
-
- - {% for port, protocol in portConfig.items %} - -
- -
- -
-
- -
-
to
-
- -
-
- - {% endfor %} - - - {% for env, value in envList.items %} - - - - {% endfor %} -
-
- -
- -
- -
-
- -
-
- -
-
- -

- -
- -
-
- -
-
-
- -
-
- -
-
-
- -
-
-
- -
- -
- -

- -
- -
- - -
-
- - - -
- -
- -
-

{$ currentStatus $}

-
- -
-

{% trans "Error message:" %} {$ errorMessage $}

-
- -
-

{% trans "Container succesfully created." %}

-
- - - -
-

{% trans "Could not connect to server. Please refresh this page." %}

-
- - -
-
- -
- -
- -
-
- - -
- -
-
-
- - - -
- - -{% endblock %} \ No newline at end of file diff --git a/emailMarketing/migrations/0001_initial.py b/emailMarketing/migrations/0001_initial.py deleted file mode 100644 index 9c0000b19..000000000 --- a/emailMarketing/migrations/0001_initial.py +++ /dev/null @@ -1,87 +0,0 @@ -# -*- coding: utf-8 -*- -# Generated by Django 1.11 on 2019-01-07 12:43 -from __future__ import unicode_literals - -from django.db import migrations, models -import django.db.models.deletion - - -class Migration(migrations.Migration): - - initial = True - - dependencies = [ - ('websiteFunctions', '0001_initial'), - ('loginSystem', '0001_initial'), - ] - - operations = [ - migrations.CreateModel( - name='EmailJobs', - fields=[ - ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), - ('date', models.CharField(max_length=200)), - ('host', models.CharField(max_length=1000)), - ('totalEmails', models.IntegerField()), - ('sent', models.IntegerField()), - ('failed', models.IntegerField()), - ], - ), - migrations.CreateModel( - name='EmailLists', - fields=[ - ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), - ('listName', models.CharField(max_length=50, unique=True)), - ('dateCreated', models.CharField(max_length=200)), - ('owner', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, to='websiteFunctions.Websites')), - ], - ), - migrations.CreateModel( - name='EmailMarketing', - fields=[ - ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), - ('userName', models.CharField(max_length=50, unique=True)), - ], - ), - migrations.CreateModel( - name='EmailsInList', - fields=[ - ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), - ('email', models.CharField(max_length=50)), - ('firstName', models.CharField(default='', max_length=20)), - ('lastName', models.CharField(default='', max_length=20)), - ('verificationStatus', models.CharField(max_length=100)), - ('dateCreated', models.CharField(max_length=200)), - ('owner', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='emailMarketing.EmailLists')), - ], - ), - migrations.CreateModel( - name='EmailTemplate', - fields=[ - ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), - ('name', models.CharField(max_length=100, unique=True)), - ('subject', models.CharField(max_length=1000)), - ('fromName', models.CharField(max_length=100)), - ('fromEmail', models.CharField(max_length=150)), - ('replyTo', models.CharField(max_length=150)), - ('emailMessage', models.CharField(max_length=3000000)), - ('owner', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='loginSystem.Administrator')), - ], - ), - migrations.CreateModel( - name='SMTPHosts', - fields=[ - ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), - ('host', models.CharField(max_length=150, unique=True)), - ('port', models.CharField(max_length=10)), - ('userName', models.CharField(max_length=50)), - ('password', models.CharField(max_length=50)), - ('owner', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='loginSystem.Administrator')), - ], - ), - migrations.AddField( - model_name='emailjobs', - name='owner', - field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='emailMarketing.EmailTemplate'), - ), - ] diff --git a/emailPremium/migrations/0001_initial.py b/emailPremium/migrations/0001_initial.py deleted file mode 100644 index 343d614e1..000000000 --- a/emailPremium/migrations/0001_initial.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Generated by Django 1.11 on 2019-01-07 12:43 -from __future__ import unicode_literals - -from django.db import migrations, models -import django.db.models.deletion - - -class Migration(migrations.Migration): - - initial = True - - dependencies = [ - ('mailServer', '0001_initial'), - ] - - operations = [ - migrations.CreateModel( - name='DomainLimits', - fields=[ - ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), - ('limitStatus', models.IntegerField(default=0)), - ('monthlyLimit', models.IntegerField(default=10000)), - ('monthlyUsed', models.IntegerField(default=0)), - ('domain', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='mailServer.Domains')), - ], - ), - migrations.CreateModel( - name='EmailLimits', - fields=[ - ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), - ('limitStatus', models.IntegerField(default=0)), - ('monthlyLimits', models.IntegerField(default=2000)), - ('monthlyUsed', models.IntegerField(default=0)), - ('hourlyLimit', models.IntegerField(default=50)), - ('hourlyUsed', models.IntegerField(default=0)), - ('emailLogs', models.IntegerField(default=0)), - ('email', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='mailServer.EUsers')), - ], - ), - migrations.CreateModel( - name='EmailLogs', - fields=[ - ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), - ('destination', models.CharField(max_length=200)), - ('timeStamp', models.CharField(max_length=200)), - ('email', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='mailServer.EUsers')), - ], - ), - ] diff --git a/firewall/migrations/0001_initial.py b/firewall/migrations/0001_initial.py deleted file mode 100644 index d3899c19d..000000000 --- a/firewall/migrations/0001_initial.py +++ /dev/null @@ -1,26 +0,0 @@ -# -*- coding: utf-8 -*- -# Generated by Django 1.11 on 2019-01-07 12:43 -from __future__ import unicode_literals - -from django.db import migrations, models - - -class Migration(migrations.Migration): - - initial = True - - dependencies = [ - ] - - operations = [ - migrations.CreateModel( - name='FirewallRules', - fields=[ - ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), - ('name', models.CharField(max_length=32, unique=True)), - ('proto', models.CharField(max_length=10)), - ('port', models.CharField(max_length=25)), - ('ipAddress', models.CharField(default=b'0.0.0.0/0', max_length=30)), - ], - ), - ] diff --git a/ftp/migrations/0001_initial.py b/ftp/migrations/0001_initial.py deleted file mode 100644 index a611f1f23..000000000 --- a/ftp/migrations/0001_initial.py +++ /dev/null @@ -1,39 +0,0 @@ -# -*- coding: utf-8 -*- -# Generated by Django 1.11 on 2019-01-07 12:43 -from __future__ import unicode_literals - -from django.db import migrations, models -import django.db.models.deletion - - -class Migration(migrations.Migration): - - initial = True - - dependencies = [ - ('websiteFunctions', '0001_initial'), - ] - - operations = [ - migrations.CreateModel( - name='Users', - fields=[ - ('id', models.AutoField(db_column=b'ID', primary_key=True, serialize=False)), - ('user', models.CharField(db_column=b'User', max_length=32, unique=True)), - ('password', models.CharField(db_column=b'Password', max_length=64)), - ('uid', models.IntegerField(db_column=b'Uid')), - ('gid', models.IntegerField(db_column=b'Gid')), - ('dir', models.CharField(db_column=b'Dir', max_length=255)), - ('quotasize', models.IntegerField(db_column=b'QuotaSize')), - ('status', models.CharField(db_column=b'Status', max_length=1)), - ('ulbandwidth', models.IntegerField(db_column=b'ULBandwidth')), - ('dlbandwidth', models.IntegerField(db_column=b'DLBandwidth')), - ('date', models.DateField(db_column=b'Date')), - ('lastmodif', models.CharField(db_column=b'LastModif', max_length=255)), - ('domain', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='websiteFunctions.Websites')), - ], - options={ - 'db_table': 'users', - }, - ), - ] diff --git a/loginSystem/migrations/0001_initial.py b/loginSystem/migrations/0001_initial.py deleted file mode 100644 index e03153842..000000000 --- a/loginSystem/migrations/0001_initial.py +++ /dev/null @@ -1,76 +0,0 @@ -# -*- coding: utf-8 -*- -# Generated by Django 1.11 on 2019-01-07 12:43 -from __future__ import unicode_literals - -from django.db import migrations, models -import django.db.models.deletion - - -class Migration(migrations.Migration): - - initial = True - - dependencies = [ - ] - - operations = [ - migrations.CreateModel( - name='ACL', - fields=[ - ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), - ('name', models.CharField(max_length=50, unique=True)), - ('adminStatus', models.IntegerField(default=0)), - ('versionManagement', models.IntegerField(default=0)), - ('createNewUser', models.IntegerField(default=0)), - ('deleteUser', models.IntegerField(default=0)), - ('resellerCenter', models.IntegerField(default=0)), - ('changeUserACL', models.IntegerField(default=0)), - ('createWebsite', models.IntegerField(default=0)), - ('modifyWebsite', models.IntegerField(default=0)), - ('suspendWebsite', models.IntegerField(default=0)), - ('deleteWebsite', models.IntegerField(default=0)), - ('createPackage', models.IntegerField(default=0)), - ('deletePackage', models.IntegerField(default=0)), - ('modifyPackage', models.IntegerField(default=0)), - ('createDatabase', models.IntegerField(default=1)), - ('deleteDatabase', models.IntegerField(default=1)), - ('listDatabases', models.IntegerField(default=1)), - ('createNameServer', models.IntegerField(default=0)), - ('createDNSZone', models.IntegerField(default=1)), - ('deleteZone', models.IntegerField(default=1)), - ('addDeleteRecords', models.IntegerField(default=1)), - ('createEmail', models.IntegerField(default=1)), - ('deleteEmail', models.IntegerField(default=1)), - ('emailForwarding', models.IntegerField(default=1)), - ('changeEmailPassword', models.IntegerField(default=1)), - ('dkimManager', models.IntegerField(default=1)), - ('createFTPAccount', models.IntegerField(default=1)), - ('deleteFTPAccount', models.IntegerField(default=1)), - ('listFTPAccounts', models.IntegerField(default=1)), - ('createBackup', models.IntegerField(default=1)), - ('restoreBackup', models.IntegerField(default=0)), - ('addDeleteDestinations', models.IntegerField(default=0)), - ('scheDuleBackups', models.IntegerField(default=0)), - ('remoteBackups', models.IntegerField(default=0)), - ('manageSSL', models.IntegerField(default=1)), - ('hostnameSSL', models.IntegerField(default=0)), - ('mailServerSSL', models.IntegerField(default=0)), - ], - ), - migrations.CreateModel( - name='Administrator', - fields=[ - ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), - ('userName', models.CharField(max_length=50, unique=True)), - ('password', models.CharField(max_length=200)), - ('firstName', models.CharField(default='None', max_length=20)), - ('lastName', models.CharField(default='None', max_length=20)), - ('email', models.CharField(max_length=50)), - ('type', models.IntegerField()), - ('owner', models.IntegerField(default=1)), - ('token', models.CharField(default='None', max_length=500)), - ('initWebsitesLimit', models.IntegerField(default=0)), - ('acl', models.ForeignKey(default=1, on_delete=django.db.models.deletion.CASCADE, to='loginSystem.ACL')), - ], - ), - ] diff --git a/mailServer/migrations/0001_initial.py b/mailServer/migrations/0001_initial.py deleted file mode 100644 index 1fce24d41..000000000 --- a/mailServer/migrations/0001_initial.py +++ /dev/null @@ -1,61 +0,0 @@ -# -*- coding: utf-8 -*- -# Generated by Django 1.11 on 2019-01-07 12:43 -from __future__ import unicode_literals - -from django.db import migrations, models -import django.db.models.deletion - - -class Migration(migrations.Migration): - - initial = True - - dependencies = [ - ('websiteFunctions', '0001_initial'), - ] - - operations = [ - migrations.CreateModel( - name='Domains', - fields=[ - ('domain', models.CharField(max_length=50, primary_key=True, serialize=False)), - ('domainOwner', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='websiteFunctions.Websites')), - ], - options={ - 'db_table': 'e_domains', - }, - ), - migrations.CreateModel( - name='EUsers', - fields=[ - ('email', models.CharField(max_length=80, primary_key=True, serialize=False)), - ('password', models.CharField(max_length=20)), - ('emailOwner', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='mailServer.Domains')), - ], - options={ - 'db_table': 'e_users', - }, - ), - migrations.CreateModel( - name='Forwardings', - fields=[ - ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), - ('source', models.CharField(max_length=80)), - ('destination', models.TextField()), - ], - options={ - 'db_table': 'e_forwardings', - }, - ), - migrations.CreateModel( - name='Transport', - fields=[ - ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), - ('domain', models.CharField(max_length=128, unique=True)), - ('transport', models.CharField(max_length=128)), - ], - options={ - 'db_table': 'e_transport', - }, - ), - ] diff --git a/managePHP/migrations/0001_initial.py b/managePHP/migrations/0001_initial.py deleted file mode 100644 index c66f5ae7a..000000000 --- a/managePHP/migrations/0001_initial.py +++ /dev/null @@ -1,38 +0,0 @@ -# -*- coding: utf-8 -*- -# Generated by Django 1.11 on 2019-01-07 12:43 -from __future__ import unicode_literals - -from django.db import migrations, models -import django.db.models.deletion - - -class Migration(migrations.Migration): - - initial = True - - dependencies = [ - ] - - operations = [ - migrations.CreateModel( - name='installedPackages', - fields=[ - ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), - ('extensionName', models.CharField(max_length=50)), - ('description', models.CharField(max_length=255)), - ('status', models.IntegerField()), - ], - ), - migrations.CreateModel( - name='PHP', - fields=[ - ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), - ('phpVers', models.CharField(max_length=5, unique=True)), - ], - ), - migrations.AddField( - model_name='installedpackages', - name='phpVers', - field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='managePHP.PHP'), - ), - ] diff --git a/packages/migrations/0001_initial.py b/packages/migrations/0001_initial.py deleted file mode 100644 index a5eb96042..000000000 --- a/packages/migrations/0001_initial.py +++ /dev/null @@ -1,32 +0,0 @@ -# -*- coding: utf-8 -*- -# Generated by Django 1.11 on 2019-01-07 12:43 -from __future__ import unicode_literals - -from django.db import migrations, models -import django.db.models.deletion - - -class Migration(migrations.Migration): - - initial = True - - dependencies = [ - ('loginSystem', '0001_initial'), - ] - - operations = [ - migrations.CreateModel( - name='Package', - fields=[ - ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), - ('packageName', models.CharField(max_length=50, unique=True)), - ('diskSpace', models.IntegerField()), - ('bandwidth', models.IntegerField()), - ('emailAccounts', models.IntegerField(null=True)), - ('dataBases', models.IntegerField(default=0)), - ('ftpAccounts', models.IntegerField(default=0)), - ('allowedDomains', models.IntegerField(default=0)), - ('admin', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='loginSystem.Administrator')), - ], - ), - ] diff --git a/plogical/container.py b/plogical/container.py deleted file mode 100644 index 58c5b8b2e..000000000 --- a/plogical/container.py +++ /dev/null @@ -1,1078 +0,0 @@ -#!/usr/local/CyberCP/bin/python2 -from __future__ import division -import os -import os.path -import sys -import django -import mimetypes - -sys.path.append('/usr/local/CyberCP') -os.environ.setdefault("DJANGO_SETTINGS_MODULE", "CyberCP.settings") -django.setup() -import json -from acl import ACLManager -import CyberCPLogFileWriter as logging -from django.shortcuts import HttpResponse, render -from loginSystem.models import Administrator, ACL -import subprocess -import shlex -import time -from dockerManager.models import Containers -from math import ceil -import docker -import docker.utils -import requests -from processUtilities import ProcessUtilities -from serverStatus.serverStatusUtil import ServerStatusUtil -import threading as multi -from mailUtilities import mailUtilities - - -# Use default socket to connect -class ContainerManager(multi.Thread): - - def __init__(self, name=None, function=None): - multi.Thread.__init__(self) - self.name = name - self.function = function - - def run(self): - try: - if self.function == 'submitInstallDocker': - self.submitInstallDocker() - elif self.function == 'restartGunicorn': - command = 'sudo systemctl restart gunicorn.socket' - ProcessUtilities.executioner(command) - except BaseException, msg: - logging.CyberCPLogFileWriter.writeToFile( str(msg) + ' [ContainerManager.run]') - - @staticmethod - def executioner(command, statusFile): - try: - res = subprocess.call(shlex.split(command), stdout=statusFile, stderr=statusFile) - if res == 1: - return 0 - else: - return 1 - except BaseException, msg: - logging.CyberCPLogFileWriter.writeToFile(str(msg)) - return 0 - - def submitInstallDocker(self): - try: - currentACL = ACLManager.loadedACL(self.name) - - if ACLManager.currentContextPermission(currentACL, 'createContainer') == 0: - return ACLManager.loadError() - - - mailUtilities.checkHome() - - statusFile = open(ServerStatusUtil.lswsInstallStatusPath, 'w') - - logging.CyberCPLogFileWriter.statusWriter(ServerStatusUtil.lswsInstallStatusPath, - "Starting Docker Installation..\n", 1) - - if ProcessUtilities.decideDistro() == ProcessUtilities.centos: - command = 'sudo yum install -y docker' - else: - command = 'sudo DEBIAN_FRONTEND=noninteractive apt-get install -y docker.io' - - if not ServerStatusUtil.executioner(command, statusFile): - logging.CyberCPLogFileWriter.statusWriter(ServerStatusUtil.lswsInstallStatusPath, - "Failed to install Docker. [404]\n", 1) - return 0 - - - command = 'sudo groupadd docker' - ServerStatusUtil.executioner(command, statusFile) - - command = 'sudo usermod -aG docker cyberpanel' - ServerStatusUtil.executioner(command, statusFile) - - command = 'sudo systemctl enable docker' - ServerStatusUtil.executioner(command, statusFile) - - command = 'sudo systemctl start docker' - ServerStatusUtil.executioner(command, statusFile) - - logging.CyberCPLogFileWriter.statusWriter(ServerStatusUtil.lswsInstallStatusPath, - "Docker successfully installed.[200]\n", 1) - - time.sleep(2) - - cm = ContainerManager(self.name, 'restartGunicorn') - cm.start() - - except BaseException, msg: - logging.CyberCPLogFileWriter.statusWriter(ServerStatusUtil.lswsInstallStatusPath, str(msg) + ' [404].', 1) - - def createContainer(self, request=None, userID=None, data=None): - try: - admin = Administrator.objects.get(pk=userID) - if admin.acl.adminStatus != 1: - return ACLManager.loadError() - - client = docker.from_env() - dockerAPI = docker.APIClient() - - adminNames = ACLManager.loadAllUsers(userID) - tag = request.GET.get('tag') - image = request.GET.get('image') - tag = tag.split(" (")[0] - - if "/" in image: - name = image.split("/")[0] + "." + image.split("/")[1] - else: - name = image - - try: - inspectImage = dockerAPI.inspect_image(image + ":" + tag) - except docker.errors.ImageNotFound: - val = request.session['userID'] - admin = Administrator.objects.get(pk=val) - return render(request, 'dockerManager/images.html', {"type": admin.type, - 'image': image, - 'tag': tag}) - - envList = {}; - if 'Env' in inspectImage['Config']: - for item in inspectImage['Config']['Env']: - if '=' in item: - splitedItem = item.split('=', 1) - print splitedItem - envList[splitedItem[0]] = splitedItem[1] - else: - envList[item] = "" - - portConfig = {}; - if 'ExposedPorts' in inspectImage['Config']: - for item in inspectImage['Config']['ExposedPorts']: - portDef = item.split('/') - portConfig[portDef[0]] = portDef[1] - - if image is None or image is '' or tag is None or tag is '': - return redirect(loadImages) - - Data = {"ownerList": adminNames, "image": image, "name": name, "tag": tag, "portConfig": portConfig, - "envList": envList} - - return render(request, 'dockerManager/runContainer.html', Data) - - except BaseException, msg: - return HttpResponse(str(msg)) - - def loadContainerHome(self, request=None, userID=None, data=None): - name = self.name - - if ACLManager.checkContainerOwnership(name, userID) != 1: - return ACLManager.loadError() - - client = docker.from_env() - dockerAPI = docker.APIClient() - try: - container = client.containers.get(name) - except docker.errors.NotFound as err: - return HttpResponse("Container not found") - - data = {} - con = Containers.objects.get(name=name) - data['name'] = name - data['image'] = con.image + ":" + con.tag - data['ports'] = json.loads(con.ports) - data['cid'] = con.cid - data['envList'] = json.loads(con.env) - print data['envList'] - - stats = container.stats(decode=False, stream=False) - logs = container.logs(stream=True) - - data['status'] = container.status - data['memoryLimit'] = con.memory - if con.startOnReboot == 1: - data['startOnReboot'] = 'true' - data['restartPolicy'] = "Yes" - else: - data['startOnReboot'] = 'false' - data['restartPolicy'] = "No" - - if 'usage' in stats['memory_stats']: - # Calculate Usage - # Source: https://github.com/docker/docker/blob/28a7577a029780e4533faf3d057ec9f6c7a10948/api/client/stats.go#L309 - data['memoryUsage'] = (stats['memory_stats']['usage'] / stats['memory_stats']['limit']) * 100 - - cpu_count = len(stats["cpu_stats"]["cpu_usage"]["percpu_usage"]) - data['cpuUsage'] = 0.0 - cpu_delta = float(stats["cpu_stats"]["cpu_usage"]["total_usage"]) - \ - float(stats["precpu_stats"]["cpu_usage"]["total_usage"]) - system_delta = float(stats["cpu_stats"]["system_cpu_usage"]) - \ - float(stats["precpu_stats"]["system_cpu_usage"]) - if system_delta > 0.0: - data['cpuUsage'] = round(cpu_delta / system_delta * 100.0 * cpu_count, 3) - else: - data['memoryUsage'] = 0 - data['cpuUsage'] = 0 - - return render(request, 'dockerManager/viewContainer.html', data) - - def listContainers(self, request=None, userID=None, data=None): - try: - client = docker.from_env() - dockerAPI = docker.APIClient() - - currentACL = ACLManager.loadedACL(userID) - containers = ACLManager.findAllContainers(currentACL, userID) - - allContainers = client.containers.list() - containersList = [] - showUnlistedContainer = True - - # TODO: Add condition to show unlisted Containers only if user has admin level access - - unlistedContainers = [] - for container in allContainers: - if container.name not in containers: - unlistedContainers.append(container) - - if not unlistedContainers: - showUnlistedContainer = False - - adminNames = ACLManager.loadAllUsers(userID) - - pages = float(len(containers)) / float(10) - pagination = [] - - if pages <= 1.0: - pages = 1 - pagination.append('
  • ') - else: - pages = ceil(pages) - finalPages = int(pages) + 1 - - for i in range(1, finalPages): - pagination.append('
  • ' + str(i) + '
  • ') - - return render(request, 'dockerManager/listContainers.html', {"pagination": pagination, - "unlistedContainers": unlistedContainers, - "adminNames": adminNames, - "showUnlistedContainer": showUnlistedContainer}) - except BaseException, msg: - return HttpResponse(str(msg)) - - def getContainerLogs(self, userID=None, data=None): - try: - name = data['name'] - - # Check if container is registered in database or unlisted - if Containers.objects.filter(name=name).exists(): - if ACLManager.checkContainerOwnership(name, userID) != 1: - return ACLManager.loadErrorJson('containerLogStatus', 0) - - client = docker.from_env() - dockerAPI = docker.APIClient() - - container = client.containers.get(name) - logs = container.logs() - - data_ret = {'containerLogStatus': 1, 'containerLog': logs, 'error_message': "None"} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - - except BaseException, msg: - data_ret = {'containerLogStatus': 0, 'containerLog': 'Error', 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def submitContainerCreation(self, userID=None, data=None): - try: - - admin = Administrator.objects.get(pk=userID) - if admin.acl.adminStatus != 1: - return ACLManager.loadErrorJson('createContainerStatus', 0) - - client = docker.from_env() - dockerAPI = docker.APIClient() - - name = data['name'] - image = data['image'] - tag = data['tag'] - dockerOwner = data['dockerOwner'] - memory = data['memory'] - envList = data['envList'] - - inspectImage = dockerAPI.inspect_image(image + ":" + tag) - portConfig = {} - - # Formatting envList for usage - envDict = {} - for key, value in envList.iteritems(): - if (value['name'] != '') or (value['value'] != ''): - envDict[value['name']] = value['value'] - - if 'ExposedPorts' in inspectImage['Config']: - for item in inspectImage['Config']['ExposedPorts']: - # Do not allow priviledged port numbers - if int(data[item]) < 1024 or int(data[item]) > 65535: - data_ret = {'createContainerStatus': 0, 'error_message': "Choose port between 1024 and 65535"} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - portConfig[item] = data[item] - - ## Create Configurations - admin = Administrator.objects.get(userName=dockerOwner) - - containerArgs = {'image': image + ":" + tag, - 'detach': True, - 'name': name, - 'ports': portConfig, - 'publish_all_ports': True, - 'environment': envDict} - - containerArgs['mem_limit'] = memory * 1048576; # Converts MB to bytes ( 0 * x = 0 for unlimited memory) - - try: - container = client.containers.create(**containerArgs) - except Exception as err: - if "port is already allocated" in err: # We need to delete container if port is not available - print "Deleting container" - container.remove(force=True) - data_ret = {'createContainerStatus': 0, 'error_message': str(err)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - con = Containers(admin=admin, - name=name, - tag=tag, - image=image, - memory=memory, - ports=json.dumps(portConfig), - env=json.dumps(envDict), - cid=container.id) - - con.save() - - data_ret = {'createContainerStatus': 1, 'error_message': "None"} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - - except BaseException, msg: - data_ret = {'createContainerStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def submitInstallImage(self, userID=None, data=None): - try: - - admin = Administrator.objects.get(pk=userID) - if admin.acl.adminStatus != 1: - return ACLManager.loadErrorJson('installImageStatus', 0) - - client = docker.from_env() - dockerAPI = docker.APIClient() - - image = data['image'] - tag = data['tag'] - - try: - inspectImage = dockerAPI.inspect_image(image + ":" + tag) - data_ret = {'installImageStatus': 0, 'error_message': "Image already installed"} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - except docker.errors.ImageNotFound: - pass - - try: - image = client.images.pull(image, tag=tag) - print image.id - except docker.errors.APIError as msg: - data_ret = {'installImageStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - data_ret = {'installImageStatus': 1, 'error_message': "None"} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - - except BaseException, msg: - data_ret = {'installImageStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def submitContainerDeletion(self, userID=None, data=None, called=False): - try: - name = data['name'] - # Check if container is registered in database or unlisted - if Containers.objects.filter(name=name).exists(): - if ACLManager.checkContainerOwnership(name, userID) != 1: - if called: - return 'Permission error' - else: - return ACLManager.loadErrorJson('websiteDeleteStatus', 0) - - client = docker.from_env() - dockerAPI = docker.APIClient() - - unlisted = data['unlisted'] - - if 'force' in data: - force = True - else: - force = False - - if not unlisted: - containerOBJ = Containers.objects.get(name=name) - - if not force: - try: - container = client.containers.get(name) - except docker.errors.NotFound as err: - if called: - return 'Container does not exist' - else: - data_ret = {'delContainerStatus': 2, 'error_message': 'Container does not exist'} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - try: - container.stop() # Stop container - container.kill() # INCASE graceful stop doesn't work - except: - pass - - try: - container.remove() # Finally remove container - except docker.errors.APIError as err: - data_ret = {'delContainerStatus': 0, 'error_message': str(err)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - except: - if called: - return "Unknown" - else: - data_ret = {'delContainerStatus': 0, 'error_message': 'Unknown error'} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - if not unlisted and not called: - containerOBJ.delete() - - if called: - return 0 - else: - data_ret = {'delContainerStatus': 1, 'error_message': "None"} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - except BaseException, msg: - if called: - return str(msg) - else: - data_ret = {'delContainerStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def getContainerList(self, userID=None, data=None): - try: - admin = Administrator.objects.get(pk=userID) - if admin.acl.adminStatus != 1: - return ACLManager.loadErrorJson('listContainerStatus', 0) - - currentACL = ACLManager.loadedACL(userID) - pageNumber = int(data['page']) - json_data = self.findContainersJson(currentACL, userID, pageNumber) - final_dic = {'listContainerStatus': 1, 'error_message': "None", "data": json_data} - final_json = json.dumps(final_dic) - return HttpResponse(final_json) - except BaseException, msg: - dic = {'listContainerStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(dic) - return HttpResponse(json_data) - - def findContainersJson(self, currentACL, userID, pageNumber): - admin = Administrator.objects.get(pk=userID) - if admin.acl.adminStatus != 1: - return ACLManager.loadError() - - finalPageNumber = ((pageNumber * 10)) - 10 - endPageNumber = finalPageNumber + 10 - containers = ACLManager.findContainersObjects(currentACL, userID)[finalPageNumber:endPageNumber] - - json_data = "[" - checker = 0 - - for items in containers: - dic = {'name': items.name, 'admin': items.admin.userName, 'tag': items.tag, 'image': items.image} - - if checker == 0: - json_data = json_data + json.dumps(dic) - checker = 1 - else: - json_data = json_data + ',' + json.dumps(dic) - - json_data = json_data + ']' - - return json_data - - def doContainerAction(self, userID=None, data=None): - try: - - name = data['name'] - if ACLManager.checkContainerOwnership(name, userID) != 1: - return ACLManager.loadErrorJson('containerActionStatus', 0) - - client = docker.from_env() - dockerAPI = docker.APIClient() - - action = data['action'] - try: - container = client.containers.get(name) - except docker.errors.NotFound as err: - data_ret = {'containerActionStatus': 0, 'error_message': 'Container does not exist'} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - except: - data_ret = {'containerActionStatus': 0, 'error_message': 'Unknown'} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - try: - if action == 'start': - container.start() - elif action == 'stop': - container.stop() - elif action == 'restart': - container.restart() - else: - data_ret = {'containerActionStatus': 0, 'error_message': 'Unknown Action'} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - except docker.errors.APIError as err: - data_ret = {'containerActionStatus': 0, 'error_message': str(err)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - time.sleep(3) # Wait 3 seconds for container to finish starting/stopping/restarting - status = container.status - data_ret = {'containerActionStatus': 1, 'error_message': 'None', 'status': status} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - except BaseException, msg: - data_ret = {'containerActionStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def getContainerStatus(self, userID=None, data=None): - try: - name = data['name'] - if ACLManager.checkContainerOwnership(name, userID) != 1: - return ACLManager.loadErrorJson('containerStatus', 0) - - client = docker.from_env() - dockerAPI = docker.APIClient() - - try: - container = client.containers.get(name) - except docker.errors.NotFound as err: - data_ret = {'containerStatus': 0, 'error_message': 'Container does not exist'} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - except: - data_ret = {'containerStatus': 0, 'error_message': 'Unknown'} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - status = container.status - data_ret = {'containerStatus': 1, 'error_message': 'None', 'status': status} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - except BaseException, msg: - data_ret = {'containerStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def exportContainer(self, request=None, userID=None, data=None): - try: - name = request.GET.get('name') - if ACLManager.checkContainerOwnership(name, userID) != 1: - return ACLManager.loadErrorJson('containerStatus', 0) - - client = docker.from_env() - dockerAPI = docker.APIClient() - - try: - container = client.containers.get(name) - except docker.errors.NotFound as err: - data_ret = {'containerStatus': 0, 'error_message': 'Container does not exist'} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - except: - data_ret = {'containerStatus': 0, 'error_message': 'Unknown'} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - eFile = container.export() # Export with default chunk size - response = HttpResponse(eFile, content_type='application/force-download') - response['Content-Disposition'] = 'attachment; filename="' + name + '.tar"' - return response - - except BaseException, msg: - data_ret = {'containerStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def getContainerTop(self, userID=None, data=None): - try: - name = data['name'] - if ACLManager.checkContainerOwnership(name, userID) != 1: - return ACLManager.loadErrorJson('containerTopStatus', 0) - - client = docker.from_env() - dockerAPI = docker.APIClient() - - try: - container = client.containers.get(name) - except docker.errors.NotFound as err: - data_ret = {'containerTopStatus': 0, 'error_message': 'Container does not exist'} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - except: - data_ret = {'containerTopStatus': 0, 'error_message': 'Unknown'} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - try: - top = container.top() - except docker.errors.APIError as err: - data_ret = {'containerTopStatus': 0, 'error_message': str(err)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - data_ret = {'containerTopStatus': 1, 'error_message': 'None', 'processes': top} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - except BaseException, msg: - data_ret = {'containerTopStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def assignContainer(self, userID=None, data=None): - try: - # Todo: add check only for super user i.e. main admin - admin = Administrator.objects.get(pk=userID) - if admin.acl.adminStatus != 1: - return ACLManager.loadErrorJson('assignContainerStatus', 0) - - client = docker.from_env() - dockerAPI = docker.APIClient() - - name = data['name'] - dockerOwner = data['admin'] - - admin = Administrator.objects.get(userName=dockerOwner) - - try: - container = client.containers.get(name) - except docker.errors.NotFound as err: - data_ret = {'assignContainerStatus': 0, 'error_message': 'Container does not exist'} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - except: - data_ret = {'assignContainerStatus': 0, 'error_message': 'Unknown'} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - con = Containers(admin=admin, - name=name, - cid=container.id) - - con.save() - - data_ret = {'assignContainerStatus': 1, 'error_message': 'None'} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - except BaseException, msg: - data_ret = {'assignContainerStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def searchImage(self, userID=None, data=None): - try: - admin = Administrator.objects.get(pk=userID) - if admin.acl.adminStatus != 1: - return ACLManager.loadErrorJson('searchImageStatus', 0) - - client = docker.from_env() - dockerAPI = docker.APIClient() - - string = data['string'] - try: - matches = client.images.search(term=string) - except docker.errors.APIError as err: - data_ret = {'searchImageStatus': 0, 'error_message': str(err)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - except: - data_ret = {'searchImageStatus': 0, 'error_message': 'Unknown'} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - print json.dumps(matches) - - for image in matches: - if "/" in image['name']: - image['name2'] = image['name'].split("/")[0] + ":" + image['name'].split("/")[1] - else: - image['name2'] = image['name'] - - data_ret = {'searchImageStatus': 1, 'error_message': 'None', 'matches': matches} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - except BaseException, msg: - data_ret = {'searchImageStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def images(self, request=None, userID=None, data=None): - try: - admin = Administrator.objects.get(pk=userID) - if admin.acl.adminStatus != 1: - return ACLManager.loadError() - - client = docker.from_env() - dockerAPI = docker.APIClient() - - try: - imageList = client.images.list() - except docker.errors.APIError as err: - return HttpResponse(str(err)) - - images = {} - names = [] - - for image in imageList: - name = image.attrs['RepoTags'][0].split(":")[0] - if "/" in name: - name2 = "" - for item in name.split("/"): - name2 += ":" + item - else: - name2 = name - - tags = [] - for tag in image.tags: - getTag = tag.split(":") - if len(getTag) == 2: - tags.append(getTag[1]) - print tags - if name in names: - images[name]['tags'].extend(tags) - else: - names.append(name) - images[name] = {"name": name, - "name2": name2, - "tags": tags} - print "======" - print images - return render(request, 'dockerManager/images.html', {"images": images, "test": ''}) - - except BaseException, msg: - return HttpResponse(str(msg)) - - def manageImages(self, request=None, userID=None, data=None): - try: - admin = Administrator.objects.get(pk=userID) - if admin.acl.adminStatus != 1: - return ACLManager.loadError() - - client = docker.from_env() - dockerAPI = docker.APIClient() - - imageList = client.images.list() - - images = {} - names = [] - - for image in imageList: - name = image.attrs['RepoTags'][0].split(":")[0] - if name in names: - images[name]['tags'].extend(image.tags) - else: - names.append(name) - tags = [] - images[name] = {"name": name, - "tags": image.tags} - return render(request, 'dockerManager/manageImages.html', {"images": images}) - - except BaseException, msg: - return HttpResponse(str(msg)) - - def getImageHistory(self, userID=None, data=None): - try: - - name = data['name'] - - client = docker.from_env() - dockerAPI = docker.APIClient() - - try: - image = client.images.get(name) - except docker.errors.APIError as err: - data_ret = {'imageHistoryStatus': 0, 'error_message': str(err)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - except: - data_ret = {'imageHistoryStatus': 0, 'error_message': 'Unknown'} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - data_ret = {'imageHistoryStatus': 1, 'error_message': 'None', 'history': image.history()} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - except BaseException, msg: - data_ret = {'imageHistoryStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def removeImage(self, userID=None, data=None): - try: - admin = Administrator.objects.get(pk=userID) - - if admin.acl.adminStatus != 1: - return ACLManager.loadError() - - client = docker.from_env() - dockerAPI = docker.APIClient() - - name = data['name'] - try: - if name == 0: - action = client.images.prune() - else: - action = client.images.remove(name) - print action - except docker.errors.APIError as err: - data_ret = {'removeImageStatus': 0, 'error_message': str(err)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - except: - data_ret = {'removeImageStatus': 0, 'error_message': 'Unknown'} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - data_ret = {'removeImageStatus': 1, 'error_message': 'None'} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - except BaseException, msg: - data_ret = {'removeImageStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - # Internal function for recreating containers - - def doRecreateContainer(self, userID, data, con): - try: - name = data['name'] - unlisted = data['unlisted'] # Pass this as 1 if image is not known for container - image = data['image'] - tag = data['tag'] - env = data['env'] - port = data['ports'] - memory = data['memory'] - - if image == 'unknown': - return "Image name not known" - # Call container delete function - delStatus = self.submitContainerDeletion(userID, data, True) - if delStatus != 0: - return delStatus - - print env - containerArgs = {'image': image + ":" + tag, - 'detach': True, - 'name': name, - 'ports': port, - 'environment': env, - 'publish_all_ports': True, - 'mem_limit': memory * 1048576} - - if con.startOnReboot == 1: - containerArgs['restart_policy'] = {"Name": "always"} - - container = client.containers.create(**containerArgs) - con.cid = container.id - con.save() - - return 0 - except BaseException, msg: - return str(msg) - - def saveContainerSettings(self, userID=None, data=None): - try: - name = data['name'] - if ACLManager.checkContainerOwnership(name, userID) != 1: - return ACLManager.loadErrorJson('saveSettingsStatus', 0) - - client = docker.from_env() - dockerAPI = docker.APIClient() - - memory = data['memory'] - startOnReboot = data['startOnReboot'] - envList = data['envList'] - - if startOnReboot == True: - startOnReboot = 1 - rPolicy = {"Name": "always"} - else: - startOnReboot = 0 - rPolicy = {} - - try: - container = client.containers.get(name) - except docker.errors.NotFound as err: - data_ret = {'saveSettingsStatus': 0, 'error_message': 'Container does not exist'} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - except: - data_ret = {'saveSettingsStatus': 0, 'error_message': 'Unknown'} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - try: - container.update(mem_limit=memory * 1048576, - restart_policy=rPolicy) - except docker.errors.APIError as err: - data_ret = {'saveSettingsStatus': 0, 'error_message': str(err)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - con = Containers.objects.get(name=name) - con.memory = memory - con.startOnReboot = startOnReboot - - if 'envConfirmation' in data and data['envConfirmation']: - # Formatting envList for usage - envDict = {} - for key, value in envList.iteritems(): - if (value['name'] != '') or (value['value'] != ''): - envDict[value['name']] = value['value'] - - print envDict - # Prepare data for recreate function - data = { - 'name': name, - 'unlisted': 0, - 'image': con.image, - 'tag': con.tag, - 'env': envDict, - 'ports': json.loads(con.ports), - # No filter needed now as its ports are filtered when adding to database - 'memory': con.memory - } - - recreateStatus = self.doRecreateContainer(userID, data, con) - if recreateStatus != 0: - data_ret = {'saveSettingsStatus': 0, 'error_message': str(recreateStatus)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - con.env = json.dumps(envDict) - con.save() - - data_ret = {'saveSettingsStatus': 1, 'error_message': 'None'} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - except BaseException, msg: - data_ret = {'saveSettingsStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def recreateContainer(self, userID=None, data=None): - try: - name = data['name'] - if ACLManager.checkContainerOwnership(name, userID) != 1: - return ACLManager.loadErrorJson('saveSettingsStatus', 0) - - client = docker.from_env() - dockerAPI = docker.APIClient() - - try: - container = client.containers.get(name) - except docker.errors.NotFound as err: - data_ret = {'recreateContainerStatus': 0, 'error_message': 'Container does not exist'} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - except: - data_ret = {'recreateContainerStatus': 0, 'error_message': 'Unknown'} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - con = Containers.objects.get(name=name) - - # Prepare data for recreate function - data = { - 'name': name, - 'unlisted': 0, - 'image': con.image, - 'tag': con.tag, - 'env': json.loads(con.env), - 'ports': json.loads(con.ports), - # No filter needed now as its ports are filtered when adding to database - 'memory': con.memory - } - - recreateStatus = self.doRecreateContainer(userID, data, con) - if recreateStatus != 0: - data_ret = {'recreateContainerStatus': 0, 'error_message': str(recreateStatus)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - data_ret = {'recreateContainerStatus': 1, 'error_message': 'None'} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - except BaseException, msg: - data_ret = {'recreateContainerStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def getTags(self, userID=None, data=None): - try: - - admin = Administrator.objects.get(pk=userID) - if admin.acl.adminStatus != 1: - return ACLManager.loadError() - - image = data['image'] - page = data['page'] - - if ":" in image: - image2 = image.split(":")[0] + "/" + image.split(":")[1] - else: - image2 = "library/" + image - - print image - registryData = requests.get('https://registry.hub.docker.com/v2/repositories/' + image2 + '/tags', - {'page': page}).json() - - tagList = [] - for tag in registryData['results']: - tagList.append(tag['name']) - - data_ret = {'getTagsStatus': 1, 'list': tagList, 'next': registryData['next'], 'error_message': None} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - except BaseException, msg: - data_ret = {'getTagsStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) \ No newline at end of file diff --git a/static/containerization/containerization.js b/static/containerization/containerization.js new file mode 100644 index 000000000..f0fad7a03 --- /dev/null +++ b/static/containerization/containerization.js @@ -0,0 +1,646 @@ +app.controller('installContainer', function ($scope, $http, $timeout, $window) { + $scope.installDockerStatus = true; + $scope.installBoxGen = true; + $scope.dockerInstallBTN = false; + + $scope.submitContainerInstall = function () { + + $scope.installDockerStatus = false; + $scope.installBoxGen = true; + $scope.dockerInstallBTN = true; + + url = "/container/submitContainerInstall"; + + var data = {}; + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + $scope.cyberPanelLoading = true; + if (response.data.status === 1) { + $scope.installBoxGen = false; + getRequestStatus(); + } + else { + new PNotify({ + title: 'Operation Failed!', + text: response.data.error_message, + type: 'error' + }); + } + + } + + function cantLoadInitialDatas(response) { + $scope.cyberPanelLoading = true; + new PNotify({ + title: 'Operation Failed!', + text: 'Could not connect to server, please refresh this page', + type: 'error' + }); + } + + }; + function getRequestStatus() { + $scope.cyberPanelLoading = false; + + url = "/serverstatus/switchTOLSWSStatus"; + + var data = {}; + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + if (response.data.abort === 0) { + $scope.requestData = response.data.requestStatus; + $timeout(getRequestStatus, 1000); + } + else { + // Notifications + $scope.cyberPanelLoading = true; + $timeout.cancel(); + $scope.requestData = response.data.requestStatus; + if (response.data.installed === 1) { + $timeout(function () { + $window.location.reload(); + }, 3000); + } + + } + } + + function cantLoadInitialDatas(response) { + $scope.cyberPanelLoading = true; + new PNotify({ + title: 'Operation Failed!', + text: 'Could not connect to server, please refresh this page', + type: 'error' + }); + + + } + + } +}); + + +app.controller('websiteContainerLimit', function ($scope, $http, $timeout, $window) { + + + // Get CPU Usage of User + + var cpu = []; + var dataset; + var totalPoints = 100; + var updateInterval = 1000; + var now = new Date().getTime(); + + var options = { + series: { + lines: { + lineWidth: 1.2 + }, + bars: { + align: "center", + fillColor: {colors: [{opacity: 1}, {opacity: 1}]}, + barWidth: 500, + lineWidth: 1 + } + }, + xaxis: { + mode: "time", + tickSize: [5, "second"], + tickFormatter: function (v, axis) { + var date = new Date(v); + + if (date.getSeconds() % 20 == 0) { + var hours = date.getHours() < 10 ? "0" + date.getHours() : date.getHours(); + var minutes = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes(); + var seconds = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds(); + + return hours + ":" + minutes + ":" + seconds; + } else { + return ""; + } + }, + axisLabel: "Time", + axisLabelUseCanvas: true, + axisLabelFontSizePixels: 12, + axisLabelFontFamily: 'Verdana, Arial', + axisLabelPadding: 10 + }, + yaxes: [ + { + min: 0, + max: 100, + tickSize: 5, + tickFormatter: function (v, axis) { + if (v % 10 == 0) { + return v + "%"; + } else { + return ""; + } + }, + axisLabel: "CPU loading", + axisLabelUseCanvas: true, + axisLabelFontSizePixels: 12, + axisLabelFontFamily: 'Verdana, Arial', + axisLabelPadding: 6 + }, { + max: 5120, + position: "right", + axisLabel: "Disk", + axisLabelUseCanvas: true, + axisLabelFontSizePixels: 12, + axisLabelFontFamily: 'Verdana, Arial', + axisLabelPadding: 6 + } + ], + legend: { + noColumns: 0, + position: "nw" + }, + grid: { + backgroundColor: {colors: ["#ffffff", "#EDF5FF"]} + } + }; + + function initData() { + for (var i = 0; i < totalPoints; i++) { + var temp = [now += updateInterval, 0]; + + cpu.push(temp); + } + } + + function GetData() { + + var data = { + domain: $("#domain").text() + }; + $.ajaxSetup({cache: false}); + + $.ajax({ + url: "/container/getUsageData", + dataType: 'json', + success: update, + type: "POST", + contentType: "application/json", + data: JSON.stringify(data), // Our valid JSON string + error: function () { + setTimeout(GetData, updateInterval); + } + }); + } + + var temp; + + function update(_data) { + cpu.shift(); + + now += updateInterval; + + temp = [now, _data.cpu]; + cpu.push(temp); + + + dataset = [ + {label: "CPU:" + _data.cpu + "%", data: cpu, lines: {fill: true, lineWidth: 1.2}, color: "#00FF00"} + ]; + + $.plot($("#flot-placeholder1"), dataset, options); + setTimeout(GetData, updateInterval); + } + + // Memory Usage of User + + var memory = []; + var datasetMemory; + var totalPointsMemory = 100; + var updateIntervalMemory = 1000; + var nowMemory = new Date().getTime(); + + var optionsMemory = { + series: { + lines: { + lineWidth: 1.2 + }, + bars: { + align: "center", + fillColor: {colors: [{opacity: 1}, {opacity: 1}]}, + barWidth: 500, + lineWidth: 1 + } + }, + xaxis: { + mode: "time", + tickSize: [5, "second"], + tickFormatter: function (v, axis) { + var date = new Date(v); + + if (date.getSeconds() % 20 == 0) { + var hours = date.getHours() < 10 ? "0" + date.getHours() : date.getHours(); + var minutes = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes(); + var seconds = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds(); + + return hours + ":" + minutes + ":" + seconds; + } else { + return ""; + } + }, + axisLabel: "Time", + axisLabelUseCanvas: true, + axisLabelFontSizePixels: 12, + axisLabelFontFamily: 'Verdana, Arial', + axisLabelPadding: 10 + }, + yaxes: [ + { + min: 0, + max: $scope.memory, + tickSize: 5, + tickFormatter: function (v, axis) { + if (v % 10 == 0) { + return v + "MB"; + } else { + return ""; + } + }, + axisLabel: "CPU loading", + axisLabelUseCanvas: true, + axisLabelFontSizePixels: 12, + axisLabelFontFamily: 'Verdana, Arial', + axisLabelPadding: 6 + }, { + max: 5120, + position: "right", + axisLabel: "Disk", + axisLabelUseCanvas: true, + axisLabelFontSizePixels: 12, + axisLabelFontFamily: 'Verdana, Arial', + axisLabelPadding: 6 + } + ], + legend: { + noColumns: 0, + position: "nw" + }, + grid: { + backgroundColor: {colors: ["#ffffff", "#EDF5FF"]} + } + }; + + function initDataMemory() { + for (var i = 0; i < totalPointsMemory; i++) { + var temp = [nowMemory += updateIntervalMemory, 0]; + + memory.push(temp); + } + } + + function GetDataMemory() { + + var data = { + domain: $("#domain").text(), + type: 'memory' + }; + $.ajaxSetup({cache: false}); + + $.ajax({ + url: "/container/getUsageData", + dataType: 'json', + success: updateMemory, + type: "POST", + contentType: "application/json", + data: JSON.stringify(data), // Our valid JSON string + error: function () { + setTimeout(GetDataMemory, updateIntervalMemory); + } + }); + } + + var tempMemory; + + function updateMemory(_data) { + memory.shift(); + + nowMemory += updateIntervalMemory; + + tempMemory = [nowMemory, _data.memory]; + memory.push(tempMemory); + + + datasetMemory = [ + { + label: "Memory:" + _data.memory + "MB", + data: memory, + lines: {fill: true, lineWidth: 1.2}, + color: "#00FF00" + } + ]; + + $.plot($("#memoryUsage"), datasetMemory, optionsMemory); + setTimeout(GetDataMemory, updateIntervalMemory); + } + + // Disk Usage + + var readRate = [], writeRate = []; + var datasetDisk; + var totalPointsDisk = 100; + var updateIntervalDisk = 5000; + var now = new Date().getTime(); + + var optionsDisk = { + series: { + lines: { + lineWidth: 1.2 + }, + bars: { + align: "center", + fillColor: {colors: [{opacity: 1}, {opacity: 1}]}, + barWidth: 500, + lineWidth: 1 + } + }, + xaxis: { + mode: "time", + tickSize: [30, "second"], + tickFormatter: function (v, axis) { + var date = new Date(v); + + if (date.getSeconds() % 20 == 0) { + var hours = date.getHours() < 10 ? "0" + date.getHours() : date.getHours(); + var minutes = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes(); + var seconds = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds(); + + return hours + ":" + minutes + ":" + seconds; + } else { + return ""; + } + }, + axisLabel: "Time", + axisLabelUseCanvas: true, + axisLabelFontSizePixels: 12, + axisLabelFontFamily: 'Verdana, Arial', + axisLabelPadding: 10 + }, + yaxes: [ + { + min: 0, + max: $scope.networkSpeed, + tickSize: 5, + tickFormatter: function (v, axis) { + if (v % 10 == 0) { + return v + "mb/sec"; + } else { + return ""; + } + }, + axisLabel: "CPU loading", + axisLabelUseCanvas: true, + axisLabelFontSizePixels: 12, + axisLabelFontFamily: 'Verdana, Arial', + axisLabelPadding: 6 + }, { + max: 5120, + position: "right", + axisLabel: "Disk", + axisLabelUseCanvas: true, + axisLabelFontSizePixels: 12, + axisLabelFontFamily: 'Verdana, Arial', + axisLabelPadding: 6 + } + ], + legend: { + noColumns: 0, + position: "nw" + }, + grid: { + backgroundColor: {colors: ["#ffffff", "#EDF5FF"]} + } + }; + + function initDataDisk() { + for (var i = 0; i < totalPointsDisk; i++) { + var temp = [now += updateIntervalDisk, 0]; + + readRate.push(temp); + writeRate.push(temp); + } + } + + function GetDataDisk() { + + var data = { + domain: $("#domain").text(), + type: 'io' + }; + + $.ajaxSetup({cache: false}); + + $.ajax({ + url: "/container/getUsageData", + dataType: 'json', + success: updateDisk, + type: "POST", + contentType: "application/json", + data: JSON.stringify(data), // Our valid JSON string + error: function () { + setTimeout(GetDataMemory, updateIntervalMemory); + } + }); + } + + var tempDisk; + + function updateDisk(_data) { + readRate.shift(); + writeRate.shift(); + + now += updateIntervalDisk; + + tempDisk = [now, _data.readRate]; + readRate.push(tempDisk); + + tempDisk = [now, _data.readRate]; + writeRate.push(tempDisk); + + datasetDisk = [ + {label: "Read IO/s " + _data.readRate + " mb/s ", data: readRate, lines: {fill: true, lineWidth: 1.2}, color: "#00FF00"}, + {label: "Write IO/s " + _data.writeRate + " mb/s ", data: writeRate, lines: {lineWidth: 1.2}, color: "#FF0000"} + ]; + + $.plot($("#diskUsage"), datasetDisk, optionsDisk); + setTimeout(GetDataDisk, updateIntervalDisk); + } + + + $(document).ready(function () { + initDataDisk(); + + datasetDisk = [ + {label: "Read IO/s: ", data: readRate, lines: {fill: true, lineWidth: 1.2}, color: "#00FF00"}, + {label: "Write IO/s: ", data: writeRate, color: "#0044FF", bars: {show: true}, yaxis: 2} + ]; + + $.plot($("#diskUsage"), datasetDisk, optionsDisk); + setTimeout(GetDataDisk, updateIntervalDisk); + }); + + //// + + $scope.cyberPanelLoading = true; + $scope.limitsInfoBox = true; + + $scope.fetchWebsiteLimits = function () { + + $scope.cyberPanelLoading = false; + + url = "/container/fetchWebsiteLimits"; + + var data = { + 'domain': $("#domain").text() + }; + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + $scope.cyberPanelLoading = true; + if (response.data.status === 1) { + $scope.cpuPers = response.data.cpuPers; + $scope.IO = response.data.IO; + $scope.IOPS = response.data.IOPS; + $scope.memory = response.data.memory; + $scope.networkSpeed = response.data.networkSpeed; + + if (response.data.enforce === 0) { + $scope.limitsInfoBox = false; + } else { + $scope.limitsInfoBox = true; + } + + + // Report Memory Usage + + initDataMemory(); + + datasetMemory = [ + {label: "Memory", data: memory, lines: {fill: true, lineWidth: 1.2}, color: "#00FF00"} + ]; + + $.plot($("#memoryUsage"), datasetMemory, optionsMemory); + setTimeout(GetDataMemory, updateIntervalMemory); + + // Report CPU Usage + + initData(); + + dataset = [ + {label: "CPU", data: cpu, lines: {fill: true, lineWidth: 1.2}, color: "#00FF00"} + ]; + + $.plot($("#flot-placeholder1"), dataset, options); + setTimeout(GetData, updateInterval); + } + else { + new PNotify({ + title: 'Operation Failed!', + text: response.data.error_message, + type: 'error' + }); + } + } + + function cantLoadInitialDatas(response) { + $scope.cyberPanelLoading = true; + new PNotify({ + title: 'Operation Failed!', + text: 'Could not connect to server, please refresh this page', + type: 'error' + }); + } + + }; + $scope.fetchWebsiteLimits(); + + $scope.saveWebsiteLimits = function () { + + $scope.cyberPanelLoading = false; + + url = "/container/saveWebsiteLimits"; + + var data = { + 'domain': $("#domain").text(), + 'cpuPers': $scope.cpuPers, + 'IO': $scope.IO, + 'IOPS': $scope.IOPS, + 'memory': $scope.memory, + 'networkSpeed': $scope.networkSpeedBox, + 'networkHandle': $scope.networkHandle, + 'enforce': $scope.enforce + }; + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + $scope.cyberPanelLoading = true; + if (response.data.status === 1) { + new PNotify({ + title: 'Success', + text: 'Changes successfully applied.', + type: 'success' + }); + $scope.fetchWebsiteLimits(); + } + else { + new PNotify({ + title: 'Operation Failed!', + text: response.data.error_message, + type: 'error' + }); + } + } + + function cantLoadInitialDatas(response) { + $scope.cyberPanelLoading = true; + new PNotify({ + title: 'Operation Failed!', + text: 'Could not connect to server, please refresh this page', + type: 'error' + }); + } + + }; + + +}); \ No newline at end of file diff --git a/websiteFunctions/migrations/0001_initial.py b/websiteFunctions/migrations/0001_initial.py deleted file mode 100644 index 69a2f29fa..000000000 --- a/websiteFunctions/migrations/0001_initial.py +++ /dev/null @@ -1,94 +0,0 @@ -# -*- coding: utf-8 -*- -# Generated by Django 1.11 on 2019-01-07 12:43 -from __future__ import unicode_literals - -from django.db import migrations, models -import django.db.models.deletion - - -class Migration(migrations.Migration): - - initial = True - - dependencies = [ - ('packages', '0001_initial'), - ('loginSystem', '0001_initial'), - ] - - operations = [ - migrations.CreateModel( - name='aliasDomains', - fields=[ - ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), - ('aliasDomain', models.CharField(max_length=75)), - ], - ), - migrations.CreateModel( - name='Backups', - fields=[ - ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), - ('fileName', models.CharField(max_length=50)), - ('date', models.CharField(max_length=50)), - ('size', models.CharField(max_length=50)), - ('status', models.IntegerField(default=0)), - ], - ), - migrations.CreateModel( - name='backupSchedules', - fields=[ - ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), - ('frequency', models.CharField(max_length=15)), - ], - ), - migrations.CreateModel( - name='ChildDomains', - fields=[ - ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), - ('domain', models.CharField(max_length=50, unique=True)), - ('path', models.CharField(default=None, max_length=200)), - ('ssl', models.IntegerField()), - ('phpSelection', models.CharField(default=None, max_length=10)), - ], - ), - migrations.CreateModel( - name='dest', - fields=[ - ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), - ('destLoc', models.CharField(max_length=18, unique=True)), - ], - ), - migrations.CreateModel( - name='Websites', - fields=[ - ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), - ('domain', models.CharField(max_length=50, unique=True)), - ('adminEmail', models.CharField(max_length=50)), - ('phpSelection', models.CharField(max_length=10)), - ('ssl', models.IntegerField()), - ('state', models.IntegerField(default=1)), - ('externalApp', models.CharField(default=None, max_length=10)), - ('admin', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='loginSystem.Administrator')), - ('package', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='packages.Package')), - ], - ), - migrations.AddField( - model_name='childdomains', - name='master', - field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='websiteFunctions.Websites'), - ), - migrations.AddField( - model_name='backupschedules', - name='dest', - field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='websiteFunctions.dest'), - ), - migrations.AddField( - model_name='backups', - name='website', - field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='websiteFunctions.Websites'), - ), - migrations.AddField( - model_name='aliasdomains', - name='master', - field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='websiteFunctions.Websites'), - ), - ]