-
Notifications
You must be signed in to change notification settings - Fork 137
/
_pylibmcmodule.c
2722 lines (2265 loc) · 81.2 KB
/
_pylibmcmodule.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* _pylibmc: hand-made libmemcached bindings for Python
*
* Copyright (c) 2008, Ludvig Ericson
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* - Neither the name of the author nor the names of the contributors may be
* used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include "_pylibmcmodule.h"
#ifdef USE_ZLIB
# include <zlib.h>
# define ZLIB_BUFSZ (1 << 14)
/* only release the GIL during inflate if the size of the data
is greater than this (deflate always releases at present) */
# define ZLIB_GIL_RELEASE ZLIB_BUFSZ
#endif
#define PyBool_TEST(t) ((t) ? Py_True : Py_False)
#define PyModule_ADD_REF(mod, nam, obj) \
{ Py_INCREF(obj); \
PyModule_AddObject(mod, nam, obj); }
/* Some Python 3 porting stuff */
#ifndef Py_TYPE
#define Py_TYPE(ob) (((PyObject*)(ob))->ob_type)
#endif
#ifndef PyInt_Check
#define PyInt_Check PyLong_Check
#endif
#define MOD_ERROR_VAL NULL
#define MOD_SUCCESS_VAL(val) val
#define MOD_INIT(name) PyMODINIT_FUNC PyInit_##name(void)
#define MOD_DEF(ob, name, doc, methods) \
static struct PyModuleDef moduledef = { \
PyModuleDef_HEAD_INIT, name, doc, -1, methods, }; \
ob = PyModule_Create(&moduledef);
/* Cache the values of {cP,p}ickle.{load,dump}s */
static PyObject *_PylibMC_pickle_loads = NULL;
static PyObject *_PylibMC_pickle_dumps = NULL;
/* {{{ Type methods */
static PylibMC_Client *PylibMC_ClientType_new(PyTypeObject *type,
PyObject *args, PyObject *kwds) {
PylibMC_Client *self;
/* GenericNew calls GenericAlloc (via the indirection type->tp_alloc) which
* adds GC tracking if flagged for, and also calls PyObject_Init. */
self = (PylibMC_Client *)PyType_GenericNew(type, args, kwds);
if (self != NULL) {
self->mc = memcached_create(NULL);
self->sasl_set = false;
}
return self;
}
/* Helper: detect whether the serialize and deserialize methods were overridden. */
static int _PylibMC_method_is_overridden(PylibMC_Client *self, const char *method) {
/* `self.__class__.serialize is _pylibmc.client.serialize`, in C */
PyObject *base_method = NULL, *current_class = NULL, *current_method = NULL;
base_method = PyObject_GetAttrString((PyObject *) &PylibMC_ClientType, method);
current_class = PyObject_GetAttrString((PyObject *) self, "__class__");
if (current_class != NULL) {
current_method = PyObject_GetAttrString(current_class, method);
}
Py_XDECREF(base_method);
Py_XDECREF(current_class);
Py_XDECREF(current_method);
if (base_method && current_class && current_method) {
return base_method == current_method;
} else {
return -1;
}
}
static void PylibMC_ClientType_dealloc(PylibMC_Client *self) {
if (self->mc != NULL) {
#if LIBMEMCACHED_WITH_SASL_SUPPORT
if (self->sasl_set) {
memcached_destroy_sasl_auth_data(self->mc);
}
#endif
memcached_free(self->mc);
}
Py_TYPE(self)->tp_free(self);
}
/* }}} */
static int PylibMC_Client_init(PylibMC_Client *self, PyObject *args,
PyObject *kwds) {
PyObject *srvs, *srvs_it, *c_srv;
unsigned char set_stype = 0, bin = 0, got_server = 0;
const char *user = NULL, *pass = NULL;
PyObject *behaviors = NULL;
memcached_return rc;
self->pickle_protocol = -1;
static char *kws[] = { "servers", "binary", "username", "password",
"behaviors", NULL };
if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|bzzO", kws,
&srvs, &bin, &user, &pass,
&behaviors)) {
return -1;
}
if ((srvs_it = PyObject_GetIter(srvs)) == NULL) {
return -1;
}
/* setup sasl */
if (user != NULL || pass != NULL) {
#if LIBMEMCACHED_WITH_SASL_SUPPORT
if (user == NULL || pass == NULL) {
PyErr_SetString(PyExc_TypeError, "SASL requires both username and password");
goto error;
}
if (!bin) {
PyErr_SetString(PyExc_TypeError, "SASL requires the memcached binary protocol");
goto error;
}
rc = memcached_set_sasl_auth_data(self->mc, user, pass);
if (rc != MEMCACHED_SUCCESS) {
PylibMC_ErrFromMemcached(self, "memcached_set_sasl_auth_data", rc);
goto error;
}
/* Can't just look at the memcached_st->sasl data, because then it
* breaks in libmemcached 0.43 and potentially earlier. */
self->sasl_set = true;
#else
PyErr_SetString(PyExc_TypeError, "libmemcached does not support SASL");
goto error;
#endif
}
rc = memcached_behavior_set(self->mc, MEMCACHED_BEHAVIOR_BINARY_PROTOCOL, bin);
if (rc != MEMCACHED_SUCCESS) {
PyErr_SetString(PyExc_RuntimeError, "binary protocol behavior set failed");
goto error;
}
if (behaviors != NULL) {
if (PylibMC_Client_set_behaviors(self, behaviors) == NULL) {
goto error;
}
}
/* Detect whether we should dispatch to user-modified Python
* serialization implementations. */
int native_serialization, native_deserialization;
if ((native_serialization = _PylibMC_method_is_overridden(self, "serialize")) == -1) {
goto error;
}
self->native_serialization = (uint8_t) native_serialization;
if ((native_deserialization = _PylibMC_method_is_overridden(self, "deserialize")) == -1) {
goto error;
}
self->native_deserialization = (uint8_t) native_deserialization;
while ((c_srv = PyIter_Next(srvs_it)) != NULL) {
unsigned char stype;
char *hostname;
unsigned short int port;
unsigned short int weight;
got_server |= 1;
port = 0;
weight = 1;
if (PyBytes_Check(c_srv)) {
memcached_server_st *list;
list = memcached_servers_parse(PyBytes_AS_STRING(c_srv));
if (list == NULL) {
PyErr_SetString(PylibMCExc_Error,
"memcached_servers_parse returned NULL");
goto it_error;
}
rc = memcached_server_push(self->mc, list);
memcached_server_list_free(list);
if (rc != MEMCACHED_SUCCESS) {
PylibMC_ErrFromMemcached(self, "memcached_server_push", rc);
goto it_error;
}
} else if (PyArg_ParseTuple(c_srv, "Bs|HH", &stype, &hostname, &port, &weight)) {
if (set_stype && set_stype != stype) {
PyErr_SetString(PyExc_ValueError, "can't mix transport types");
goto it_error;
} else {
set_stype = stype;
if (stype == PYLIBMC_SERVER_UDP) {
rc = memcached_behavior_set(self->mc, MEMCACHED_BEHAVIOR_USE_UDP, 1);
if (rc != MEMCACHED_SUCCESS) {
PyErr_SetString(PyExc_RuntimeError, "udp behavior set failed");
goto it_error;
}
}
}
switch (stype) {
case PYLIBMC_SERVER_UDP:
#if LIBMEMCACHED_VERSION_HEX <= 0x00053000
rc = memcached_server_add_udp_with_weight(self->mc, hostname, port, weight);
break;
#endif
case PYLIBMC_SERVER_TCP:
rc = memcached_server_add_with_weight(self->mc, hostname, port, weight);
break;
case PYLIBMC_SERVER_UNIX:
if (port) {
PyErr_SetString(PyExc_ValueError,
"can't set port on unix sockets");
goto it_error;
}
rc = memcached_server_add_unix_socket_with_weight(self->mc, hostname, weight);
break;
default:
PyErr_Format(PyExc_ValueError, "bad type: %u", stype);
goto it_error;
}
if (rc != MEMCACHED_SUCCESS) {
PylibMC_ErrFromMemcached(self, "memcached_server_add_*", rc);
goto it_error;
}
}
Py_DECREF(c_srv);
continue;
it_error:
Py_DECREF(c_srv);
goto error;
}
if (!got_server) {
PyErr_SetString(PylibMCExc_Error, "empty server list");
goto error;
}
Py_DECREF(srvs_it);
return 0;
error:
Py_DECREF(srvs_it);
return -1;
}
/* {{{ Compression helpers */
#ifdef USE_ZLIB
static int _PylibMC_Deflate(char *value, Py_ssize_t value_len,
char **result, Py_ssize_t *result_len,
int compress_level) {
/* FIXME Failures are entirely silent. */
int rc;
/* n.b.: this is called while *not* holding the GIL, and must not
contain Python-API code */
ssize_t out_sz;
z_stream strm;
*result = NULL;
*result_len = 0;
/* Don't ask me about this one. Got it from zlibmodule.c in Python 2.6. */
out_sz = value_len + value_len / 1000 + 12 + 1;
if ((*result = malloc(out_sz)) == NULL) {
goto error;
}
/* TODO Should break up next_in into blocks of max 0xffffffff in length. */
assert(value_len < 0xffffffffU);
assert(out_sz < 0xffffffffU);
strm.avail_in = (uInt)value_len;
strm.avail_out = (uInt)out_sz;
strm.next_in = (Bytef *)value;
strm.next_out = (Bytef *)*result;
/* we just pre-allocated all of it up front */
strm.zalloc = (alloc_func)NULL;
strm.zfree = (free_func)Z_NULL;
if (deflateInit((z_streamp)&strm, compress_level) != Z_OK) {
goto error;
}
rc = deflate((z_streamp)&strm, Z_FINISH);
if (rc != Z_STREAM_END) {
goto error;
}
if (deflateEnd((z_streamp)&strm) != Z_OK) {
goto error;
}
if ((Py_ssize_t)strm.total_out >= value_len) {
/* if no data was saved, don't use compression */
goto error;
}
/* *result should already be populated since that's the address we
passed into the z_stream */
*result_len = strm.total_out;
return 1;
error:
/* if any error occurred, we'll just use the original value
instead of trying to compress it */
if(*result != NULL) {
free(*result);
*result = NULL;
}
return 0;
}
static int _PylibMC_Inflate(char *value, Py_ssize_t size,
char** result, Py_ssize_t* result_size,
char** failure_reason) {
/*
can be called while not holding the GIL. returns the zlib return value,
returns the size of the inflated data in *result_size and the data itself
in *result, and the failed call in failure_reason if appropriate
while deflate can silently ignore errors, we can't
*/
int rc;
char* out = NULL;
char* tryrealloc = NULL;
z_stream strm;
/* Output buffer */
size_t rvalsz = ZLIB_BUFSZ;
out = malloc(ZLIB_BUFSZ);
if(out == NULL) {
return Z_MEM_ERROR;
}
/* TODO 64-bit fix size/rvalsz */
assert(size < 0xffffffffU);
assert(rvalsz < 0xffffffffU);
/* Set up zlib stream. */
strm.avail_in = (uInt)size;
strm.avail_out = (uInt)rvalsz;
strm.next_in = (Byte*)value;
strm.next_out = (Byte*)out;
strm.zalloc = (alloc_func)NULL;
strm.zfree = (free_func)Z_NULL;
strm.opaque = (voidpf)NULL;
/* TODO Add controlling of windowBits with inflateInit2? */
if ((rc = inflateInit((z_streamp)&strm)) != Z_OK) {
*failure_reason = "inflateInit";
goto error;
}
do {
*failure_reason = "inflate";
rc = inflate((z_streamp)&strm, Z_FINISH);
switch (rc) {
case Z_STREAM_END:
break;
/* When a Z_BUF_ERROR occurs, we should be out of memory.
* This is also true for Z_OK, hence the fall-through. */
case Z_BUF_ERROR:
if (strm.avail_out) {
goto zerror;
}
/* Fall-through */
case Z_OK:
if ((tryrealloc = realloc(out, rvalsz << 1)) == NULL) {
*failure_reason = "realloc";
rc = Z_MEM_ERROR;
goto zerror;
}
out = tryrealloc;
/* Wind forward */
strm.next_out = (unsigned char*)(out + rvalsz);
strm.avail_out = rvalsz;
rvalsz = rvalsz << 1;
break;
default:
goto zerror;
}
} while (rc != Z_STREAM_END);
if ((rc = inflateEnd(&strm)) != Z_OK) {
*failure_reason = "inflateEnd";
goto error;
}
if ((tryrealloc = realloc(out, strm.total_out)) == NULL) {
*failure_reason = "realloc";
rc = Z_MEM_ERROR;
goto error;
}
out = tryrealloc;
*result = out;
*result_size = strm.total_out;
return Z_OK;
zerror:
inflateEnd(&strm);
error:
if (out != NULL) {
free(out);
}
*result = NULL;
return rc;
}
#endif
/* }}} */
/* Helper for multiset / multiget:
1. Take the iterable `keys` and build a map of UTF-8 encoded bytestrings
to Unicode keys.
2. If `key_array` and `nkeys` are not NULL, additionally copy *new*
references to everything in the iterable into `key_array`. Store
the actual number of items in `nkeys`.
*/
static PyObject *_PylibMC_map_str_keys(PyObject *keys, PyObject **key_array, Py_ssize_t *nkeys) {
PyObject *key_str_map = NULL;
PyObject *iter = NULL;
PyObject *key = NULL;
PyObject *key_bytes = NULL;
Py_ssize_t i = 0;
key_str_map = PyDict_New();
if (key_str_map == NULL)
goto cleanup;
if ((iter = PyObject_GetIter(keys)) == NULL)
goto cleanup;
while ((key = PyIter_Next(iter)) != NULL) {
if (PyUnicode_Check(key)) {
key_bytes = PyUnicode_AsUTF8String(key);
if (key_bytes == NULL)
goto cleanup;
PyDict_SetItem(key_str_map, key_bytes, key);
Py_DECREF(key_bytes);
}
/* stash our owned reference to `key` in this array: */
if (key_array != NULL && i < *nkeys) {
key_array[i++] = key;
} else {
Py_DECREF(key);
}
}
if (nkeys != NULL) {
*nkeys = i;
}
Py_DECREF(iter);
return key_str_map;
cleanup:
if (key_array != NULL) {
for (Py_ssize_t j = 0; j < i; j++) {
Py_DECREF(key_array[j]);
}
}
Py_XDECREF(key);
Py_XDECREF(iter);
Py_XDECREF(key_str_map);
return NULL;
}
/* }}} */
static PyObject *_PylibMC_parse_memcached_value(PylibMC_Client *self,
char *value, Py_ssize_t size, uint32_t flags) {
PyObject *retval = NULL;
#if USE_ZLIB
PyObject *inflated = NULL;
/* Decompress value if necessary. */
if (flags & PYLIBMC_FLAG_ZLIB) {
int rc;
char* inflated_buf = NULL;
Py_ssize_t inflated_size = 0;
char* failure_reason = NULL;
if(size >= ZLIB_GIL_RELEASE) {
Py_BEGIN_ALLOW_THREADS;
rc = _PylibMC_Inflate(value, size,
&inflated_buf, &inflated_size,
&failure_reason);
Py_END_ALLOW_THREADS;
} else {
rc = _PylibMC_Inflate(value, size,
&inflated_buf, &inflated_size,
&failure_reason);
}
if(rc != Z_OK) {
/* set up the exception */
if(failure_reason == NULL) {
PyErr_Format(PylibMCExc_Error,
"Failed to decompress value: %d", rc);
} else {
PyErr_Format(PylibMCExc_Error,
"Failed to decompress value: %s", failure_reason);
}
return NULL;
}
inflated = PyBytes_FromStringAndSize(inflated_buf, inflated_size);
free(inflated_buf);
if(inflated == NULL) {
return NULL;
}
value = PyBytes_AS_STRING(inflated);
size = PyBytes_GET_SIZE(inflated);
}
#else
if (flags & PYLIBMC_FLAG_ZLIB) {
PyErr_SetString(PylibMCExc_Error,
"key is compressed but pylibmc is compiled without zlib support");
return NULL;
}
#endif
if (self->native_deserialization) {
retval = _PylibMC_deserialize_native(self, NULL, value, size, flags);
} else {
retval = PyObject_CallMethod((PyObject *)self, "deserialize", "y#I", value, size, (unsigned int) flags);
}
#if USE_ZLIB
Py_XDECREF(inflated);
#endif
return retval;
}
/** Helper because PyLong_FromString requires a null-terminated string. */
static PyObject *_PyLong_FromStringAndSize(char *value, Py_ssize_t size, char **pend, int base) {
PyObject *retval;
char *tmp;
if ((tmp = malloc(size+1)) == NULL) {
return PyErr_NoMemory();
}
strncpy(tmp, value, size);
tmp[size] = '\0';
retval = PyLong_FromString(tmp, pend, base);
free(tmp);
return retval;
}
/** C implementation of deserialization.
This either takes a Python bytestring as `value`, or else `value` is NULL and
the value to be deserialized is a byte array `value_str` of length
`value_size`.
*/
static PyObject *_PylibMC_deserialize_native(PylibMC_Client *self, PyObject *value, char *value_str, Py_ssize_t value_size, uint32_t flags) {
assert(value || value_str);
PyObject *retval = NULL;
uint32_t dtype = flags & PYLIBMC_FLAG_TYPES;
switch (dtype) {
case PYLIBMC_FLAG_PICKLE:
retval = value ? _PylibMC_Unpickle_Bytes(self, value) : _PylibMC_Unpickle(self, value_str, value_size);
break;
case PYLIBMC_FLAG_INTEGER:
case PYLIBMC_FLAG_LONG:
if (value) {
retval = PyLong_FromString(PyBytes_AS_STRING(value), NULL, 10);
} else {
retval = _PyLong_FromStringAndSize(value_str, value_size, NULL, 10);;
}
break;
case PYLIBMC_FLAG_TEXT:
if (value) {
retval = PyUnicode_FromEncodedObject(value, "utf-8", "strict");
} else {
retval = PyUnicode_FromStringAndSize(value_str, value_size);
}
break;
case PYLIBMC_FLAG_NONE:
if (value) {
/* acquire an additional reference for parity */
Py_INCREF(value);
retval = value;
} else {
retval = PyBytes_FromStringAndSize(value_str, value_size);
}
break;
default:
PyErr_Format(PylibMCExc_Error,
"unknown memcached key flags %u", dtype);
}
return retval;
}
static PyObject *PylibMC_Client_deserialize(PylibMC_Client *self, PyObject *args) {
PyObject *value;
unsigned int flags;
if (!PyArg_ParseTuple(args, "OI", &value, &flags)) {
return NULL;
}
return _PylibMC_deserialize_native(self, value, NULL, 0, flags);
}
static PyObject *_PylibMC_parse_memcached_result(PylibMC_Client *self, memcached_result_st *res) {
return _PylibMC_parse_memcached_value(
self,
(char *)memcached_result_value(res),
memcached_result_length(res),
memcached_result_flags(res));
}
/* Helper to call after _PylibMC_parse_memcached_value;
determines whether the deserialized value should be ignored
and treated as a miss.
*/
static int _PylibMC_cache_miss_simulated(PyObject *r) {
if (r == NULL && PyErr_Occurred() && PyErr_ExceptionMatches(PylibMCExc_CacheMiss)) {
PyErr_Clear();
return 1;
}
return 0;
}
static PyObject *PylibMC_Client_get(PylibMC_Client *self, PyObject *args) {
char *mc_val;
size_t val_size;
uint32_t flags;
memcached_return error;
PyObject *key;
/* if a default argument was in fact passed, it's still a borrowed reference
at this point, so borrow a reference to Py_None as well for parity. */
PyObject *default_value = Py_None;
if (!PyArg_UnpackTuple(args, "get", 1, 2, &key, &default_value)) {
return NULL;
}
if (!_key_normalized_obj(&key)) {
return NULL;
} else if (!PySequence_Length(key)) {
Py_INCREF(default_value);
return default_value;
}
Py_BEGIN_ALLOW_THREADS;
mc_val = memcached_get(self->mc,
PyBytes_AS_STRING(key), PyBytes_GET_SIZE(key),
&val_size, &flags, &error);
Py_END_ALLOW_THREADS;
Py_DECREF(key);
if (error == MEMCACHED_SUCCESS) {
/* note that mc_val can and is NULL for zero-length values. */
PyObject *r = _PylibMC_parse_memcached_value(self, mc_val, val_size, flags);
if (mc_val != NULL) {
free(mc_val);
}
if (_PylibMC_cache_miss_simulated(r)) {
Py_INCREF(default_value);
return default_value;
}
return r;
}
if (error == MEMCACHED_NOTFOUND) {
Py_INCREF(default_value);
return default_value;
}
return PylibMC_ErrFromMemcachedWithKey(self, "memcached_get", error,
PyBytes_AS_STRING(key),
PyBytes_GET_SIZE(key));
}
static PyObject *PylibMC_Client_gets(PylibMC_Client *self, PyObject *arg) {
const char* keys[2];
size_t keylengths[2];
memcached_result_st *res = NULL;
memcached_return rc;
PyObject* ret = NULL;
if (!_key_normalized_obj(&arg)) {
return NULL;
} else if (!PySequence_Length(arg)) {
return Py_BuildValue("(OO)", Py_None, Py_None);
} else if (!memcached_behavior_get(self->mc, MEMCACHED_BEHAVIOR_SUPPORT_CAS)) {
PyErr_SetString(PyExc_ValueError, "gets without cas behavior");
return NULL;
}
/* Use an mget to fetch the key.
* mget is the only function that returns a memcached_result_st,
* which is the only way to get at the returned cas value. */
*keys = PyBytes_AS_STRING(arg);
*keylengths = (size_t)PyBytes_GET_SIZE(arg);
Py_DECREF(arg);
Py_BEGIN_ALLOW_THREADS;
rc = memcached_mget(self->mc, keys, keylengths, 1);
if (rc == MEMCACHED_SUCCESS)
res = memcached_fetch_result(self->mc, res, &rc);
Py_END_ALLOW_THREADS;
int miss = 0;
int fail = 0;
if (rc == MEMCACHED_SUCCESS && res != NULL) {
PyObject *val = _PylibMC_parse_memcached_result(self, res);
if (_PylibMC_cache_miss_simulated(val)) {
miss = 1;
} else {
ret = Py_BuildValue("(NL)",
val,
memcached_result_cas(res));
}
/* we have to fetch the last result from the mget cursor */
if (NULL != memcached_fetch_result(self->mc, NULL, &rc)) {
memcached_quit(self->mc);
Py_DECREF(ret);
ret = NULL;
fail = 1;
PyErr_SetString(PyExc_RuntimeError, "fetch not done");
}
} else if (rc == MEMCACHED_END || rc == MEMCACHED_NOTFOUND) {
miss = 1;
} else {
ret = PylibMC_ErrFromMemcached(self, "memcached_gets", rc);
}
if (miss && !fail) {
/* Key not found => (None, None) */
ret = Py_BuildValue("(OO)", Py_None, Py_None);
}
if (res != NULL) {
memcached_result_free(res);
}
return ret;
}
static PyObject *PylibMC_Client_hash(PylibMC_Client *self, PyObject *args, PyObject *kwds) {
char *key;
Py_ssize_t key_len = 0;
uint32_t h;
if (!PyArg_ParseTuple(args, "s#:hash", &key, &key_len)) {
return NULL;
}
h = memcached_generate_hash(self->mc, key, (Py_ssize_t)key_len);
return PyLong_FromLong((long)h);
}
/* {{{ Set commands (set, replace, add, prepend, append) */
static PyObject *_PylibMC_RunSetCommandSingle(PylibMC_Client *self,
_PylibMC_SetCommand f, char *fname, PyObject *args,
PyObject *kwds) {
/* function called by the set/add/etc commands */
static char *kws[] = { "key", "val", "time",
"min_compress_len", "compress_level",
NULL };
const char *key_raw;
PyObject *key;
Py_ssize_t keylen;
PyObject *value;
pylibmc_mset serialized = { NULL };
unsigned int time = 0; /* this will be turned into a time_t */
unsigned int min_compress = 0;
int compress_level = -1;
bool success = false;
/*
* "s#" specifies that (Unicode) text objects will be encoded
* to UTF-8 byte strings for use as keys, and this seems to be
* the only sensible thing to do when the user attempts this
*/
if (!PyArg_ParseTupleAndKeywords(args, kwds, "s#O|IIi", kws,
&key_raw, &keylen, &value,
&time, &min_compress, &compress_level)) {
return NULL;
}
#ifdef USE_ZLIB
if (compress_level == -1) {
compress_level = Z_DEFAULT_COMPRESSION;
} else if (compress_level < 0 || compress_level > 9) {
PyErr_SetString(PyExc_ValueError, "compress_level must be between 0 and 9 inclusive");
return NULL;
}
#else
if (min_compress) {
PyErr_SetString(PyExc_TypeError, "min_compress_len without zlib");
return NULL;
}
#endif
/*
Kind of clumsy to convert to a char* and then to a Python
bytes object, but using "s#" for argument parsing seems to
be the cleanest way to accept both byte strings and text
strings as keys.
*/
key = PyBytes_FromStringAndSize(key_raw, keylen);
success = _PylibMC_SerializeValue(self, key, NULL, value, time, &serialized);
if (!success)
goto cleanup;
success = _PylibMC_RunSetCommand(self, f, fname,
&serialized, 1,
min_compress, compress_level);
cleanup:
_PylibMC_FreeMset(&serialized);
Py_DECREF(key);
if(PyErr_Occurred() != NULL) {
return NULL;
} else if(success) {
Py_RETURN_TRUE;
} else {
Py_RETURN_FALSE;
}
}
static PyObject *_PylibMC_RunSetCommandMulti(PylibMC_Client *self,
_PylibMC_SetCommand f, char *fname, PyObject *args,
PyObject *kwds) {
/* function called by the set/add/incr/etc commands */
PyObject *keys = NULL;
const char *key_prefix_raw = NULL;
Py_ssize_t key_prefix_len = 0;
PyObject *key_prefix = NULL;
unsigned int time = 0;
unsigned int min_compress = 0;
int compress_level = -1;
PyObject *failed = NULL;
Py_ssize_t idx = 0;
PyObject *curr_key, *curr_value;
PyObject *key_str_map = NULL;
Py_ssize_t i;
Py_ssize_t nkeys;
pylibmc_mset* serialized = NULL;
bool allsuccess;
static char *kws[] = { "keys", "time", "key_prefix",
"min_compress_len", "compress_level",
NULL };
if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!|Is#Ii", kws,
&PyDict_Type, &keys,
&time, &key_prefix_raw, &key_prefix_len,
&min_compress, &compress_level)) {
return NULL;
}
#ifdef USE_ZLIB
if (compress_level == -1) {
compress_level = Z_DEFAULT_COMPRESSION;
} else if (compress_level < 0 || compress_level > 9) {
PyErr_SetString(PyExc_ValueError, "compress_level must be between 0 and 9 inclusive");
return NULL;
}
#else
if (min_compress) {
PyErr_SetString(PyExc_TypeError, "min_compress_len without zlib");
return NULL;
}
#endif
nkeys = (Py_ssize_t)PyDict_Size(keys);
key_str_map = _PylibMC_map_str_keys(keys, NULL, NULL);
if (key_str_map == NULL) {
goto cleanup;
}
serialized = PyMem_New(pylibmc_mset, nkeys);
if (serialized == NULL) {
goto cleanup;
}
if (key_prefix_raw != NULL) {
key_prefix = PyBytes_FromStringAndSize(key_prefix_raw, key_prefix_len);
}
for (i = 0, idx = 0; PyDict_Next(keys, &i, &curr_key, &curr_value); idx++) {
int success = _PylibMC_SerializeValue(self, curr_key, key_prefix,
curr_value, time,
&serialized[idx]);
if (!success || PyErr_Occurred() != NULL) {
nkeys = idx + 1;
goto cleanup;
}
}
allsuccess = _PylibMC_RunSetCommand(self, f, fname,
serialized, nkeys,
min_compress, compress_level);
if (PyErr_Occurred() != NULL) {
goto cleanup;
}
if ((failed = PyList_New(0)) == NULL)
return PyErr_NoMemory();
for (idx = 0; !allsuccess && idx < nkeys; idx++) {
PyObject *key_obj;
if (serialized[idx].success)
continue;
key_obj = serialized[idx].key_obj;
if (PyDict_Contains(key_str_map, key_obj)) {
key_obj = PyDict_GetItem(key_str_map, key_obj);
}
if (PyList_Append(failed, key_obj) != 0) {
Py_DECREF(failed);
failed = PyErr_NoMemory();
goto cleanup;
}
}
cleanup: