Setup a bash environment inside a container.

    Creates a new chroot, which the user can use as a bash to run the wanted
    projects inside the mounted container, that also gets returned afterwards.
545754
def setup_bash_in_container(builddir, _container, outfile, shell):
    
    with local.cwd(builddir):
        # Switch to bash inside uchroot
        print("Entering bash inside User-Chroot. Prepare your image and "
              "type 'exit' when you are done. If bash exits with a non-zero"
              "exit code, no new container will be stored.")
        store_new_container = True
        try:
            run_in_container(shell, _container)
        except ProcessExecutionError:
            store_new_container = False

        if store_new_container:
            print("Packing new container image.")
            pack_container(_container, outfile)
            config_path = str(CFG["config_file"])
            CFG.store(config_path)
            print("Storing config in {0}".format(os.path.abspath(config_path)))
1124138
private function createEnv(): void
    {
        if (file_exists(base_dir('.env'))) {
            $dotEnv = new Dotenv();
            $dotEnv->load(base_dir('.env'));
            $this->env = $dotEnv;
        }
    }
723488
def create(output_dir):
    """"""
    template_path = os.path.join(os.path.dirname(__file__), 'project_template')

    click.secho('Let\'s create a new component!', fg='green')
    name = click.prompt('What is the name of this component (ex. python-pip)?')

    click.secho('')
    click.secho('We assume this will be pushed to GitHub and Docker Hub eventually, but these don\'t have to exist yet.', fg='green')
    repo_owner = click.prompt('GitHub repo owner (i.e. your username or organization name)')
    repo_name = click.prompt('GitHub repo name', default=name)
    dockerhub_owner = click.prompt('Docker Hub repo owner', default=repo_owner)
    dockerhub_name = click.prompt('Docker Hub repo name', default=repo_name)

    license_owner = click.prompt('Who should be the copyright owner on project?', default=repo_owner)

    extra_context = {
        'name': name,
        'name_shields_io': name.replace('-', '--'),
        'current_year': datetime.datetime.now().year,
        'dependencies_cli_version': __version__,
        'repo_owner': repo_owner,
        'repo_name': repo_name,
        'dockerhub_owner': dockerhub_owner,
        'dockerhub_name': dockerhub_name,
        'license_owner': license_owner,
    }
    project_dir = cookiecutter(template_path, no_input=True, extra_context=extra_context, output_dir=output_dir)

    click.secho('')
    click.secho('{name} is ready to go, `cd {project_dir}` and try running `dependencies test`!'.format(name=name, project_dir=project_dir), fg='green')
    click.secho(
        'We started you out with a fully functioning component based in python.\n' +
        'Once you\'ve got a handle on how it works then you can change it to whatever language you want.'
    )
52149
def _run_web_container(self, port, command, address, log_syslog=False,
                           datapusher=True, interactive=False):
        
        if is_boot2docker():
            ro = {}
            volumes_from = self._get_container_name('venv')
        else:
            ro = {self.datadir + '/venv': '/usr/lib/ckan'}
            volumes_from = None

        links = {
            self._get_container_name('solr'): 'solr',
            self._get_container_name('postgres'): 'db'
        }

        links.update({self._get_container_name(container): container
                      for container in self.extra_containers})

        if datapusher:
            if 'datapusher' not in self.containers_running():
                raise DatacatsError(container_logs(self._get_container_name('datapusher'), "all",
                                                   False, False))
            links[self._get_container_name('datapusher')] = 'datapusher'

        ro = dict({
                  self.target: '/project/',
                  scripts.get_script_path('web.sh'): '/scripts/web.sh',
                  scripts.get_script_path('adjust_devini.py'): '/scripts/adjust_devini.py'},
                  **ro)
        rw = {
            self.sitedir + '/files': '/var/www/storage',
            self.sitedir + '/run/development.ini': '/project/development.ini'
            }
        try:
            if not interactive:
                run_container(
                    name=self._get_container_name('web'),
                    image='datacats/web',
                    rw=rw,
                    ro=ro,
                    links=links,
                    volumes_from=volumes_from,
                    command=command,
                    port_bindings={
                        5000: port if is_boot2docker() else (address, port)},
                    log_syslog=log_syslog
                    )
            else:
                # FIXME: share more code with interactive_shell
                if is_boot2docker():
                    switches = ['--volumes-from',
                                self._get_container_name('pgdata'), '--volumes-from',
                                self._get_container_name('venv')]
                else:
                    switches = []
                switches += ['--volume={}:{}:ro'.format(vol, ro[vol]) for vol in ro]
                switches += ['--volume={}:{}'.format(vol, rw[vol]) for vol in rw]
                links = ['--link={}:{}'.format(link, links[link]) for link in links]
                args = ['docker', 'run', '-it', '--name', self._get_container_name('web'),
                        '-p', '{}:5000'.format(port) if is_boot2docker()
                        else '{}:{}:5000'.format(address, port)] + \
                    switches + links + ['datacats/web', ] + command
                subprocess.call(args)
        except APIError as e:
            if '409' in str(e):
                raise DatacatsError('Web container already running. '
                                    'Please stop_web before running.')
            else:
                raise
