Commit dae7def0 authored by Jeremy Hylton's avatar Jeremy Hylton

Remove a bunch of old files.

parent 8e901edd
*shared*
cPersistence cPersistence.c -I../../Components/ExtensionClass/src
cPickleCache cPickleCache.c -I../../Components/ExtensionClass/src
TimeStamp TimeStamp.c -I../../Components/ExtensionClass/src -DUSE_EXTENSION_CLASS
coptimizations coptimizations.c -I../../Components/ExtensionClass/src
# This is an auxilary file that provides file locking on windows.
# It is essentially null on any other platform.
winlock winlock.c
/*****************************************************************************
Copyright (c) 2001, 2002 Zope Corporation and Contributors.
All Rights Reserved.
This software is subject to the provisions of the Zope Public License,
Version 2.0 (ZPL). A copy of the ZPL should accompany this distribution.
THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
FOR A PARTICULAR PURPOSE
****************************************************************************/
static char TimeStamp_module_documentation[] =
"Defines 64-bit TimeStamp objects used as ZODB serial numbers.\n"
"\n"
"\n$Id: TimeStamp.c,v 1.20 2003/09/15 16:29:15 jeremy Exp $\n";
#ifdef USE_EXTENSION_CLASS
#include "ExtensionClass.h"
#else
#include "Python.h"
#endif
#include <time.h>
/* ----------------------------------------------------- */
#define UNLESS(E) if(!(E))
#define OBJECT(O) ((PyObject*)(O))
/* Declarations for objects of type TimeStamp */
typedef struct {
PyObject_HEAD
unsigned char data[8];
} TimeStamp;
static double
TimeStamp_yad(int y)
{
double d, s;
y -= 1900;
d=(y-1)*365;
if (y > 0)
{
s=1.0;
y=y-1;
}
else
{
s=-1.0;
y = -y;
}
return d+s*(y/4-y/100+(y+300)/400);
}
static char month_len[2][12]={
{31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31},
{31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}
};
static short joff[2][12] = {
{0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334},
{0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335}
};
static double
TimeStamp_abst(int y, int mo, int d, int m, int s)
{
int l;
l = y%4==0 && (y%100 != 0 || y%400==0);
return (TimeStamp_yad(y)+ joff[l][mo]+d)*86400 + m*60 + s;
}
static double gmoff=0, sconv=0;
static int
TimeStamp_init_gmoff(void)
{
struct tm *t;
time_t z=0;
t=gmtime(&z);
if (! t)
{
PyErr_SetString(PyExc_SystemError, "gmtime failed");
return -1;
}
gmoff=TimeStamp_abst(
t->tm_year+1900, t->tm_mon, t->tm_mday-1,
t->tm_hour*60+t->tm_min, t->tm_sec);
sconv=((double)60)/((double)(1<<16))/((double)(1<<16));
return 0;
}
static PyObject *
TimeStamp___init__(TimeStamp *self, PyObject *args)
{
int y, mo, d, h=0, m=0;
double sec=0;
char *s;
unsigned int v;
if (PyArg_ParseTuple(args, "s#", &s, &m))
{
if (m != 8)
{
PyErr_SetString(PyExc_ValueError, "8-character string expected");
return NULL;
}
memcpy(self->data, s, 8);
}
else
{
PyErr_Clear();
if (PyArg_ParseTuple(args, "iii|iid", &y, &mo, &d, &h, &m, &sec))
{
s=(char *)self->data;
v=((((y-1900)*12+mo-1)*31+d-1)*24+h)*60+m;
s[0]=v/16777216;
s[1]=(v%16777216)/65536;
s[2]=(v%65536)/256;
s[3]=v%256;
sec /= sconv;
v=(unsigned int)sec;
s[4]=v/16777216;
s[5]=(v%16777216)/65536;
s[6]=(v%65536)/256;
s[7]=v%256;
}
else
{
return NULL;
}
}
Py_INCREF(Py_None);
return Py_None;
}
static int TimeStamp_y, TimeStamp_m, TimeStamp_d, TimeStamp_mi;
static void
TimeStamp_parts(TimeStamp *self)
{
unsigned long v;
v=self->data[0]*16777216+self->data[1]*65536+self->data[2]*256+self->data[3];
TimeStamp_y=v/535680+1900;
TimeStamp_m=(v%535680)/44640+1;
TimeStamp_d=(v%44640)/1440+1;
TimeStamp_mi=v%1440;
}
static double
TimeStamp_sec(TimeStamp *self)
{
unsigned int v;
v=self->data[4]*16777216+self->data[5]*65536+self->data[6]*256+self->data[7];
return sconv*v;
}
static PyObject *
TimeStamp_year(TimeStamp *self, PyObject *args)
{
TimeStamp_parts(self);
return PyInt_FromLong(TimeStamp_y);
}
static PyObject *
TimeStamp_month(TimeStamp *self, PyObject *args)
{
TimeStamp_parts(self);
return PyInt_FromLong(TimeStamp_m);
}
static PyObject *
TimeStamp_day(TimeStamp *self, PyObject *args)
{
TimeStamp_parts(self);
return PyInt_FromLong(TimeStamp_d);
}
static PyObject *
TimeStamp_hour(TimeStamp *self, PyObject *args)
{
TimeStamp_parts(self);
return PyInt_FromLong(TimeStamp_mi/60);
}
static PyObject *
TimeStamp_minute(TimeStamp *self, PyObject *args)
{
TimeStamp_parts(self);
return PyInt_FromLong(TimeStamp_mi%60);
}
static PyObject *
TimeStamp_second(TimeStamp *self, PyObject *args)
{
return PyFloat_FromDouble(TimeStamp_sec(self));
}
static PyObject *
TimeStamp_timeTime(TimeStamp *self, PyObject *args)
{
TimeStamp_parts(self);
return PyFloat_FromDouble(
TimeStamp_abst(TimeStamp_y, TimeStamp_m-1, TimeStamp_d-1,
TimeStamp_mi, 0)+
TimeStamp_sec(self)-gmoff
);
}
static PyObject *
TimeStamp_laterThan(TimeStamp *self, PyObject *args)
{
TimeStamp *o=NULL;
unsigned char s[8];
int i;
UNLESS(PyArg_ParseTuple(args, "O!", self->ob_type, &o)) return NULL;
if (memcmp(self->data, o->data, 8) > 0)
{
Py_INCREF(self);
return OBJECT(self);
}
self=o;
memcpy(s, self->data, 8);
for (i=7; i > 3; i--)
{
if (s[i] == 255)
s[i]=0;
else
{
s[i]++;
return PyObject_CallFunction(OBJECT(self->ob_type), "N",
PyString_FromStringAndSize(s, 8));
}
}
TimeStamp_parts(self);
if (TimeStamp_mi >= 1439)
{
TimeStamp_mi=0;
i = TimeStamp_y%4==0 && (TimeStamp_y%100 != 0 || TimeStamp_y%400==0);
if (TimeStamp_d == month_len[i][TimeStamp_m-1])
{
TimeStamp_d=1;
if (TimeStamp_m == 12)
{
TimeStamp_m=1;
TimeStamp_y++;
}
else
TimeStamp_m++;
}
else
TimeStamp_d++;
}
else
TimeStamp_mi++;
return PyObject_CallFunction(OBJECT(self->ob_type), "iiiii",
TimeStamp_y, TimeStamp_m, TimeStamp_d,
TimeStamp_mi/60, TimeStamp_mi%60);
}
static struct PyMethodDef TimeStamp_methods[] = {
{"year", (PyCFunction)TimeStamp_year, METH_VARARGS, ""},
{"minute", (PyCFunction)TimeStamp_minute, METH_VARARGS, ""},
{"month", (PyCFunction)TimeStamp_month, METH_VARARGS, ""},
{"day", (PyCFunction)TimeStamp_day, METH_VARARGS, ""},
{"hour", (PyCFunction)TimeStamp_hour, METH_VARARGS, ""},
{"second", (PyCFunction)TimeStamp_second, METH_VARARGS, ""},
{"seconds", (PyCFunction)TimeStamp_second, METH_VARARGS, ""},
{"timeTime", (PyCFunction)TimeStamp_timeTime, METH_VARARGS, ""},
{"laterThan", (PyCFunction)TimeStamp_laterThan, METH_VARARGS, ""},
#ifdef USE_EXTENSION_CLASS
{"__init__", (PyCFunction)TimeStamp___init__, METH_VARARGS,
""},
#endif
{NULL, NULL} /* sentinel */
};
#ifndef USE_EXTENSION_CLASS
static TimeStampobject *
newTimeStamp(PyObject *ignored, PyObject *args)
{
TimeStamp *self;
UNLESS(self = PyObject_NEW(TimeStamp, &TimeStampType)) return NULL;
ignored=__init__(self, args);
if (! ignored) return NULL;
Py_DECREF(ignored);
return self;
}
#endif
static void
TimeStamp_dealloc(TimeStamp *self)
{
#ifdef USE_EXTENSION_CLASS
Py_DECREF(self->ob_type);
#endif
PyObject_DEL(self);
}
static PyObject *
TimeStamp_repr(TimeStamp *self)
{
return PyString_FromStringAndSize((char *)self->data, 8);
}
static PyObject *
TimeStamp_str(TimeStamp *self)
{
char buf[128];
int l;
TimeStamp_parts(self);
l=sprintf(buf, "%4.4d-%2.2d-%2.2d %2.2d:%2.2d:%09.6f",
TimeStamp_y, TimeStamp_m, TimeStamp_d,
TimeStamp_mi/60, TimeStamp_mi%60, TimeStamp_sec(self));
return PyString_FromStringAndSize(buf, l);
}
static int
TimeStamp_compare(TimeStamp *v, TimeStamp *w)
{
int cmp = memcmp(v->data, w->data, 8);
if (cmp < 0) return -1;
if (cmp > 0) return 1;
return 0;
}
static long
TimeStamp_hash(TimeStamp *self)
{
return self->data[0]+self->data[1]+self->data[2]+self->data[3]
+self->data[4]+self->data[5]+self->data[6]+self->data[7];
}
static PyObject *
TimeStamp_getattro(TimeStamp *self, PyObject *name)
{
#ifndef USE_EXTENSION_CLASS
char *s;
if (! (s=PyString_AsString(name))) return NULL;
return Py_FindMethod(TimeStamp_methods, self, s);
#else
return Py_FindAttr(OBJECT(self), name);
#endif
}
#ifdef USE_EXTENSION_CLASS
static PyExtensionClass
#else
static PyTypeObject
#endif
TimeStampType = {
PyObject_HEAD_INIT(NULL)
0, /*ob_size*/
"TimeStamp", /*tp_name*/
sizeof(TimeStamp), /*tp_basicsize*/
0, /*tp_itemsize*/
/* methods */
(destructor)TimeStamp_dealloc, /*tp_dealloc*/
(printfunc)0, /*tp_print*/
(getattrfunc)0, /*obsolete tp_getattr*/
(setattrfunc)0, /*obsolete tp_setattr*/
(cmpfunc)TimeStamp_compare, /*tp_compare*/
(reprfunc)TimeStamp_repr, /*tp_repr*/
0, /*tp_as_number*/
0, /*tp_as_sequence*/
0, /*tp_as_mapping*/
(hashfunc)TimeStamp_hash, /*tp_hash*/
(ternaryfunc)0, /*tp_call*/
(reprfunc)TimeStamp_str, /*tp_str*/
(getattrofunc)TimeStamp_getattro,
(setattrofunc)0,
/* Space for future expansion */
0L,0L,
"Simple time stamps"
#ifdef USE_EXTENSION_CLASS
, METHOD_CHAIN(TimeStamp_methods),
#endif
};
static struct PyMethodDef Module_Level__methods[] = {
#ifndef USE_EXTENSION_CLASS
{"TimeStamp", (PyCFunction)newTimeStamp, METH_VARARGS, ""},
#endif
{NULL, (PyCFunction)NULL, 0, NULL} /* sentinel */
};
void
initTimeStamp(void)
{
PyObject *m, *d, *s;
if (TimeStamp_init_gmoff() < 0) return;
if (! ExtensionClassImported) return;
/* Create the module and add the functions */
m = Py_InitModule4("TimeStamp", Module_Level__methods,
TimeStamp_module_documentation,
(PyObject*)NULL,PYTHON_API_VERSION);
/* Add some symbolic constants to the module */
d = PyModule_GetDict(m);
#ifndef USE_EXTENSION_CLASS
TimeStampType.ob_type=&PyType_Type;
#else
PyExtensionClass_Export(d, "TimeStamp", TimeStampType);
#endif
PyDict_SetItemString(d,"TimeStampType", OBJECT(&TimeStampType));
s = PyString_FromString("TimeStamp.error");
PyDict_SetItemString(d, "error", s);
Py_XDECREF(s);
/* Check for errors */
if (PyErr_Occurred())
Py_FatalError("can't initialize module TimeStamp");
}
/*****************************************************************************
Copyright (c) 2001, 2002 Zope Corporation and Contributors.
All Rights Reserved.
This software is subject to the provisions of the Zope Public License,
Version 2.0 (ZPL). A copy of the ZPL should accompany this distribution.
THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
FOR A PARTICULAR PURPOSE
****************************************************************************/
/*
Objects are stored under three different regimes:
Regime 1: Persistent Classes
Persistent Classes are part of ZClasses. They are stored in the
self->data dictionary, and are never garbage collected.
The klass_items() method returns a sequence of (oid,object) tuples for
every Persistent Class, which should make it possible to implement
garbage collection in Python if necessary.
Regime 2: Ghost Objects
There is no benefit to keeping a ghost object which has no external
references, therefore a weak reference scheme is used to ensure that
ghost objects are removed from memory as soon as possible, when the
last external reference is lost.
Ghost objects are stored in the self->data dictionary. Normally a
dictionary keeps a strong reference on its values, however this
reference count is 'stolen'.
This weak reference scheme leaves a dangling reference, in the
dictionary, when the last external reference is lost. To clean up this
dangling reference the persistent object dealloc function calls
self->cache->_oid_unreferenced(self->oid). The cache looks up the oid
in the dictionary, ensures it points to an object whose reference
count is zero, then removes it from the dictionary. Before removing
the object from the dictionary it must temporarily resurrect the
object in much the same way that class instances are resurrected
before their __del__ is called.
Since ghost objects are stored under a different regime to non-ghost
objects, an extra ghostify function in cPersistenceAPI replaces
self->state=GHOST_STATE assignments that were common in other
persistent classes (such as BTrees).
Regime 3: Non-Ghost Objects
Non-ghost objects are stored in two data structures: the dictionary
mapping oids to objects and a doubly-linked list that encodes the
order in which the objects were accessed. The dictionary reference is
borrowed, as it is for ghosts. The list reference is a new reference;
the list stores recently used objects, even if they are otherwise
unreferenced, to avoid loading the object from the database again.
The doubly-link-list nodes contain next and previous pointers linking
together the cache and all non-ghost persistent objects.
The node embedded in the cache is the home position. On every
attribute access a non-ghost object will relink itself just behind the
home position in the ring. Objects accessed least recently will
eventually find themselves positioned after the home position.
Occasionally other nodes are temporarily inserted in the ring as
position markers. The cache contains a ring_lock flag which must be
set and unset before and after doing so. Only if the flag is unset can
the cache assume that all nodes are either his own home node, or nodes
from persistent objects. This assumption is useful during the garbage
collection process.
The number of non-ghost objects is counted in self->non_ghost_count.
The garbage collection process consists of traversing the ring, and
deactivating (that is, turning into a ghost) every object until
self->non_ghost_count is down to the target size, or until it
reaches the home position again.
Note that objects in the sticky or changed states are still kept in
the ring, however they can not be deactivated. The garbage collection
process must skip such objects, rather than deactivating them.
*/
static char cPickleCache_doc_string[] =
"Defines the PickleCache used by ZODB Connection objects.\n"
"\n"
"$Id: cPickleCache.c,v 1.86 2003/10/02 18:17:19 jeremy Exp $\n";
#define ASSIGN(V,E) {PyObject *__e; __e=(E); Py_XDECREF(V); (V)=__e;}
#define UNLESS(E) if(!(E))
#define UNLESS_ASSIGN(V,E) ASSIGN(V,E) UNLESS(V)
#define OBJECT(O) ((PyObject*)O)
#define DONT_USE_CPERSISTENCECAPI
#include "cPersistence.h"
#include <time.h>
#include <stddef.h>
#undef Py_FindMethod
static PyObject *py__p_oid, *py_reload, *py__p_jar, *py__p_changed;
static cPersistenceCAPIstruct *capi;
/* Do we want 'engine noise'.... abstract debugging output useful for
visualizing cache behavior */
#if 0
#define ENGINE_NOISE(A) printf(A)
#else
#define ENGINE_NOISE(A) ((void)A)
#endif
/* This object is the pickle cache. The CACHE_HEAD macro guarantees
that layout of this struct is the same as the start of
ccobject_head in cPersistence.c */
typedef struct {
CACHE_HEAD
int klass_count; /* count of persistent classes */
PyObject *data; /* oid -> object dict */
PyObject *jar; /* Connection object */
PyObject *setklassstate; /* ??? */
int cache_size; /* target number of items in cache */
/* Most of the time the ring contains only:
* many nodes corresponding to persistent objects
* one 'home' node from the cache.
In some cases it is handy to temporarily add other types
of node into the ring as placeholders. 'ring_lock' is a boolean
indicating that someone has already done this. Currently this
is only used by the garbage collection code. */
int ring_lock;
/* 'cache_drain_resistance' controls how quickly the cache size will drop
when it is smaller than the configured size. A value of zero means it will
not drop below the configured size (suitable for most caches). Otherwise,
it will remove cache_non_ghost_count/cache_drain_resistance items from
the cache every time (suitable for rarely used caches, such as those
associated with Zope versions. */
int cache_drain_resistance;
} ccobject;
static int cc_ass_sub(ccobject *self, PyObject *key, PyObject *v);
/* ---------------------------------------------------------------- */
#define OBJECT_FROM_RING(SELF, HERE, CTX) \
((cPersistentObject *)(((char *)here) - offsetof(cPersistentObject, ring)))
static int
scan_gc_items(ccobject *self,int target)
{
/* This function must only be called with the ring lock held,
because it places a non-object placeholder in the ring.
*/
cPersistentObject *object;
int error;
CPersistentRing placeholder;
CPersistentRing *here = self->ring_home.next;
/* Scan through the ring until we either find the ring_home (i.e. start
* of the ring, or we've ghosted enough objects to reach the target
* size.
*/
while (1) {
/* back to the home position. stop looking */
if (here == &self->ring_home)
return 0;
/* At this point we know that the ring only contains nodes
from persistent objects, plus our own home node. We know
this because the ring lock is held. We can safely assume
the current ring node is a persistent object now we know it
is not the home */
object = OBJECT_FROM_RING(self, here, "scan_gc_items");
if (!object)
return -1;
/* we are small enough */
if (self->non_ghost_count <= target)
return 0;
else if (object->state == cPersistent_UPTODATE_STATE) {
/* deactivate it. This is the main memory saver. */
/* Add a placeholder; a dummy node in the ring. We need
to do this to mark our position in the ring. It is
possible that the PyObject_SetAttr() call below will
invoke an __setattr__() hook in Python. If it does,
another thread might run; if that thread accesses a
persistent object and moves it to the head of the ring,
it might cause the gc scan to start working from the
head of the list.
*/
placeholder.next = here->next;
placeholder.prev = here;
here->next->prev = &placeholder;
here->next = &placeholder;
ENGINE_NOISE("G");
/* In Python, "obj._p_changed = None" spells, ghostify */
error = PyObject_SetAttr((PyObject *)object, py__p_changed,
Py_None);
/* unlink the placeholder */
placeholder.next->prev = placeholder.prev;
placeholder.prev->next = placeholder.next;
here = placeholder.next;
if (error)
return -1; /* problem */
}
else {
ENGINE_NOISE(".");
here = here->next;
}
}
}
static PyObject *
lockgc(ccobject *self, int target_size)
{
/* This is thread-safe because of the GIL, and there's nothing
* in between checking the ring_lock and acquiring it that calls back
* into Python.
*/
if (self->ring_lock) {
Py_INCREF(Py_None);
return Py_None;
}
ENGINE_NOISE("<");
self->ring_lock = 1;
if (scan_gc_items(self, target_size)) {
self->ring_lock = 0;
return NULL;
}
self->ring_lock = 0;
ENGINE_NOISE(">\n");
Py_INCREF(Py_None);
return Py_None;
}
static PyObject *
cc_incrgc(ccobject *self, PyObject *args)
{
int n = 1;
int starting_size = self->non_ghost_count;
int target_size = self->cache_size;
if (self->cache_drain_resistance >= 1) {
/* This cache will gradually drain down to a small size. Check
a (small) number of objects proportional to the current size */
int target_size_2 = (starting_size - 1
- starting_size / self->cache_drain_resistance);
if (target_size_2 < target_size)
target_size = target_size_2;
}
if (!PyArg_ParseTuple(args, "|i:incrgc", &n))
return NULL;
return lockgc(self, target_size);
}
static PyObject *
cc_full_sweep(ccobject *self, PyObject *args)
{
int dt = 0;
if (!PyArg_ParseTuple(args, "|i:full_sweep", &dt))
return NULL;
if (dt == 0)
return lockgc(self, 0);
else
return cc_incrgc(self, args);
}
static PyObject *
cc_minimize(ccobject *self, PyObject *args)
{
int ignored;
if (!PyArg_ParseTuple(args, "|i:minimize", &ignored))
return NULL;
return lockgc(self, 0);
}
static void
_invalidate(ccobject *self, PyObject *key)
{
PyObject *v = PyDict_GetItem(self->data, key);
if (!v)
return;
if (PyExtensionClass_Check(v)) {
if (v->ob_refcnt <= 1) {
self->klass_count--;
if (PyDict_DelItem(self->data, key) < 0)
PyErr_Clear();
}
else {
v = PyObject_CallFunction(self->setklassstate, "O", v);
if (v)
Py_DECREF(v);
else
PyErr_Clear();
}
} else {
if (PyObject_DelAttr(v, py__p_changed) < 0)
PyErr_Clear();
}
}
static PyObject *
cc_invalidate(ccobject *self, PyObject *args)
{
PyObject *inv, *key, *v;
int i = 0;
if (PyArg_ParseTuple(args, "O!", &PyDict_Type, &inv)) {
while (PyDict_Next(inv, &i, &key, &v))
_invalidate(self, key);
PyDict_Clear(inv);
}
else {
PyErr_Clear();
if (!PyArg_ParseTuple(args, "O:invalidate", &inv))
return NULL;
if (PyString_Check(inv))
_invalidate(self, inv);
else {
int l;
PyErr_Clear();
l = PyObject_Length(inv);
if (l < 0)
return NULL;
for (i=l; --i >= 0; ) {
key = PySequence_GetItem(inv, i);
if (!key)
return NULL;
_invalidate(self, key);
Py_DECREF(key);
}
/* XXX Do we really want to modify the input? */
PySequence_DelSlice(inv, 0, l);
}
}
Py_INCREF(Py_None);
return Py_None;
}
static PyObject *
cc_get(ccobject *self, PyObject *args)
{
PyObject *r, *key, *d = NULL;
if (!PyArg_ParseTuple(args, "O|O:get", &key, &d))
return NULL;
r = PyDict_GetItem(self->data, key);
if (!r) {
if (d) {
r = d;
} else {
PyErr_SetObject(PyExc_KeyError, key);
return NULL;
}
}
Py_INCREF(r);
return r;
}
static PyObject *
cc_klass_items(ccobject *self, PyObject *args)
{
PyObject *l,*k,*v;
int p = 0;
if (!PyArg_ParseTuple(args, ":klass_items"))
return NULL;
l = PyList_New(PyDict_Size(self->data));
if (l == NULL)
return NULL;
while (PyDict_Next(self->data, &p, &k, &v)) {
if(PyExtensionClass_Check(v)) {
v = Py_BuildValue("OO", k, v);
if (v == NULL) {
Py_DECREF(l);
return NULL;
}
if (PyList_Append(l, v) < 0) {
Py_DECREF(v);
Py_DECREF(l);
return NULL;
}
Py_DECREF(v);
}
}
return l;
}
static PyObject *
cc_lru_items(ccobject *self, PyObject *args)
{
PyObject *l;
CPersistentRing *here;
if (!PyArg_ParseTuple(args, ":lru_items"))
return NULL;
if (self->ring_lock) {
/* When the ring lock is held, we have no way of know which
ring nodes belong to persistent objects, and which a
placeholders. */
PyErr_SetString(PyExc_ValueError,
".lru_items() is unavailable during garbage collection");
return NULL;
}
l = PyList_New(0);
if (l == NULL)
return NULL;
here = self->ring_home.next;
while (here != &self->ring_home) {
PyObject *v;
cPersistentObject *object = OBJECT_FROM_RING(self, here, "cc_items");
if (object == NULL) {
Py_DECREF(l);
return NULL;
}
v = Py_BuildValue("OO", object->oid, object);
if (v == NULL) {
Py_DECREF(l);
return NULL;
}
if (PyList_Append(l, v) < 0) {
Py_DECREF(v);
Py_DECREF(l);
return NULL;
}
Py_DECREF(v);
here = here->next;
}
return l;
}
/* Be very careful about calling clear().
It removes all non-ghost objects from the ring without otherwise
removing them from the cache. The method should only be called
after the cache is no longer in use.
*/
static PyObject *
cc_clear(ccobject *self, PyObject *args)
{
CPersistentRing *here;
if (!PyArg_ParseTuple(args, ":clear"))
return NULL;
if (self->ring_lock) {
/* When the ring lock is held, we have no way of know which
ring nodes belong to persistent objects, and which a
placeholders. */
PyErr_SetString(PyExc_ValueError,
".lru_items() is unavailable during garbage collection");
return NULL;
}
self->ring_lock = 1;
while ((here = self->ring_home.next) != & self->ring_home) {
cPersistentObject *o = OBJECT_FROM_RING(self, here, "clear");
self->non_ghost_count--;
o->ring.next->prev = &self->ring_home;
self->ring_home.next = o->ring.next;
o->ring.next = NULL;
o->ring.prev = NULL;
Py_DECREF(o);
}
self->ring_lock = 0;
/* Free two references to the Connection, which can't be discovered
via garbage collection.
*/
Py_XDECREF(self->setklassstate);
self->setklassstate = NULL;
Py_XDECREF(self->jar);
self->jar = NULL;
Py_INCREF(Py_None);
return Py_None;
}
static int
cc_oid_unreferenced(ccobject *self, PyObject *oid)
{
/* This is called by the persistent object deallocation function
when the reference count on a persistent object reaches
zero. We need to fix up our dictionary; its reference is now
dangling because we stole its reference count. Be careful to
not release the global interpreter lock until this is
complete. */
PyObject *v;
v = PyDict_GetItem(self->data, oid);
if (v == NULL) {
PyErr_SetObject(PyExc_KeyError, oid);
return -1;
}
assert(v->ob_refcnt == 0);
/* Need to be very hairy here because a dictionary is about
to decref an already deleted object.
*/
#ifdef Py_TRACE_REFS
/* This is called from the deallocation function after the
interpreter has untracked the reference. Track it again.
*/
_Py_NewReference(v);
/* Don't increment total refcount as a result of the
shenanigans played in this function. The _Py_NewReference()
call above creates artificial references to v.
*/
_Py_RefTotal--;
assert(v->ob_type);
#else
Py_INCREF(v);
#endif
assert(v->ob_refcnt == 1);
/* Incremement the refcount again, because delitem is going to
DECREF it. If it's refcount reached zero again, we'd call back to
the dealloc function that called us.
*/
Py_INCREF(v);
/* XXX Should we call _Py_ForgetReference() on error exit? */
if (PyDict_DelItem(self->data, oid) < 0)
return -1;
Py_DECREF((ccobject *)((cPersistentObject *)v)->cache);
if (v->ob_refcnt != 1) {
PyErr_SetString(PyExc_ValueError,
"refcount is not 1 after removal from dict");
return -1;
}
/* Undo the temporary resurrection.
Don't DECREF the object, because this function is called from
the object's dealloc function. If the refcnt reaches zero, it
will all be invoked recursively.
*/
_Py_ForgetReference(v);
return 0;
}
static PyObject *
cc_ringlen(ccobject *self, PyObject *args)
{
CPersistentRing *here;
int c = 0;
if (!PyArg_ParseTuple(args, ":ringlen"))
return NULL;
for (here = self->ring_home.next; here != &self->ring_home;
here = here->next)
c++;
return PyInt_FromLong(c);
}
static struct PyMethodDef cc_methods[] = {
{"lru_items", (PyCFunction)cc_lru_items, METH_VARARGS,
"List (oid, object) pairs from the lru list, as 2-tuples.\n"
},
{"klass_items", (PyCFunction)cc_klass_items, METH_VARARGS,
"List (oid, object) pairs of cached persistent classes.\n"
},
{"full_sweep", (PyCFunction)cc_full_sweep, METH_VARARGS,
"full_sweep([age]) -- Perform a full sweep of the cache\n\n"
"Supported for backwards compatibility. If the age argument is 0,\n"
"behaves like minimize(). Otherwise, behaves like incrgc()."
},
{"minimize", (PyCFunction)cc_minimize, METH_VARARGS,
"minimize([ignored]) -- Remove as many objects as possible\n\n"
"Ghostify all objects that are not modified. Takes an optional\n"
"argument, but ignores it."
},
{"incrgc", (PyCFunction)cc_incrgc, METH_VARARGS,
"incrgc([n]) -- Perform incremental garbage collection\n\n"
"Some other implementations support an optional parameter 'n' which\n"
"indicates a repetition count; this value is ignored.\n"},
{"invalidate", (PyCFunction)cc_invalidate, METH_VARARGS,
"invalidate(oids) -- invalidate one, many, or all ids"},
{"get", (PyCFunction)cc_get, METH_VARARGS,
"get(key [, default]) -- get an item, or a default"},
{"ringlen", (PyCFunction)cc_ringlen, METH_VARARGS,
"ringlen() -- Returns number of non-ghost items in cache."},
{"clear", (PyCFunction)cc_clear, METH_VARARGS,
"clear() -- remove all objects from the cache"},
{NULL, NULL} /* sentinel */
};
static void
cc_dealloc(ccobject *self)
{
Py_XDECREF(self->data);
Py_XDECREF(self->jar);
Py_XDECREF(self->setklassstate);
PyMem_DEL(self);
}
static PyObject *
cc_getattr(ccobject *self, char *name)
{
if(*name=='c')
{
if(strcmp(name,"cache_age")==0)
return PyInt_FromLong(0); /* this cache does not use this value */
if(strcmp(name,"cache_size")==0)
return PyInt_FromLong(self->cache_size);
if(strcmp(name,"cache_drain_resistance")==0)
return PyInt_FromLong(self->cache_drain_resistance);
if(strcmp(name,"cache_non_ghost_count")==0)
return PyInt_FromLong(self->non_ghost_count);
if(strcmp(name,"cache_klass_count")==0)
return PyInt_FromLong(self->klass_count);
if(strcmp(name,"cache_data")==0)
{
/* now a copy of our data; the ring is too fragile */
return PyDict_Copy(self->data);
}
}
if (strcmp(name, "items") == 0)
return PyObject_GetAttrString(self->data, name);
return Py_FindMethod(cc_methods, (PyObject *)self, name);
}
static int
cc_setattr(ccobject *self, char *name, PyObject *value)
{
if(value)
{
int v;
if(strcmp(name,"cache_age")==0)
{
/* this cache doesnt use the age */
return 0;
}
if(strcmp(name,"cache_size")==0)
{
UNLESS(PyArg_Parse(value,"i",&v)) return -1;
self->cache_size=v;
return 0;
}
if(strcmp(name,"cache_drain_resistance")==0)
{
UNLESS(PyArg_Parse(value,"i",&v)) return -1;
self->cache_drain_resistance=v;
return 0;
}
}
PyErr_SetString(PyExc_AttributeError, name);
return -1;
}
static int
cc_length(ccobject *self)
{
return PyObject_Length(self->data);
}
static PyObject *
cc_subscript(ccobject *self, PyObject *key)
{
PyObject *r;
r = PyDict_GetItem(self->data, key);
if (r == NULL) {
PyErr_SetObject(PyExc_KeyError, key);
return NULL;
}
Py_INCREF(r);
return r;
}
static int
cc_add_item(ccobject *self, PyObject *key, PyObject *v)
{
int result;
PyObject *oid, *object_again, *jar;
cPersistentObject *p;
if (PyExtensionClass_Check(v)) {
/* Its a persistent class, such as a ZClass. Thats ok. */
}
else if( PyExtensionInstance_Check(v) &&
(((PyExtensionClass*)(v->ob_type))->class_flags & PERSISTENT_TYPE_FLAG) &&
(v->ob_type->tp_basicsize >= sizeof(cPersistentObject)) ) {
/* Its and instance of a persistent class, (ie Python classeses that
derive from Persistence.Persistent, BTrees, etc). Thats ok. */
}
else {
PyErr_SetString(PyExc_TypeError,
"Cache values must be persistent objects.");
return -1;
}
/* Can't access v->oid directly because the object might be a
* persistent class.
*/
oid = PyObject_GetAttr(v, py__p_oid);
if (oid == NULL)
return -1;
if (!PyString_Check(oid)) {
PyErr_Format(PyExc_TypeError,
"Cached object oid must be a string, not a %s",
oid->ob_type->tp_name);
return -1;
}
/* we know they are both strings.
* now check if they are the same string.
*/
result = PyObject_Compare(key, oid);
if (PyErr_Occurred()) {
Py_DECREF(oid);
return -1;
}
Py_DECREF(oid);
if (result) {
PyErr_SetString(PyExc_ValueError, "Cache key does not match oid");
return -1;
}
/* useful sanity check, but not strictly an invariant of this class */
jar = PyObject_GetAttr(v, py__p_jar);
if (jar == NULL)
return -1;
if (jar==Py_None) {
Py_DECREF(jar);
PyErr_SetString(PyExc_ValueError,
"Cached object jar missing");
return -1;
}
Py_DECREF(jar);
object_again = PyDict_GetItem(self->data, key);
if (object_again) {
if (object_again != v) {
PyErr_SetString(PyExc_ValueError,
"Can not re-register object under a different oid");
return -1;
} else {
/* re-register under the same oid - no work needed */
return 0;
}
}
if (PyExtensionClass_Check(v)) {
if (PyDict_SetItem(self->data, key, v) < 0)
return -1;
self->klass_count++;
return 0;
} else {
PerCache *cache = ((cPersistentObject *)v)->cache;
if (cache) {
if (cache != (PerCache *)self)
/* This object is already in a different cache. */
PyErr_SetString(PyExc_ValueError,
"Cache values may only be in one cache.");
return -1;
}
/* else:
This object is already one of ours, which is ok. It
would be very strange if someone was trying to register
the same object under a different key.
*/
}
if (PyDict_SetItem(self->data, key, v) < 0)
return -1;
/* the dict should have a borrowed reference */
Py_DECREF(v);
p = (cPersistentObject *)v;
Py_INCREF(self);
p->cache = (PerCache *)self;
if (p->state >= 0) {
/* insert this non-ghost object into the ring just
behind the home position. */
self->non_ghost_count++;
p->ring.next = &self->ring_home;
p->ring.prev = self->ring_home.prev;
self->ring_home.prev->next = &p->ring;
self->ring_home.prev = &p->ring;
/* this list should have a new reference to the object */
Py_INCREF(v);
}
return 0;
}
static int
cc_del_item(ccobject *self, PyObject *key)
{
PyObject *v;
cPersistentObject *p;
/* unlink this item from the ring */
v = PyDict_GetItem(self->data, key);
if (v == NULL)
return -1;
if (PyExtensionClass_Check(v)) {
self->klass_count--;
} else {
p = (cPersistentObject *)v;
if (p->state >= 0) {
self->non_ghost_count--;
p->ring.next->prev = p->ring.prev;
p->ring.prev->next = p->ring.next;
p->ring.prev = NULL;
p->ring.next = NULL;
/* The DelItem below will account for the reference
held by the list. */
} else {
/* This is a ghost object, so we havent kept a reference
count on it. For it have stayed alive this long
someone else must be keeping a reference to
it. Therefore we need to temporarily give it back a
reference count before calling DelItem below */
Py_INCREF(v);
}
Py_DECREF((PyObject *)p->cache);
p->cache = NULL;
}
if (PyDict_DelItem(self->data, key) < 0) {
PyErr_SetString(PyExc_RuntimeError,
"unexpectedly couldn't remove key in cc_ass_sub");
return -1;
}
return 0;
}
static int
cc_ass_sub(ccobject *self, PyObject *key, PyObject *v)
{
if (!PyString_Check(key)) {
PyErr_Format(PyExc_TypeError,
"cPickleCache key must be a string, not a %s",
key->ob_type->tp_name);
return -1;
}
if (v)
return cc_add_item(self, key, v);
else
return cc_del_item(self, key);
}
static PyMappingMethods cc_as_mapping = {
(inquiry)cc_length, /*mp_length*/
(binaryfunc)cc_subscript, /*mp_subscript*/
(objobjargproc)cc_ass_sub, /*mp_ass_subscript*/
};
static PyTypeObject Cctype = {
PyObject_HEAD_INIT(NULL)
0, /*ob_size*/
"cPickleCache", /*tp_name*/
sizeof(ccobject), /*tp_basicsize*/
0, /*tp_itemsize*/
/* methods */
(destructor)cc_dealloc, /*tp_dealloc*/
(printfunc)0, /*tp_print*/
(getattrfunc)cc_getattr, /*tp_getattr*/
(setattrfunc)cc_setattr, /*tp_setattr*/
(cmpfunc)0, /*tp_compare*/
(reprfunc)0, /*tp_repr*/
0, /*tp_as_number*/
0, /*tp_as_sequence*/
&cc_as_mapping, /*tp_as_mapping*/
(hashfunc)0, /*tp_hash*/
(ternaryfunc)0, /*tp_call*/
(reprfunc)0, /*tp_str*/
};
static ccobject *
newccobject(PyObject *jar, int cache_size)
{
ccobject *self;
self = PyObject_NEW(ccobject, &Cctype);
if (self == NULL)
return NULL;
self->setklassstate = self->jar = NULL;
self->data = PyDict_New();
if (self->data == NULL) {
Py_DECREF(self);
return NULL;
}
self->setklassstate = PyObject_GetAttrString(jar, "setklassstate");
if (self->setklassstate == NULL) {
Py_DECREF(self);
return NULL;
}
self->jar = jar;
Py_INCREF(jar);
self->cache_size = cache_size;
self->non_ghost_count = 0;
self->klass_count = 0;
self->cache_drain_resistance = 0;
self->ring_lock = 0;
self->ring_home.next = &self->ring_home;
self->ring_home.prev = &self->ring_home;
return self;
}
static PyObject *
cCM_new(PyObject *self, PyObject *args)
{
int cache_size=100;
PyObject *jar;
if (!PyArg_ParseTuple(args, "O|i", &jar, &cache_size))
return NULL;
return (PyObject*)newccobject(jar, cache_size);
}
static struct PyMethodDef cCM_methods[] = {
{"PickleCache", (PyCFunction)cCM_new, METH_VARARGS},
{NULL, NULL} /* sentinel */
};
void
initcPickleCache(void)
{
PyObject *m, *d;
Cctype.ob_type = &PyType_Type;
if (!ExtensionClassImported)
return;
capi = (cPersistenceCAPIstruct *)PyCObject_Import("cPersistence", "CAPI");
if (!capi)
return;
capi->percachedel = (percachedelfunc)cc_oid_unreferenced;
m = Py_InitModule4("cPickleCache", cCM_methods, cPickleCache_doc_string,
(PyObject*)NULL, PYTHON_API_VERSION);
py_reload = PyString_InternFromString("reload");
py__p_jar = PyString_InternFromString("_p_jar");
py__p_changed = PyString_InternFromString("_p_changed");
py__p_oid = PyString_InternFromString("_p_oid");
d = PyModule_GetDict(m);
PyDict_SetItemString(d, "cache_variant", PyString_FromString("stiff/c"));
}
##############################################################################
#
# Copyright (c) 2002 Zope Corporation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.0 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE
#
##############################################################################
"""Low-level text dumps of FileStorage contents.
fsdump() prints a two-line summary of each transaction and a one-line
summary of each data record in that transaction. This report is often
useful when analyzing a storage's contents.
Dumper() prints a very detailed representation of the contents. Each
header field is printed on a separate line. This produces lots of
data that is useful when debugging the storage implementation.
"""
from ZODB.FileStorage import TRANS_HDR, TRANS_HDR_LEN
from ZODB.FileStorage import DATA_HDR, DATA_HDR_LEN, DATA_VERSION_HDR_LEN
from ZODB.FileStorage import FileIterator
from ZODB.utils import u64
from ZODB.tests.StorageTestBase import zodb_unpickle
from persistent.TimeStamp import TimeStamp
from cPickle import Unpickler
from cStringIO import StringIO
import md5
import struct
import types
def get_pickle_metadata(data):
# ZODB's data records contain two pickles. The first is the class
# of the object, the second is the object.
if data.startswith('(c'):
# Don't actually unpickle a class, because it will attempt to
# load the class. Just break open the pickle and get the
# module and class from it.
modname, classname, rest = data.split('\n', 2)
modname = modname[2:]
return modname, classname
f = StringIO(data)
u = Unpickler(f)
try:
class_info = u.load()
except Exception, err:
print "Error", err
return '', ''
if isinstance(class_info, types.TupleType):
if isinstance(class_info[0], types.TupleType):
modname, classname = class_info[0]
else:
modname, classname = class_info
else:
# XXX not sure what to do here
modname = repr(class_info)
classname = ''
return modname, classname
def fsdump(path, file=None, with_offset=True, start=None, stop=None):
i = 0
iter = FileIterator(path, start, stop)
for trans in iter:
if with_offset:
print >> file, ("Trans #%05d tid=%016x time=%s size=%d"
% (i, u64(trans.tid), str(TimeStamp(trans.tid)),
trans._tend - trans._tpos))
else:
print >> file, "Trans #%05d tid=%016x time=%s" % \
(i, u64(trans.tid), str(TimeStamp(trans.tid)))
print >> file, "\toffset=%d status=%s user=%s description=%s" % \
(trans._tpos, `trans.status`, trans.user, trans.description)
j = 0
for rec in trans:
if rec.data is None:
fullclass = "undo or abort of object creation"
else:
modname, classname = get_pickle_metadata(rec.data)
dig = md5.new(rec.data).hexdigest()
fullclass = "%s.%s" % (modname, classname)
# special case for testing purposes
if fullclass == "ZODB.tests.MinPO.MinPO":
obj = zodb_unpickle(rec.data)
fullclass = "%s %s" % (fullclass, obj.value)
if rec.version:
version = "version=%s " % rec.version
else:
version = ''
if rec.data_txn:
# XXX It would be nice to print the transaction number
# (i) but it would be too expensive to keep track of.
bp = "bp=%016x" % u64(rec.data_txn)
else:
bp = ""
if rec.data_txn:
size = 8 + len(rec.version)
else:
if rec.data is None:
# XXX why is rec.data None and rec.data_txn False?
size = len(rec.version)
else:
size = len(rec.data) + len(rec.version)
if rec.version:
size += DATA_VERSION_HDR_LEN
else:
size += DATA_HDR_LEN
print >> file, " data #%05d oid=%016x %sclass=%s size=%d %s" % \
(j, u64(rec.oid), version, fullclass, size, bp)
j += 1
print >> file
i += 1
iter.close()
def fmt(p64):
# Return a nicely formatted string for a packaged 64-bit value
return "%016x" % u64(p64)
class Dumper:
"""A very verbose dumper for debuggin FileStorage problems."""
def __init__(self, path, dest=None):
self.file = open(path, "rb")
self.dest = dest
def dump(self):
fid = self.file.read(4)
print >> self.dest, "*" * 60
print >> self.dest, "file identifier: %r" % fid
while self.dump_txn():
pass
def dump_txn(self):
pos = self.file.tell()
h = self.file.read(TRANS_HDR_LEN)
if not h:
return False
tid, stlen, status, ul, dl, el = struct.unpack(TRANS_HDR, h)
end = pos + u64(stlen)
print >> self.dest, "=" * 60
print >> self.dest, "offset: %d" % pos
print >> self.dest, "end pos: %d" % end
print >> self.dest, "transaction id: %s" % fmt(tid)
print >> self.dest, "trec len: %d" % u64(stlen)
print >> self.dest, "status: %r" % status
user = descr = extra = ""
if ul:
user = self.file.read(ul)
if dl:
descr = self.file.read(dl)
if el:
extra = self.file.read(el)
print >> self.dest, "user: %r" % user
print >> self.dest, "description: %r" % descr
print >> self.dest, "len(extra): %d" % el
while self.file.tell() < end:
self.dump_data(pos)
stlen2 = self.file.read(8)
print >> self.dest, "redundant trec len: %d" % u64(stlen2)
return 1
def dump_data(self, tloc):
pos = self.file.tell()
h = self.file.read(DATA_HDR_LEN)
assert len(h) == DATA_HDR_LEN
oid, revid, sprev, stloc, vlen, sdlen = struct.unpack(DATA_HDR, h)
dlen = u64(sdlen)
print >> self.dest, "-" * 60
print >> self.dest, "offset: %d" % pos
print >> self.dest, "oid: %s" % fmt(oid)
print >> self.dest, "revid: %s" % fmt(revid)
print >> self.dest, "previous record offset: %d" % u64(sprev)
print >> self.dest, "transaction offset: %d" % u64(stloc)
if vlen:
pnv = self.file.read(8)
sprevdata = self.file.read(8)
version = self.file.read(vlen)
print >> self.dest, "version: %r" % version
print >> self.dest, "non-version data offset: %d" % u64(pnv)
print >> self.dest, \
"previous version data offset: %d" % u64(sprevdata)
print >> self.dest, "len(data): %d" % dlen
self.file.read(dlen)
if not dlen:
sbp = self.file.read(8)
print >> self.dest, "backpointer: %d" % u64(sbp)
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment