init and lxc config json loading

This commit is contained in:
Mathieu Broillet 2023-06-09 11:49:51 +02:00
parent 4dba728748
commit e6a27d0bef
11 changed files with 314 additions and 30 deletions

View File

@ -1,12 +1,29 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ChangeListManager">
<list default="true" id="ef90a940-975e-45ac-b0cb-e18c5b09ff29" name="Changes" comment="" />
<list default="true" id="ef90a940-975e-45ac-b0cb-e18c5b09ff29" name="Changes" comment="base">
<change afterPath="$PROJECT_DIR$/README.md" afterDir="false" />
<change afterPath="$PROJECT_DIR$/requirements.txt" afterDir="false" />
<change afterPath="$PROJECT_DIR$/run.py" afterDir="false" />
<change afterPath="$PROJECT_DIR$/src/get_path_file.py" afterDir="false" />
<change afterPath="$PROJECT_DIR$/src/main.py" afterDir="false" />
<change afterPath="$PROJECT_DIR$/src/utils/__init__.py" afterDir="false" />
<change afterPath="$PROJECT_DIR$/src/utils/lxc_utils.py" afterDir="false" />
<change beforePath="$PROJECT_DIR$/.idea/workspace.xml" beforeDir="false" afterPath="$PROJECT_DIR$/.idea/workspace.xml" afterDir="false" />
<change beforePath="$PROJECT_DIR$/main.py" beforeDir="false" />
</list>
<option name="SHOW_DIALOG" value="false" />
<option name="HIGHLIGHT_CONFLICTS" value="true" />
<option name="HIGHLIGHT_NON_ACTIVE_CHANGELIST" value="false" />
<option name="LAST_RESOLUTION" value="IGNORE" />
</component>
<component name="FileTemplateManagerImpl">
<option name="RECENT_TEMPLATES">
<list>
<option value="Python Script" />
</list>
</option>
</component>
<component name="Git.Settings">
<option name="RECENT_GIT_ROOT_PATH" value="$PROJECT_DIR$" />
</component>
@ -14,7 +31,9 @@
<option name="stateVersion" value="1" />
</component>
<component name="ProjectId" id="2QxREeVLT4IlTxqXEpzPYhB1R0E" />
<component name="ProjectLevelVcsManager" settingsEditedManually="true" />
<component name="ProjectLevelVcsManager" settingsEditedManually="true">
<ConfirmationsSetting value="2" id="Add" />
</component>
<component name="ProjectViewState">
<option name="hideEmptyMiddlePackages" value="true" />
<option name="showLibraryContents" value="true" />
@ -27,7 +46,12 @@
&quot;settings.editor.selected.configurable&quot;: &quot;preferences.pluginManager&quot;
}
}</component>
<component name="RunManager">
<component name="RecentsManager">
<key name="MoveFile.RECENT_KEYS">
<recent name="C:\Users\lmbbrm3\PycharmProjects\ProxmoxDeploy\resources\lxc" />
</key>
</component>
<component name="RunManager" selected="Python.run">
<configuration name="main" type="PythonConfigurationType" factoryName="Python" nameIsGenerated="true">
<module name="ProxmoxDeploy" />
<option name="INTERPRETER_OPTIONS" value="" />
@ -50,6 +74,33 @@
<option name="INPUT_FILE" value="" />
<method v="2" />
</configuration>
<configuration name="run" type="PythonConfigurationType" factoryName="Python" temporary="true" nameIsGenerated="true">
<module name="ProxmoxDeploy" />
<option name="INTERPRETER_OPTIONS" value="" />
<option name="PARENT_ENVS" value="true" />
<envs>
<env name="PYTHONUNBUFFERED" value="1" />
</envs>
<option name="SDK_HOME" value="" />
<option name="WORKING_DIRECTORY" value="$PROJECT_DIR$" />
<option name="IS_MODULE_SDK" value="true" />
<option name="ADD_CONTENT_ROOTS" value="true" />
<option name="ADD_SOURCE_ROOTS" value="true" />
<EXTENSION ID="PythonCoverageRunConfigurationExtension" runner="coverage.py" />
<option name="SCRIPT_NAME" value="$PROJECT_DIR$/run.py" />
<option name="PARAMETERS" value="" />
<option name="SHOW_COMMAND_LINE" value="false" />
<option name="EMULATE_TERMINAL" value="false" />
<option name="MODULE_MODE" value="false" />
<option name="REDIRECT_INPUT" value="false" />
<option name="INPUT_FILE" value="" />
<method v="2" />
</configuration>
<recent_temporary>
<list>
<item itemvalue="Python.run" />
</list>
</recent_temporary>
</component>
<component name="SpellCheckerSettings" RuntimeDictionaries="0" Folders="0" CustomDictionaries="0" DefaultDictionary="application-level" UseSingleDictionary="true" transferred="true" />
<component name="TaskManager">
@ -60,8 +111,16 @@
<option name="presentableId" value="Default" />
<updated>1686293135999</updated>
<workItem from="1686293144782" duration="176000" />
<workItem from="1686293341823" duration="151000" />
<workItem from="1686293341823" duration="6751000" />
</task>
<task id="LOCAL-00001" summary="base">
<created>1686293500295</created>
<option name="number" value="00001" />
<option name="presentableId" value="LOCAL-00001" />
<option name="project" value="LOCAL" />
<updated>1686293500295</updated>
</task>
<option name="localTasksCounter" value="2" />
<servers />
</component>
<component name="TypeScriptGeneratedFilesManager">
@ -78,15 +137,12 @@
</map>
</option>
</component>
<component name="XDebuggerManager">
<breakpoint-manager>
<breakpoints>
<line-breakpoint enabled="true" suspend="THREAD" type="python-line">
<url>file://$PROJECT_DIR$/main.py</url>
<line>8</line>
<option name="timeStamp" value="1" />
</line-breakpoint>
</breakpoints>
</breakpoint-manager>
<component name="VcsManagerConfiguration">
<MESSAGE value="base" />
<option name="LAST_COMMIT_MESSAGE" value="base" />
</component>
<component name="com.intellij.coverage.CoverageDataManagerImpl">
<SUITE FILE_PATH="coverage/ProxmoxDeploy$main.coverage" NAME="main Coverage Results" MODIFIED="1686295586466" SOURCE_PROVIDER="com.intellij.coverage.DefaultCoverageFileProvider" RUNNER="coverage.py" COVERAGE_BY_TEST_ENABLED="true" COVERAGE_TRACING_ENABLED="false" WORKING_DIRECTORY="$PROJECT_DIR$" />
<SUITE FILE_PATH="coverage/ProxmoxDeploy$run.coverage" NAME="run Coverage Results" MODIFIED="1686304048372" SOURCE_PROVIDER="com.intellij.coverage.DefaultCoverageFileProvider" RUNNER="coverage.py" COVERAGE_BY_TEST_ENABLED="true" COVERAGE_TRACING_ENABLED="false" WORKING_DIRECTORY="$PROJECT_DIR$" />
</component>
</project>

