Given a pexpect/child object, return the shutit_pexpect_session object.
500067
def get_shutit_pexpect_session_from_child(self, shutit_pexpect_child):
		
		shutit_global.shutit_global_object.yield_to_draw()
		if not isinstance(shutit_pexpect_child, pexpect.pty_spawn.spawn):
			self.fail('Wrong type in get_shutit_pexpect_session_child: ' + str(type(shutit_pexpect_child)),throw_exception=True) # pragma: no cover
		for key in self.shutit_pexpect_sessions:
			if self.shutit_pexpect_sessions[key].pexpect_child == shutit_pexpect_child:
				return self.shutit_pexpect_sessions[key]
		return self.fail('Should not get here in get_shutit_pexpect_session',throw_exception=True)
364813
def by_id(cls, _id, engine_or_session):
        
        ses, auto_close = ensure_session(engine_or_session)
        obj = ses.query(cls).get(_id)
        if auto_close:
            ses.close()
        return obj
667401
def add_to_bashrc(self, line, shutit_pexpect_child=None, match_regexp=None, note=None, loglevel=logging.DEBUG):
		
		shutit_global.shutit_global_object.yield_to_draw()
		shutit_pexpect_child = shutit_pexpect_child or self.get_current_shutit_pexpect_session().pexpect_child
		shutit_pexpect_session = self.get_shutit_pexpect_session_from_child(shutit_pexpect_child)
		shutit_pexpect_session.add_to_bashrc(line,match_regexp=match_regexp,note=note,loglevel=loglevel)
		return True
34423
def kill_session(self):
        """"""

        proc = self.cmd('kill-session', '-t%s' % self.id)

        if proc.stderr:
            raise exc.LibTmuxException(proc.stderr)
469571
def return_socket(self, sock_info):
        """"""
        if self.pid != os.getpid():
            self.reset()
        else:
            if sock_info.pool_id != self.pool_id:
                sock_info.close()
            elif not sock_info.closed:
                sock_info.update_last_checkin_time()
                with self.lock:
                    self.sockets.appendleft(sock_info)

        self._socket_semaphore.release()
        with self.lock:
            self.active_sockets -= 1
728385
def expect(self,
	           expect,
	           searchwindowsize=None,
	           maxread=None,
	           timeout=None,
	           iteration_n=1):
		
		if isinstance(expect, str):
			expect = [expect]
		if searchwindowsize != None:
			old_searchwindowsize = self.pexpect_child.searchwindowsize
			self.pexpect_child.searchwindowsize = searchwindowsize
		if maxread != None:
			old_maxread = self.pexpect_child.maxread
			self.pexpect_child.maxread = maxread
		res = self.pexpect_child.expect(expect + [pexpect.TIMEOUT] + [pexpect.EOF], timeout=timeout)
		if searchwindowsize != None:
			self.pexpect_child.searchwindowsize = old_searchwindowsize
		if maxread != None:
			self.pexpect_child.maxread = old_maxread
		# Add to session lines only if pane manager exists.
		if shutit_global.shutit_global_object.pane_manager and iteration_n == 1:
			time_seen = time.time()
			lines_to_add = []
			if isinstance(self.pexpect_child.before, (str,unicode)):
				for line_str in self.pexpect_child.before.split('\n'):
					lines_to_add.append(line_str)
			if isinstance(self.pexpect_child.after, (str,unicode)):
				for line_str in self.pexpect_child.after.split('\n'):
					lines_to_add.append(line_str)
			# If first or last line is empty, remove it.
			#if len(lines_to_add) > 0 and lines_to_add[1] == '':
			#	lines_to_add = lines_to_add[1:]
			#if len(lines_to_add) > 0 and lines_to_add[-1] == '':
			#	lines_to_add = lines_to_add[:-1]
			for line in lines_to_add:
				self.session_output_lines.append(SessionPaneLine(line_str=line, time_seen=time_seen, line_type='output'))
		return res
1331792
def defaultSessionFactory(env={}, usePTY=False, *args, **kwargs):
    
    return SSHSession(env, usePTY, *args, **kwargs)
872031
def get_current_shutit_pexpect_session_environment(self, note=None):
		
		self.handle_note(note)
		current_session = self.get_current_shutit_pexpect_session()
		if current_session is not None:
			res = current_session.current_environment
		else:
			res = None
		self.handle_note_after(note)
		return res
725226
def is_shutit_installed(self,
	                        module_id,
	                        note=None,
	                        loglevel=logging.DEBUG):
		
		shutit_global.shutit_global_object.yield_to_draw()
		shutit_pexpect_session = self.get_current_shutit_pexpect_session()
		return shutit_pexpect_session.is_shutit_installed(module_id,note=note,loglevel=loglevel)
