Ejemplo n.º 1
0
 def decrement(self, delta=1):
     result = self.value
     try:
         self.value = self.value - delta
     except OverflowError:
         self.value = long(self.value) - delta
     return result
Ejemplo n.º 2
0
def go (file):
    try:
        k, a, b, a1, b1 = long(2), long(4), long(1), long(12), long(4)
        while 1:
            # Next approximation
            p, q, k = k*k, long(2)*k+long(1), k+long(1)
            a, b, a1, b1 = a1, b1, p*a+q*a1, p*b+q*b1
            # Print common digits
            d, d1 = a/b, a1/b1
            while d == d1:
                if file.write (str(int(d))):
                    raise StopException
                a, a1 = long(10)*(a%b), long(10)*(a1%b1)
                d, d1 = a/b, a1/b1
    except StopException:
        return
Ejemplo n.º 3
0
def get_asctime(now=None):
    if now is None: # for testing
        now = time.time() # pragma: no cover
    msecs = (now - long(now)) * 1000
    part1 = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(now))
    asctime = '%s,%03d' % (part1, msecs)
    return asctime
Ejemplo n.º 4
0
 def decrement(self, delta=1):
     result = self.value
     try:
         self.value = self.value - delta
     except OverflowError:
         self.value = long(self.value) - delta
     return result
Ejemplo n.º 5
0
def go(file):
    try:
        k, a, b, a1, b1 = long(2), long(4), long(1), long(12), long(4)
        while 1:
            # Next approximation
            p, q, k = k * k, long(2) * k + long(1), k + long(1)
            a, b, a1, b1 = a1, b1, p * a + q * a1, p * b + q * b1
            # Print common digits
            d, d1 = a / b, a1 / b1
            while d == d1:
                if file.write(str(int(d))):
                    raise StopException
                a, a1 = long(10) * (a % b), long(10) * (a1 % b1)
                d, d1 = a / b, a1 / b1
    except StopException:
        return
Ejemplo n.º 6
0
 def make_nonce (self, request):
     """A digest-authentication <nonce>, constructed as suggested in RFC 2069"""
     ip = request.channel.server.ip
     now = str(long(time.time()))
     if now[-1:] == 'L':
         now = now[:-1]
     private_key = str (id (self))
     nonce = ':'.join([ip, now, private_key])
     return self.apply_hash (nonce)
Ejemplo n.º 7
0
 def make_nonce(self, request):
     """A digest-authentication <nonce>, constructed as suggested in RFC 2069"""
     ip = request.channel.server.ip
     now = str(long(time.time()))
     if now[-1:] == 'L':
         now = now[:-1]
     private_key = str(id(self))
     nonce = ':'.join([ip, now, private_key])
     return self.apply_hash(nonce)
Ejemplo n.º 8
0
def unix_longify(file, stat_info):
    # for now, only pay attention to the lower bits
    mode = ('%o' % stat_info[stat.ST_MODE])[-3:]
    mode = ''.join([mode_table[x] for x in mode])
    if stat.S_ISDIR(stat_info[stat.ST_MODE]):
        dirchar = 'd'
    else:
        dirchar = '-'
    date = ls_date(long(time.time()), stat_info[stat.ST_MTIME])
    return '%s%s %3d %-8d %-8d %8d %s %s' % (
        dirchar, mode, stat_info[stat.ST_NLINK], stat_info[stat.ST_UID],
        stat_info[stat.ST_GID], stat_info[stat.ST_SIZE], date, file)
Ejemplo n.º 9
0
 def asdict(self):
     if self.dictrepr is None:
         now = time.time()
         msecs = (now - long(now)) * 1000
         part1 = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(now))
         asctime = '%s,%03d' % (part1, msecs)
         levelname = LOG_LEVELS_BY_NUM[self.level]
         msg = as_string(self.msg)
         if self.kw:
             msg = msg % self.kw
         self.dictrepr = {'message':msg, 'levelname':levelname,
                          'asctime':asctime}
     return self.dictrepr
Ejemplo n.º 10
0
 def asdict(self):
     if self.dictrepr is None:
         now = time.time()
         msecs = (now - long(now)) * 1000
         part1 = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(now))
         asctime = "%s,%03d" % (part1, msecs)
         levelname = LOG_LEVELS_BY_NUM[self.level]
         if self.kw:
             msg = self.msg % self.kw
         else:
             msg = self.msg
         self.dictrepr = {"message": msg, "levelname": levelname, "asctime": asctime}
     return self.dictrepr
