<commit_before>#
#

# Copyright (C) 2006, 2007, 2008 Google Inc.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 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
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301, USA.


"""Module with helper classes and functions for daemons"""


import select
import signal
import errno
import time

from ganeti import utils


class Timer(object):
  def __init__(self, owner, timer_id, start, interval, repeat):
    self.owner = owner
    self.timer_id = timer_id
    self.start = start
    self.interval = interval
    self.repeat = repeat


class Mainloop(object):
  """Generic mainloop for daemons

  """
  def __init__(self):
    """Constructs a new Mainloop instance.

    """
    self._io_wait = {}
    self._io_wait_add = []
    self._io_wait_remove = []
    self._signal_wait = []
    self._timer_id_last = 0
    self._timer = {}
    self._timer_add = []
    self._timer_remove = []

  def Run(self, handle_sigchld=True, handle_sigterm=True, stop_on_empty=False):
    """Runs the mainloop.

    @type handle_sigchld: bool
    @param handle_sigchld: Whether to install handler for SIGCHLD
    @type handle_sigterm: bool
    @param handle_sigterm: Whether to install handler for SIGTERM
    @type stop_on_empty: bool
    @param stop_on_empty: Whether to stop mainloop once all I/O waiters
                          unregistered

    """
    poller = select.poll()

    # Setup signal handlers
    if handle_sigchld:
      sigchld_handler = utils.SignalHandler([signal.SIGCHLD])
    else:
      sigchld_handler = None
    try:
      if handle_sigterm:
        sigterm_handler = utils.SignalHandler([signal.SIGTERM])
      else:
        sigterm_handler = None

      try:
        running = True
        timeout = None
        timeout_needs_update = True

        # Start actual main loop
        while running:
          # Entries could be added again afterwards, hence removing first
          if self._io_wait_remove:
            for fd in self._io_wait_remove:
              try:
                poller.unregister(fd)
              except KeyError:
                pass
              try:
                del self._io_wait[fd]
              except KeyError:
                pass
            self._io_wait_remove = []

          # Add new entries
          if self._io_wait_add:
            for (owner, fd, conditions) in self._io_wait_add:
              self._io_wait[fd] = owner
              poller.register(fd, conditions)
            self._io_wait_add = []

          # Add new timers
          if self._timer_add:
            timeout_needs_update = True
            for timer in self._timer_add:
              self._timer[timer.timer_id] = timer
            del self._timer_add[:]

          # Remove timers
          if self._timer_remove:
            timeout_needs_update = True
            for timer_id in self._timer_remove:
              try:
                del self._timer[timer_id]
              except KeyError:
                pass
            del self._timer_remove[:]

          # Stop if nothing is listening anymore
          if stop_on_empty and not (self._io_wait or self._timer):
            break

          # Calculate timeout again if required
          if timeout_needs_update:
            timeout = self._CalcTimeout(time.time())

          # Wait for I/O events
          try:
            io_events = poller.poll(timeout)
          except select.error, err:
            # EINTR can happen when signals are sent
            if err.args and err.args[0] in (errno.EINTR,):<commit_msg>Mainloop: avoid calculating timeout every time<commit_after>#
#

# Copyright (C) 2006, 2007, 2008 Google Inc.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 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
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301, USA.


"""Module with helper classes and functions for daemons"""


import select
import signal
import errno
import time

from ganeti import utils


class Timer(object):
  def __init__(self, owner, timer_id, start, interval, repeat):
    self.owner = owner
    self.timer_id = timer_id
    self.start = start
    self.interval = interval
    self.repeat = repeat


class Mainloop(object):
  """Generic mainloop for daemons

  """
  def __init__(self):
    """Constructs a new Mainloop instance.

    """
    self._io_wait = {}
    self._io_wait_add = []
    self._io_wait_remove = []
    self._signal_wait = []
    self._timer_id_last = 0
    self._timer = {}
    self._timer_add = []
    self._timer_remove = []

  def Run(self, handle_sigchld=True, handle_sigterm=True, stop_on_empty=False):
    """Runs the mainloop.

    @type handle_sigchld: bool
    @param handle_sigchld: Whether to install handler for SIGCHLD
    @type handle_sigterm: bool
    @param handle_sigterm: Whether to install handler for SIGTERM
    @type stop_on_empty: bool
    @param stop_on_empty: Whether to stop mainloop once all I/O waiters
                          unregistered

    """
    poller = select.poll()

    # Setup signal handlers
    if handle_sigchld:
      sigchld_handler = utils.SignalHandler([signal.SIGCHLD])
    else:
      sigchld_handler = None
    try:
      if handle_sigterm:
        sigterm_handler = utils.SignalHandler([signal.SIGTERM])
      else:
        sigterm_handler = None

      try:
        running = True
        timeout = None
        timeout_needs_update = True

        # Start actual main loop
        while running:
          # Entries could be added again afterwards, hence removing first
          if self._io_wait_remove:
            for fd in self._io_wait_remove:
              try:
                poller.unregister(fd)
              except KeyError:
                pass
              try:
                del self._io_wait[fd]
              except KeyError:
                pass
            self._io_wait_remove = []

          # Add new entries
          if self._io_wait_add:
            for (owner, fd, conditions) in self._io_wait_add:
              self._io_wait[fd] = owner
              poller.register(fd, conditions)
            self._io_wait_add = []

          # Add new timers
          if self._timer_add:
            timeout_needs_update = True
            for timer in self._timer_add:
              self._timer[timer.timer_id] = timer
            del self._timer_add[:]

          # Remove timers
          if self._timer_remove:
            timeout_needs_update = True
            for timer_id in self._timer_remove:
              try:
                del self._timer[timer_id]
              except KeyError:
                pass
            del self._timer_remove[:]

          # Stop if nothing is listening anymore
          if stop_on_empty and not (self._io_wait or self._timer):
            break

          # Calculate timeout again if required
          if timeout_needs_update:
            timeout = self._CalcTimeout(time.time())
            timeout_needs_update = False

          # Wait for I/O events
          try:
            io_events = poller.poll(timeout)
          except select.error, err:
            # EINTR can happen when signals are sent
            if err.args and err.args[0] in (errno.EINTR,):
{'fraction_non_alphanumeric': 0.07046332046332046, 'fraction_numerical': 0.006274131274131274, 'mean_word_length': 2.1220338983050846, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6221561', 'n_tokens_mistral': 2353, 'n_tokens_neox': 2242, 'n_words': 768}