463831
def setup():
    

    init_tasks()

    run_hook("before_setup")

    # Create shared folder
    env.run("mkdir -p %s" % (paths.get_shared_path()))
    env.run("chmod 755 %s" % (paths.get_shared_path()))

    # Create backup folder
    env.run("mkdir -p %s" % (paths.get_backup_path()))
    env.run("chmod 750 %s" % (paths.get_backup_path()))

    # Create uploads folder
    env.run("mkdir -p %s" % (paths.get_upload_path()))
    env.run("chmod 775 %s" % (paths.get_upload_path()))

    run_hook("setup")
    run_hook("after_setup")
297261
def prepareSystem(cls):
        
        try:
            resourceRootDirPath = os.environ[cls.rootDirPathEnvName]
        except KeyError:
            # Create directory holding local copies of requested resources ...
            resourceRootDirPath = mkdtemp()
            # .. and register its location in an environment variable such that child processes
            # can find it.
            os.environ[cls.rootDirPathEnvName] = resourceRootDirPath
        assert os.path.isdir(resourceRootDirPath)
277746
def get_init_container(self,
                           init_command,
                           init_args,
                           env_vars,
                           context_mounts,
                           persistence_outputs,
                           persistence_data):
        """"""
        env_vars = to_list(env_vars, check_none=True)
        outputs_path = stores.get_job_outputs_path(
            persistence=persistence_outputs,
            job_name=self.job_name)
        _, outputs_volume_mount = get_pod_outputs_volume(persistence_outputs=persistence_outputs)
        volume_mounts = outputs_volume_mount + to_list(context_mounts, check_none=True)
        init_command = init_command or ["/bin/sh", "-c"]
        init_args = init_args or to_list(
            get_output_args(command=InitCommands.CREATE,
                            outputs_path=outputs_path))
        init_args += to_list(get_auth_context_args(entity='job',
                                                   entity_name=self.job_name))
        return client.V1Container(
            name=self.init_container_name,
            image=self.init_docker_image,
            image_pull_policy=self.init_docker_image_pull_policy,
            command=init_command,
            args=[''.join(init_args)],
            env=env_vars,
            volume_mounts=volume_mounts)
566018
def start_container(self, image, container_name: str, repo_path: Path):
        
        command = "bash -i"

        if self.inherit_image:
            command = "sh -i"

        container = self.client.containers.run(image, command=command, detach=True, tty=True, name=container_name,
                                               working_dir=str((Path("/srv/data") / self.cwd).resolve()),
                                               auto_remove=True)

        container.exec_run(["mkdir", "-p", "/srv/scripts"])
        container.put_archive("/srv", self.tar_files(repo_path))
        container.put_archive("/srv/scripts", self.tar_runner())

        return container
206718
def create_new_environment(project_root, environment_name)
      # Check if the environment exist
      return error(_('wizard.environment.name_exist')%{environment: environment_name}) if Bebox::Environment.environment_exists?(project_root, environment_name)
      # Environment creation
      environment = Bebox::Environment.new(environment_name, project_root)
      output = environment.create
      ok _('wizard.environment.creation_success')
      return output
    end
1268384
def create_environment(home_dir, site_packages=False, clear=False,
                       unzip_setuptools=False,
                       prompt=None, search_dirs=None, download=False,
                       no_setuptools=False, no_pip=False, no_wheel=False,
                       symlink=True):
    
    home_dir, lib_dir, inc_dir, bin_dir = path_locations(home_dir)

    py_executable = os.path.abspath(install_python(
        home_dir, lib_dir, inc_dir, bin_dir,
        site_packages=site_packages, clear=clear, symlink=symlink))

    install_distutils(home_dir)

    to_install = []

    if not no_setuptools:
        to_install.append('setuptools')

    if not no_pip:
        to_install.append('pip')

    if not no_wheel:
        to_install.append('wheel')

    if to_install:
        install_wheel(
            to_install,
            py_executable,
            search_dirs,
            download=download,
        )

    install_activate(home_dir, bin_dir, prompt)

    install_python_config(home_dir, bin_dir, prompt)
1184418
def create(self, environment, target_name):
        
        remote_server_command(
            ["ssh", environment.deploy_target, "create", target_name],
            environment, self,
            clean_up=True,
            )
1026622
def create(path)
      raise ContainerError, "Container already exists." if exists?

      if path.is_a?(Hash)
        args = "-n #{name}"

        if !!path[:config_file]
          unless File.exists?(path[:config_file])
            raise ArgumentError, "File #{path[:config_file]} does not exist."
          end
          args += " -f #{path[:config_file]}"
        end

        if !!path[:template]
          template_dir =  path[:template_dir] || "/usr/lib/lxc/templates"
          template_path = File.join(template_dir,"lxc-#{path[:template]}")
          unless File.exists?(template_path)
            raise ArgumentError, "Template #{path[:template]} does not exist."
          end
          args += " -t #{path[:template]} "
        end

        args += " -B #{path[:backingstore]}" if !!path[:backingstore]
        args += " -- #{path[:template_options].join(" ")}".strip if !!path[:template_options]

        LXC.run("create", args)
        exists?
      else
        unless File.exists?(path)
          raise ArgumentError, "File #{path} does not exist."
        end

        LXC.run("create", "-n", name, "-f", path)
        exists?
      end
    end
