Fix some bugs when testing opensds ansible
[stor4nfv.git] / src / ceph / src / mgr / PyModuleRunner.cc
1 // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
2 // vim: ts=8 sw=2 smarttab
3 /*
4  * Ceph - scalable distributed file system
5  *
6  * Copyright (C) 2016 John Spray <john.spray@redhat.com>
7  *
8  * This is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Lesser General Public
10  * License version 2.1, as published by the Free Software
11  * Foundation.  See file COPYING.
12  */
13
14
15 // Python.h comes first because otherwise it clobbers ceph's assert
16 #include "Python.h"
17
18 #include "common/debug.h"
19 #include "mgr/Gil.h"
20
21 #include "PyModuleRunner.h"
22
23 #define dout_context g_ceph_context
24 #define dout_subsys ceph_subsys_mgr
25
26
27 std::string handle_pyerror();
28
29 PyModuleRunner::~PyModuleRunner()
30 {
31   Gil gil(pMyThreadState, true);
32
33   if (pClassInstance) {
34     Py_XDECREF(pClassInstance);
35     pClassInstance = nullptr;
36   }
37
38   Py_DECREF(pClass);
39   pClass = nullptr;
40 }
41
42 int PyModuleRunner::serve()
43 {
44   assert(pClassInstance != nullptr);
45
46   // This method is called from a separate OS thread (i.e. a thread not
47   // created by Python), so tell Gil to wrap this in a new thread state.
48   Gil gil(pMyThreadState, true);
49
50   auto pValue = PyObject_CallMethod(pClassInstance,
51       const_cast<char*>("serve"), nullptr);
52
53   int r = 0;
54   if (pValue != NULL) {
55     Py_DECREF(pValue);
56   } else {
57     derr << module_name << ".serve:" << dendl;
58     derr << handle_pyerror() << dendl;
59     return -EINVAL;
60   }
61
62   return r;
63 }
64
65 void PyModuleRunner::shutdown()
66 {
67   assert(pClassInstance != nullptr);
68
69   Gil gil(pMyThreadState, true);
70
71   auto pValue = PyObject_CallMethod(pClassInstance,
72       const_cast<char*>("shutdown"), nullptr);
73
74   if (pValue != NULL) {
75     Py_DECREF(pValue);
76   } else {
77     derr << "Failed to invoke shutdown() on " << module_name << dendl;
78     derr << handle_pyerror() << dendl;
79   }
80 }
81
82 void PyModuleRunner::log(int level, const std::string &record)
83 {
84 #undef dout_prefix
85 #define dout_prefix *_dout << "mgr[" << module_name << "] "
86   dout(level) << record << dendl;
87 #undef dout_prefix
88 #define dout_prefix *_dout << "mgr " << __func__ << " "
89 }
90
91 void* PyModuleRunner::PyModuleRunnerThread::entry()
92 {
93   // No need to acquire the GIL here; the module does it.
94   dout(4) << "Entering thread for " << mod->get_name() << dendl;
95   mod->serve();
96   return nullptr;
97 }