Ejemplo n.º 11
0
def unix_longify (file, stat_info):
    # for now, only pay attention to the lower bits
    mode = ('%o' % stat_info[stat.ST_MODE])[-3:]
    mode = ''.join([mode_table[x] for x in mode])
    if stat.S_ISDIR (stat_info[stat.ST_MODE]):
        dirchar = 'd'
    else:
        dirchar = '-'
    date = ls_date (long(time.time()), stat_info[stat.ST_MTIME])
    return '%s%s %3d %-8d %-8d %8d %s %s' % (
            dirchar,
            mode,
            stat_info[stat.ST_NLINK],
            stat_info[stat.ST_UID],
            stat_info[stat.ST_GID],
            stat_info[stat.ST_SIZE],
            date,
            file
            )
Ejemplo n.º 12
0
 def as_long(self):
     return long(self.value)
Ejemplo n.º 13
0
    def handle_request(self, request):
        path = request.split_uri()[0]
        self.hit_counter.increment()
        if path == self.statusdir:  # and not a subdirectory
            up_time = ''.join(english_time(long(time.time()) - START_TIME))
            request['Content-Type'] = 'text/html'
            request.push('<html>'
                         '<title>Medusa Status Reports</title>'
                         '<body bgcolor="#ffffff">'
                         '<h1>Medusa Status Reports</h1>'
                         '<b>Up:</b> %s' % up_time)
            for i in range(len(self.objects)):
                try:
                    request.push(self.objects[i].status())
                except:
                    import traceback
                    stream = StringIO()
                    traceback.print_exc(None, stream)
                    request.push(
                        '<h2><font color="red">Error in Channel %3d: %s</font><pre>%s</pre>'
                        % (i, escape(repr(
                            self.objects[i])), escape(stream.getvalue())))
                request.push('<hr>\r\n')
            request.push(
                '<p><a href="%s/channel_list">Channel List</a>'
                '<hr>'
                '<img src="%s/medusa.gif" align=right width=%d height=%d>'
                '</body></html>' % (self.statusdir, self.statusdir,
                                    medusa_gif.width, medusa_gif.height))
            request.done()
        elif path == self.statusdir + '/channel_list':
            request['Content-Type'] = 'text/html'
            request.push('<html><body>')
            request.push(channel_list_producer(self.statusdir))
            request.push(
                '<hr>'
                '<img src="%s/medusa.gif" align=right width=%d height=%d>' %
                (self.statusdir, medusa_gif.width, medusa_gif.height) +
                '</body></html>')
            request.done()

        elif path == self.statusdir + '/medusa.gif':
            request['Content-Type'] = 'image/gif'
            request['Content-Length'] = len(medusa_gif.data)
            request.push(medusa_gif.data)
            request.done()

        elif path == self.statusdir + '/close_zombies':
            message = ('<h2>Closing all zombie http client connections...</h2>'
                       '<p><a href="%s">Back to the status page</a>' %
                       self.statusdir)
            request['Content-Type'] = 'text/html'
            request['Content-Length'] = len(message)
            request.push(message)
            now = int(time.time())
            for channel in asyncore.socket_map.keys():
                if channel.__class__ == http_server.http_channel:
                    if channel != request.channel:
                        if (now - channel.creation_time
                            ) > channel.zombie_timeout:
                            channel.close()
            request.done()

        # Emergency Debug Mode
        # If a server is running away from you, don't KILL it!
        # Move all the AF_INET server ports and perform an autopsy...
        # [disabled by default to protect the innocent]
        elif self.allow_emergency_debug and path == self.statusdir + '/emergency_debug':
            request.push('<html>Moving All Servers...</html>')
            request.done()
            for channel in asyncore.socket_map.keys():
                if channel.accepting:
                    if type(channel.addr) is type(()):
                        ip, port = channel.addr
                        channel.socket.close()
                        channel.del_channel()
                        channel.addr = (ip, port + 10000)
                        fam, typ = channel.family_and_type
                        channel.create_socket(fam, typ)
                        channel.set_reuse_addr()
                        channel.bind(channel.addr)
                        channel.listen(5)

        else:
            m = self.hyper_regex.match(path)
            if m:
                oid = int(m.group(1))
                for object in self.hyper_objects:
                    if id(object) == oid:
                        if hasattr(object, 'hyper_respond'):
                            object.hyper_respond(self, path, request)
            else:
                request.error(404)
                return
Ejemplo n.º 14
0
#

import time
import re
from cgi import escape

from supervisor.compat import StringIO
from supervisor.compat import long

import supervisor.medusa.asyncore_25 as asyncore
import supervisor.medusa.http_server as http_server
import supervisor.medusa.medusa_gif as medusa_gif
import supervisor.medusa.producers as producers
from supervisor.medusa.counter import counter

