desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Executes "log all" and returns response as a list of messages. Each message is a list of 3 elements: time, flags and text. @rtype: list @return: List of messages'
def messages(self):
return map((lambda x: x.split(',')), self.execute('log', 'all'))
'Executes "kill IP:port" command and returns response as a string @type addr: str @param addr: Real address of client to kill (in IP:port format) @rtype: str @return: Response string'
def killbyaddr(self, addr):
return self.execute('kill', addr)[0]
'Executes "kill cn" command and returns response as a string @type cn: str @param cn: Common name of client(s) to kill @rtype: str @return: Response string'
def killbycn(self, cn):
return self.execute('kill', cn)[0]
'Parses generically formatted response (param1=value1,param2=value2,param3=value3) @type response: str @param response: Response string @return: Dictionary'
@staticmethod def _pgenresp(response):
return dict(map((lambda x: x.split('=')), response.split(',')))
'Executes "load-stats" command and returns response as a dictionary: >>> print manager.stats() {\'nclients\': \'2\', \'bytesout\': \'21400734\', \'bytesin\': \'10129283\'} @rtype: dict @return: Dictionary'
def stats(self):
return self._pgenresp(self.execute('load-stats')[0])
'Executes "signal" command and returns response as a string. @type signal: str @param signal: Signal name (SIGHUP, SIGTERM, SIGUSR1 or SIGUSR2) @rtype: str @return: Response string'
def signal(self, signal):
assert (signal in ['SIGHUP', 'SIGTERM', 'SIGUSR1', 'SIGUSR2']) return self.execute('signal', signal)[0]
'Executes "pid" command and returns response as a dictionary. @return: Dictionary'
def pid(self):
return self._pgenresp(self.execute('pid')[0])['pid']
'Should return a default config dict'
def create_config(self):
return None
'Returns all :class:`Service` s.'
@cache_value(1) def get_all(self):
r = [] for mgr in self.managers: r += mgr.get_all() return r
'Returns a :class:`Service` by name.'
def get_one(self, name):
for mgr in self.managers: s = mgr.get_one(name) if s: return s return None
'Returns a :class:`Service` by name.'
def get_one(self, name):
for s in self.get_all(): if (s.name == name): return s return None
'returns state string'
def measure(self, path):
if (not path): return (-1) output = subprocess.check_output(['hdparm', '-C', ('/dev/' + path)]).splitlines() if (len(output) < 3): return None r = output[(-1)].split(':')[(-1)].strip() return r
'-1 = No SMART 0 = DISK FAILING 1 = PRE-FAIL 2 = Unknown error 3 = Errors in log 4 = DISK OK'
def measure(self, path):
if (not path): return (-1) r = subprocess.call(['smartctl', '-H', ('/dev/' + path)]) if (r & 2): return (-1) if (r & 8): return 0 if (r & 16): return 1 if (r & 64): return 3 if (r == 0): return 4 return 2
'Reset state to ``"stream"`` and empty parameter attributes.'
def reset(self):
self.state = u'stream' self.flags = {} self.params = [] self.current = u''
'Consumes a single string character and advance the state as necessary. :param str char: a character to consume.'
def consume(self, char):
if (not isinstance(char, str)): raise TypeError((u'%s requires str input' % self.__class__.__name__)) try: self.handlers.get(self.state)(char) except TypeError: pass except KeyError: if __debug__: self.flags[u'state'] = self.state self.flags[u'unhandled'] = char self.dispatch(u'debug', *self.params) self.reset() else: raise
'Consumes a string and advance the state as necessary. :param str chars: a string to feed from.'
def feed(self, chars):
if (not isinstance(chars, str)): raise TypeError((u'%s requires text input' % self.__class__.__name__)) for char in chars: self.consume(char)
'Adds a given screen to the listeners queue. :param pyte.screens.Screen screen: a screen to attach to. :param list only: a list of events you want to dispatch to a given screen (empty by default, which means -- dispatch all events).'
def attach(self, screen, only=()):
self.listeners.append((screen, set(only)))
'Removes a given screen from the listeners queue and failes silently if it\'s not attached. :param pyte.screens.Screen screen: a screen to detach.'
def detach(self, screen):
for (idx, (listener, _)) in enumerate(self.listeners): if (screen is listener): self.listeners.pop(idx)
'Dispatches an event. Event handlers are looked up implicitly in the listeners\' ``__dict__``, so, if a listener only wants to handle ``DRAW`` events it should define a ``draw()`` method or pass ``only=["draw"]`` argument to :meth:`attach`. .. warning:: If any of the attached listeners throws an exception, the subsequent callbacks are be aborted. :param str event: event to dispatch. :param list args: arguments to pass to event handlers.'
def dispatch(self, event, *args, **kwargs):
for (listener, only) in self.listeners: if (only and (event not in only)): continue try: handler = getattr(listener, event) except AttributeError: continue if hasattr(listener, u'__before__'): listener.__before__(event) handler(*args, **self.flags) if hasattr(listener, u'__after__'): listener.__after__(event) else: if kwargs.get(u'reset', True): self.reset()
'Processes a character when in the default ``"stream"`` state.'
def _stream(self, char):
if (char in self.basic): self.dispatch(self.basic[char]) elif (char == ctrl.ESC): self.state = u'escape' elif (char == ctrl.CSI): self.state = u'arguments' elif (char not in [ctrl.NUL, ctrl.DEL]): self.dispatch(u'draw', char)
'Handles characters seen when in an escape sequence. Most non-VT52 commands start with a left-bracket after the escape and then a stream of parameters and a command; with a single notable exception -- :data:`escape.DECOM` sequence, which starts with a sharp. .. versionchanged:: 0.4.10 For compatibility with Linux terminal stream also recognizes ``ESC % C`` sequences for selecting control character set. However, in the current version these are no-op.'
def _escape(self, char):
if (char == u'#'): self.state = u'sharp' elif (char == u'%'): self.state = u'percent' elif (char == u'['): self.state = u'arguments' elif (char in u'()'): self.state = u'charset' self.flags[u'mode'] = char else: self.dispatch(self.escape[char])
'Parses arguments of a `"#"` sequence.'
def _sharp(self, char):
self.dispatch(self.sharp[char])
'Parses arguments of a `"%"` sequence.'
def _percent(self, char):
self.dispatch(self.percent[char])
'Parses ``G0`` or ``G1`` charset code.'
def _charset(self, char):
self.dispatch(u'set_charset', char)
'Parses arguments of an escape sequence. All parameters are unsigned, positive decimal integers, with the most significant digit sent first. Any parameter greater than 9999 is set to 9999. If you do not specify a value, a 0 value is assumed. .. seealso:: `VT102 User Guide <http://vt100.net/docs/vt102-ug/>`_ For details on the formatting of escape arguments. `VT220 Programmer Reference <http://http://vt100.net/docs/vt220-rm/>`_ For details on the characters valid for use as arguments.'
def _arguments(self, char):
if (char == u'?'): self.flags[u'private'] = True elif (char in [ctrl.BEL, ctrl.BS, ctrl.HT, ctrl.LF, ctrl.VT, ctrl.FF, ctrl.CR]): self.dispatch(self.basic[char], reset=False) elif (char == ctrl.SP): pass elif (char in [ctrl.CAN, ctrl.SUB]): self.dispatch(u'draw', char) self.state = u'stream' elif char.isdigit(): self.current += char else: self.params.append(min(int((self.current or 0)), 9999)) if (char == u';'): self.current = u'' else: self.dispatch(self.csi[char], *self.params)
'Returns screen size -- ``(lines, columns)``'
@property def size(self):
return (self.lines, self.columns)
'Returns a :func:`list` of screen lines as unicode strings.'
@property def display(self):
return [u''.join(map(operator.attrgetter(u'data'), line)) for line in self.buffer]
'Resets the terminal to its initial state. * Scroll margins are reset to screen boundaries. * Cursor is moved to home location -- ``(0, 0)`` and its attributes are set to defaults (see :attr:`default_char`). * Screen is cleared -- each character is reset to :attr:`default_char`. * Tabstops are reset to "every eight columns". .. note:: Neither VT220 nor VT102 manuals mentioned that terminal modes and tabstops should be reset as well, thanks to :manpage:`xterm` -- we now know that.'
def reset(self):
self.buffer[:] = (take(self.columns, self.default_line) for _ in range(self.lines)) self.mode = set([mo.DECAWM, mo.DECTCEM]) self.margins = Margins(0, (self.lines - 1)) self.charset = 0 self.g0_charset = cs.IBMPC_MAP self.g1_charset = cs.VT100_MAP self.tabstops = set(range(7, self.columns, 8)) self.cursor = Cursor(0, 0) self.cursor_position()
'Resize the screen to the given dimensions. If the requested screen size has more lines than the existing screen, lines will be added at the bottom. If the requested size has less lines than the existing screen lines will be clipped at the top of the screen. Similarly, if the existing screen has less columns than the requested screen, columns will be added at the right, and if it has more -- columns will be clipped at the right. .. note:: According to `xterm`, we should also reset origin mode and screen margins, see ``xterm/screen.c:1761``. :param int lines: number of lines in the new screen. :param int columns: number of columns in the new screen.'
def resize(self, lines=None, columns=None):
lines = (lines or self.lines) columns = (columns or self.columns) diff = (self.lines - lines) if (diff < 0): self.buffer.extend((take(self.columns, self.default_line) for _ in range(diff, 0))) elif (diff > 0): self.buffer[:diff] = () diff = (self.columns - columns) if (diff < 0): for y in range(lines): self.buffer[y].extend(take(abs(diff), self.default_line)) elif (diff > 0): for line in self.buffer: del line[columns:] (self.lines, self.columns) = (lines, columns) self.margins = Margins(0, (self.lines - 1)) self.reset_mode(mo.DECOM)
'Selects top and bottom margins for the scrolling region. Margins determine which screen lines move during scrolling (see :meth:`index` and :meth:`reverse_index`). Characters added outside the scrolling region do not cause the screen to scroll. :param int top: the smallest line number that is scrolled. :param int bottom: the biggest line number that is scrolled.'
def set_margins(self, top=None, bottom=None):
if ((top is None) or (bottom is None)): return top = max(0, min((top - 1), (self.lines - 1))) bottom = max(0, min((bottom - 1), (self.lines - 1))) if ((bottom - top) >= 1): self.margins = Margins(top, bottom) self.cursor_position()
'Set active ``G0`` or ``G1`` charset. :param str code: character set code, should be a character from ``"B0UK"`` -- otherwise ignored. :param str mode: if ``"("`` ``G0`` charset is set, if ``")"`` -- we operate on ``G1``. .. warning:: User-defined charsets are currently not supported.'
def set_charset(self, code, mode):
if (code in cs.MAPS): setattr(self, {u'(': u'g0_charset', u')': u'g1_charset'}[mode], cs.MAPS[code])
'Sets (enables) a given list of modes. :param list modes: modes to set, where each mode is a constant from :mod:`pyte.modes`.'
def set_mode(self, *modes, **kwargs):
if kwargs.get(u'private'): modes = [(mode << 5) for mode in modes] self.mode.update(modes) if (mo.DECCOLM in modes): self.resize(columns=132) self.erase_in_display(2) self.cursor_position() if (mo.DECOM in modes): self.cursor_position() if (mo.DECSCNM in modes): self.buffer[:] = ([char._replace(reverse=True) for char in line] for line in self.buffer) self.select_graphic_rendition(g._SGR[u'+reverse']) if (mo.DECTCEM in modes): self.cursor.hidden = False
'Resets (disables) a given list of modes. :param list modes: modes to reset -- hopefully, each mode is a constant from :mod:`pyte.modes`.'
def reset_mode(self, *modes, **kwargs):
if kwargs.get(u'private'): modes = [(mode << 5) for mode in modes] self.mode.difference_update(modes) if (mo.DECCOLM in modes): self.resize(columns=80) self.erase_in_display(2) self.cursor_position() if (mo.DECOM in modes): self.cursor_position() if (mo.DECSCNM in modes): self.buffer[:] = ([char._replace(reverse=False) for char in line] for line in self.buffer) self.select_graphic_rendition(g._SGR[u'-reverse']) if (mo.DECTCEM in modes): self.cursor.hidden = True
'Activates ``G0`` character set.'
def shift_in(self):
self.charset = 0
'Activates ``G1`` character set.'
def shift_out(self):
self.charset = 1
'Display a character at the current cursor position and advance the cursor if :data:`~pyte.modes.DECAWM` is set. :param str char: a character to display.'
def draw(self, char):
char = char.translate([self.g0_charset, self.g1_charset][self.charset]) if (self.cursor.x == self.columns): if (mo.DECAWM in self.mode): self.carriage_return() self.linefeed() else: self.cursor.x -= 1 if (mo.IRM in self.mode): self.insert_characters(1) self.buffer[self.cursor.y][self.cursor.x] = self.cursor.attrs._replace(data=char) self.cursor.x += 1
'Move the cursor to the beginning of the current line.'
def carriage_return(self):
self.cursor.x = 0
'Move the cursor down one line in the same column. If the cursor is at the last line, create a new line at the bottom.'
def index(self):
(top, bottom) = self.margins if (self.cursor.y == bottom): self.buffer.pop(top) self.buffer.insert(bottom, take(self.columns, self.default_line)) else: self.cursor_down()
'Move the cursor up one line in the same column. If the cursor is at the first line, create a new line at the top.'
def reverse_index(self):
(top, bottom) = self.margins if (self.cursor.y == top): self.buffer.pop(bottom) self.buffer.insert(top, take(self.columns, self.default_line)) else: self.cursor_up()
'Performs an index and, if :data:`~pyte.modes.LNM` is set, a carriage return.'
def linefeed(self):
self.index() if (mo.LNM in self.mode): self.carriage_return() self.ensure_bounds()
'Move to the next tab space, or the end of the screen if there aren\'t anymore left.'
def tab(self):
for stop in sorted(self.tabstops): if (self.cursor.x < stop): column = stop break else: column = (self.columns - 1) self.cursor.x = column
'Move cursor to the left one or keep it in it\'s position if it\'s at the beginning of the line already.'
def backspace(self):
self.cursor_back()
'Push the current cursor position onto the stack.'
def save_cursor(self):
self.savepoints.append(Savepoint(copy.copy(self.cursor), self.g0_charset, self.g1_charset, self.charset, (mo.DECOM in self.mode), (mo.DECAWM in self.mode)))
'Set the current cursor position to whatever cursor is on top of the stack.'
def restore_cursor(self):
if self.savepoints: savepoint = self.savepoints.pop() self.g0_charset = savepoint.g0_charset self.g1_charset = savepoint.g1_charset self.charset = savepoint.charset if savepoint.origin: self.set_mode(mo.DECOM) if savepoint.wrap: self.set_mode(mo.DECAWM) self.cursor = savepoint.cursor self.ensure_bounds(use_margins=True) else: self.reset_mode(mo.DECOM) self.cursor_position()
'Inserts the indicated # of lines at line with cursor. Lines displayed **at** and below the cursor move down. Lines moved past the bottom margin are lost. :param count: number of lines to delete.'
def insert_lines(self, count=None):
count = (count or 1) (top, bottom) = self.margins if (top <= self.cursor.y <= bottom): for line in range(self.cursor.y, min((bottom + 1), (self.cursor.y + count))): self.buffer.pop(bottom) self.buffer.insert(line, take(self.columns, self.default_line)) self.carriage_return()
'Deletes the indicated # of lines, starting at line with cursor. As lines are deleted, lines displayed below cursor move up. Lines added to bottom of screen have spaces with same character attributes as last line moved up. :param int count: number of lines to delete.'
def delete_lines(self, count=None):
count = (count or 1) (top, bottom) = self.margins if (top <= self.cursor.y <= bottom): for _ in range(min(((bottom - self.cursor.y) + 1), count)): self.buffer.pop(self.cursor.y) self.buffer.insert(bottom, list(repeat(self.cursor.attrs, self.columns))) self.carriage_return()
'Inserts the indicated # of blank characters at the cursor position. The cursor does not move and remains at the beginning of the inserted blank characters. Data on the line is shifted forward. :param int count: number of characters to insert.'
def insert_characters(self, count=None):
count = (count or 1) for _ in range(min((self.columns - self.cursor.y), count)): self.buffer[self.cursor.y].insert(self.cursor.x, self.cursor.attrs) self.buffer[self.cursor.y].pop()
'Deletes the indicated # of characters, starting with the character at cursor position. When a character is deleted, all characters to the right of cursor move left. Character attributes move with the characters. :param int count: number of characters to delete.'
def delete_characters(self, count=None):
count = (count or 1) for _ in range(min((self.columns - self.cursor.x), count)): self.buffer[self.cursor.y].pop(self.cursor.x) self.buffer[self.cursor.y].append(self.cursor.attrs)
'Erases the indicated # of characters, starting with the character at cursor position. Character attributes are set cursor attributes. The cursor remains in the same position. :param int count: number of characters to erase. .. warning:: Even though *ALL* of the VTXXX manuals state that character attributes **should be reset to defaults**, ``libvte``, ``xterm`` and ``ROTE`` completely ignore this. Same applies too all ``erase_*()`` and ``delete_*()`` methods.'
def erase_characters(self, count=None):
count = (count or 1) for column in range(self.cursor.x, min((self.cursor.x + count), self.columns)): self.buffer[self.cursor.y][column] = self.cursor.attrs
'Erases a line in a specific way. :param int type_of: defines the way the line should be erased in: * ``0`` -- Erases from cursor to end of line, including cursor position. * ``1`` -- Erases from beginning of line to cursor, including cursor position. * ``2`` -- Erases complete line. :param bool private: when ``True`` character attributes are left unchanged **not implemented**.'
def erase_in_line(self, type_of=0, private=False):
interval = (range(self.cursor.x, self.columns), range(0, (self.cursor.x + 1)), range(0, self.columns))[type_of] for column in interval: self.buffer[self.cursor.y][column] = self.cursor.attrs
'Erases display in a specific way. :param int type_of: defines the way the line should be erased in: * ``0`` -- Erases from cursor to end of screen, including cursor position. * ``1`` -- Erases from beginning of screen to cursor, including cursor position. * ``2`` -- Erases complete display. All lines are erased and changed to single-width. Cursor does not move. :param bool private: when ``True`` character attributes are left unchanged **not implemented**.'
def erase_in_display(self, type_of=0, private=False):
interval = (range((self.cursor.y + 1), self.lines), range(0, self.cursor.y), range(0, self.lines))[type_of] for line in interval: self.buffer[line][:] = (self.cursor.attrs for _ in range(self.columns)) if (type_of in [0, 1]): self.erase_in_line(type_of)
'Sest a horizontal tab stop at cursor position.'
def set_tab_stop(self):
self.tabstops.add(self.cursor.x)
'Clears a horizontal tab stop in a specific way, depending on the ``type_of`` value: * ``0`` or nothing -- Clears a horizontal tab stop at cursor position. * ``3`` -- Clears all horizontal tab stops.'
def clear_tab_stop(self, type_of=None):
if (not type_of): self.tabstops.discard(self.cursor.x) elif (type_of == 3): self.tabstops = set()
'Ensure that current cursor position is within screen bounds. :param bool use_margins: when ``True`` or when :data:`~pyte.modes.DECOM` is set, cursor is bounded by top and and bottom margins, instead of ``[0; lines - 1]``.'
def ensure_bounds(self, use_margins=None):
if (use_margins or (mo.DECOM in self.mode)): (top, bottom) = self.margins else: (top, bottom) = (0, (self.lines - 1)) self.cursor.x = min(max(0, self.cursor.x), (self.columns - 1)) self.cursor.y = min(max(top, self.cursor.y), bottom)
'Moves cursor up the indicated # of lines in same column. Cursor stops at top margin. :param int count: number of lines to skip.'
def cursor_up(self, count=None):
self.cursor.y -= (count or 1) self.ensure_bounds(use_margins=True)
'Moves cursor up the indicated # of lines to column 1. Cursor stops at bottom margin. :param int count: number of lines to skip.'
def cursor_up1(self, count=None):
self.cursor_up(count) self.carriage_return()
'Moves cursor down the indicated # of lines in same column. Cursor stops at bottom margin. :param int count: number of lines to skip.'
def cursor_down(self, count=None):
self.cursor.y += (count or 1) self.ensure_bounds(use_margins=True)
'Moves cursor down the indicated # of lines to column 1. Cursor stops at bottom margin. :param int count: number of lines to skip.'
def cursor_down1(self, count=None):
self.cursor_down(count) self.carriage_return()
'Moves cursor left the indicated # of columns. Cursor stops at left margin. :param int count: number of columns to skip.'
def cursor_back(self, count=None):
self.cursor.x -= (count or 1) self.ensure_bounds()
'Moves cursor right the indicated # of columns. Cursor stops at right margin. :param int count: number of columns to skip.'
def cursor_forward(self, count=None):
self.cursor.x += (count or 1) self.ensure_bounds()
'Set the cursor to a specific `line` and `column`. Cursor is allowed to move out of the scrolling region only when :data:`~pyte.modes.DECOM` is reset, otherwise -- the position doesn\'t change. :param int line: line number to move the cursor to. :param int column: column number to move the cursor to.'
def cursor_position(self, line=None, column=None):
column = ((column or 1) - 1) line = ((line or 1) - 1) if (mo.DECOM in self.mode): line += self.margins.top if (not (self.margins.top <= line <= self.margins.bottom)): return (self.cursor.x, self.cursor.y) = (column, line) self.ensure_bounds()
'Moves cursor to a specific column in the current line. :param int column: column number to move the cursor to.'
def cursor_to_column(self, column=None):
self.cursor.x = ((column or 1) - 1) self.ensure_bounds()
'Moves cursor to a specific line in the current column. :param int line: line number to move the cursor to.'
def cursor_to_line(self, line=None):
self.cursor.y = ((line or 1) - 1) if (mo.DECOM in self.mode): self.cursor.y += self.margins.top self.ensure_bounds()
'Fills screen with uppercase E\'s for screen focus and alignment.'
def alignment_display(self):
for line in self.buffer: for (column, char) in enumerate(line): line[column] = char._replace(data=u'E')
'Set display attributes. :param list attrs: a list of display attributes to set.'
def select_graphic_rendition(self, *attrs):
replace = {} for attr in (attrs or [0]): if (attr in g.FG): replace[u'fg'] = g.FG[attr] elif (attr in g.BG): replace[u'bg'] = g.BG[attr] elif (attr in g.TEXT): attr = g.TEXT[attr] replace[attr[1:]] = attr.startswith(u'+') elif (not attr): replace = self.default_char._asdict() self.cursor.attrs = self.cursor.attrs._replace(**replace)
'Ensures a screen is at the bottom of the history buffer.'
def __before__(self, command):
if (command not in [u'prev_page', u'next_page']): while (self.history.position < self.history.size): self.next_page() super(HistoryScreen, self).__before__(command)
'Ensures all lines on a screen have proper width (:attr:`columns`). Extra characters are truncated, missing characters are filled with whitespace.'
def __after__(self, command):
if (command in [u'prev_page', u'next_page']): for (idx, line) in enumerate(self.buffer): if (len(line) > self.columns): self.buffer[idx] = line[:self.columns] elif (len(line) < self.columns): self.buffer[idx] = (line + take((self.columns - len(line)), self.default_line)) self.cursor.hidden = (not ((abs((self.history.position - self.history.size)) < self.lines) and (mo.DECTCEM in self.mode))) super(HistoryScreen, self).__after__(command)
'Overloaded to reset screen history state: history position is reset to bottom of both queues; queues themselves are emptied.'
def reset(self):
super(HistoryScreen, self).reset() self.history.top.clear() self.history.bottom.clear() self.history = self.history._replace(position=self.history.size)
'Overloaded to update top history with the removed lines.'
def index(self):
(top, bottom) = self.margins if (self.cursor.y == bottom): self.history.top.append(self.buffer[top]) super(HistoryScreen, self).index()
'Overloaded to update bottom history with the removed lines.'
def reverse_index(self):
(top, bottom) = self.margins if (self.cursor.y == top): self.history.bottom.append(self.buffer[bottom]) super(HistoryScreen, self).reverse_index()
'Moves the screen page up through the history buffer. Page size is defined by ``history.ratio``, so for instance ``ratio = .5`` means that half the screen is restored from history on page switch.'
def prev_page(self):
if ((self.history.position > self.lines) and self.history.top): mid = min(len(self.history.top), int(math.ceil((self.lines * self.history.ratio)))) self.history.bottom.extendleft(reversed(self.buffer[(- mid):])) self.history = self.history._replace(position=(self.history.position - self.lines)) self.buffer[:] = (list(reversed([self.history.top.pop() for _ in range(mid)])) + self.buffer[:(- mid)]) self.dirty = set(range(self.lines))
'Moves the screen page down through the history buffer.'
def next_page(self):
if ((self.history.position < self.history.size) and self.history.bottom): mid = min(len(self.history.bottom), int(math.ceil((self.lines * self.history.ratio)))) self.history.top.extend(self.buffer[:mid]) self.history = self.history._replace(position=(self.history.position + self.lines)) self.buffer[:] = (self.buffer[mid:] + [self.history.bottom.popleft() for _ in range(mid)]) self.dirty = set(range(self.lines))
'Marks this session as dead'
def destroy(self):
self.active = False for g in self.greenlets: g.kill() self.manager.vacuum()
'Updates the "last used" timestamp'
def touch(self):
self.timestamp = time.time()
'Spawns a ``greenlet`` that will be stopped and garbage-collected when the session is destroyed :params: Same as for :func:`gevent.spawn`'
def spawn(self, *args, **kwargs):
g = gevent.spawn(*args, **kwargs) self.greenlets += [g]
'Adds headers to :class:`ajenti.http.HttpContext` that set the session cookie'
def set_cookie(self, context):
context.add_header('Set-Cookie', Cookie('session', self.id, path='/', httponly=True).render_response())
'Eliminates dead sessions'
def vacuum(self):
for session in [x for x in self.sessions.values() if x.is_dead()]: del self.sessions[session.id]
'Creates a new session for the :class:`ajenti.http.HttpContext`'
def open_session(self, context):
session_id = self.generate_session_id(context) session = Session(self, session_id) self.sessions[session_id] = session return session
'Pushes the middleware onto the stack'
def add(self, middleware):
self.stack.append(middleware)
'Dispatches the WSGI request'
def dispatch(self, env, start_response):
if (not _validate_origin(env)): start_response('403 Invalid Origin', []) return '' context = HttpContext(env, start_response) for middleware in self.stack: output = middleware.handle(context) if (output is not None): return output
'Adds a given HTTP header to the response :type key: str :type value: str'
def add_header(self, key, value):
self.headers += [(key, value)]
'Removed a given HTTP header from the response :type key: str'
def remove_header(self, key):
self.headers = filter((lambda h: (h[0] != key)), self.headers)
'Executes a ``handler`` in this context :returns: handler-supplied output'
def fallthrough(self, handler):
return handler.handle(self)
'Creates a response with given HTTP status line :type status: str'
def respond(self, status):
self.start_response(status, self.headers) self.response_ready = True
'Creates a ``HTTP 200 OK`` response'
def respond_ok(self):
self.respond('200 OK')
'Returns a HTTP ``500 Server Error`` response'
def respond_server_error(self):
self.respond('500 Server Error') return 'Server Error'
'Returns a HTTP ``403 Forbidden`` response'
def respond_forbidden(self):
self.respond('403 Forbidden') return 'Forbidden'
'Returns a ``HTTP 404 Not Found`` response'
def respond_not_found(self):
self.respond('404 Not Found') return 'Not Found'
'Returns a ``HTTP 302 Found`` redirect response with given ``url`` :type url: str'
def redirect(self, url):
self.add_header('Location', url) self.respond('302 Found') return ''
'Returns a GZip compressed response with given ``content`` and correct headers :type content: str :type compression: int :rtype: str'
def gzip(self, content, compression=9):
io = StringIO() gz = gzip.GzipFile('', 'wb', compression, io) gz.write(content) gz.close() compressed = io.getvalue() self.add_header('Content-Length', str(len(compressed))) self.add_header('Content-Encoding', 'gzip') self.respond_ok() return compressed
'Returns a GZip compressed response with content of file located in ``path`` and correct headers :type path: str :type stream: bool'
def file(self, path, stream=False):
if ('..' in path): self.respond_forbidden() return if (not os.path.isfile(path)): self.respond_not_found() return content_types = {'.css': 'text/css', '.js': 'application/javascript', '.png': 'image/png', '.jpg': 'image/jpeg', '.woff': 'application/x-font-woff'} ext = os.path.splitext(path)[1] if (ext in content_types): self.add_header('Content-Type', content_types[ext]) else: self.add_header('Content-Type', 'application/octet-stream') mtime = datetime.utcfromtimestamp(math.trunc(os.path.getmtime(path))) rtime = self.env.get('HTTP_IF_MODIFIED_SINCE', None) if rtime: try: rtime = datetime.strptime(rtime, '%a, %b %d %Y %H:%M:%S GMT') if (mtime <= rtime): self.respond('304 Not Modified') return except: pass range = self.env.get('HTTP_RANGE', None) rfrom = rto = None if (range and range.startswith('bytes')): rsize = os.stat(path).st_size (rfrom, rto) = range.split('=')[1].split('-') rfrom = (int(rfrom) if rfrom else 0) rto = (int(rto) if rto else (rsize - 1)) else: rfrom = 0 rto = 999999999 self.add_header('Last-Modified', mtime.strftime('%a, %b %d %Y %H:%M:%S GMT')) self.add_header('Accept-Ranges', 'bytes') if stream: if rfrom: self.add_header('Content-Length', str(((rto - rfrom) + 1))) self.add_header('Content-Range', ('bytes %i-%i/%i' % (rfrom, rto, rsize))) self.respond('206 Partial Content') else: self.respond_ok() fd = os.open(path, os.O_RDONLY) os.lseek(fd, (rfrom or 0), os.SEEK_SET) bufsize = (100 * 1024) read = rfrom buf = 1 while buf: buf = os.read(fd, bufsize) gevent.sleep(0) if ((read + len(buf)) > rto): buf = buf[:((rto + 1) - read)] (yield buf) read += len(buf) if (read >= rto): break os.close(fd) else: (yield self.gzip(open(path).read()))
'Verifies the given username/password combo :type username: str :type password: str :rtype: bool'
def check_password(self, username, password, env=None):
if ((not username) or (not password)): return False provider = self.get_sync_provider(fallback=True) if ((username == 'root') and (not provider.syncs_root)): provider = ajenti.usersync.AjentiSyncProvider.get() if (not (username in ajenti.config.tree.users)): return False try: provider.sync() except Exception as e: logging.error(str(e)) result = provider.check_password(username, password) provider_name = type(provider).__name__ ip_notion = '' ip = (env.get('REMOTE_ADDR', None) if env else None) if ip: ip_notion = (' from %s' % ip) if (not result): msg = ('failed login attempt for %s ("%s") through %s%s' % (username, password, provider_name, ip_notion)) syslog.syslog(syslog.LOG_WARNING, msg) logging.warn(msg) else: msg = ('user %s logged in through %s%s' % (username, provider_name, ip_notion)) syslog.syslog(syslog.LOG_INFO, msg) logging.info(msg) return result
':type password: str :rtype: str'
def hash_password(self, password):
if (not password.startswith('sha512|')): password = ('sha512|%s' % sha512_crypt.encrypt(password)) return password
'Checks whether the current user has a permission :type permission: str :rtype: bool'
def has_permission(self, context, permission):
if (context.user.name == 'root'): return True if (not (permission in context.user.permissions)): return False return True
'Checks current user for given permission and raises :class:`SecurityError` if he doesn\'t have one :type permission: str :raises: SecurityError'
def require_permission(self, context, permission):
if (not self.has_permission(context, permission)): raise SecurityError(permission)
':type fallback: bool :rtype: ajenti.usersync.UserSyncProvider'
def get_sync_provider(self, fallback=False):
for p in ajenti.usersync.UserSyncProvider.get_classes(): p.get() if (p.id == self.classconfig['sync-provider']): try: p.get().test() except: if fallback: return ajenti.usersync.AjentiSyncProvider.get() return p.get()
'Should return a list of permission names :rtype: list'
def get_permissions(self):
return []
'Should return a human-friendly name for this set of permissions (displayed in Configurator) :rtype: str'
def get_name(self):
return ''
':param bool is_user: this event was fired by user'
def set_path(self, path, is_user=False):
self.clear_buttons() pathlist = util.rec_split_path(path) for (abspath, name) in pathlist: self.append_button(abspath, name) if is_user: self.add_view_history(path) self.back_button.set_sensitive(self.can_back()) self.forward_button.set_sensitive(self.can_forward()) self.show_all()
''
def load_next(self):
def on_load_next(info, error=None): self.loading_spin.stop() self.loading_spin.hide() if (not info): self.app.toast(_('Network error')) elif (info.get('errno', (-1)) != 0): self.app.toast(info.get('error_msg', _('Network error'))) if (error or (not info) or (info.get('errno', (-1)) != 0)): logger.error(('HomePage.load_next: %s, %s' % (info, error))) return if info['list']: self.icon_window.load_next(info['list']) else: self.has_next = False if (not self.has_next): return self.page_num = (self.page_num + 1) self.path_box.set_path(self.path) self.loading_spin.start() self.loading_spin.show_all() gutil.async_call(pcs.list_dir, self.app.cookie, self.app.tokens, self.path, self.page_num, callback=on_load_next)