1 /* 2 * Copyright (C) 2023 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 package com.android.tradefed.testtype.bazel; 17 18 import com.google.devtools.build.lib.buildeventstream.BuildEventStreamProtos.BuildEvent; 19 import com.google.protobuf.InvalidProtocolBufferException; 20 21 import java.io.BufferedInputStream; 22 import java.io.FileInputStream; 23 import java.io.FileNotFoundException; 24 import java.io.IOException; 25 import java.nio.file.Path; 26 import java.time.Duration; 27 28 final class BepFileTailer implements AutoCloseable { 29 private static final Duration BEP_PARSE_SLEEP_TIME = Duration.ofMillis(100); 30 31 private final BufferedInputStream mIn; 32 private volatile boolean mStop; 33 create(Path bepFile)34 static BepFileTailer create(Path bepFile) throws FileNotFoundException { 35 return new BepFileTailer(new BufferedInputStream(new FileInputStream(bepFile.toFile()))); 36 } 37 BepFileTailer(BufferedInputStream In)38 private BepFileTailer(BufferedInputStream In) { 39 mIn = In; 40 mStop = false; 41 } 42 nextEvent()43 public BuildEvent nextEvent() throws InterruptedException, IOException { 44 while (true) { 45 boolean stop = mStop; 46 47 // Mark the current position in the input stream. 48 mIn.mark(Integer.MAX_VALUE); 49 50 try { 51 BuildEvent event = BuildEvent.parseDelimitedFrom(mIn); 52 53 // When event is null and we hit EOF, wait for an event to be written and try again. 54 if (event != null) { 55 return event; 56 } 57 if (stop) { 58 return null; 59 } 60 } catch (InvalidProtocolBufferException e) { 61 if (stop) { 62 throw e; 63 } 64 // Partial read. Restore the old position in the input stream. 65 mIn.reset(); 66 } 67 Thread.sleep(BEP_PARSE_SLEEP_TIME.toMillis()); 68 } 69 } 70 71 @Override close()72 public void close() throws IOException { 73 mIn.close(); 74 } 75 stop()76 public void stop() { 77 mStop = true; 78 } 79 } 80