START_TIME = long(time.time())


class status_extension:
    hit_counter = counter()

    def __init__(self, objects, statusdir='/status', allow_emergency_debug=0):
        self.objects = objects
        self.statusdir = statusdir
        self.allow_emergency_debug = allow_emergency_debug
        # We use /status instead of statusdir here because it's too
        # hard to pass statusdir to the logger, who makes the HREF
        # to the object dir.  We don't need the security-through-
        # obscurity here in any case, because the id is obscurity enough
        self.hyper_regex = re.compile('/status/object/([0-9]+)/.*')
        self.hyper_objects = []
Ejemplo n.º 15
0
def integer(value):
    try:
        return int(value)
    except (ValueError, OverflowError):
        return long(value) # why does this help ValueError? (CM)
Ejemplo n.º 16
0
    def handle_request (self, request):
        path = request.split_uri()[0]
        self.hit_counter.increment()
        if path == self.statusdir:          # and not a subdirectory
            up_time = ''.join(english_time(long(time.time()) - START_TIME))
            request['Content-Type'] = 'text/html'
            request.push (
                    '<html>'
                    '<title>Medusa Status Reports</title>'
                    '<body bgcolor="#ffffff">'
                    '<h1>Medusa Status Reports</h1>'
                    '<b>Up:</b> %s' % up_time
                    )
            for i in range(len(self.objects)):
                try:
                    request.push (self.objects[i].status())
                except:
                    import traceback
                    stream = StringIO()
                    traceback.print_exc(None,stream)
                    request.push('<h2><font color="red">Error in Channel %3d: %s</font><pre>%s</pre>' % (i,escape(repr(self.objects[i])), escape(stream.getvalue())))
                request.push ('<hr>\r\n')
            request.push (
                    '<p><a href="%s/channel_list">Channel List</a>'
                    '<hr>'
                    '<img src="%s/medusa.gif" align=right width=%d height=%d>'
                    '</body></html>' % (
                            self.statusdir,
                            self.statusdir,
                            medusa_gif.width,
                            medusa_gif.height
                            )
                    )
            request.done()
        elif path == self.statusdir + '/channel_list':
            request['Content-Type'] = 'text/html'
            request.push ('<html><body>')
            request.push(channel_list_producer(self.statusdir))
            request.push (
                    '<hr>'
                    '<img src="%s/medusa.gif" align=right width=%d height=%d>' % (
                            self.statusdir,
                            medusa_gif.width,
                            medusa_gif.height
                            ) +
                    '</body></html>'
                    )
            request.done()

        elif path == self.statusdir + '/medusa.gif':
            request['Content-Type'] = 'image/gif'
            request['Content-Length'] = len(medusa_gif.data)
            request.push (medusa_gif.data)
            request.done()

        elif path == self.statusdir + '/close_zombies':
            message = (
                    '<h2>Closing all zombie http client connections...</h2>'
                    '<p><a href="%s">Back to the status page</a>' % self.statusdir
                    )
            request['Content-Type'] = 'text/html'
            request['Content-Length'] = len (message)
            request.push (message)
            now = int (time.time())
            for channel in asyncore.socket_map.keys():
                if channel.__class__ == http_server.http_channel:
                    if channel != request.channel:
                        if (now - channel.creation_time) > channel.zombie_timeout:
                            channel.close()
            request.done()

        # Emergency Debug Mode
        # If a server is running away from you, don't KILL it!
        # Move all the AF_INET server ports and perform an autopsy...
        # [disabled by default to protect the innocent]
        elif self.allow_emergency_debug and path == self.statusdir + '/emergency_debug':
            request.push ('<html>Moving All Servers...</html>')
            request.done()
            for channel in asyncore.socket_map.keys():
                if channel.accepting:
                    if type(channel.addr) is type(()):
                        ip, port = channel.addr
                        channel.socket.close()
                        channel.del_channel()
                        channel.addr = (ip, port+10000)
                        fam, typ = channel.family_and_type
                        channel.create_socket (fam, typ)
                        channel.set_reuse_addr()
                        channel.bind (channel.addr)
                        channel.listen(5)

        else:
            m = self.hyper_regex.match (path)
            if m:
                oid = int(m.group(1))
                for object in self.hyper_objects:
                    if id (object) == oid:
                        if hasattr (object, 'hyper_respond'):
                            object.hyper_respond (self, path, request)
            else:
                request.error (404)
                return
Ejemplo n.º 17
0
#

import time
import re
from cgi import escape

