<commit_before>#!/usr/bin/python

# lxc_bootstrap
# Copyright (C) 2017  <NAME> <<EMAIL>>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

# LXC Bootstrapper, around the lxc-create 'Download' template for userspace
# containers; creates then modifies the container based on specifications.
#
# Designed for Ubuntu / Debian systems.

import sys
import argparse
import crypt
import subprocess as sp
import random
import platform
from string import ascii_letters, digits

SHADOW_SALT_CHARSET = ascii_letters + digits


class TransparentDict(dict):

    def __missing__(self, key):
        return key


# noinspection PyTypeChecker
ARCHITECTURE_MAP = TransparentDict({
    'x86_64': 'amd64',
    'x86': 'i386',
    'armv7l': 'armhf',
    'armv8l': 'arm64'
})


class User:

    def __init__(self, name, password, salt, admin):
        self.name = name
        self.password = password
        self.salt = salt
        self.admin = admin

    @property
    def shadow_password(self):
        if not self.salt or len(self.salt) != 8:
            # Create a random salt
            for _ in range(8):
                try:
                    self.salt += random.SystemRandom().choice(SHADOW_SALT_CHARSET)
                except (TypeError, UnboundLocalError):
                    self.salt = random.SystemRandom().choice(SHADOW_SALT_CHARSET)

        return crypt.crypt(self.password, ('$6${}$'.format(self.salt)))


class Container:
    create_cmd = "/usr/bin/lxc-create -t download -n {0.name} -- -d {0.distribution} -r {0.release} -a {0.architecture}"
    start_cmd = 'lxc-start -n {0.name}'
    attach_cmd = "/usr/bin/lxc-attach -n {0.name} -- "

    def __init__(self,
                 name=None,
                 architecture=None,
                 distribution=None,
                 release=None):
        self.name = name
        self.architecture = architecture
        self.distribution = distribution
        self.release = release
        self.attach_cmd = self.attach_cmd.format(self).split()

    def __call__(self, cmd, error_msg=None):
        cmd = self.attach_cmd + cmd.split()
        try:
            sp.check_call(cmd, stdout=sys.stdout, stderr=sys.stderr)
        except sp.CalledProcessError as e:
            if not error_msg:
                raise e
            print error_msg
            print e
            exit()

    def create(self):
        cmd = self.create_cmd.format(self).split()
        try:
            sp.check_call(cmd, stdout=sys.stdout, stderr=sys.stderr)
        except sp.CalledProcessError as e:
            print "Something went wrong when creating the container."
            print e
            exit()

    def start(self):
        cmd = self.start_cmd.format(self).split()
        try:
            sp.check_call(cmd, stdout=sys.stdout, stderr=sys.stderr)
        except sp.CalledProcessError as e:
            print "Could not start the container, cannot continue with bootstrap."
            print e
            exit()

    def bootstrap_users(self, users):
        # Default comes with 'ubuntu' user and group; let's nuke them
        self("deluser --remove-all-files {}".format("ubuntu"),
             "Could not delete default user and/or group, please refer to error logs.")
        try:
            self("delgroup --only-if-empty {}".format("ubuntu"))
        except sp.CalledProcessError as e:
            if e.returncode == 5:
                print "Could not delete default group, it's not empty!"
            elif e.returncode == 3:
                # return code of 3 means that the group doesn't exist, so we can
                # move on.
                pass

        # Since we just nuked the '1000' group and user (default Ubuntu), let's
        # start there now.
        uid, gid = 1000, 1000

        for user in users:
            try:
                self("useradd --create-home -u {uid} -g {gid} -p {user.shadow_password} "
                     "--shell=/bin/bash {user.name}".format(
                     user=user, gid=gid, uid=uid))
                self(
                    "groupadd -g {gid} {user.name}".format(user=user, gid=gid))
                if user.admin:
                    self("usermod -a -G sudo {user.name}".format(user=user))
            except sp.CalledProcessError:
                print "Something went wrong when bootstrapping user '{0.name}'...".format(user)
            uid += 1
            gid += 1

    def bootstrap_packages(self, to_add, to_exclude, autoremove=False):
        self("apt-get install -y {}".format(" ".join(to_add)), "Something went wrong installing "
                                                               "additional packages.")
        self("apt-get remove -y --purge {}".format(" ".join(to_exclude)), "Something went wrong "
                                                                          "removing specified packages.")
        if autoremove:
            self("apt-get autoremove -y --purge", "Something went wrong cleaning up after removal with 'autoremove'.")<commit_msg>More FLAKE<commit_after>#!/usr/bin/python

# lxc_bootstrap
# Copyright (C) 2017  <NAME> <<EMAIL>>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

