Skip to content

Commit

Permalink
added host to container copying function and fixed setup.py
Browse files Browse the repository at this point in the history
  • Loading branch information
mofm committed Mar 2, 2022
1 parent 96cc420 commit 7290923
Show file tree
Hide file tree
Showing 10 changed files with 129 additions and 52 deletions.
56 changes: 37 additions & 19 deletions README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,19 @@ Install:

.. code-block::
$ pip install -e nspctl
$ pip install nspctl/
If you would like to install for your user:

.. code-block::
$ pip install --user nspctl/
and you need to add '.local/bin' directory to your path

.. code-block::
$ export PATH="~/.local/bin/:$PATH"
Usage:
######
Expand All @@ -101,115 +113,121 @@ Usage:
Commands:
*********

- '*list*' : List currently running (online) containers.
- *list* : List currently running (online) containers.

.. code-block::
$ nspctl list
- '*list-stopped*' : List stopped containers.( shortopts: 'lss')
- *list-stopped* : List stopped containers.( shortopts: 'lss')

.. code-block::
$ nspctl list-stopped
$ nspctl lss
- '*list-running*' : List currently running containers.(alias: 'list', shortopt: 'lsr')
- *list-running* : List currently running containers.(alias: 'list', shortopt: 'lsr')

.. code-block::
$ nspctl list-running
$ nspctl lsr
- '*list-all*' : List all containers.(shortopt: 'lsa')
- *list-all* : List all containers.(shortopt: 'lsa')

.. code-block::
$ nspctl list-all
$ nspctl lsa
- '*info NAME*' : Show properties of container.
- *info NAME* : Show properties of container.

.. code-block::
$ nspctl info ubuntu-20.04
- '*start NAME*' : Start a container as system service.
- *start NAME* : Start a container as system service.

.. code-block::
$ nspctl start ubuntu-20.04
- '*reboot NAME*' : Reboot a container.
- *reboot NAME* : Reboot a container.

.. code-block::
$ nspctl reboot ubuntu-20.04
- '*stop NAME*' : Stop a container. Shutdown cleanly.(alias: 'poweroff')
- *stop NAME* : Stop a container. Shutdown cleanly.(alias: 'poweroff')

.. code-block::
$ nspctl stop ubuntu-20.04
- '*terminate NAME*' : Immediately terminates container without cleanly shutting it down.
- *terminate NAME* : Immediately terminates container without cleanly shutting it down.

.. code-block::
$ nspctl terminate ubuntu-20.04
- '*poweroff NAME*' : Poweroff a container. Shutdown cleanly.
- *poweroff NAME* : Poweroff a container. Shutdown cleanly.

.. code-block::
$ nspctl poweroff ubuntu-20.04
- '*enable NAME*' : Enable a container as a system service at system boot.
- *enable NAME* : Enable a container as a system service at system boot.

.. code-block::
$ nspctl enable ubuntu-20.04
- '*disable NAME*' : Disable a container as a system service at system boot.
- *disable NAME* : Disable a container as a system service at system boot.

.. code-block::
$ nspctl disable ubuntu-20.04
- '*remove NAME*' : Remove a container completely.
- *remove NAME* : Remove a container completely.

.. code-block::
$ nspctl remove ubuntu-20.04
- '*shell NAME*' : Open an interactive shell session in a container.
- *shell NAME* : Open an interactive shell session in a container.

.. code-block::
$ nspctl shell ubuntu-20.04
- *copy-to NAME SOURCE DESTINATION* : Copies files from the host system into a running container.

.. code-block::
$ nspctl copy-to ubuntu-20.04 /home/hostuser/magicfile /home/containeruser/
Container Operations:
*********************

- '*pull-tar URL NAME*' : Downloads a .tar container image from the specified URL.(tar, tar.gz, tar.xz, tar.bz2)
- *pull-tar URL NAME* : Downloads a .tar container image from the specified URL.(tar, tar.gz, tar.xz, tar.bz2)