0
README.md Normal file
View File

16
main.py
View File

@ -1,16 +0,0 @@
# This is a sample Python script.
# Press Shift+F10 to execute it or replace it with your code.
# Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings.
def print_hi(name):
# Use a breakpoint in the code line below to debug your script.
print(f'Hi, {name}') # Press Ctrl+F8 to toggle the breakpoint.
# Press the green button in the gutter to run the script.
if __name__ == '__main__':
print_hi('PyCharm')
# See PyCharm help at https://www.jetbrains.com/help/pycharm/

0
requirements.txt Normal file
View File

View File

@ -0,0 +1,26 @@
{
"lxc_id": "0000",
"lxc_hostname": "test",
"os": "alpine",
"release": "3.17",
"resources": {
"cpu": "1",
"memory": "512",
"disk": "10",
"storage": "local-lvm"
},
"network": {
"bridge": "vmbr0",
"ipv4": "dhcp",
"ipv6": "",
"mac": "00:00:00:00:00:00",
"gateway": "",
"vlan": ""
},
"options": {
"privileged": "false",
"start_on_boot": "false",
"password": "qwertz1234",
"ssh": false
}
}

View File

7
run.py Normal file
View File

@ -0,0 +1,7 @@
import logging
from src import main
if __name__ == '__main__':
logging.getLogger().setLevel(logging.INFO)
main.run()

3
src/get_path_file.py Normal file
View File

@ -0,0 +1,3 @@
import pathlib
project_path = pathlib.Path(__file__).parent.parent.resolve()

29
src/main.py Normal file
View File

@ -0,0 +1,29 @@
import logging
import os
from src.get_path_file import project_path
from src.utils.lxc_utils import load_lxc, get_all_lxcs
def run():
# Read all files in the resources directory
resources = os.listdir(project_path / "resources")
logging.info(f"Resources found: {resources}")
# Go through each LXC file
for resource in resources:
if resource == "lxc":
logging.info("LXC folder found")
# Read all files in the LXC directory
lxc_folders = os.listdir(project_path / "resources" / "lxc")
for lxc_folder in lxc_folders:
lxc_file = os.path.join(project_path / "resources" / "lxc", lxc_folder, "config.json")
logging.info(f"Reading LXC ID {lxc_file}")
# Open the file
with open(lxc_file, "r") as file:
# Load the LXC
load_lxc(file.read())
print(get_all_lxcs())

