1+ /* ******************************************************************************
2+
3+ Copyright (c) 2024, Perforce Software, Inc. All rights reserved.
4+
5+ Redistribution and use in source and binary forms, with or without
6+ modification, are permitted provided that the following conditions are met:
7+
8+ 1. Redistributions of source code must retain the above copyright
9+ notice, this list of conditions and the following disclaimer.
10+
11+ 2. Redistributions in binary form must reproduce the above copyright
12+ notice, this list of conditions and the following disclaimer in the
13+ documentation and/or other materials provided with the distribution.
14+
15+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
16+ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18+ ARE DISCLAIMED. IN NO EVENT SHALL PERFORCE SOFTWARE, INC. BE LIABLE FOR ANY
19+ DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
20+ (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
21+ LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
22+ ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
23+ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
24+ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
25+
26+ *******************************************************************************/
27+
28+ /* ******************************************************************************
29+ * Name : PythonKeepAlive.cpp
30+ *
31+ * Author : Himanshu Jain <hjain@perforce.com>
32+ *
33+ * Description : C++ subclass for KeepAlive used by Python KeepAlive.
34+ * Allows Perforce API to implement a customized IsAlive function
35+ *
36+ * $Id: //depot/main/p4-python/PythonKeepAlive.cpp#1 $
37+ *
38+ ******************************************************************************/
39+
40+ #include < Python.h>
41+ #include < keepalive.h>
42+ #include " PythonThreadGuard.h"
43+ #include " PythonKeepAlive.h"
44+
45+ PythonKeepAlive::PythonKeepAlive (PyObject* callable) : py_callable(callable) {
46+ // Increment the reference count for the callable
47+ Py_XINCREF (py_callable);
48+ }
49+
50+ PythonKeepAlive::~PythonKeepAlive () {
51+ // Decrement the reference count for the callable
52+ Py_XDECREF (py_callable);
53+ }
54+
55+ int PythonKeepAlive::IsAlive () {
56+
57+ EnsurePythonLock guard;
58+
59+ if (py_callable && PyCallable_Check (py_callable)) {
60+ PyObject* result = PyObject_CallObject (py_callable, NULL );
61+ if (result != NULL && PyLong_Check (result) && PyLong_AsLong (result) == 0 ) {
62+ Py_DECREF (result);
63+ return ( 0 ); // To terminate the connection
64+ }
65+
66+ return ( 1 );
67+ }
68+
69+ return ( 1 ); // Default to true if callable is not set or failed
70+ }
0 commit comments