import logging from urllib.parse import urlparse from cliff.command import Command from utils import utils import os class AddService(Command): "Adds a new service to Traefik" log = logging.getLogger(__name__) def get_parser(self, prog_name): parser = super().get_parser(prog_name) parser.add_argument('name', help='The name of the service') parser.add_argument('domain', help='The domain for the service') parser.add_argument('service', help='The service of the service') return parser def take_action(self, parsed_args): name = parsed_args.name host = parsed_args.domain service = parsed_args.service parsedUrl = urlparse(service) protocol = parsedUrl.scheme service = parsedUrl.hostname port = parsedUrl.port if not port: if protocol == "https": port = 443 elif protocol == "http": port = 80 # The name of the TLS secret # Examples: # - fascinated.cc -> fascinated-cc # - bob.fascinated.cc -> fascinated-cc # - bob.local.fascinated.cc -> local-fascinated-cc host_parts = host.split('.') if len(host_parts) > 2: tls_secret = '-'.join(host_parts[1:]) # Join everything from the second part onward else: tls_secret = '-'.join(host_parts) # Use the entire host for two-part domains # Define the path to save the YAML file filePath = f'{utils.getServicesPath()}/{host}.yml' # Check if the service file already exists, if so exit if os.path.exists(filePath): print(f"Service \"{name}\" already exists ({filePath})") return isInstalled = utils.checkIfKubectlInstalled() if not isInstalled: self.log.error("kubectl is not installed") return 1 utils.createService(filePath, name, host, service, protocol, port, tls_secret)