# LXC Bootstrapper, around the lxc-create 'Download' template for userspace
# containers; creates then modifies the container based on specifications.
#
# Designed for Ubuntu / Debian systems.

import sys
import argparse
import crypt
import subprocess as sp
import random
import platform
from string import ascii_letters, digits

SHADOW_SALT_CHARSET = ascii_letters + digits


class TransparentDict(dict):

    def __missing__(self, key):
        return key


# noinspection PyTypeChecker
ARCHITECTURE_MAP = TransparentDict({
    'x86_64': 'amd64',
    'x86': 'i386',
    'armv7l': 'armhf',
    'armv8l': 'arm64'
})


class User:

    def __init__(self, name, password, salt, admin):
        self.name = name
        self.password = password
        self.salt = salt
        self.admin = admin

    @property
    def shadow_password(self):
        if not self.salt or len(self.salt) != 8:
            # Create a random salt
            for _ in range(8):
                try:
                    self.salt += random.SystemRandom().choice(SHADOW_SALT_CHARSET)
                except (TypeError, UnboundLocalError):
                    self.salt = random.SystemRandom().choice(SHADOW_SALT_CHARSET)

        return crypt.crypt(self.password, ('$6${}$'.format(self.salt)))


class Container:
    create_cmd = "/usr/bin/lxc-create -t download -n {0.name} -- -d {0.distribution} -r {0.release} -a {0.architecture}"
    start_cmd = 'lxc-start -n {0.name}'
    attach_cmd = "/usr/bin/lxc-attach -n {0.name} -- "

    def __init__(self,
                 name=None,
                 architecture=None,
                 distribution=None,
                 release=None):
        self.name = name
        self.architecture = architecture
        self.distribution = distribution
        self.release = release
        self.attach_cmd = self.attach_cmd.format(self).split()

    def __call__(self, cmd, error_msg=None):
        cmd = self.attach_cmd + cmd.split()
        try:
            sp.check_call(cmd, stdout=sys.stdout, stderr=sys.stderr)
        except sp.CalledProcessError as e:
            if not error_msg:
                raise e
            print error_msg
            print e
            exit()

    def create(self):
        cmd = self.create_cmd.format(self).split()
        try:
            sp.check_call(cmd, stdout=sys.stdout, stderr=sys.stderr)
        except sp.CalledProcessError as e:
            print "Something went wrong when creating the container."
            print e
            exit()

    def start(self):
        cmd = self.start_cmd.format(self).split()
        try:
            sp.check_call(cmd, stdout=sys.stdout, stderr=sys.stderr)
        except sp.CalledProcessError as e:
            print "Could not start the container, cannot continue with bootstrap."
            print e
            exit()

    def bootstrap_users(self, users):
        # Default comes with 'ubuntu' user and group; let's nuke them
        self("deluser --remove-all-files {}".format("ubuntu"),
             "Could not delete default user and/or group, please refer to error logs.")
        try:
            self("delgroup --only-if-empty {}".format("ubuntu"))
        except sp.CalledProcessError as e:
            if e.returncode == 5:
                print "Could not delete default group, it's not empty!"
            elif e.returncode == 3:
                # return code of 3 means that the group doesn't exist, so we can
                # move on.
                pass

        # Since we just nuked the '1000' group and user (default Ubuntu), let's
        # start there now.
        uid, gid = 1000, 1000

        for user in users:
            try:
                self("useradd --create-home -u {uid} -g {gid} -p {user.shadow_password} "
                     "--shell=/bin/bash {user.name}".format(
                     user=user, gid=gid, uid=uid))
                self("groupadd -g {gid} {user.name}".format(user=user, gid=gid))
                if user.admin:
                    self("usermod -a -G sudo {user.name}".format(user=user))
            except sp.CalledProcessError:
                print "Something went wrong when bootstrapping user '{0.name}'...".format(user)
            uid += 1
            gid += 1

    def bootstrap_packages(self, to_add, to_exclude, autoremove=False):
        self("apt-get install -y {}".format(" ".join(to_add)), "Something went wrong installing "
                                                               "additional packages.")
        self("apt-get remove -y --purge {}".format(" ".join(to_exclude)), "Something went wrong "
                                                                          "removing specified packages.")
        if autoremove:
            self("apt-get autoremove -y --purge", "Something went wrong cleaning up after removal with 'autoremove'.")
{'fraction_non_alphanumeric': 0.10158900196393501, 'fraction_numerical': 0.008391358685948938, 'mean_word_length': 2.031935047361299, 'pattern_counts': {'":': 0, '<': 11, '<?xml version=': 0, '>': 11, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 14, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2950827', 'n_tokens_mistral': 3258, 'n_tokens_neox': 3032, 'n_words': 1003}