-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathContainerLogger.js
253 lines (219 loc) · 9.26 KB
/
ContainerLogger.js
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
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
'use strict';
const EventEmitter = require('events');
const Q = require('q');
const logger = require('cf-logs').Logger('codefresh:containerLogger');
const CFError = require('cf-errors');
const LoggerStrategy = require('./enums').LoggerStrategy;
const { Transform } = require('stream');
class ContainerLogger extends EventEmitter {
constructor({
containerId,
containerInterface,
stepLogger,
logSizeLimit,
isWorkflowLogSizeExceeded, // eslint-disable-line
loggerStrategy
}) {
super();
this.containerId = containerId;
this.containerInterface = containerInterface;
this.stepLogger = stepLogger;
this.loggerStrategy = loggerStrategy;
this.tty = false;
this.logSizeLimit = logSizeLimit;
this.logSize = 0;
this.isWorkflowLogSizeExceeded = isWorkflowLogSizeExceeded;
this.stepFinished = false;
this.finishedStreams = 0;
this.handledStreams = 0;
}
start() {
return Q.ninvoke(this.containerInterface, 'inspect')
.then((inspectedContainer) => {
this.tty = inspectedContainer.Config.Tty;
if (this.loggerStrategy === LoggerStrategy.ATTACH) {
return this._getAttachStrategyStream();
} else if (this.loggerStrategy === LoggerStrategy.LOGS) {
return this._getLogsStrategyStream();
} else {
return Q.reject(new CFError(`Strategy: ${this.loggerStrategy} is not supported`));
}
})
.then(([stdout, stderr]) => {
logger.info(`Attached stream to container: ${this.containerId}`);
// Listening on the stream needs to be performed different depending if a tty is attached or not
// See documentation of the docker api here: https://docs.docker.com/engine/reference/api/docker_remote_api_v1.24/#/attach-to-a-container
if (this.tty) {
stdout.on('end', () => {
this.stepFinished = true;
logger.info(`stdout end event was fired for container: ${this.containerId}`);
});
if (this.stepLogger.opts && this.stepLogger.opts.logsRateLimitConfig) {
logger.info(`Found logger rate limit configuration, using streams api`);
this._streamTty(stdout, stderr);
return;
}
this._registerToTtyStreams(stdout, stderr);
} else {
this._handleNonTtyStream(stdout, false);
if (stderr) {
this._handleNonTtyStream(stderr, true);
}
}
}, (err) => {
return Q.reject(new CFError({
cause: err,
message: `Failed to handle container:${this.containerId}`
}));
});
}
_getAttachStrategyStream() {
return Q.all([
Q.ninvoke(this.containerInterface, 'attach', {
stream: true,
stdout: true,
stderr: false,
tty: true
}),
Q.ninvoke(this.containerInterface, 'attach', {
stream: true,
stdout: false,
stderr: true,
tty: true
})
]);
}
_getLogsStrategyStream() {
return Q.all([
Q.ninvoke(this.containerInterface, 'logs', {
follow: true,
stdout: true,
stderr: true,
tail: 1000
})
]);
}
_streamTty(stdout, stderr) {
logger.info(`Piping stdout and stderr step streams`);
const stepLoggerWritableStream = this.stepLogger.writeStream();
stepLoggerWritableStream.on('error', err => logger.error(`stepLoggerWritableStream: ${err}`));
// Attention(!) all streams piped to step logger writable stream must be a new streams(!) in order to avoid message piping twice to writable stream.
// { end = false } on the stepLoggerWritableStream because there is only one instance of it for all the steps.
this.handledStreams++;
stdout
.pipe(this._logSizeLimitStream())
.pipe(this.stepLogger.createMaskingStream())
.pipe(this.stepLogger.stepNameTransformStream().once('end', this._handleFinished.bind(this)))
.pipe(stepLoggerWritableStream, {end: false});
if (!stderr) {
return;
}
this.handledStreams++;
stderr
.pipe(this._logSizeLimitStream())
.pipe(this._errorTransformerStream())
.pipe(this.stepLogger.createMaskingStream())
.pipe(this.stepLogger.stepNameTransformStream().once('end', this._handleFinished.bind(this)))
.pipe(stepLoggerWritableStream, {end: false});
stderr.once('end', () => {
this.stepFinished = true;
logger.info(`stderr end event was fired for container: ${this.containerId}`);
});
}
_registerToTtyStreams(stdout, stderr) {
this._handleTtyStream(stdout, false);
if (stderr) {
stderr.once('end', () => {
this.stepFinished = true;
logger.info(`stderr end event was fired for container: ${this.containerId}`);
});
this._handleTtyStream(stderr, true);
}
}
_handleTtyStream(stream, isError) {
this.handledStreams++;
stream.on('end', this._handleFinished.bind(this));
stream.on('data', (chunk) => {
const buf = new Buffer(chunk);
const message = buf.toString('utf8');
this._logMessage(message, isError);
});
logger.info(`Listening on stream 'data' event for container: ${this.containerId}`);
}
_handleNonTtyStream(stream, isError) {
this.handledStreams++;
stream.on('readable', () => {
let header = stream.read(8);
while (header !== null) {
const payload = stream.read(header.readUInt32BE(4));
if (payload === null) {
break;
}
this._logMessage(new Buffer(payload).toString('utf8'), isError);
header = stream.read(8);
}
});
stream.on('end', this._handleFinished.bind(this));
logger.info(`Listening on stream 'readable' event for container: ${this.containerId}`);
}
_stepLogSizeExceeded() {
return this.logSize > this.logSizeLimit;
}
_logMessage(message, isError) {
if (this.logSizeLimit && (this._stepLogSizeExceeded() || this.isWorkflowLogSizeExceeded()) && !isError) {
if (!this.logExceededLimitsNotified) {
this.logExceededLimitsNotified = true;
message = `\x1B[01;93mLog size exceeded for ${this._stepLogSizeExceeded() ? 'this step' : 'the workflow'}.\nThe step will continue to execute until it finished but new logs will not be stored.\x1B[0m\r\n`;
} else {
return;
}
}
if (isError) {
message = `\x1B[31m${message}\x1B[0m`;
}
this.stepLogger.write(message);
if (this.logSizeLimit) {
this.logSize += Buffer.byteLength(message);
this.stepLogger.setLogSize(this.logSize);
}
this.emit('message.logged');
}
_errorTransformerStream() {
return new Transform({
transform: (data, encoding, done) => {
const message = `\x1B[31m${data.toString('utf8')}\x1B[0m`;
done(null, Buffer.from(message));
}
});
}
_logSizeLimitStream() {
return new Transform({
transform: (data, encoding, done) => {
if (this.logSizeLimit && (this._stepLogSizeExceeded() || this.isWorkflowLogSizeExceeded())) {
if (!this.logExceededLimitsNotified) {
this.logExceededLimitsNotified = true;
const message = `\x1B[01;93mLog size exceeded for ${this._stepLogSizeExceeded() ? 'this step' : 'the workflow'}.\nThe step will continue to execute until it finished but new logs will not be stored.\x1B[0m\r\n`;
done(null, Buffer.from(message));
return;
}
done(null, Buffer.alloc(0)); // discard chunk
return;
}
if (this.logSizeLimit) {
this.logSize += Buffer.byteLength(data);
this.stepLogger.setLogSize(this.logSize);
}
this.emit('message.logged');
done(null, data);
}
});
}
_handleFinished() {
this.finishedStreams++;
if (this.finishedStreams === this.handledStreams) {
// the emission of this event reflects the ending of all streams handled by this container logger
this.emit('end');
}
}
}
module.exports = ContainerLogger;