}
string ks(k);
if (ks == "severity") {
- if (!PyString_Check(v)) {
+ if (auto [vs, valid] = PyString_ToString(v); !valid) {
derr << __func__ << " check " << check_name
<< " severity value not string" << dendl;
continue;
- }
- string vs(PyString_AsString(v));
- if (vs == "warning") {
+ } else if (vs == "warning") {
severity = HEALTH_WARN;
} else if (vs == "error") {
severity = HEALTH_ERR;
}
} else if (ks == "summary") {
- if (!PyString_Check(v) && !PyUnicode_Check(v)) {
+ if (auto [vs, valid] = PyString_ToString(v); !valid) {
derr << __func__ << " check " << check_name
<< " summary value not [unicode] string" << dendl;
continue;
+ } else {
+ summary = std::move(vs);
}
- summary = PyString_AsString(v);
} else if (ks == "detail") {
if (!PyList_Check(v)) {
derr << __func__ << " check " << check_name
}
for (int k = 0; k < PyList_Size(v); ++k) {
PyObject *di = PyList_GET_ITEM(v, k);
- if (!PyString_Check(di) && !PyUnicode_Check(di)) {
+ if (auto [vs, valid] = PyString_ToString(di); !valid) {
derr << __func__ << " check " << check_name
<< " detail item " << k << " not a [unicode] string" << dendl;
continue;
+ } else {
+ detail.push_back(std::move(vs));
}
- detail.push_back(PyString_AsString(di));
}
} else {
derr << __func__ << " check " << check_name
#pragma once
#include <Python.h>
+#include <string>
// Python's pyconfig-64.h conflicts with ceph's acconfig.h
#undef HAVE_SYS_WAIT_H
}
#define PyString_Type PyUnicode_Type
#endif
+
+inline std::pair<std::string, bool> PyString_ToString(PyObject *o) {
+#if PY_MAJOR_VERSION >= 3
+ if (PyUnicode_Check(o)) {
+ return {PyUnicode_AsUTF8(o), true};
+ } else {
+ return {{}, false};
+ }
+#else
+ if (PyString_Check(o) || PyUnicode_Check(o)) {
+ return {PyString_AsString(o), true};
+ } else {
+ return {{}, false};
+ }
+#endif
+}