1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
use bytes::BytesMut;
use futures_core::Stream;
use hyper::body::Bytes;
use pin_project::pin_project;
use serde::de::DeserializeOwned;
use serde_json;
use std::pin::Pin;
use std::string::String;
use std::task::{Context, Poll};
use std::{
    cmp,
    io::{self},
    marker::PhantomData,
};
use tokio::io::AsyncRead;
use tokio_util::codec::Decoder;

use crate::container::LogOutput;

use crate::errors::Error;
use crate::errors::ErrorKind::{JsonDataError, JsonDeserializeError, StrParseError};

#[derive(Debug, Copy, Clone)]
pub(crate) struct NewlineLogOutputDecoder {}

impl NewlineLogOutputDecoder {
    pub(crate) fn new() -> NewlineLogOutputDecoder {
        NewlineLogOutputDecoder {}
    }
}

impl Decoder for NewlineLogOutputDecoder {
    type Item = LogOutput;
    type Error = Error;
    fn decode(&mut self, src: &mut BytesMut) -> Result<Option<Self::Item>, Self::Error> {
        let nl_index = src.iter().position(|b| *b == b'\n');

        if src.len() > 0 {
            let pos = nl_index.unwrap_or(src.len() - 1);

            let slice = src.split_to(pos + 1);
            let slice = &slice[..slice.len() - 1];

            if slice.len() == 0 {
                Ok(Some(LogOutput::Console {
                    message: String::new(),
                }))
            } else {
                match &slice[0] {
                    0 if slice.len() <= 8 => Ok(Some(LogOutput::StdIn {
                        message: String::new(),
                    })),
                    0 => Ok(Some(LogOutput::StdIn {
                        message: String::from_utf8_lossy(&slice[8..]).to_string(),
                    })),
                    1 if slice.len() <= 8 => Ok(Some(LogOutput::StdOut {
                        message: String::new(),
                    })),
                    1 => Ok(Some(LogOutput::StdOut {
                        message: String::from_utf8_lossy(&slice[8..]).to_string(),
                    })),
                    2 if slice.len() <= 8 => Ok(Some(LogOutput::StdErr {
                        message: String::new(),
                    })),
                    2 => Ok(Some(LogOutput::StdErr {
                        message: String::from_utf8_lossy(&slice[8..]).to_string(),
                    })),
                    _ =>
                    // `start_exec` API on unix socket will emit values without a header
                    {
                        Ok(Some(LogOutput::Console {
                            message: String::from_utf8_lossy(&slice).to_string(),
                        }))
                    }
                }
                .map_err(|e| {
                    StrParseError {
                        content: hex::encode(slice.to_owned()),
                        err: e,
                    }
                    .into()
                })
            }
        } else {
            debug!("NewlineLogOutputDecoder returning due to an empty line");
            Ok(None)
        }
    }
}

#[pin_project]
#[derive(Debug)]
pub(crate) struct JsonLineDecoder<T> {
    ty: PhantomData<T>,
}

impl<T> JsonLineDecoder<T> {
    #[inline]
    pub(crate) fn new() -> JsonLineDecoder<T> {
        JsonLineDecoder { ty: PhantomData }
    }
}

impl<T> Decoder for JsonLineDecoder<T>
where
    T: DeserializeOwned,
{
    type Item = T;
    type Error = Error;
    fn decode(&mut self, src: &mut BytesMut) -> Result<Option<Self::Item>, Self::Error> {
        let nl_index = src.iter().position(|b| *b == b'\n');

        if src.len() > 0 {
            if let Some(pos) = nl_index {
                let slice = src.split_to(pos + 1);
                let slice = &slice[..slice.len() - 1];

                debug!(
                    "Decoding JSON line from stream: {}",
                    String::from_utf8_lossy(&slice).to_string()
                );

                match serde_json::from_slice(slice) {
                    Ok(json) => Ok(json),
                    Err(ref e) if e.is_data() => Err(JsonDataError {
                        message: e.to_string(),
                        column: e.column(),
                        contents: String::from_utf8_lossy(&slice).to_string(),
                    }
                    .into()),
                    Err(e) => Err(JsonDeserializeError {
                        content: String::from_utf8_lossy(slice).to_string(),
                        err: e,
                    }
                    .into()),
                }
            } else {
                Ok(None)
            }
        } else {
            Ok(None)
        }
    }
}

#[derive(Debug)]
enum ReadState {
    Ready(Bytes, usize),
    NotReady,
}

#[pin_project]
#[derive(Debug)]
pub(crate) struct StreamReader<S> {
    #[pin]
    stream: S,
    state: ReadState,
}

impl<S> StreamReader<S>
where
    S: Stream<Item = Result<Bytes, Error>>,
{
    #[inline]
    pub(crate) fn new(stream: S) -> StreamReader<S> {
        StreamReader {
            stream,
            state: ReadState::NotReady,
        }
    }
}

impl<S> AsyncRead for StreamReader<S>
where
    S: Stream<Item = Result<Bytes, Error>>,
{
    fn poll_read(
        self: Pin<&mut Self>,
        cx: &mut Context<'_>,
        buf: &mut [u8],
    ) -> Poll<io::Result<usize>> {
        let mut this = self.project();
        loop {
            let ret;

            match this.state {
                ReadState::Ready(ref mut chunk, ref mut pos) => {
                    let chunk_start = *pos;
                    let len = cmp::min(buf.len(), chunk.len() - chunk_start);
                    let chunk_end = chunk_start + len;

                    buf[..len].copy_from_slice(&chunk[chunk_start..chunk_end]);
                    *pos += len;

                    if *pos == chunk.len() {
                        ret = len;
                    } else {
                        return Poll::Ready(Ok(len));
                    }
                }

                ReadState::NotReady => match this.stream.as_mut().poll_next(cx) {
                    Poll::Ready(Some(Ok(chunk))) => {
                        *this.state = ReadState::Ready(chunk, 0);

                        continue;
                    }
                    Poll::Ready(None) => return Poll::Ready(Ok(0)),
                    Poll::Pending => {
                        return Poll::Pending;
                    }
                    Poll::Ready(Some(Err(e))) => {
                        return Poll::Ready(Err(io::Error::new(
                            io::ErrorKind::Other,
                            e.to_string(),
                        )));
                    }
                },
            }

            *this.state = ReadState::NotReady;

            return Poll::Ready(Ok(ret));
        }
    }
}