1 // 2 // Copyright (C) 2019 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 #pragma once 17 18 #include <condition_variable> 19 #include <functional> 20 #include <list> 21 #include <memory> 22 #include <mutex> 23 #include <thread> 24 #include <string> 25 #include <vector> 26 27 #include "common/libs/fs/shared_fd.h" 28 #include "common/libs/thread_safe_queue/thread_safe_queue.h" 29 30 namespace cvd { 31 32 using TeeBufferPtr = std::shared_ptr<std::vector<char>>; 33 using TeeSubscriber = std::function<void(const TeeBufferPtr)>; 34 35 struct TeeTarget { 36 std::thread runner; 37 ThreadSafeQueue<TeeBufferPtr> content_queue; 38 TeeSubscriber handler; 39 TeeTargetTeeTarget40 TeeTarget(TeeSubscriber handler) : handler(handler) {} 41 }; 42 43 class Tee { 44 std::thread reader_; 45 std::list<TeeTarget> targets_; 46 public: 47 ~Tee(); 48 49 TeeSubscriber* AddSubscriber(TeeSubscriber); 50 51 void Start(SharedFD source); 52 void Join(); 53 }; 54 55 TeeSubscriber SharedFDWriter(SharedFD fd); 56 57 class TeeStderrToFile { 58 cvd::SharedFD log_file_; 59 cvd::SharedFD original_stderr_; 60 std::condition_variable notifier_; 61 std::mutex mutex_; 62 Tee tee_; // This should be destroyed first, so placed last. 63 public: 64 TeeStderrToFile(); 65 ~TeeStderrToFile(); 66 67 void SetFile(SharedFD file); 68 }; 69 70 } // namespace cvd 71