Compare commits

...

10 Commits

Author SHA1 Message Date
9e25494f8f 1.0.47 2023-08-01 15:05:46 +02:00
dd8ba4736a fix(core): update 2023-08-01 15:05:45 +02:00
d395310410 1.0.46 2023-08-01 12:38:54 +02:00
49233ce45f fix(core): update 2023-08-01 12:38:53 +02:00
fb93dce8bc 1.0.45 2023-08-01 12:24:22 +02:00
30cbc05aa2 fix(core): update 2023-08-01 12:24:22 +02:00
2a595a1a9a 1.0.44 2023-07-05 23:45:48 +02:00
d62b18e93c fix(core): update 2023-07-05 23:45:48 +02:00
d6176f820a 1.0.43 2023-07-05 17:27:24 +02:00
0ebc1d5288 fix(core): update 2023-07-05 17:27:24 +02:00
9 changed files with 195 additions and 33 deletions

View File

@ -1,6 +1,6 @@
{
"name": "@apiclient.xyz/elasticsearch",
"version": "1.0.42",
"version": "1.0.47",
"private": false,
"description": "log to elasticsearch in a kibana compatible format",
"main": "dist_ts/index.js",

0
test/00tapwrap.ts Normal file
View File

View File

@ -2,17 +2,20 @@ import { expect, tap } from '@pushrocks/tapbundle';
import { Qenv } from '@pushrocks/qenv';
import * as elasticsearch from '../ts/index.js';
let testElasticLog: elasticsearch.ElasticSearch<any>;
let testElasticLog: elasticsearch.ElsSmartlogDestination<any>;
let testElasticDoc: elasticsearch.ElasticDoc;
tap.test('first test', async () => {
testElasticLog = new elasticsearch.ElasticSearch({
testElasticLog = new elasticsearch.ElsSmartlogDestination({
indexPrefix: 'testprefix',
indexRetention: 7,
node: 'http://localhost:9200',
user: 'elastic',
pass: 'YourPassword'
auth: {
username: 'elastic',
password: 'YourPassword'
}
});
expect(testElasticLog).toBeInstanceOf(elasticsearch.ElasticSearch);
expect(testElasticLog).toBeInstanceOf(elasticsearch.ElsSmartlogDestination);
});
tap.test('should send a message to Elasticsearch', async () => {
@ -33,4 +36,27 @@ tap.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();

View File

@ -3,6 +3,6 @@
*/
export const commitinfo = {
name: '@apiclient.xyz/elasticsearch',
version: '1.0.42',
version: '1.0.47',
description: 'log to elasticsearch in a kibana compatible format'
}

View File

@ -1,21 +1,21 @@
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(prefixArg: string, indexNameArg: string) {
if (this.stringmap.checkString(indexNameArg)) {
return;
return indexNameArg;
}
const responseArg = await this.elasticSearchRef.client.cat.indices({
format: 'json',
bytes: 'm',
@ -27,7 +27,6 @@ export class ElasticIndex {
throw new Error('Could not get valid response from elastic search');
}
// lets delete indexes that violate the retention
if (Array.isArray(responseArg.body)) {
const filteredIndices = responseArg.body.filter((indexObjectArg) => {
return indexObjectArg.index.startsWith(prefixArg);
@ -49,6 +48,7 @@ export class ElasticIndex {
if (!index) {
await this.createNewIndex(indexNameArg);
}
this.stringmap.addString(indexNameArg);
return index;
}
@ -57,6 +57,23 @@ export class ElasticIndex {
const response = await this.elasticSearchRef.client.indices.create({
wait_for_active_shards: '1',
index: indexNameArg,
body: {
mappings: {
properties: {
'@timestamp': {
type: 'date',
},
logPackageArg: {
properties: {
payload: {
type: 'object',
dynamic: true
}
}
},
},
},
},
});
}

View File

@ -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;

View 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();
}
}

View File

@ -15,11 +15,13 @@ export interface IElasticSearchConstructorOptions {
indexPrefix: string;
indexRetention: number;
node: string;
user?: string;
pass?: 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);
@ -34,12 +36,9 @@ export class ElasticSearch<T> {
constructor(optionsArg: IElasticSearchConstructorOptions) {
this.client = new ElasticClient({
node: optionsArg.node,
auth: {
username: optionsArg.user,
password: optionsArg.pass,
}
...(optionsArg.auth && { auth: optionsArg.auth }),
});
this.indexPrefix = optionsArg.indexPrefix;
this.indexPrefix = `${optionsArg.indexPrefix}`;
this.indexRetention = optionsArg.indexRetention;
}
@ -52,8 +51,31 @@ export class ElasticSearch<T> {
return;
}
const response = await this.elasticIndex.ensureIndex(this.indexPrefix, indexToUse);
console.log(response);
// 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,

View File

@ -1 +1,2 @@
export * from './elasticsearch.classes.elasticsearch.js';
export * from './els.classes.smartlogdestination.js';
export * from './els.classes.elasticdoc.js';