]>
git.proxmox.com Git - ceph.git/blob - ceph/src/mgr/PyFormatter.cc
8e58f6e9a84ab99aa55592a7d3fe473af1aa3868
1 // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
2 // vim: ts=8 sw=2 smarttab
4 * Ceph - scalable distributed file system
6 * Copyright (C) 2015 Red Hat Inc
8 * Author: John Spray <john.spray@redhat.com>
10 * This is free software; you can redistribute it and/or
11 * modify it under the terms of the GNU Lesser General Public
12 * License version 2.1, as published by the Free Software
13 * Foundation. See file COPYING.
18 #include "PyFormatter.h"
21 #define LARGE_SIZE 1024
24 void PyFormatter::open_array_section(std::string_view name
)
26 PyObject
*list
= PyList_New(0);
27 dump_pyobject(name
, list
);
32 void PyFormatter::open_object_section(std::string_view name
)
34 PyObject
*dict
= PyDict_New();
35 dump_pyobject(name
, dict
);
40 void PyFormatter::dump_unsigned(std::string_view name
, uint64_t u
)
42 PyObject
*p
= PyLong_FromUnsignedLong(u
);
44 dump_pyobject(name
, p
);
47 void PyFormatter::dump_int(std::string_view name
, int64_t u
)
49 PyObject
*p
= PyLong_FromLongLong(u
);
51 dump_pyobject(name
, p
);
54 void PyFormatter::dump_float(std::string_view name
, double d
)
56 dump_pyobject(name
, PyFloat_FromDouble(d
));
59 void PyFormatter::dump_string(std::string_view name
, std::string_view s
)
61 dump_pyobject(name
, PyUnicode_FromString(s
.data()));
64 void PyFormatter::dump_bool(std::string_view name
, bool b
)
68 dump_pyobject(name
, Py_True
);
71 dump_pyobject(name
, Py_False
);
75 std::ostream
& PyFormatter::dump_stream(std::string_view name
)
77 // Give the caller an ostream, construct a PyString,
78 // and remember the association between the two. On flush,
79 // we'll read from the ostream into the PyString
80 auto ps
= std::make_shared
<PendingStream
>();
84 pending_streams
.push_back(ps
);
89 void PyFormatter::dump_format_va(std::string_view name
, const char *ns
, bool quoted
, const char *fmt
, va_list ap
)
92 vsnprintf(buf
, LARGE_SIZE
, fmt
, ap
);
94 dump_pyobject(name
, PyUnicode_FromString(buf
));
98 * Steals reference to `p`
100 void PyFormatter::dump_pyobject(std::string_view name
, PyObject
*p
)
102 if (PyList_Check(cursor
)) {
103 PyList_Append(cursor
, p
);
105 } else if (PyDict_Check(cursor
)) {
106 PyObject
*key
= PyUnicode_DecodeUTF8(name
.data(), name
.size(), nullptr);
107 PyDict_SetItem(cursor
, key
, p
);
115 void PyFormatter::finish_pending_streams()
117 for (const auto &i
: pending_streams
) {
118 PyObject
*tmp_cur
= cursor
;
122 PyUnicode_FromString(i
->stream
.str().c_str()));
126 pending_streams
.clear();
129 PyObject
* PyJSONFormatter::get()
131 if(json_formatter::stack_size()) {
134 ceph_assert(!json_formatter::stack_size());
135 std::ostringstream ss
;
137 std::string s
= ss
.str();
138 PyObject
* obj
= PyBytes_FromStringAndSize(std::move(s
.c_str()), s
.size());