626498
def _run(name,
         cmd,
         exec_driver=None,
         output=None,
         stdin=None,
         python_shell=True,
         output_loglevel='debug',
         ignore_retcode=False,
         use_vt=False,
         keep_env=None):
    '''
    
    '''
    if exec_driver is None:
        exec_driver = _get_exec_driver()
    ret = __salt__['container_resource.run'](
        name,
        cmd,
        container_type=__virtualname__,
        exec_driver=exec_driver,
        output=output,
        stdin=stdin,
        python_shell=python_shell,
        output_loglevel=output_loglevel,
        ignore_retcode=ignore_retcode,
        use_vt=use_vt,
        keep_env=keep_env)

    if output in (None, 'all'):
        return ret
    else:
        return ret[output]
750541
def _make_container_root(name):
    '''
    
    '''
    path = _root(name)
    if os.path.exists(path):
        __context__['retcode'] = salt.defaults.exitcodes.SALT_BUILD_FAIL
        raise CommandExecutionError(
            'Container {0} already exists'.format(name)
        )
    else:
        try:
            os.makedirs(path)
            return path
        except OSError as exc:
            raise CommandExecutionError(
                'Unable to make container root directory {0}: {1}'
                .format(name, exc)
            )
42254
def install_ssh_components(container, host)
      case host['platform']
      when /ubuntu/, /debian/
        container.exec(%w(apt-get update))
        container.exec(%w(apt-get install -y openssh-server openssh-client))
      when /cumulus/
        container.exec(%w(apt-get update))
        container.exec(%w(apt-get install -y openssh-server openssh-client))
      when /fedora-(2[2-9])/
        container.exec(%w(dnf clean all))
        container.exec(%w(dnf install -y sudo openssh-server openssh-clients))
        container.exec(%w(ssh-keygen -t rsa -f /etc/ssh/ssh_host_rsa_key))
        container.exec(%w(ssh-keygen -t dsa -f /etc/ssh/ssh_host_dsa_key))
      when /^el-/, /centos/, /fedora/, /redhat/, /eos/
        container.exec(%w(yum clean all))
        container.exec(%w(yum install -y sudo openssh-server openssh-clients))
        container.exec(%w(ssh-keygen -t rsa -f /etc/ssh/ssh_host_rsa_key))
        container.exec(%w(ssh-keygen -t dsa -f /etc/ssh/ssh_host_dsa_key))
      when /opensuse/, /sles/
        container.exec(%w(zypper -n in openssh))
        container.exec(%w(ssh-keygen -t rsa -f /etc/ssh/ssh_host_rsa_key))
        container.exec(%w(ssh-keygen -t dsa -f /etc/ssh/ssh_host_dsa_key))
        container.exec(%w(sed -ri 's/^#?UsePAM .*/UsePAM no/' /etc/ssh/sshd_config))
      when /archlinux/
        container.exec(%w(pacman --noconfirm -Sy archlinux-keyring))
        container.exec(%w(pacman --noconfirm -Syu))
        container.exec(%w(pacman -S --noconfirm openssh))
        container.exec(%w(ssh-keygen -A))
        container.exec(%w(sed -ri 's/^#?UsePAM .*/UsePAM no/' /etc/ssh/sshd_config))
        container.exec(%w(systemctl enable sshd))
      when /alpine/
        container.exec(%w(apk add --update openssh))
        container.exec(%w(ssh-keygen -A))
      else
        # TODO add more platform steps here
        raise "platform #{host['platform']} not yet supported on docker"
      end

      # Make sshd directory, set root password
      container.exec(%w(mkdir -p /var/run/sshd))
      container.exec(['/bin/sh', '-c', "echo root:#{root_password} | chpasswd"])
    end
1287647
def create(*args)
    # since we don't care about the inputs, just glob args
    rc, new_path = czk.create(*args)
    [rc, @req_registry.strip_chroot_from(new_path)]
  end
221533
def _container_init(self):
        
        if ENV_CONTAINER in os.environ:
            if os.environ[ENV_CONTAINER] in ['docker', 'oci']:
                self._in_container = True
        if ENV_HOST_SYSROOT in os.environ:
            self._host_sysroot = os.environ[ENV_HOST_SYSROOT]
        use_sysroot = self._in_container and self._host_sysroot != '/'
        if use_sysroot:
            host_tmp_dir = os.path.abspath(self._host_sysroot + self._tmp_dir)
            self._tmp_dir = host_tmp_dir
        return self._host_sysroot if use_sysroot else None