~aleteoryx/muditaos

ref: d1726c6ccc528b7eaa2006c8feb9dd659fb986f3 muditaos/module-services/service-desktop/endpoints/deviceInfo/DeviceInfoEndpointCommon.cpp -rw-r--r-- 5.6 KiB
d1726c6c — Bartosz [MOS-000] Update PR template 3 years ago
                                                                                
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
// Copyright (c) 2017-2022, Mudita Sp. z.o.o. All rights reserved.
// For licensing, see https://github.com/mudita/MuditaOS/LICENSE.md

#include <endpoints/deviceInfo/DeviceInfoEndpointCommon.hpp>
#include <endpoints/message/Sender.hpp>
#include <endpoints/JsonKeyNames.hpp>

#include <EventStore.hpp>
#include <product/version.hpp>
#include <service-desktop/ServiceDesktop.hpp>

#include <cstdint>
#include <string>
#include <vector>
#include <sys/statvfs.h>
#include <purefs/filesystem_paths.hpp>

#include <ctime>

namespace sdesktop::endpoints
{
    auto DeviceInfoEndpointCommon::handle(Context &context) -> void
    {
        http::Code status;
        switch (context.getMethod()) {
        case http::Method::get:
            status = handleGet(context);
            break;
        default:
            status = http::Code::BadRequest;
            break;
        }
        context.setResponseStatus(status);
        sender::putToSendQueue(context.createSimpleResponse());
    }

    auto DeviceInfoEndpointCommon::handleGet(Context &context) -> http::Code
    {
        const auto &requestBody = context.getBody();

        if (requestBody[json::fileList].is_number()) {

            const auto diagFileType = parseDiagnosticFileType(requestBody[json::fileList]);

            if (!magic_enum::enum_contains<DiagnosticFileType>(diagFileType)) {
                LOG_ERROR("Bad diagnostic type %d requested", static_cast<unsigned>(diagFileType));

                return http::Code::BadRequest;
            }

            return gatherListOfDiagnostics(context, diagFileType);
        }
        else {
            return getDeviceInfo(context);
        }
    }

    auto DeviceInfoEndpointCommon::parseDiagnosticFileType(const json11::Json &fileList) -> DiagnosticFileType
    {
        return magic_enum::enum_cast<DiagnosticFileType>(fileList.int_value()).value();
    }

    auto DeviceInfoEndpointCommon::gatherListOfDiagnostics(Context &context, DiagnosticFileType diagDataType)
        -> http::Code
    {
        std::vector<std::string> fileList;
        auto status = http::Code::NoContent;

        try {
            requestLogsFlush();
        }
        catch (const std::runtime_error &e) {
            LOG_ERROR("Logs flush exception: %s", e.what());
        }

        switch (diagDataType) {
        case DiagnosticFileType::Logs: {
            fileList = listDirectory(purefs::dir::getLogsPath());
            break;
        }

        case DiagnosticFileType::CrashDumps: {
            fileList = listDirectory(purefs::dir::getCrashDumpsPath());
            break;
        }
        }

        if (!fileList.empty()) {
            status = http::Code::OK;
            context.setResponseBody(fileListToJsonObject(fileList));
        }

        return status;
    }

    auto DeviceInfoEndpointCommon::requestLogsFlush() const -> void
    {
        auto owner = dynamic_cast<ServiceDesktop *>(ownerServicePtr);
        if (owner) {
            owner->requestLogsFlush();
        }
    }

    auto DeviceInfoEndpointCommon::fileListToJsonObject(const std::vector<std::string> &fileList) const
        -> json11::Json::object const
    {
        json11::Json::array fileArray;

        for (const auto &file : fileList) {
            fileArray.push_back(file);
        }

        return json11::Json::object{{json::files, fileArray}};
    }

    auto DeviceInfoEndpointCommon::listDirectory(const std::string &path) -> std::vector<std::string>
    {
        std::vector<std::string> entries;

        for (const auto &entry : std::filesystem::directory_iterator(path)) {
            entries.push_back(entry.path());
        }

        return entries;
    }

    auto DeviceInfoEndpointCommon::getStorageStats(const std::string &path) -> std::tuple<long, long>
    {
        std::unique_ptr<struct statvfs> vfstat = std::make_unique<struct statvfs>();
        if (statvfs(path.c_str(), vfstat.get()) < 0) {
            return {-1, -1};
        }

        unsigned long totalMbytes = (uint64_t(vfstat->f_blocks) * uint64_t(vfstat->f_bsize)) / (1024LLU * 1024LLU);
        unsigned long freeMbytes  = (uint64_t(vfstat->f_bfree) * uint64_t(vfstat->f_bsize)) / (1024LLU * 1024LLU);

        return {totalMbytes, freeMbytes};
    }

    auto DeviceInfoEndpointCommon::getStorageInfo() -> std::tuple<long, long, long>
    {
        const std::array<std::filesystem::path, 2> storagePaths{purefs::dir::getRootDiskPath(),
                                                                purefs::dir::getPreviousOSPath()};

        unsigned long totalMbytes    = 0;
        unsigned long freeUserMbytes = 0;
        unsigned long freePercent    = 0;

        for (const auto &p : storagePaths) {
            auto [totalSpace, freeSpace] = getStorageStats(p);

            if (totalSpace < 0 || freeSpace < 0) {
                LOG_ERROR("Failed to get stats for %s", p.c_str());
                continue;
            }

            totalMbytes += totalSpace;
        }

        // User partition stats
        const auto storagePath       = purefs::dir::getUserDiskPath();
        auto [totalSpace, freeSpace] = getStorageStats(storagePath);

        if (totalSpace < 0 || freeSpace < 0) {
            LOG_ERROR("Failed to get stats for %s", storagePath.c_str());
        }
        else {
            totalMbytes += totalSpace;
            freeUserMbytes = freeSpace;

            // Deduct 1024 MB reserved for OS data on User partition
            freeUserMbytes -= OS_RESERVED_SPACE_IN_MB;
        }

        if (totalMbytes) {
            freePercent = (freeUserMbytes * 100) / totalMbytes;
        }

        return {totalMbytes, freeUserMbytes, freePercent};
    }

} // namespace sdesktop::endpoints