-
Notifications
You must be signed in to change notification settings - Fork 8.3k
/
Copy pathservice_api_client.ts
184 lines (156 loc) · 5.44 KB
/
service_api_client.ts
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
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/
import axios from 'axios';
import { forkJoin, from as rxjsFrom, Observable, of } from 'rxjs';
import { catchError, tap } from 'rxjs/operators';
import * as https from 'https';
import { SslConfig } from '@kbn/server-http-tools';
import { Logger } from '@kbn/core/server';
import { MonitorFields, ServiceLocations, ServiceLocationErrors } from '../../common/runtime_types';
import { convertToDataStreamFormat } from './formatters/convert_to_data_stream';
import { ServiceConfig } from '../../common/config';
const TEST_SERVICE_USERNAME = 'localKibanaIntegrationTestsUser';
export interface ServiceData {
monitors: Array<Partial<MonitorFields>>;
output: {
hosts: string[];
api_key: string;
};
runOnce?: boolean;
}
export class ServiceAPIClient {
private readonly username?: string;
private readonly authorization: string;
public locations: ServiceLocations;
private logger: Logger;
private readonly config: ServiceConfig;
private readonly kibanaVersion: string;
constructor(logger: Logger, config: ServiceConfig, kibanaVersion: string) {
this.config = config;
const { username, password } = config;
this.username = username;
this.kibanaVersion = kibanaVersion;
if (username && password) {
this.authorization = 'Basic ' + Buffer.from(`${username}:${password}`).toString('base64');
} else {
this.authorization = '';
}
this.logger = logger;
this.locations = [];
}
getHttpsAgent() {
const config = this.config;
if (config.tls && config.tls.certificate && config.tls.key) {
const tlsConfig = new SslConfig(config.tls);
const rejectUnauthorized = process.env.NODE_ENV === 'production';
return new https.Agent({
rejectUnauthorized,
cert: tlsConfig.certificate,
key: tlsConfig.key,
});
}
}
async post(data: ServiceData) {
return this.callAPI('POST', data);
}
async put(data: ServiceData) {
return this.callAPI('PUT', data);
}
async delete(data: ServiceData) {
return this.callAPI('DELETE', data);
}
async runOnce(data: ServiceData) {
return this.callAPI('POST', { ...data, runOnce: true });
}
async checkAccountAccessStatus() {
if (this.authorization) {
// in case username/password is provided, we assume it's always allowed
return { allowed: true, signupUrl: null };
}
const httpsAgent = this.getHttpsAgent();
if (this.locations.length > 0 && httpsAgent) {
// get a url from a random location
const url = this.locations[Math.floor(Math.random() * this.locations.length)].url;
try {
const { data } = await axios({
method: 'GET',
url: url + '/allowed',
headers:
process.env.NODE_ENV !== 'production' && this.authorization
? {
Authorization: this.authorization,
}
: undefined,
httpsAgent,
});
const { allowed, signupUrl } = data;
return { allowed, signupUrl };
} catch (e) {
this.logger.error(e);
}
}
return { allowed: false, signupUrl: null };
}
async callAPI(
method: 'POST' | 'PUT' | 'DELETE',
{ monitors: allMonitors, output, runOnce }: ServiceData
) {
if (this.username === TEST_SERVICE_USERNAME) {
// we don't want to call service while local integration tests are running
return;
}
const callServiceEndpoint = (monitors: ServiceData['monitors'], url: string) => {
// don't need to pass locations to heartbeat
const monitorsStreams = monitors.map(({ locations, ...rest }) =>
convertToDataStreamFormat(rest)
);
return axios({
method,
url: url + (runOnce ? '/run' : '/monitors'),
data: { monitors: monitorsStreams, output, stack_version: this.kibanaVersion },
headers:
process.env.NODE_ENV !== 'production' && this.authorization
? {
Authorization: this.authorization,
}
: undefined,
httpsAgent: this.getHttpsAgent(),
});
};
const pushErrors: ServiceLocationErrors = [];
const promises: Array<Observable<unknown>> = [];
this.locations.forEach(({ id, url }) => {
const locMonitors = allMonitors.filter(
({ locations }) =>
!locations || locations.length === 0 || locations?.find((loc) => loc.id === id)
);
if (locMonitors.length > 0) {
promises.push(
rxjsFrom(callServiceEndpoint(locMonitors, url)).pipe(
tap((result) => {
this.logger.debug(result.data);
this.logger.debug(
`Successfully called service with method ${method} with ${allMonitors.length} monitors `
);
}),
catchError((err) => {
pushErrors.push({ locationId: id, error: err.response?.data });
this.logger.error(err);
if (err.response?.data?.reason) {
this.logger.error(err.response?.data?.reason);
}
// we don't want to throw an unhandled exception here
return of(true);
})
)
);
}
});
await forkJoin(promises).toPromise();
return pushErrors;
}
}