.. code-block::
$ nspctl pul-tar https://github.com/mofm/meta-econ/releases/download/v0.3.0-r2/econ-tiny-nginx-20220123-qemux86-64.tar.xz econ-nginx
- '*pull-raw URL NAME*' : Downloads a .raw container from the specified URL.(qcow2 or compressed as gz, xz, bz2)
- *pull-raw URL NAME* : Downloads a .raw container from the specified URL.(qcow2 or compressed as gz, xz, bz2)

.. code-block::
$ nspctl pull-raw http://ftp.fau.de/gentoo/experimental/amd64/qemu/allpython-amd64-qemu-20100531.qcow2.xz gentoo-python
- '*pull-dkr URL NAME INDEX*' : Download a docker image from the specified URL.
- *pull-dkr URL NAME INDEX* : Download a docker image from the specified URL.

.. code-block::
$ nspctl pull-dkr centos/centos6 cent6 https://get.docker.com
- '*bootstrap NAME DIST VERSION*' : Bootstrap a container from package servers. Supported Distributions are Debian, Ubuntu and Arch Linux.
- *bootstrap NAME DIST VERSION* : Bootstrap a container from package servers. Supported Distributions are Debian, Ubuntu and Arch Linux.

.. code-block::
Expand Down
7 changes: 7 additions & 0 deletions scripts/nspctl
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,13 @@ from nspctl.lib.help import nspctl_help
from nspctl import __version__

if __name__ == "__main__":
if not main.check_system():
sys.stderr.write(
"The nspctl command failed to load:"
"only work on systems that have been booted with systemd."
)
sys.exit(1)

parser = argparse.ArgumentParser(add_help=False)
subparsers = parser.add_subparsers(dest='subcommand')
subparsers.add_parser('help')
Expand Down
2 changes: 1 addition & 1 deletion setup.cfg
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[metadata]
name = nspctl
version = 0.0.1-dev1
version = attr: nspctl.__version__
author = Emre Eryilmaz
author_email = [email protected]
license = GPLv3
Expand Down
2 changes: 0 additions & 2 deletions setup.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
from setuptools import setup, find_packages
from src.nspctl import __version__


