1 /*
2  * Copyright (C) 2020 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #include "XmlServiceSupplier.h"
18 #include "ServiceDescriptor.h"
19 
20 using dumpstate::hal::configuration::V1_0::Service;
21 
22 static std::optional<ServiceDescriptor> serviceFromXml(const Service& svc) {
23     if (svc.hasName() && svc.hasCommand()) {
24         return ServiceDescriptor{svc.getName(), svc.getCommand()};
25     }
26     return std::nullopt;
27 }
28 
29 std::optional<XmlServiceSupplier> XmlServiceSupplier::fromFile(const std::string& path) {
30     if (auto cfg = dumpstate::hal::configuration::V1_0::readFile(path.c_str())) {
31         return XmlServiceSupplier{*cfg};
32     }
33     return std::nullopt;
34 }
35 
36 std::optional<XmlServiceSupplier> XmlServiceSupplier::fromBuffer(const std::string& buffer) {
37     if (auto cfg = dumpstate::hal::configuration::V1_0::readBuffer(buffer)) {
38         return XmlServiceSupplier{*cfg};
39     }
40     return std::nullopt;
41 }
42 
43 XmlServiceSupplier::XmlServiceSupplier(const DumpstateHalConfiguration& cfg) {
44     // TODO(egranata): perform semantic validation before constructing
45 
46     if (cfg.hasSystemLogs()) {
47         auto sl = cfg.getFirstSystemLogs();
48         if (sl->hasService()) {
49             auto xsvc = sl->getFirstService();
50             if (auto svc = serviceFromXml(*xsvc)) {
51                 mSystemLogs = *svc;
52             }
53         }
54     }
55 
56     if (cfg.hasServices()) {
57         auto svcs = cfg.getFirstServices();
58         for (const auto& xsvc : svcs->getService()) {
59             if (auto svc = serviceFromXml(xsvc)) {
60                 mServices.push_back(*svc);
61             }
62         }
63     }
64 }
65 
66 std::optional<ServiceDescriptor> XmlServiceSupplier::GetSystemLogsService() const {
67     return mSystemLogs;
68 }
69 
70 std::vector<ServiceDescriptor> XmlServiceSupplier::GetServices() const {
71     return mServices;
72 }
73