Compare commits
14 Commits
Author | SHA1 | Date | |
---|---|---|---|
d395310410 | |||
49233ce45f | |||
fb93dce8bc | |||
30cbc05aa2 | |||
2a595a1a9a | |||
d62b18e93c | |||
d6176f820a | |||
0ebc1d5288 | |||
2b0003546a | |||
60617f2fca | |||
9c767d07e4 | |||
f3aa94dcb7 | |||
a0be0edd9d | |||
ad24ba2f5d |
@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@apiclient.xyz/elasticsearch",
|
||||
"version": "1.0.39",
|
||||
"version": "1.0.46",
|
||||
"private": false,
|
||||
"description": "log to elasticsearch in a kibana compatible format",
|
||||
"main": "dist_ts/index.js",
|
||||
|
0
test/00tapwrap.ts
Normal file
0
test/00tapwrap.ts
Normal file
@ -2,23 +2,24 @@ import { expect, tap } from '@pushrocks/tapbundle';
|
||||
import { Qenv } from '@pushrocks/qenv';
|
||||
import * as elasticsearch from '../ts/index.js';
|
||||
|
||||
const testQenv = new Qenv('./', './.nogit/');
|
||||
|
||||
let testElasticLog: elasticsearch.ElasticSearch<any>;
|
||||
let testElasticLog: elasticsearch.ElsSmartlogDestination<any>;
|
||||
let testElasticDoc: elasticsearch.ElasticDoc;
|
||||
|
||||
tap.test('first test', async () => {
|
||||
testElasticLog = new elasticsearch.ElasticSearch({
|
||||
indexPrefix: 'smartlog',
|
||||
testElasticLog = new elasticsearch.ElsSmartlogDestination({
|
||||
indexPrefix: 'testprefix',
|
||||
indexRetention: 7,
|
||||
domain: testQenv.getEnvVarOnDemand('ELK_DOMAIN'),
|
||||
port: parseInt(testQenv.getEnvVarOnDemand('ELK_PORT'), 10),
|
||||
ssl: true,
|
||||
node: 'http://localhost:9200',
|
||||
auth: {
|
||||
username: 'elastic',
|
||||
password: 'YourPassword'
|
||||
}
|
||||
});
|
||||
expect(testElasticLog).toBeInstanceOf(elasticsearch.ElasticSearch);
|
||||
expect(testElasticLog).toBeInstanceOf(elasticsearch.ElsSmartlogDestination);
|
||||
});
|
||||
|
||||
tap.skip.test('should send a message to Elasticsearch', async () => {
|
||||
testElasticLog.log({
|
||||
tap.test('should send a message to Elasticsearch', async () => {
|
||||
await testElasticLog.log({
|
||||
timestamp: Date.now(),
|
||||
type: 'increment',
|
||||
level: 'info',
|
||||
@ -35,4 +36,27 @@ tap.skip.test('should send a message to Elasticsearch', async () => {
|
||||
});
|
||||
});
|
||||
|
||||
tap.test('should create an ElasticDoc instance', async () => {
|
||||
testElasticDoc = new elasticsearch.ElasticDoc({
|
||||
index: 'testindex',
|
||||
node: 'http://localhost:9200',
|
||||
auth: {
|
||||
username: 'elastic',
|
||||
password: 'YourPassword'
|
||||
}
|
||||
});
|
||||
expect(testElasticDoc).toBeInstanceOf(elasticsearch.ElasticDoc);
|
||||
});
|
||||
|
||||
tap.test('should add and update documents in a piping session', async () => {
|
||||
await testElasticDoc.startPipingSession();
|
||||
await testElasticDoc.pipeDocument('1', { name: 'doc1' });
|
||||
await testElasticDoc.pipeDocument('2', { name: 'doc2' });
|
||||
await testElasticDoc.pipeDocument('1', { name: 'updated doc1' });
|
||||
});
|
||||
|
||||
tap.test('should delete documents not part of the piping session', async () => {
|
||||
await testElasticDoc.endPipingSession();
|
||||
});
|
||||
|
||||
tap.start();
|
||||
|
@ -3,6 +3,6 @@
|
||||
*/
|
||||
export const commitinfo = {
|
||||
name: '@apiclient.xyz/elasticsearch',
|
||||
version: '1.0.39',
|
||||
version: '1.0.46',
|
||||
description: 'log to elasticsearch in a kibana compatible format'
|
||||
}
|
||||
|
@ -1,102 +1,102 @@
|
||||
import * as plugins from './elasticsearch.plugins.js';
|
||||
import { ElasticSearch } from './elasticsearch.classes.elasticsearch.js';
|
||||
import { ElsSmartlogDestination } from './els.classes.smartlogdestination.js';
|
||||
import { type ILogPackage } from '@pushrocks/smartlog-interfaces';
|
||||
|
||||
import { Stringmap } from '@pushrocks/lik';
|
||||
|
||||
export class ElasticIndex {
|
||||
private stringmap = new Stringmap();
|
||||
private elasticSearchRef: ElasticSearch<any>;
|
||||
private elasticSearchRef: ElsSmartlogDestination<any>;
|
||||
|
||||
constructor(elasticSearchInstanceArg: ElasticSearch<ILogPackage>) {
|
||||
constructor(elasticSearchInstanceArg: ElsSmartlogDestination<ILogPackage>) {
|
||||
this.elasticSearchRef = elasticSearchInstanceArg;
|
||||
}
|
||||
|
||||
public async ensureIndex(indexArg: string) {
|
||||
const done = plugins.smartpromise.defer();
|
||||
if (this.stringmap.checkString(indexArg)) {
|
||||
done.resolve();
|
||||
return;
|
||||
}
|
||||
this.elasticSearchRef.client.cat.indices(
|
||||
{
|
||||
format: 'json',
|
||||
bytes: 'm',
|
||||
},
|
||||
async (err, responseArg: any[]) => {
|
||||
if (err) {
|
||||
console.log(err);
|
||||
return;
|
||||
public async ensureIndex(prefixArg: string, indexNameArg: string) {
|
||||
if (this.stringmap.checkString(indexNameArg)) {
|
||||
return indexNameArg;
|
||||
}
|
||||
|
||||
// lets delete indexes that violate the retention
|
||||
if (Array.isArray(responseArg)) {
|
||||
const filteredIndices = responseArg.filter((indexObjectArg) => {
|
||||
return indexObjectArg.index.startsWith('smartlog');
|
||||
const responseArg = await this.elasticSearchRef.client.cat.indices({
|
||||
format: 'json',
|
||||
bytes: 'm',
|
||||
}).catch(err => {
|
||||
console.log(err);
|
||||
});
|
||||
|
||||
if (!responseArg) {
|
||||
throw new Error('Could not get valid response from elastic search');
|
||||
}
|
||||
|
||||
if (Array.isArray(responseArg.body)) {
|
||||
const filteredIndices = responseArg.body.filter((indexObjectArg) => {
|
||||
return indexObjectArg.index.startsWith(prefixArg);
|
||||
});
|
||||
const filteredIndexNames = filteredIndices.map((indexObjectArg) => {
|
||||
return indexObjectArg.index;
|
||||
});
|
||||
this.deleteOldIndices(filteredIndexNames);
|
||||
await this.deleteOldIndices(prefixArg, filteredIndexNames);
|
||||
}
|
||||
|
||||
let index = null;
|
||||
|
||||
if (Array.isArray(responseArg)) {
|
||||
index = responseArg.find((indexObject) => {
|
||||
return indexObject.index === indexArg;
|
||||
if (Array.isArray(responseArg.body)) {
|
||||
index = responseArg.body.find((indexItemArg) => {
|
||||
return indexItemArg.index === indexNameArg;
|
||||
});
|
||||
}
|
||||
|
||||
if (!index) {
|
||||
const done2 = plugins.smartpromise.defer();
|
||||
this.elasticSearchRef.client.indices.create(
|
||||
{
|
||||
waitForActiveShards: '1',
|
||||
index: indexArg,
|
||||
await this.createNewIndex(indexNameArg);
|
||||
}
|
||||
|
||||
this.stringmap.addString(indexNameArg);
|
||||
return index;
|
||||
}
|
||||
|
||||
public async createNewIndex(indexNameArg: string) {
|
||||
const response = await this.elasticSearchRef.client.indices.create({
|
||||
wait_for_active_shards: '1',
|
||||
index: indexNameArg,
|
||||
body: {
|
||||
mappings: {
|
||||
properties: {
|
||||
'@timestamp': {
|
||||
type: 'date',
|
||||
},
|
||||
(error, response) => {
|
||||
// console.lof(response)
|
||||
done2.resolve();
|
||||
logPackageArg: {
|
||||
properties: {
|
||||
payload: {
|
||||
type: 'object',
|
||||
dynamic: true
|
||||
}
|
||||
);
|
||||
await done2.promise;
|
||||
}
|
||||
this.stringmap.addString(indexArg);
|
||||
done.resolve();
|
||||
}
|
||||
);
|
||||
await done.promise;
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
public createNewIndex(indexNameArg: string) {}
|
||||
|
||||
public async deleteOldIndices(indicesArray: string[]) {
|
||||
public async deleteOldIndices(prefixArg: string, indicesArray: string[]) {
|
||||
const todayAsUnix: number = Date.now();
|
||||
const rententionPeriodAsUnix: number = plugins.smarttime.units.days(
|
||||
this.elasticSearchRef.indexRetention
|
||||
);
|
||||
for (const indexName of indicesArray) {
|
||||
const regexResult = /^smartlog-([0-9]*)\.([0-9]*)\.([0-9]*)$/.exec(indexName);
|
||||
if (!indexName.startsWith(prefixArg)) continue;
|
||||
const indexRegex = new RegExp(`^${prefixArg}-([0-9]*)-([0-9]*)-([0-9]*)$`)
|
||||
const regexResult = indexRegex.exec(indexName);
|
||||
const dateAsUnix: number = new Date(
|
||||
`${regexResult[1]}-${regexResult[2]}-${regexResult[3]}`
|
||||
).getTime();
|
||||
if (todayAsUnix - rententionPeriodAsUnix > dateAsUnix) {
|
||||
console.log(`found old index ${indexName}`);
|
||||
const done2 = plugins.smartpromise.defer();
|
||||
this.elasticSearchRef.client.indices.delete(
|
||||
const response = await this.elasticSearchRef.client.indices.delete(
|
||||
{
|
||||
index: indexName,
|
||||
},
|
||||
(err2, response2) => {
|
||||
if (err2) {
|
||||
console.log(err2);
|
||||
}
|
||||
console.log(`deleted ${indexName}`);
|
||||
done2.resolve();
|
||||
}
|
||||
);
|
||||
await done2.promise;
|
||||
}).catch(err => {
|
||||
console.log(err);
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -1,29 +1,48 @@
|
||||
import { ElasticSearch, type IStandardLogParams } from './elasticsearch.classes.elasticsearch.js';
|
||||
import { ElsSmartlogDestination, type IStandardLogParams } from './els.classes.smartlogdestination.js';
|
||||
|
||||
export class ElasticScheduler {
|
||||
elasticSearchRef: ElasticSearch<any>;
|
||||
elasticSearchRef: ElsSmartlogDestination<any>;
|
||||
docsScheduled = false;
|
||||
docsStorage: any[] = [];
|
||||
|
||||
constructor(elasticLogRefArg: ElasticSearch<any>) {
|
||||
// maximum size of the buffer
|
||||
maxBufferSize = 500;
|
||||
|
||||
constructor(elasticLogRefArg: ElsSmartlogDestination<any>) {
|
||||
this.elasticSearchRef = elasticLogRefArg;
|
||||
}
|
||||
|
||||
public addFailedDoc(objectArg: any | IStandardLogParams) {
|
||||
this.docsStorage.push(objectArg);
|
||||
this.addToStorage(objectArg);
|
||||
this.setRetry();
|
||||
}
|
||||
|
||||
public scheduleDoc(logObject: any) {
|
||||
this.addToStorage(logObject);
|
||||
}
|
||||
|
||||
private addToStorage(logObject: any) {
|
||||
this.docsStorage.push(logObject);
|
||||
|
||||
// if buffer is full, send logs immediately
|
||||
if (this.docsStorage.length >= this.maxBufferSize) {
|
||||
this.flushLogsToElasticSearch();
|
||||
}
|
||||
}
|
||||
|
||||
private flushLogsToElasticSearch() {
|
||||
const oldStorage = this.docsStorage;
|
||||
this.docsStorage = [];
|
||||
|
||||
for (let logObject of oldStorage) {
|
||||
this.elasticSearchRef.log(logObject, true);
|
||||
}
|
||||
}
|
||||
|
||||
public setRetry() {
|
||||
setTimeout(() => {
|
||||
const oldStorage = this.docsStorage;
|
||||
this.docsStorage = [];
|
||||
for (let logObject of oldStorage) {
|
||||
this.elasticSearchRef.log(logObject, true);
|
||||
}
|
||||
this.flushLogsToElasticSearch();
|
||||
|
||||
if (this.docsStorage.length === 0) {
|
||||
console.log('ElasticLog retry success!!!');
|
||||
this.docsScheduled = false;
|
||||
|
77
ts/els.classes.elasticdoc.ts
Normal file
77
ts/els.classes.elasticdoc.ts
Normal file
@ -0,0 +1,77 @@
|
||||
import { Client as ElasticClient } from '@elastic/elasticsearch';
|
||||
|
||||
export interface IElasticDocConstructorOptions {
|
||||
index: string;
|
||||
node: string;
|
||||
auth?: {
|
||||
username: string;
|
||||
password: string;
|
||||
};
|
||||
}
|
||||
|
||||
export class ElasticDoc {
|
||||
public client: ElasticClient;
|
||||
public index: string;
|
||||
private sessionDocs: Set<string> = new Set();
|
||||
|
||||
private BATCH_SIZE = 1000;
|
||||
|
||||
constructor(options: IElasticDocConstructorOptions) {
|
||||
this.client = new ElasticClient({
|
||||
node: options.node,
|
||||
...(options.auth && { auth: options.auth }),
|
||||
});
|
||||
this.index = options.index;
|
||||
}
|
||||
|
||||
async startPipingSession() {
|
||||
// Clear the session docs set
|
||||
this.sessionDocs.clear();
|
||||
}
|
||||
|
||||
async pipeDocument(docId: string, doc: any) {
|
||||
await this.client.index({
|
||||
index: this.index,
|
||||
id: docId,
|
||||
body: doc,
|
||||
});
|
||||
this.sessionDocs.add(docId);
|
||||
}
|
||||
|
||||
async endPipingSession() {
|
||||
const allDocIds: string[] = [];
|
||||
const responseQueue = [];
|
||||
let response = await this.client.search({ index: this.index, scroll: '1m', size: this.BATCH_SIZE });
|
||||
while (true) {
|
||||
response.body.hits.hits.forEach((hit: any) => allDocIds.push(hit._id));
|
||||
if (!response.body.hits.hits.length) {
|
||||
break;
|
||||
}
|
||||
response = await this.client.scroll({ scroll_id: response.body._scroll_id, scroll: '1m' });
|
||||
}
|
||||
|
||||
// Batch delete docs
|
||||
for (const docId of allDocIds) {
|
||||
if (!this.sessionDocs.has(docId)) {
|
||||
responseQueue.push({
|
||||
delete: {
|
||||
_index: this.index,
|
||||
_id: docId,
|
||||
},
|
||||
});
|
||||
|
||||
if (responseQueue.length >= this.BATCH_SIZE) {
|
||||
await this.client.bulk({ refresh: true, body: responseQueue });
|
||||
responseQueue.length = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (responseQueue.length > 0) {
|
||||
await this.client.bulk({ refresh: true, body: responseQueue });
|
||||
}
|
||||
|
||||
// Clear the session docs set
|
||||
this.sessionDocs.clear();
|
||||
}
|
||||
}
|
@ -14,14 +14,14 @@ export interface IStandardLogParams {
|
||||
export interface IElasticSearchConstructorOptions {
|
||||
indexPrefix: string;
|
||||
indexRetention: number;
|
||||
port: number;
|
||||
domain: string;
|
||||
ssl: boolean;
|
||||
user?: string;
|
||||
pass?: string;
|
||||
node: string;
|
||||
auth?: {
|
||||
username: string;
|
||||
password: string;
|
||||
};
|
||||
}
|
||||
|
||||
export class ElasticSearch<T> {
|
||||
export class ElsSmartlogDestination<T> {
|
||||
public client: ElasticClient;
|
||||
public elasticScheduler = new ElasticScheduler(this);
|
||||
public elasticIndex: ElasticIndex = new ElasticIndex(this);
|
||||
@ -35,49 +35,50 @@ export class ElasticSearch<T> {
|
||||
*/
|
||||
constructor(optionsArg: IElasticSearchConstructorOptions) {
|
||||
this.client = new ElasticClient({
|
||||
node: this.computeHostString(optionsArg),
|
||||
// log: 'trace'
|
||||
node: optionsArg.node,
|
||||
...(optionsArg.auth && { auth: optionsArg.auth }),
|
||||
});
|
||||
this.indexPrefix = optionsArg.indexPrefix;
|
||||
this.indexPrefix = `${optionsArg.indexPrefix}`;
|
||||
this.indexRetention = optionsArg.indexRetention;
|
||||
}
|
||||
|
||||
/**
|
||||
* computes the host string from the constructor options
|
||||
* @param optionsArg
|
||||
*/
|
||||
private computeHostString(optionsArg: IElasticSearchConstructorOptions): string {
|
||||
let hostString = `${optionsArg.domain}:${optionsArg.port}`;
|
||||
if (optionsArg.user && optionsArg.pass) {
|
||||
hostString = `${optionsArg.user}:${optionsArg.pass}@${hostString}`;
|
||||
}
|
||||
if (optionsArg.ssl) {
|
||||
hostString = `https://${hostString}`;
|
||||
} else {
|
||||
hostString = `http://${hostString}`;
|
||||
}
|
||||
console.log(hostString);
|
||||
return hostString;
|
||||
}
|
||||
|
||||
public async log(logPackageArg: ILogPackage, scheduleOverwrite = false) {
|
||||
const now = new Date();
|
||||
const indexToUse = `${this.indexPrefix}-${now.getFullYear()}.${(
|
||||
'0' +
|
||||
(now.getMonth() + 1)
|
||||
).slice(-2)}.${('0' + now.getDate()).slice(-2)}`;
|
||||
const indexToUse = `${this.indexPrefix}-${now.toISOString().split('T')[0]}`;
|
||||
|
||||
if (this.elasticScheduler.docsScheduled && !scheduleOverwrite) {
|
||||
this.elasticScheduler.scheduleDoc(logPackageArg);
|
||||
return;
|
||||
}
|
||||
|
||||
await this.elasticIndex.ensureIndex(indexToUse);
|
||||
// Make sure the index is created with a mapping for dynamic JSON
|
||||
const indexExists = await this.client.indices.exists({ index: indexToUse });
|
||||
if (!indexExists.body) {
|
||||
await this.client.indices.create({
|
||||
index: indexToUse,
|
||||
body: {
|
||||
mappings: {
|
||||
properties: {
|
||||
'@timestamp': {
|
||||
type: 'date',
|
||||
},
|
||||
logPackageArg: {
|
||||
properties: {
|
||||
payload: {
|
||||
type: 'object',
|
||||
dynamic: true
|
||||
}
|
||||
}
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
this.client.index(
|
||||
{
|
||||
index: indexToUse,
|
||||
type: 'log',
|
||||
body: {
|
||||
'@timestamp': new Date(logPackageArg.timestamp).toISOString(),
|
||||
...logPackageArg,
|
@ -1 +1,2 @@
|
||||
export * from './elasticsearch.classes.elasticsearch.js';
|
||||
export * from './els.classes.smartlogdestination.js';
|
||||
export * from './els.classes.elasticdoc.js';
|
Reference in New Issue
Block a user