classifiers = [
Expand All @@ -20,7 +19,6 @@

setup(
name='nspctl',
version=__version__,
packages=find_packages(where='src'),
packages_dir={"": "src"},
url='https://github.com/mofm/nspctl',
Expand Down
2 changes: 1 addition & 1 deletion src/nspctl/__init__.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
""" management tool for systemd-nspawn containers"""
from .version import __version__

__author__ = "Emre Eryilmaz, [email protected]"
__credits__ = "Emre Eryilmaz"
__version__ = "0.0.1-dev01"
25 changes: 4 additions & 21 deletions src/nspctl/_nspctl.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,10 @@
import functools
import shutil

from nspctl.utils.systemd import systemd_booted, systemd_version
from nspctl.utils.platform import is_linux
from nspctl.utils.systemd import systemd_version
from nspctl.utils.cmd import run_cmd, popen
from nspctl.utils.args import invalid_kwargs, clean_kwargs
from nspctl.utils.container_resource import cont_run, copy_to, con_init, login_shell
from nspctl.utils.container_resource import cont_run, cont_cpt, con_init, login_shell
from nspctl.utils.path import which
from nspctl.lib.functools import alias_function
from nspctl.utils.user import get_uid
Expand All @@ -21,22 +20,6 @@
EXEC_DRIVER = "nsenter"


def __virtual__():
"""
Only work on systems that have been booted with systemd
"""
if is_linux() and systemd_booted():
if systemd_version() is None:
logger.error("nspctl: Unable to determine systemd version")
else:
return __virtualname__
return (
False,
"The nspctl command failed to load: "
"only work on systems that have been booted with systemd.",
)


def _sd_version():
"""
Returns systemd version
Expand Down Expand Up @@ -684,7 +667,7 @@ def _failed_remove(name, exc):

@_ensure_exists
@_check_useruid
def con_copy(name, source, dest, overwrite=False, makedirs=False):
def copy_to(name, source, dest, overwrite=False, makedirs=False):
"""
Copy a file from host in to a container
"""
Expand All @@ -697,7 +680,7 @@ def con_copy(name, source, dest, overwrite=False, makedirs=False):
else:
orig_state = state(name)
pid = con_pid(name)
ret = copy_to(
ret = cont_cpt(
pid,
source,
dest,
Expand Down
13 changes: 13 additions & 0 deletions src/nspctl/lib/help.py
Original file line number Diff line number Diff line change
Expand Up @@ -175,5 +175,18 @@ def nspctl_help():
+ turquoise("container name")
+ " ] "
)
print(
" "
+ turquoise("nspctl")
+ " [ "
+ green("cpt -> copy-to")
+ " ] [ "
+ turquoise("container name")
+ " ] [ "
+ turquoise("source")
+ " ] [ "
+ turquoise("destination")
+ " ] "
)
print()
print(" For more help: https://github.com/mofm/nspctl \n")
34 changes: 34 additions & 0 deletions src/nspctl/lib/main.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,24 @@
import argparse

from nspctl.utils.platform import is_linux
from nspctl.utils.systemd import systemd_booted, systemd_version
from nspctl import _nspctl
from nspctl.lib.output import nprint
import logging

logger = logging.getLogger(__name__)


def check_system():
"""
Only work on systems that have been booted with systemd
"""
if is_linux() and systemd_booted():
if systemd_version() is None:
logger.error("nspctl: Unable to determine systemd version")
else:
return True
return False


# Create a decorator pattern that maintains a registry
Expand Down Expand Up @@ -339,3 +356,20 @@ def bootstrap(self, args=None, subparsers=None):

args = 'bootstrap'
return args

@command
def copy_to(self, args=None, subparsers=None):
"""
Copy a file from host in to a container
All parameters are mandatory
"""
if subparsers is not None:
sp = subparsers.add_parser("copy-to", aliases=['cpt'])
sp.add_argument("name")
sp.add_argument("source")
sp.add_argument("dest")
sp.set_defaults(func=self.copy_to)
return

args = 'copy_to'
return args
29 changes: 21 additions & 8 deletions src/nspctl/utils/container_resource.py
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,7 @@ def cont_run(


@_validate
def copy_to(
def cont_cpt(
pid,
source,
dest,
Expand Down Expand Up @@ -127,18 +127,27 @@ def copy_to(
if not os.path.isabs(dest):
raise Exception("Destination path must be absolute")
if (
cont_run(pid, "test -d {}".format(dest), exec_driver=exec_driver, is_shell=True)["returncode"]
cont_run(pid, "test -d {}".format(dest),
container_type=container_type,
exec_driver=exec_driver,
is_shell=True)["returncode"]
== 0
):
dest = os.path.join(dest, source_name)
else:
dest_dir, dest_name = os.path.split(dest)
if (
cont_run(pid, "test -d {}".format(dest_dir), exec_driver=exec_driver, is_shell=True)["returncode"]
cont_run(pid, "test -d {}".format(dest_dir),
container_type=container_type,
exec_driver=exec_driver,
is_shell=True)["returncode"]
!= 0
):
if makedirs:
res = cont_run(pid, "mkdir -p {}".format(dest_dir), exec_driver=exec_driver, is_shell=True)
res = cont_run(pid, "mkdir -p {}".format(dest_dir),
container_type=container_type,
exec_driver=exec_driver,
is_shell=True)
if res["returncode"] != 0:
error = (
"Unable to create destination directory {} "
Expand All @@ -152,7 +161,10 @@ def copy_to(

if (
not overwrite and
cont_run(pid, "test -e {}".format(dest), exec_driver=exec_driver, is_shell=True)["returncode"]
cont_run(pid, "test -e {}".format(dest),
container_type=container_type,
exec_driver=exec_driver,
is_shell=True)["returncode"]
== 0
):
raise Exception(
Expand All @@ -163,10 +175,11 @@ def copy_to(
if exec_driver == "nsenter":
copy_cmd = 'cat "{}" | {} env -i {} tee "{}"'.format(
source, _nsenter(pid), PATH, dest)
if copy_cmd != os.EX_OK:
raise Exception("failed copying file!")
cmd_exec = run_cmd(copy_cmd, is_shell=True)
if cmd_exec["returncode"] != 0:
raise Exception("Failed copying the file!")
else:
return "copy command completed"
return "Copy command completed!"


@_validate
Expand Down
Loading

0 comments on commit 7290923

Please sign in to comment.