from supervisor.compat import StringIO
from supervisor.compat import long

import supervisor.medusa.asyncore_25 as asyncore
import supervisor.medusa.http_server as http_server
import supervisor.medusa.medusa_gif as medusa_gif
import supervisor.medusa.producers as producers
from supervisor.medusa.counter import counter

START_TIME = long(time.time())

class status_extension:
    hit_counter = counter()

    def __init__ (self, objects, statusdir='/status', allow_emergency_debug=0):
        self.objects = objects
        self.statusdir = statusdir
        self.allow_emergency_debug = allow_emergency_debug
        # We use /status instead of statusdir here because it's too
        # hard to pass statusdir to the logger, who makes the HREF
        # to the object dir.  We don't need the security-through-
        # obscurity here in any case, because the id is obscurity enough
        self.hyper_regex = re.compile('/status/object/([0-9]+)/.*')
        self.hyper_objects = []
        for object in objects:
Ejemplo n.º 18
0
 def __str__(self):
     s = str(long(self.value))
     if s[-1:] == 'L':
         s = s[:-1]
     return s
Ejemplo n.º 19
0
        for k in d.keys():
            if self._keysz is None:
                self._keysz = len(k)
            else:
                assert self._keysz == len(k)

    def __call__(self, v):
        v = v.lower()
        for s, m in self._d.items():
            if v[-self._keysz:] == s:
                return int(v[:-self._keysz]) * m
        return int(v) * self._default

byte_size = SuffixMultiplier({'kb': 1024,
                              'mb': 1024*1024,
                              'gb': 1024*1024*long(1024),})

def url(value):
    # earlier Python 2.6 urlparse (2.6.4 and under) can't parse unix:// URLs,
    # later ones can but we need to straddle
    uri = value.replace('unix://', 'http://', 1).strip()
    scheme, netloc, path, params, query, fragment = urlparse.urlparse(uri)
    if scheme and (netloc or path):
        return value
    raise ValueError("value %s is not a URL" % value)

# all valid signal numbers
SIGNUMS = [ getattr(signal, k) for k in dir(signal) if k.startswith('SIG') ]

def signal_number(value):
    try:
Ejemplo n.º 20
0
                self._keysz = len(k)
            else:
                assert self._keysz == len(k)

    def __call__(self, v):
        v = v.lower()
        for s, m in self._d.items():
            if v[-self._keysz:] == s:
                return int(v[:-self._keysz]) * m
        return int(v) * self._default


byte_size = SuffixMultiplier({
    'kb': 1024,
    'mb': 1024 * 1024,
    'gb': 1024 * 1024 * long(1024),
})


def url(value):
    # earlier Python 2.6 urlparse (2.6.4 and under) can't parse unix:// URLs,
    # later ones can but we need to straddle
    uri = value.replace('unix://', 'http://', 1).strip()
    scheme, netloc, path, params, query, fragment = urlparse.urlparse(uri)
    if scheme and (netloc or path):
        return value
    raise ValueError("value %r is not a URL" % value)


# all valid signal numbers
SIGNUMS = [getattr(signal, k) for k in dir(signal) if k.startswith('SIG')]
Ejemplo n.º 21
0
 def as_long(self):
     return long(self.value)
Ejemplo n.º 22
0
 def __str__(self):
     s = str(long(self.value))
     if s[-1:] == 'L':
         s = s[:-1]
     return s
Ejemplo n.º 23
0
def integer(value):
    try:
        return int(value)
    except (ValueError, OverflowError):
        return long(value)  # why does this help ValueError? (CM)
Ejemplo n.º 24
0
        self._keysz = None
        for k in d.keys():
            if self._keysz is None:
                self._keysz = len(k)
            else:
                assert self._keysz == len(k)

    def __call__(self, v):
        v = v.lower()
        for s, m in self._d.items():
            if v[-self._keysz :] == s:
                return int(v[: -self._keysz]) * m
        return int(v) * self._default


byte_size = SuffixMultiplier({"kb": 1024, "mb": 1024 * 1024, "gb": 1024 * 1024 * long(1024)})


def url(value):
    # earlier Python 2.6 urlparse (2.6.4 and under) can't parse unix:// URLs,
    # later ones can but we need to straddle
    uri = value.replace("unix://", "http://", 1).strip()
    scheme, netloc, path, params, query, fragment = urlparse.urlparse(uri)
    if scheme and (netloc or path):
        return value
    raise ValueError("value %s is not a URL" % value)


# all valid signal numbers
SIGNUMS = [getattr(signal, k) for k in dir(signal) if k.startswith("SIG")]