xref: /aosp_15_r20/external/sandboxed-api/contrib/jsonnet/examples/jsonnet_formatter_example.cc (revision ec63e07ab9515d95e79c211197c445ef84cefa6a)
1 // Copyright 2020 Google LLC
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 //     https://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 
15 #include <libgen.h>
16 #include <syscall.h>
17 
18 #include <cstdlib>
19 #include <iostream>
20 
21 #include "jsonnet_sapi.sapi.h"  // NOLINT(build/include)
22 #include "absl/flags/parse.h"
23 #include "absl/log/check.h"
24 #include "absl/log/globals.h"
25 #include "absl/log/initialize.h"
26 #include "sandboxed_api/util/fileops.h"
27 #include "sandboxed_api/util/path.h"
28 
29 class JsonnetSapiSandbox : public JsonnetSandbox {
30  public:
JsonnetSapiSandbox(std::string in_file,std::string out_file)31   explicit JsonnetSapiSandbox(std::string in_file, std::string out_file)
32       : in_file_(std::move(in_file)), out_file_(std::move(out_file)) {}
33 
34   // We need only the input file here, not the whole input directory
ModifyPolicy(sandbox2::PolicyBuilder *)35   std::unique_ptr<sandbox2::Policy> ModifyPolicy(
36       sandbox2::PolicyBuilder*) override {
37     return sandbox2::PolicyBuilder()
38         .AllowStaticStartup()
39         .AllowOpen()
40         .AllowRead()
41         .AllowWrite()
42         .AllowStat()
43         .AllowSystemMalloc()
44         .AllowExit()
45         .AllowSyscalls({
46             __NR_futex,
47             __NR_close,
48         })
49         .AddDirectoryAt(dirname(&out_file_[0]), "/output", /*is_ro=*/false)
50         .AddFile(in_file_, true)
51         .BuildOrDie();
52   }
53 
54  private:
55   std::string in_file_;
56   std::string out_file_;
57 };
58 
JsonnetMain(std::string in_file,std::string out_file)59 absl::Status JsonnetMain(std::string in_file, std::string out_file) {
60   using sapi::file::JoinPath;
61   using sapi::file_util::fileops::Basename;
62 
63   // Initialize sandbox.
64   JsonnetSapiSandbox sandbox(in_file, out_file);
65   SAPI_RETURN_IF_ERROR(sandbox.Init());
66 
67   JsonnetApi api(&sandbox);
68 
69   // Initialize library's main structure.
70   SAPI_ASSIGN_OR_RETURN(JsonnetVm * jsonnet_vm, api.c_jsonnet_make());
71   sapi::v::RemotePtr vm_pointer(jsonnet_vm);
72 
73   // Read input file.
74   std::string in_file_in_sandboxee(JoinPath("/input", Basename(in_file)));
75   sapi::v::ConstCStr in_file_var(in_file_in_sandboxee.c_str());
76   SAPI_ASSIGN_OR_RETURN(char* input,
77                         api.c_read_input(false, in_file_var.PtrBefore()));
78 
79   // Process jsonnet data.
80   sapi::v::RemotePtr input_pointer(input);
81   sapi::v::Int error;
82   SAPI_ASSIGN_OR_RETURN(char* output, api.c_jsonnet_fmt_snippet(
83                                           &vm_pointer, in_file_var.PtrBefore(),
84                                           &input_pointer, error.PtrAfter()));
85 
86   CHECK(!error.GetValue()) << "Jsonnet code evaluation failed: "
87                            << error.GetValue() << "\n";
88 
89   // Write data to file.
90   std::string out_file_in_sandboxee(JoinPath("/output", Basename(out_file)));
91   sapi::v::ConstCStr out_file_var(out_file_in_sandboxee.c_str());
92   sapi::v::RemotePtr output_pointer(output);
93 
94   SAPI_ASSIGN_OR_RETURN(
95       bool success,
96       api.c_write_output_file(&output_pointer, out_file_var.PtrBefore()));
97   CHECK(success) << "Writing to output file failed: " << success;
98 
99   // Clean up.
100   SAPI_ASSIGN_OR_RETURN(char* result,
101                         api.c_jsonnet_realloc(&vm_pointer, &output_pointer, 0));
102   SAPI_RETURN_IF_ERROR(api.c_jsonnet_destroy(&vm_pointer));
103   SAPI_RETURN_IF_ERROR(api.c_free_input(&input_pointer));
104 
105   return absl::OkStatus();
106 }
107 
main(int argc,char * argv[])108 int main(int argc, char* argv[]) {
109   using sapi::file_util::fileops::Basename;
110 
111   absl::SetStderrThreshold(absl::LogSeverityAtLeast::kInfo);
112   absl::ParseCommandLine(argc, argv);
113   absl::InitializeLog();
114 
115   if (argc != 3) {
116     std::cerr << "Usage:\n"
117               << Basename(argv[0])
118               << " /absolute/path/to/INPUT.jsonnet /absolute/path/to/OUTPUT\n";
119     return EXIT_FAILURE;
120   }
121 
122   std::string in_file(argv[1]);
123   std::string out_file(argv[2]);
124 
125   absl::Status status = JsonnetMain(in_file, out_file);
126   if (!status.ok()) {
127     LOG(ERROR) << "Failed: " << status.ToString();
128     return EXIT_FAILURE;
129   }
130 
131   return EXIT_SUCCESS;
132 }
133