558916
def session(self):
        
        engine = self.engine
        connection = engine.connect()
        db_session = scoped_session(
            sessionmaker(autocommit=False, autoflush=True, bind=engine))
        yield db_session
        db_session.close()
        connection.close()
842492
def sendline(self, sendspec):
		
		assert not sendspec.started, shutit_util.print_debug()
		shutit = self.shutit
		shutit.log('Sending in pexpect session (' + str(id(self)) + '): ' + str(sendspec.send), level=logging.DEBUG)
		if sendspec.expect:
			shutit.log('Expecting: ' + str(sendspec.expect), level=logging.DEBUG)
		else:
			shutit.log('Not expecting anything', level=logging.DEBUG)
		try:
			# Check there are no background commands running that have block_other_commands set iff
			# this sendspec says
			if self._check_blocked(sendspec) and sendspec.ignore_background != True:
				shutit.log('sendline: blocked', level=logging.DEBUG)
				return False
			# If this is marked as in the background, create a background object and run in the background.
			if sendspec.run_in_background:
				shutit.log('sendline: run_in_background', level=logging.DEBUG)
				# If this is marked as in the background, create a background object and run in the background after newlines sorted.
				shutit_background_command_object = self.login_stack.get_current_login_item().append_background_send(sendspec)
				# Makes no sense to check exit for a background command.
				sendspec.check_exit = False
			if sendspec.nonewline != True:
				sendspec.send += '\n'
				# sendspec has newline added now, so no need to keep marker
				sendspec.nonewline = True
			if sendspec.run_in_background:
				shutit_background_command_object.run_background_command()
				return True
			#shutit.log('sendline: actually sending: ' + sendspec.send, level=logging.DEBUG)
			self.pexpect_child.send(sendspec.send)
			return False
		except OSError:
			self.shutit.fail('Caught failure to send, assuming user has exited from pause point.')
667665
def pexpireat(self, name, when):
        
        if isinstance(when, datetime.datetime):
            ms = int(when.microsecond / 1000)
            when = int(mod_time.mktime(when.timetuple())) * 1000 + ms
        return self.execute_command('PEXPIREAT', name, when)
252286
def _session(self):
        """"""
        # Taken from the session docs.
        session = self._session_maker()
        try:
            yield session
            session.commit()
        except:
            session.rollback()
            raise
        finally:
            session.close()
1354818
def expect_end(self):
        
        logger.debug("Waiting for termination of '{0}'".format(self.name))
        try:
            # Make sure we fetch the last output bytes.
            # Recommendation from the pexpect docs.
            self._spawn.expect(pexpect.EOF)
            self._spawn.wait()
            dircontent = str(os.listdir(self.job.working_dir))
            logger.debug("Working directory after execution: " + dircontent)
            return self.get_exitstatus(), self.get_output()
        except pexpect.exceptions.EOF as e:
            logger.debug("Raising termination exception.")
            raise TerminationException(instance=self, real_exception=e, output=self.get_output())
        except pexpect.exceptions.TIMEOUT as e:
            logger.debug("Raising timeout exception.")
            raise TimeoutException(instance=self, real_exception=e, output=self.get_output())
        except Exception as e:
            logger.debug("Waiting for expected program end failed.")
            raise NestedException(instance=self, real_exception=e, output=self.get_output())
1128451
def _get_socket(self, sid):
        """"""
        try:
            s = self.sockets[sid]
        except KeyError:
            raise KeyError('Session not found')
        if s.closed:
            del self.sockets[sid]
            raise KeyError('Session is disconnected')
        return s
1299366
def build(self, shutit):
		
		target_child = self.start_container(shutit, 'target_child')
		self.setup_host_child(shutit)
		# TODO: on the host child, check that the image running has bash as its cmd/entrypoint.
		self.setup_target_child(shutit, target_child)
		shutit.send('chmod -R 777 ' + shutit_global.shutit_global_object.shutit_state_dir + ' && mkdir -p ' + shutit_global.shutit_global_object.shutit_state_dir_build_db_dir + '/' + shutit_global.shutit_global_object.build_id, shutit_pexpect_child=target_child, echo=False)
		return True
1257092
def _expect_method(self, command):
        
        child = pexpect.spawn(self._ipmitool_path, self.args + command)
        
        i = child.expect([pexpect.TIMEOUT, 'Password: '], timeout=10)
        if i == 0:
            child.terminate()
            self.error = 'ipmitool command timed out'
            self.status = 1
        else:
            child.sendline(self.password)
        
        i = child.expect([pexpect.TIMEOUT, pexpect.EOF], timeout=10)
        if i == 0:
            child.terminate()
            self.error = 'ipmitool command timed out'
            self.status = 1
        else:
            if child.exitstatus:
                self.error = child.before
            else:
                self.output = child.before

            self.status = child.exitstatus
            child.close()