mirror of
https://github.com/elastic/kibana.git
synced 2025-06-27 18:51:07 -04:00
Fixes https://github.com/elastic/kibana/issues/151938 In this PR, I'm re-writing the Task Manager poller so it doesn't run concurrently when timeouts occur while also fixing the issue where polling requests would pile up when polling takes time. To support this, I've also made the following changes: - Removed the observable monitor and the `xpack.task_manager.max_poll_inactivity_cycles` setting - Make the task store `search` and `updateByQuery` functions have no retries. This prevents the request from retrying 5x whenever a timeout occurs, causing each call taking up to 2 1/2 minutes before Kibana sees the error (now down to 30s each). We have polling to manage retries in these situations. - Switch the task poller tests to use `sinon` for faking timers - Removing the `assertStillInSetup` checks on plugin setup. Felt like a maintenance burden that wasn't necessary to fix with my code changes. The main code changes are within these files (to review thoroughly so the polling cycle doesn't suddenly stop): - x-pack/plugins/task_manager/server/polling/task_poller.ts - x-pack/plugins/task_manager/server/polling_lifecycle.ts (easier to review if you disregard whitespace `?w=1`) ## To verify 1. Tasks run normally (create a rule or something that goes through task manager regularly). 2. When the update by query takes a while, the request is cancelled after 30s or the time manually configured. 4. When the search for claimed tasks query takes a while, the request is cancelled after 30s or the time manually configured. **Tips:** <details><summary>how to slowdown search for claimed task queries</summary> ``` diff --git a/x-pack/plugins/task_manager/server/queries/task_claiming.ts b/x-pack/plugins/task_manager/server/queries/task_claiming.ts index 07042650a37..2caefd63672 100644 --- a/x-pack/plugins/task_manager/server/queries/task_claiming.ts +++ b/x-pack/plugins/task_manager/server/queries/task_claiming.ts @@ -247,7 +247,7 @@ export class TaskClaiming { taskTypes, }); - const docs = tasksUpdated > 0 ? await this.sweepForClaimedTasks(taskTypes, size) : []; + const docs = await this.sweepForClaimedTasks(taskTypes, size); this.emitEvents(docs.map((doc) => asTaskClaimEvent(doc.id, asOk(doc)))); @@ -346,6 +346,13 @@ export class TaskClaiming { size, sort: SortByRunAtAndRetryAt, seq_no_primary_term: true, + aggs: { + delay: { + shard_delay: { + value: '40s', + }, + }, + }, }); return docs; ``` </details> <details><summary>how to slow down update by queries</summary> Not the cleanest way but you'll see occasional request timeouts from the updateByQuery calls. I had more luck creating rules running every 1s. ``` diff --git a/x-pack/plugins/task_manager/server/task_store.ts b/x-pack/plugins/task_manager/server/task_store.ts index a06ee7b918a..07aa81e5388 100644 --- a/x-pack/plugins/task_manager/server/task_store.ts +++ b/x-pack/plugins/task_manager/server/task_store.ts @@ -126,6 +126,7 @@ export class TaskStore { // Timeouts are retried and make requests timeout after (requestTimeout * (1 + maxRetries)) // The poller doesn't need retry logic because it will try again at the next polling cycle maxRetries: 0, + requestTimeout: 900, }); } @@ -458,6 +459,7 @@ export class TaskStore { ignore_unavailable: true, refresh: true, conflicts: 'proceed', + requests_per_second: 1, body: { ...opts, max_docs, ``` </details> --------- Co-authored-by: Kibana Machine <42973632+kibanamachine@users.noreply.github.com>
137 lines
4 KiB
TypeScript
137 lines
4 KiB
TypeScript
/*
|
|
* 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.
|
|
*/
|
|
|
|
/*
|
|
* This module contains the logic for polling the task manager index for new work.
|
|
*/
|
|
|
|
import { Observable, Subject } from 'rxjs';
|
|
|
|
import { Option, none } from 'fp-ts/lib/Option';
|
|
import { Logger } from '@kbn/core/server';
|
|
import { Result, asOk, asErr } from '../lib/result_type';
|
|
|
|
type WorkFn<H> = () => Promise<H>;
|
|
|
|
interface Opts<H> {
|
|
logger: Logger;
|
|
initialPollInterval: number;
|
|
pollInterval$: Observable<number>;
|
|
pollIntervalDelay$: Observable<number>;
|
|
getCapacity: () => number;
|
|
work: WorkFn<H>;
|
|
}
|
|
|
|
/**
|
|
* constructs a new TaskPoller stream, which emits events on demand and on a scheduled interval, waiting for capacity to be available before emitting more events.
|
|
*
|
|
* @param opts
|
|
* @prop {number} pollInterval - How often, in milliseconds, we will an event be emnitted, assuming there's capacity to do so
|
|
* @prop {() => number} getCapacity - A function specifying whether there is capacity to emit new events
|
|
* @prop {() => Promise<H>} work - The worker we wish to execute in order to `poll`
|
|
*
|
|
* @returns {Observable<Set<T>>} - An observable which emits an event whenever a polling event is due to take place, providing access to a singleton Set representing a queue
|
|
* of unique request argumets of type T.
|
|
*/
|
|
export function createTaskPoller<T, H>({
|
|
logger,
|
|
initialPollInterval,
|
|
pollInterval$,
|
|
pollIntervalDelay$,
|
|
getCapacity,
|
|
work,
|
|
}: Opts<H>): {
|
|
start: () => void;
|
|
stop: () => void;
|
|
events$: Observable<Result<H, PollingError<T>>>;
|
|
} {
|
|
const hasCapacity = () => getCapacity() > 0;
|
|
let running: boolean = false;
|
|
let timeoutId: NodeJS.Timeout | null = null;
|
|
let hasSubscribed: boolean = false;
|
|
let pollInterval = initialPollInterval;
|
|
let pollIntervalDelay = 0;
|
|
const subject = new Subject<Result<H, PollingError<T>>>();
|
|
|
|
async function runCycle() {
|
|
timeoutId = null;
|
|
const start = Date.now();
|
|
if (hasCapacity()) {
|
|
try {
|
|
const result = await work();
|
|
subject.next(asOk(result));
|
|
} catch (e) {
|
|
subject.next(asPollingError<T>(e, PollingErrorType.WorkError));
|
|
}
|
|
}
|
|
if (running) {
|
|
// Set the next runCycle call
|
|
timeoutId = setTimeout(
|
|
runCycle,
|
|
Math.max(pollInterval - (Date.now() - start) + (pollIntervalDelay % pollInterval), 0)
|
|
);
|
|
// Reset delay, it's designed to shuffle only once
|
|
pollIntervalDelay = 0;
|
|
}
|
|
}
|
|
|
|
function subscribe() {
|
|
if (hasSubscribed) {
|
|
return;
|
|
}
|
|
pollInterval$.subscribe((interval) => {
|
|
pollInterval = interval;
|
|
logger.debug(`Task poller now using interval of ${interval}ms`);
|
|
});
|
|
pollIntervalDelay$.subscribe((delay) => {
|
|
pollIntervalDelay = delay;
|
|
logger.debug(`Task poller now delaying emission by ${delay}ms`);
|
|
});
|
|
hasSubscribed = true;
|
|
}
|
|
|
|
return {
|
|
events$: subject,
|
|
start: () => {
|
|
if (!running) {
|
|
running = true;
|
|
runCycle();
|
|
// We need to subscribe shortly after start. Otherwise, the observables start emiting events
|
|
// too soon for the task run statistics module to capture.
|
|
setTimeout(() => subscribe(), 0);
|
|
}
|
|
},
|
|
stop: () => {
|
|
if (timeoutId) {
|
|
clearTimeout(timeoutId);
|
|
timeoutId = null;
|
|
}
|
|
running = false;
|
|
},
|
|
};
|
|
}
|
|
|
|
export enum PollingErrorType {
|
|
WorkError,
|
|
WorkTimeout,
|
|
RequestCapacityReached,
|
|
}
|
|
|
|
function asPollingError<T>(err: string | Error, type: PollingErrorType, data: Option<T> = none) {
|
|
return asErr(new PollingError<T>(`Failed to poll for work: ${err}`, type, data));
|
|
}
|
|
|
|
export class PollingError<T> extends Error {
|
|
public readonly type: PollingErrorType;
|
|
public readonly data: Option<T>;
|
|
constructor(message: string, type: PollingErrorType, data: Option<T>) {
|
|
super(message);
|
|
Object.setPrototypeOf(this, new.target.prototype);
|
|
this.type = type;
|
|
this.data = data;
|
|
}
|
|
}
|