1
0
Fork 0
mirror of https://github.com/yavook/kiwi-scp.git synced 2024-11-23 05:13:01 +00:00
kiwi-scp/src/kiwi/subcommands/net.py

93 lines
2.6 KiB
Python
Raw Normal View History

2020-08-17 10:20:38 +00:00
# system
import logging
import subprocess
# local
from ._subcommand import SubCommand
from .utils.dockercommand import DockerCommand
from .utils.misc import are_you_sure
2020-08-17 10:20:38 +00:00
# parent
from ..config import LoadedConfig
2020-08-17 10:20:38 +00:00
def _find_net(net_name):
ps = DockerCommand('docker').run(None, [
'network', 'ls', '--filter', f"name={net_name}", '--format', '{{.Name}}'
], stdout=subprocess.PIPE)
2020-08-17 10:20:38 +00:00
net_found = str(ps.stdout, 'utf-8').strip()
return net_found == net_name
2020-08-17 10:20:38 +00:00
class NetUpCommand(SubCommand):
"""kiwi net-up"""
def __init__(self):
super().__init__(
'net-up',
2020-08-19 14:23:52 +00:00
action="Creating the local network hub for",
2020-08-17 10:20:38 +00:00
description="Create the local network hub for this instance"
)
def _run_instance(self, runner, args):
config = LoadedConfig.get()
net_name = config['network:name']
net_cidr = config['network:cidr']
if _find_net(net_name):
logging.info(f"Network '{net_name}' already exists")
2020-08-17 13:00:05 +00:00
return True
2020-08-17 10:20:38 +00:00
try:
DockerCommand('docker').run(None, [
'network', 'create',
'--driver', 'bridge',
'--internal',
'--subnet', net_cidr,
net_name
], check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
logging.info(f"Network '{net_name}' created")
2020-08-17 10:20:38 +00:00
except subprocess.CalledProcessError:
logging.error(f"Error creating network '{net_name}'")
2020-08-17 13:00:05 +00:00
return False
return True
2020-08-17 10:20:38 +00:00
class NetDownCommand(SubCommand):
"""kiwi net-down"""
def __init__(self):
super().__init__(
'net-down',
2020-08-19 14:23:52 +00:00
action="Removing the local network hub for",
2020-08-17 10:20:38 +00:00
description="Remove the local network hub for this instance"
)
def _run_instance(self, runner, args):
net_name = LoadedConfig.get()['network:name']
if not _find_net(net_name):
logging.info(f"Network '{net_name}' does not exist")
2020-08-17 13:00:05 +00:00
return True
2020-08-17 10:20:38 +00:00
try:
2020-08-17 12:51:43 +00:00
if are_you_sure("This will bring down this instance's hub network!"):
2020-08-17 13:00:05 +00:00
if runner.run('down'):
DockerCommand('docker').run(None, [
'network', 'rm', net_name
], check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
logging.info(f"Network '{net_name}' removed")
2020-08-17 13:00:05 +00:00
else:
return False
2020-08-17 10:20:38 +00:00
except subprocess.CalledProcessError:
logging.error(f"Error removing network '{net_name}'")
2020-08-17 13:00:05 +00:00
return False
2020-08-17 13:21:42 +00:00
return True