Compare commits
27 Commits
91860994b4
...
master
Author | SHA1 | Date | |
---|---|---|---|
b6bd431c40 | |||
da1030c960 | |||
209536614e | |||
89da5d6c0d | |||
019261a988 | |||
7d861aad76 | |||
6430dc5bc4 | |||
304451ef7c | |||
ee7a0b7f63 | |||
a1ec2c1602 | |||
71b55d5d17 | |||
30e3d3363c | |||
97ac22e62e | |||
35ef584cd7 | |||
f3599cc4ac | |||
2c0d4cdcae | |||
9ca94d0e05 | |||
cacdf1f5b9 | |||
4ee7337e9d | |||
d37c414466 | |||
e65d84c915 | |||
deb7f4fc5a | |||
c00432b425 | |||
669a371c0d | |||
4ba7eec661 | |||
60da6b0ae7 | |||
7b83facc21 |
@ -4,7 +4,7 @@ FROM python:3.10-slim AS builder
|
||||
# Install Docker
|
||||
RUN apt update
|
||||
RUN apt install curl -y
|
||||
RUN curl -sSL https://s.fascinated.cc/s/install-docker | bash
|
||||
RUN curl -sSL https://get.docker.com/ | CHANNEL=stable bash
|
||||
|
||||
# Step 2: Create the final image
|
||||
FROM python:3.10-slim
|
||||
|
9
LICENSE
Normal file
9
LICENSE
Normal file
@ -0,0 +1,9 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2023 Fascinated
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
@ -4,7 +4,8 @@ This is a helper container for traefik. It can add, remove and update services.
|
||||
|
||||
## NOTICE
|
||||
|
||||
PLEASE PLEASE PLEASE MAKE SURE YOU HAVE A BACKUP OF YOUR CONFIG FILE BEFORE USING THIS CONTAINER. I AM NOT RESPONSIBLE FOR ANY DATA LOSS.
|
||||
PLEASE PLEASE PLEASE MAKE SURE YOU HAVE A BACKUP OF YOUR CONFIG FILE BEFORE USING THIS CONTAINER. I AM NOT RESPONSIBLE FOR ANY DATA LOSS. </br>
|
||||
This helper also assumes that you have SSL certificates setup for your services.
|
||||
|
||||
## Usage
|
||||
|
||||
@ -22,6 +23,10 @@ traefik-helper
|
||||
|
||||
## Windows Alias
|
||||
|
||||
Ensure you have ran `Set-ExecutionPolicy Unrestricted` in PowerShell as an administrator.
|
||||
|
||||
Create the directory `~/Documents/WindowsPowerShell` and create a file called `Microsoft.PowerShell_profile.ps1` in that directory. Add the following code to the file.
|
||||
|
||||
```bash
|
||||
function Traefik-Helper {
|
||||
$argsAsString = $args -join ' '
|
||||
@ -34,3 +39,5 @@ function Traefik-Helper {
|
||||
# Set the alias
|
||||
Set-Alias -Name "traefik" -Value "Traefik-Helper"
|
||||
```
|
||||
|
||||
This will allow you to run the `traefik` command in PowerShell.
|
||||
|
12
src/command/command.py
Normal file
12
src/command/command.py
Normal file
@ -0,0 +1,12 @@
|
||||
class Command:
|
||||
def __init__(self, name:str, description:str, usage:str):
|
||||
self.name = name
|
||||
self.description = description
|
||||
self.usage = usage
|
||||
|
||||
async def execute(self, traefikConfig, args):
|
||||
pass
|
||||
|
||||
def printUsage(self):
|
||||
print("Usage: %s" % self.usage)
|
||||
pass
|
36
src/command/commandManager.py
Normal file
36
src/command/commandManager.py
Normal file
@ -0,0 +1,36 @@
|
||||
from command.impl.addCommand import AddCommand
|
||||
from command.impl.listCommand import ListCommand
|
||||
from command.impl.removeCommand import RemoveCommand
|
||||
from command.impl.restartCommand import RestartCommand
|
||||
from command.impl.logsCommand import LogsCommand
|
||||
from command.impl.addSubPathCommand import AddSubPathCommand
|
||||
from command.impl.addCatchAllCommand import AddCatchAllCommand
|
||||
|
||||
class CommandManager:
|
||||
|
||||
commands = []
|
||||
|
||||
def __init__(self):
|
||||
self.addCommand(AddCommand())
|
||||
self.addCommand(RemoveCommand())
|
||||
self.addCommand(ListCommand())
|
||||
self.addCommand(RestartCommand())
|
||||
self.addCommand(LogsCommand())
|
||||
self.addCommand(AddSubPathCommand())
|
||||
self.addCommand(AddCatchAllCommand())
|
||||
pass
|
||||
|
||||
|
||||
def addCommand(self, command):
|
||||
self.commands.append(command)
|
||||
pass
|
||||
|
||||
def getCommand(self, name):
|
||||
for command in self.commands:
|
||||
if command.name == name:
|
||||
return command
|
||||
return None
|
||||
|
||||
def commandExists(self, name):
|
||||
return self.getCommand(name) != None
|
||||
|
32
src/command/impl/addCatchAllCommand.py
Normal file
32
src/command/impl/addCatchAllCommand.py
Normal file
@ -0,0 +1,32 @@
|
||||
from command.command import Command
|
||||
from traefik.traefikConfig import TraefikConfig
|
||||
from utils.dockerUtils import restartTraefik
|
||||
|
||||
class AddCatchAllCommand(Command):
|
||||
def __init__(self):
|
||||
super().__init__("add-catch-all", "Add a catch all domain", "add-catch-all <name> <domain> <service host>")
|
||||
|
||||
def execute(self, traefikConfig: TraefikConfig, args):
|
||||
if len(args) < 3:
|
||||
self.printUsage()
|
||||
return
|
||||
|
||||
name = args[0]
|
||||
domain = args[1]
|
||||
serviceHost = args[2]
|
||||
|
||||
if traefikConfig.hasRouter(name):
|
||||
print(f"Router \"{name}\" already exists")
|
||||
return
|
||||
|
||||
# Validate if the service host is a valid URL
|
||||
if not serviceHost.startswith("http://") and not serviceHost.startswith("https://"):
|
||||
print(f"Service host \"{serviceHost}\" is not a valid URL")
|
||||
return
|
||||
|
||||
print(f"Adding \"{domain}\" -> \"{serviceHost}\"")
|
||||
|
||||
traefikConfig.addCatchAllRouter(name, domain, serviceHost)
|
||||
traefikConfig.save()
|
||||
|
||||
print(f"Access your service at http://{domain}")
|
32
src/command/impl/addCommand.py
Normal file
32
src/command/impl/addCommand.py
Normal file
@ -0,0 +1,32 @@
|
||||
from command.command import Command
|
||||
from traefik.traefikConfig import TraefikConfig
|
||||
from utils.dockerUtils import restartTraefik
|
||||
|
||||
class AddCommand(Command):
|
||||
def __init__(self):
|
||||
super().__init__("add", "Add a domain", "add <name> <domain> <service host>")
|
||||
|
||||
def execute(self, traefikConfig: TraefikConfig, args):
|
||||
if len(args) < 3:
|
||||
self.printUsage()
|
||||
return
|
||||
|
||||
name = args[0]
|
||||
domain = args[1]
|
||||
serviceHost = args[2]
|
||||
|
||||
if traefikConfig.hasRouter(name):
|
||||
print(f"Router \"{name}\" already exists")
|
||||
return
|
||||
|
||||
# Validate if the service host is a valid URL
|
||||
if not serviceHost.startswith("http://") and not serviceHost.startswith("https://"):
|
||||
print(f"Service host \"{serviceHost}\" is not a valid URL")
|
||||
return
|
||||
|
||||
print(f"Adding \"{domain}\" -> \"{serviceHost}\"")
|
||||
|
||||
traefikConfig.addRouter(name, domain, serviceHost)
|
||||
traefikConfig.save()
|
||||
|
||||
print(f"Access your service at http://{domain}")
|
43
src/command/impl/addSubPathCommand.py
Normal file
43
src/command/impl/addSubPathCommand.py
Normal file
@ -0,0 +1,43 @@
|
||||
from command.command import Command
|
||||
from traefik.traefikConfig import TraefikConfig
|
||||
from utils.dockerUtils import restartTraefik
|
||||
|
||||
class AddSubPathCommand(Command):
|
||||
def __init__(self):
|
||||
super().__init__("add-path", "Add sub path to a domain (eg: bob.com/joe)", "add-path <name> <domain> <path> <service host>")
|
||||
|
||||
def execute(self, traefikConfig: TraefikConfig, args):
|
||||
if len(args) < 3:
|
||||
self.printUsage()
|
||||
return
|
||||
|
||||
router = args[0]
|
||||
domain = args[1]
|
||||
path = args[2]
|
||||
# Fix the path
|
||||
if path.startswith("/") == False:
|
||||
path = "/" + path
|
||||
if path.endswith("/") == True:
|
||||
path = path[:-1] # Remove the trailing slash
|
||||
serviceHost = args[3]
|
||||
subPathName = domain + path
|
||||
|
||||
if traefikConfig.hasPathRewrite(subPathName):
|
||||
print(f"Sub path for \"{domain}{path}\" already exists")
|
||||
return
|
||||
|
||||
if traefikConfig.hasRouter(router) == False:
|
||||
print(f"Router \"{router}\" does not exist")
|
||||
return
|
||||
|
||||
# Validate if the service host is a valid URL
|
||||
if not serviceHost.startswith("http://") and not serviceHost.startswith("https://"):
|
||||
print(f"Service host \"{serviceHost}\" is not a valid URL")
|
||||
return
|
||||
|
||||
print(f"Adding \"{domain}{path}\" -> \"{serviceHost}\"")
|
||||
|
||||
traefikConfig.addSubPathRouter(subPathName, domain, path, serviceHost)
|
||||
traefikConfig.save()
|
||||
|
||||
print(f"Access your service at http://{domain}{path}")
|
19
src/command/impl/listCommand.py
Normal file
19
src/command/impl/listCommand.py
Normal file
@ -0,0 +1,19 @@
|
||||
from colorama import Fore
|
||||
from command.command import Command
|
||||
from traefik.traefikConfig import TraefikConfig
|
||||
|
||||
class ListCommand(Command):
|
||||
def __init__(self):
|
||||
super().__init__("list", "List all services", "list")
|
||||
|
||||
def execute(self, traefikConfig: TraefikConfig, args):
|
||||
print("Listing all services:")
|
||||
|
||||
domains = traefikConfig.getAll()
|
||||
|
||||
# Print domains
|
||||
for name, domain in domains.items():
|
||||
print(f" - {Fore.CYAN}[{name}] {Fore.GREEN}http://{domain['domain']} {Fore.RESET}-> {Fore.YELLOW}{domain['serviceHost']}{Fore.RESET}")
|
||||
|
||||
print("")
|
||||
print("Total: %s" % len(domains))
|
10
src/command/impl/logsCommand.py
Normal file
10
src/command/impl/logsCommand.py
Normal file
@ -0,0 +1,10 @@
|
||||
from command.command import Command
|
||||
from traefik.traefikConfig import TraefikConfig
|
||||
from utils.dockerUtils import getTraefikLogs
|
||||
|
||||
class LogsCommand(Command):
|
||||
def __init__(self):
|
||||
super().__init__("logs", "Get traefik logs", "logs")
|
||||
|
||||
def execute(self, traefikConfig: TraefikConfig, args):
|
||||
getTraefikLogs()
|
24
src/command/impl/removeCommand.py
Normal file
24
src/command/impl/removeCommand.py
Normal file
@ -0,0 +1,24 @@
|
||||
from colorama import Fore
|
||||
from command.command import Command
|
||||
from traefik.traefikConfig import TraefikConfig
|
||||
|
||||
class RemoveCommand(Command):
|
||||
def __init__(self):
|
||||
super().__init__("remove", "Remove a domain", "remove <name>")
|
||||
|
||||
def execute(self, traefikConfig: TraefikConfig, args):
|
||||
if len(args) < 0:
|
||||
self.printUsage()
|
||||
return
|
||||
|
||||
name = args[0]
|
||||
|
||||
if not traefikConfig.hasRouter(name):
|
||||
print(f"Router \"{name}\" does not exist")
|
||||
return
|
||||
|
||||
print(f"Removing \"{name}\"")
|
||||
|
||||
traefikConfig.removeRouter(name)
|
||||
|
||||
traefikConfig.save()
|
27
src/command/impl/removeSubPathCommand.py
Normal file
27
src/command/impl/removeSubPathCommand.py
Normal file
@ -0,0 +1,27 @@
|
||||
from colorama import Fore
|
||||
from command.command import Command
|
||||
from traefik.traefikConfig import TraefikConfig
|
||||
from utils.dockerUtils import restartTraefik
|
||||
|
||||
class RemoveCommand(Command):
|
||||
def __init__(self):
|
||||
super().__init__("remove-sub-path", "Remove sub path from a domain", "remove-sub-path <name> <path>")
|
||||
|
||||
def execute(self, traefikConfig: TraefikConfig, args):
|
||||
if len(args) < 0:
|
||||
self.printUsage()
|
||||
return
|
||||
|
||||
name = args[0]
|
||||
|
||||
if not traefikConfig.hasRouter(name):
|
||||
print(f"Router \"{name}\" does not exist")
|
||||
return
|
||||
|
||||
print(f"Removing \"{name}\"")
|
||||
|
||||
traefikConfig.removeRouter(name)
|
||||
|
||||
traefikConfig.save()
|
||||
|
||||
restartTraefik()
|
10
src/command/impl/restartCommand.py
Normal file
10
src/command/impl/restartCommand.py
Normal file
@ -0,0 +1,10 @@
|
||||
from command.command import Command
|
||||
from traefik.traefikConfig import TraefikConfig
|
||||
from utils.dockerUtils import restartTraefik
|
||||
|
||||
class RestartCommand(Command):
|
||||
def __init__(self):
|
||||
super().__init__("restart", "Restart traefik", "restart")
|
||||
|
||||
def execute(self, traefikConfig: TraefikConfig, args):
|
||||
restartTraefik()
|
170
src/manage.py
170
src/manage.py
@ -1,171 +1,31 @@
|
||||
import sys
|
||||
import subprocess
|
||||
import yaml
|
||||
import os
|
||||
from colorama import Fore
|
||||
|
||||
from command.commandManager import CommandManager
|
||||
from traefik.traefikConfig import TraefikConfig
|
||||
|
||||
# Variables
|
||||
configFile = "./config.yml"
|
||||
containerName = "traefik"
|
||||
|
||||
# Are we running in a Docker container?
|
||||
if os.environ.get("CONFIG_FILE"):
|
||||
configFile = os.environ.get("CONFIG_FILE")
|
||||
if os.environ.get("CONTAINER_NAME"):
|
||||
containerName = os.environ.get("CONTAINER_NAME")
|
||||
|
||||
# DO NOT TOUCH
|
||||
commands = ["add", "remove", "list", "update"]
|
||||
traefikConfig = TraefikConfig(configFile)
|
||||
if traefikConfig.isValid() == False:
|
||||
print("Invalid traefik config file, please check your config.yml file")
|
||||
exit(1)
|
||||
|
||||
command = len(sys.argv) > 1 and sys.argv[1]
|
||||
commandManager = CommandManager()
|
||||
|
||||
if command not in commands:
|
||||
print("")
|
||||
print("Usage: manage.py [command]")
|
||||
if not commandManager.commandExists(command):
|
||||
print("Usage: manage [command]")
|
||||
print("")
|
||||
print("Commands:")
|
||||
print(" - add [name] [domain] [service host]")
|
||||
print(" - remove [name]")
|
||||
print(" - update [name] [new service host]")
|
||||
print(" - list")
|
||||
for command in commandManager.commands:
|
||||
print(f" - {command.usage}")
|
||||
exit()
|
||||
|
||||
with open(configFile, "r") as config:
|
||||
configYml = yaml.safe_load(config)
|
||||
|
||||
http = configYml["http"]
|
||||
routers = http["routers"]
|
||||
services = http["services"]
|
||||
|
||||
def restartTraefik():
|
||||
print("Restarting Traefik, please wait this can take a while...")
|
||||
|
||||
# Restart Traefik in the base directory
|
||||
subprocess.run(["docker", "restart", "traefik"])
|
||||
|
||||
print(f"{Fore.GREEN}Done!{Fore.RESET}")
|
||||
|
||||
def addDomain(name, domain, serviceHost):
|
||||
# Check if name already exists
|
||||
if name in routers:
|
||||
print(f"Name \"{Fore.RED}{name}{Fore.RESET}\" already exists")
|
||||
exit()
|
||||
|
||||
print(f"Adding domain \"{Fore.CYAN}{name}{Fore.RESET}\" -> \"{Fore.YELLOW}{serviceHost}{Fore.RESET}\"")
|
||||
print(f"Domain: {Fore.GREEN}http://{domain}{Fore.RESET}")
|
||||
|
||||
# Add router
|
||||
routers[name] = {
|
||||
"entryPoints": ["https"],
|
||||
"rule": "Host(`%s`)" % domain,
|
||||
"middlewares": ["default-headers", "https-redirectscheme"],
|
||||
"tls": {},
|
||||
"service": name
|
||||
}
|
||||
|
||||
# Add service
|
||||
services[name] = {
|
||||
"loadBalancer": {
|
||||
"servers": [
|
||||
{
|
||||
"url": serviceHost
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
# Write to file
|
||||
with open(configFile, "w") as config:
|
||||
yaml.dump(configYml, config)
|
||||
|
||||
# Restart Traefik
|
||||
restartTraefik()
|
||||
|
||||
def removeDomain(name):
|
||||
# Check if name exists
|
||||
if name not in routers:
|
||||
print(f"Name \"{Fore.RED}{name}{Fore.RESET}\" does not exist")
|
||||
exit()
|
||||
|
||||
print(f"Removing domain \"{Fore.CYAN}{name}{Fore.RESET}\"")
|
||||
|
||||
# Remove router
|
||||
del routers[name]
|
||||
|
||||
# Remove service
|
||||
del services[name]
|
||||
|
||||
# Write to file
|
||||
with open(configFile, "w") as config:
|
||||
yaml.dump(configYml, config)
|
||||
|
||||
# Restart Traefik
|
||||
restartTraefik()
|
||||
|
||||
def listDomains():
|
||||
print("Listing domains:")
|
||||
|
||||
# name and domain -> service host
|
||||
domains = {}
|
||||
|
||||
# Loop through routers
|
||||
for name, router in routers.items():
|
||||
# Get domain
|
||||
domain = router["rule"].split("`")[1]
|
||||
|
||||
# Get service host
|
||||
serviceHost = services[name]["loadBalancer"]["servers"][0]["url"]
|
||||
|
||||
# Add to domains
|
||||
domains[name] = {
|
||||
"domain": domain,
|
||||
"serviceHost": serviceHost
|
||||
}
|
||||
|
||||
# Print domains
|
||||
for name, domain in domains.items():
|
||||
print(f" - {Fore.CYAN}[{name}] {Fore.GREEN}http://{domain['domain']} {Fore.RESET}-> {Fore.YELLOW}{domain['serviceHost']}{Fore.RESET}")
|
||||
|
||||
print("")
|
||||
print("Total: %s" % len(domains))
|
||||
|
||||
def updateDomain(name, serviceHost):
|
||||
# Check if name exists
|
||||
if name not in routers:
|
||||
print("Name \"%s\" does not exist" % name)
|
||||
exit()
|
||||
|
||||
print(f"Updating domain \"{Fore.CYAN}{name}{Fore.RESET}\" -> \"{Fore.YELLOW}{serviceHost}{Fore.RESET}\"")
|
||||
|
||||
# Update service
|
||||
services[name] = {
|
||||
"loadBalancer": {
|
||||
"servers": [
|
||||
{
|
||||
"url": serviceHost
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
# Write to file
|
||||
with open(configFile, "w") as config:
|
||||
yaml.dump(configYml, config)
|
||||
|
||||
# Restart Traefik
|
||||
restartTraefik()
|
||||
|
||||
match command:
|
||||
case "add":
|
||||
name = sys.argv[2]
|
||||
domain = sys.argv[3]
|
||||
serviceHost = sys.argv[4]
|
||||
addDomain(name, domain, serviceHost)
|
||||
case "remove":
|
||||
name = sys.argv[2]
|
||||
removeDomain(name)
|
||||
case "update":
|
||||
name = sys.argv[2]
|
||||
serviceHost = sys.argv[3]
|
||||
updateDomain(name, serviceHost)
|
||||
case "list":
|
||||
listDomains()
|
||||
args = sys.argv[2:]
|
||||
commandManager.getCommand(command).execute(traefikConfig, args)
|
||||
|
143
src/traefik/traefikConfig.py
Normal file
143
src/traefik/traefikConfig.py
Normal file
@ -0,0 +1,143 @@
|
||||
import yaml
|
||||
|
||||
|
||||
class TraefikConfig:
|
||||
|
||||
def __init__(self, configFile) -> None:
|
||||
self.configFile = configFile
|
||||
with open(configFile, "r") as config:
|
||||
self.configYml = yaml.safe_load(config)
|
||||
|
||||
def isValid(self) -> bool:
|
||||
return "http" in self.configYml and "routers" in self.configYml["http"] and "services" in self.configYml["http"]
|
||||
|
||||
def getRouter(self, name):
|
||||
return self.configYml["http"]["routers"][name]
|
||||
|
||||
def getService(self, name):
|
||||
return self.configYml["http"]["services"][name]
|
||||
|
||||
def addRouter(self, name, domain, serviceHost):
|
||||
# Add router
|
||||
self.configYml["http"]["routers"][name] = {
|
||||
"entryPoints": ["https"],
|
||||
"rule": "Host(`%s`)" % domain,
|
||||
"middlewares": ["default-headers", "https-redirectscheme"],
|
||||
"tls": {},
|
||||
"service": name
|
||||
}
|
||||
|
||||
# Add service
|
||||
self.configYml["http"]["services"][name] = {
|
||||
"loadBalancer": {
|
||||
"servers": [
|
||||
{
|
||||
"url": serviceHost
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
def addCatchAllRouter(self, name, domain, serviceHost):
|
||||
# Add router
|
||||
self.configYml["http"]["routers"][name] = {
|
||||
"entryPoints": ["https"],
|
||||
"rule": "HostRegexp(`{subdomain:[A-Za-z0-9-]+}.%s`)" % domain,
|
||||
"middlewares": ["default-headers", "https-redirectscheme"],
|
||||
"tls": {},
|
||||
"priority": 1,
|
||||
"service": name
|
||||
}
|
||||
|
||||
# Add service
|
||||
self.configYml["http"]["services"][name] = {
|
||||
"loadBalancer": {
|
||||
"servers": [
|
||||
{
|
||||
"url": serviceHost
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
def addSubPathRouter(self, name, domain, path, serviceHost):
|
||||
# Add trailing slashs
|
||||
if not path.endswith("/"):
|
||||
path += "/"
|
||||
if not serviceHost.endswith("/"):
|
||||
serviceHost += "/"
|
||||
|
||||
# Add path stripper middleware
|
||||
self.configYml["http"]["middlewares"][name] = {
|
||||
"stripPrefix": {
|
||||
"prefixes": [path]
|
||||
}
|
||||
}
|
||||
|
||||
# Add router
|
||||
self.configYml["http"]["routers"][name] = {
|
||||
"entryPoints": ["https"],
|
||||
"rule": "Host(`%s`) && PathPrefix(`%s`)" % (domain, path),
|
||||
"middlewares": ["default-headers", "https-redirectscheme", name],
|
||||
"tls": {},
|
||||
"service": name
|
||||
}
|
||||
|
||||
# Add service
|
||||
self.configYml["http"]["services"][name] = {
|
||||
"loadBalancer": {
|
||||
"servers": [
|
||||
{
|
||||
"url": serviceHost
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
def removeRouter(self, name):
|
||||
# Remove router
|
||||
del self.configYml["http"]["routers"][name]
|
||||
|
||||
# Remove service
|
||||
del self.configYml["http"]["services"][name]
|
||||
|
||||
def hasRouter(self, name):
|
||||
return name in self.configYml["http"]["routers"]
|
||||
|
||||
def hasPathRewrite(self, name):
|
||||
return name in self.configYml["http"]["middlewares"]
|
||||
|
||||
def hasService(self, name):
|
||||
return name in self.configYml["http"]["services"]
|
||||
|
||||
def getRouters(self):
|
||||
return self.configYml["http"]["routers"]
|
||||
|
||||
def getServices(self):
|
||||
return self.configYml["http"]["services"]
|
||||
|
||||
def getAll(self):
|
||||
domains = {}
|
||||
|
||||
routers = self.getRouters()
|
||||
services = self.getServices()
|
||||
|
||||
# Loop through routers
|
||||
for name, router in routers.items():
|
||||
# Get domain
|
||||
domain = router["rule"].split("`")[1]
|
||||
|
||||
# Get service host
|
||||
serviceHost = services[name]["loadBalancer"]["servers"][0]["url"]
|
||||
|
||||
# Add to domains
|
||||
domains[name] = {
|
||||
"domain": domain,
|
||||
"serviceHost": serviceHost
|
||||
}
|
||||
|
||||
return domains
|
||||
|
||||
def save(self):
|
||||
with open(self.configFile, "w") as config:
|
||||
yaml.dump(self.configYml, config)
|
22
src/utils/dockerUtils.py
Normal file
22
src/utils/dockerUtils.py
Normal file
@ -0,0 +1,22 @@
|
||||
import subprocess
|
||||
import os
|
||||
|
||||
containerName = "traefik"
|
||||
if os.environ.get("CONTAINER_NAME"):
|
||||
containerName = os.environ.get("CONTAINER_NAME")
|
||||
|
||||
def restartTraefik():
|
||||
# Check if we're in Windows, if so, don't restart Traefik
|
||||
if os.name == "nt":
|
||||
print("Restarting Traefik is not supported on Windows.")
|
||||
return
|
||||
print("Restarting Traefik, please wait this can take a while...")
|
||||
|
||||
# Restart Traefik in the base directory
|
||||
subprocess.run(["docker", "restart", containerName])
|
||||
|
||||
print("Done!")
|
||||
|
||||
def getTraefikLogs():
|
||||
print("Getting Traefik logs, please wait...")
|
||||
subprocess.run(["docker", "logs", containerName, "-f", "--tail=250"])
|
Reference in New Issue
Block a user