• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright 2018, gRPC Authors All rights reserved.
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 package io.grpc.services;
18 
19 import com.google.protobuf.MessageLite;
20 import java.io.BufferedOutputStream;
21 import java.io.File;
22 import java.io.FileOutputStream;
23 import java.io.IOException;
24 import java.io.OutputStream;
25 import java.util.logging.Level;
26 import java.util.logging.Logger;
27 
28 /**
29  * The output file goes to the JVM's temp dir with a prefix of BINARY_INFO. The proto messages
30  * are written serially using {@link MessageLite#writeDelimitedTo(OutputStream)}.
31  */
32 class TempFileSink implements BinaryLogSink {
33   private static final Logger logger = Logger.getLogger(TempFileSink.class.getName());
34 
35   private final String outPath;
36   private final OutputStream out;
37   private boolean closed;
38 
TempFileSink()39   TempFileSink() throws IOException {
40     File outFile = File.createTempFile("BINARY_INFO.", "");
41     outPath = outFile.getPath();
42     logger.log(Level.INFO, "Writing binary logs to to {0}", outFile.getAbsolutePath());
43     out = new BufferedOutputStream(new FileOutputStream(outFile));
44   }
45 
getPath()46   String getPath() {
47     return this.outPath;
48   }
49 
50   @Override
write(MessageLite message)51   public synchronized void write(MessageLite message) {
52     if (closed) {
53       logger.log(Level.FINEST, "Attempt to write after TempFileSink is closed.");
54       return;
55     }
56     try {
57       message.writeDelimitedTo(out);
58     } catch (IOException e) {
59       logger.log(Level.SEVERE, "Caught exception while writing", e);
60       closeQuietly();
61     }
62   }
63 
64   @Override
close()65   public synchronized void close() throws IOException {
66     if (closed) {
67       return;
68     }
69     closed = true;
70     try {
71       out.flush();
72     } finally {
73       out.close();
74     }
75   }
76 
closeQuietly()77   private synchronized void closeQuietly() {
78     try {
79       close();
80     } catch (IOException e) {
81       logger.log(Level.SEVERE, "Caught exception while closing", e);
82     }
83   }
84 }
85