0
src/utils/__init__.py Normal file
View File

179
src/utils/lxc_utils.py Normal file
View File

@ -0,0 +1,179 @@
import json
lxcs = []
def get_all_lxcs():
"""
Get all LXCs
:return: list of all lxcs
"""
return lxcs
def get_lxc(id):
"""
Get LXC by ID
:param id: lxc id
:return: lxc object
"""
for lxc in lxcs:
if lxc.get_lxc_id() == id:
return lxc
return None
def load_lxc(file):
"""
Load LXC from JSON file
:param file: json config file
:return:
"""
# Load JSON data
data = json.loads(file)
# Extract values from JSON
lxc_id = data["lxc_id"]
lxc_hostname = data["lxc_hostname"]
disk_size = data["resources"]["disk"]
core_count = data["resources"]["cpu"]
ram_size = data["resources"]["memory"]
bridge = data["network"]["bridge"]
ipv4 = data["network"]["ipv4"]
gateway = data["network"]["gateway"]
disable_ipv6 = "yes" if data["network"]["ipv6"] == "" else "no"
mac = data["network"]["mac"]
vlan = data["network"]["vlan"]
ssh = "yes" if data["options"]["ssh"] else "no"
# Create LXC object
lxc = LXC(
lxc_id=lxc_id,
lxc_hostname=lxc_hostname,
disk_size=disk_size,
core_count=core_count,
ram_size=ram_size,
bridge=bridge,
ipv4=ipv4,
gateway=gateway,
disable_ipv6=disable_ipv6,
mac=mac,
vlan=vlan,
ssh=ssh
)
lxcs.append(lxc)
class LXC:
"""
LXC class
"""
def __init__(self, lxc_id, lxc_hostname, disk_size, core_count, ram_size, bridge, ipv4, gateway, disable_ipv6, mac,
vlan, ssh):
self.lxc_id = lxc_id
self.lxc_hostname = lxc_hostname
self.disk_size = disk_size
self.core_count = core_count
self.ram_size = ram_size
self.bridge = bridge
self.ipv4 = ipv4
self.gateway = gateway
self.disable_ipv6 = disable_ipv6
self.mac = mac
self.vlan = vlan
self.ssh = ssh
def __str__(self):
return f"LXC {self.lxc_id} ({self.lxc_hostname})"
def __repr__(self):
return f"LXC {self.lxc_id} ({self.lxc_hostname})"
def __eq__(self, other):
return self.lxc_id == other.lxc_id
def __hash__(self):
return hash(self.lxc_id)
def get_lxc_id(self):
return self.lxc_id
def get_lxc_hostname(self):
return self.lxc_hostname
def get_disk_size(self):
return self.disk_size
def get_core_count(self):
return self.core_count
def get_ram_size(self):
return self.ram_size
def get_bridge(self):
return self.bridge
def get_ipv4(self):
return self.ipv4
def get_gateway(self):
return self.gateway
def get_disable_ipv6(self):
return self.disable_ipv6
def get_mac(self):
return self.mac
def get_vlan(self):
return self.vlan
def get_ssh(self):
return self.ssh
def get_tteck_env_variables(self):
"""
Get TTECK environment variables to run scripts silently
:return: environment variables
"""
env_template = '''CT_TYPE="1"
PW=""
CT_ID={lxc_id}
HN={lxc_hostname}
DISK_SIZE="{disk_size}"
CORE_COUNT="{core_count}"
RAM_SIZE="{ram_size}"
BRG="{bridge}"
NET="{ipv4}"
GATE="{gateway}"
DISABLEIP6="{disable_ipv6}"
MTU=""
SD=""
NS=""
MAC="{mac}"
VLAN="{vlan}"
SSH="{ssh}"
VERB="no"'''
# Format the environment variables template
env_variables = env_template.format(
lxc_id=self.lxc_id,
lxc_hostname=self.lxc_hostname,
disk_size=self.disk_size,
core_count=self.core_count,
ram_size=self.ram_size,
bridge=self.bridge,
ipv4=self.ipv4,
gateway=self.gateway,
disable_ipv6=self.disable_ipv6,
mac=self.mac,
vlan=self.vlan,
ssh=self.ssh
)
return env_variables