Search in sources :

Example 1 with LockService

use of org.opensearch.jobscheduler.spi.utils.LockService in project anomaly-detection by opensearch-project.

the class AnomalyDetectorJobRunner method runAnomalyDetectionJob.

private void runAnomalyDetectionJob(AnomalyDetectorJob jobParameter, LockService lockService, LockModel lock, Instant detectionStartTime, Instant executionStartTime, String detectorId, String user, List<String> roles) {
    try (InjectSecurity injectSecurity = new InjectSecurity(detectorId, settings, client.threadPool().getThreadContext())) {
        // Injecting user role to verify if the user has permissions for our API.
        injectSecurity.inject(user, roles);
        AnomalyResultRequest request = new AnomalyResultRequest(detectorId, detectionStartTime.toEpochMilli(), executionStartTime.toEpochMilli());
        client.execute(AnomalyResultAction.INSTANCE, request, ActionListener.wrap(response -> {
            indexAnomalyResult(jobParameter, lockService, lock, detectionStartTime, executionStartTime, response);
        }, exception -> {
            handleAdException(jobParameter, lockService, lock, detectionStartTime, executionStartTime, exception);
        }));
    } catch (Exception e) {
        indexAnomalyResultException(jobParameter, lockService, lock, detectionStartTime, executionStartTime, e, true);
        log.error("Failed to execute AD job " + detectorId, e);
    }
}
Also used : ResourceNotFoundException(org.opensearch.ad.common.exception.ResourceNotFoundException) ADTaskState(org.opensearch.ad.model.ADTaskState) AnomalyDetectionException(org.opensearch.ad.common.exception.AnomalyDetectionException) AnomalyDetectorFunction(org.opensearch.ad.rest.handler.AnomalyDetectorFunction) XContentParser(org.opensearch.common.xcontent.XContentParser) AD_THREAD_POOL_NAME(org.opensearch.ad.AnomalyDetectorPlugin.AD_THREAD_POOL_NAME) DiscoveryNode(org.opensearch.cluster.node.DiscoveryNode) WriteRequest(org.opensearch.action.support.WriteRequest) ADIndex(org.opensearch.ad.indices.ADIndex) ActionListener(org.opensearch.action.ActionListener) GetResponse(org.opensearch.action.get.GetResponse) Client(org.opensearch.client.Client) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) LoggingDeprecationHandler(org.opensearch.common.xcontent.LoggingDeprecationHandler) Set(java.util.Set) XContentParserUtils.ensureExpectedToken(org.opensearch.common.xcontent.XContentParserUtils.ensureExpectedToken) ADTaskManager(org.opensearch.ad.task.ADTaskManager) Settings(org.opensearch.common.settings.Settings) Instant(java.time.Instant) UPDATED(org.opensearch.action.DocWriteResponse.Result.UPDATED) List(java.util.List) AnomalyResultAction(org.opensearch.ad.transport.AnomalyResultAction) Logger(org.apache.logging.log4j.Logger) AnomalyResult(org.opensearch.ad.model.AnomalyResult) CAN_NOT_FIND_LATEST_TASK(org.opensearch.ad.constant.CommonErrorMessages.CAN_NOT_FIND_LATEST_TASK) CREATED(org.opensearch.action.DocWriteResponse.Result.CREATED) IntervalSchedule(org.opensearch.jobscheduler.spi.schedule.IntervalSchedule) XContentType(org.opensearch.common.xcontent.XContentType) InjectSecurity(org.opensearch.commons.InjectSecurity) JobExecutionContext(org.opensearch.jobscheduler.spi.JobExecutionContext) DiscoveryNodeFilterer(org.opensearch.ad.util.DiscoveryNodeFilterer) AnomalyIndexHandler(org.opensearch.ad.transport.handler.AnomalyIndexHandler) AnomalyResultRequest(org.opensearch.ad.transport.AnomalyResultRequest) ThreadPool(org.opensearch.threadpool.ThreadPool) FeatureData(org.opensearch.ad.model.FeatureData) AnomalyDetectorSettings(org.opensearch.ad.settings.AnomalyDetectorSettings) ArrayList(java.util.ArrayList) ProfileRequest(org.opensearch.ad.transport.ProfileRequest) XCONTENT_WITH_TYPE(org.opensearch.ad.util.RestHandlerUtils.XCONTENT_WITH_TYPE) HashSet(java.util.HashSet) ImmutableList(com.google.common.collect.ImmutableList) LockModel(org.opensearch.jobscheduler.spi.LockModel) ExecutorService(java.util.concurrent.ExecutorService) EndRunException(org.opensearch.ad.common.exception.EndRunException) LockService(org.opensearch.jobscheduler.spi.utils.LockService) InternalFailure(org.opensearch.ad.common.exception.InternalFailure) GetRequest(org.opensearch.action.get.GetRequest) Throwables(com.google.common.base.Throwables) IOException(java.io.IOException) AnomalyDetectionIndices(org.opensearch.ad.indices.AnomalyDetectionIndices) DetectorProfileName(org.opensearch.ad.model.DetectorProfileName) ScheduledJobParameter(org.opensearch.jobscheduler.spi.ScheduledJobParameter) AnomalyResultTransportAction(org.opensearch.ad.transport.AnomalyResultTransportAction) XContentBuilder(org.opensearch.common.xcontent.XContentBuilder) User(org.opensearch.commons.authuser.User) AnomalyResultResponse(org.opensearch.ad.transport.AnomalyResultResponse) AnomalyDetectorJob(org.opensearch.ad.model.AnomalyDetectorJob) NamedXContentRegistry(org.opensearch.common.xcontent.NamedXContentRegistry) ScheduledJobRunner(org.opensearch.jobscheduler.spi.ScheduledJobRunner) IndexRequest(org.opensearch.action.index.IndexRequest) IntervalTimeConfiguration(org.opensearch.ad.model.IntervalTimeConfiguration) LogManager(org.apache.logging.log4j.LogManager) ProfileAction(org.opensearch.ad.transport.ProfileAction) AnomalyResultRequest(org.opensearch.ad.transport.AnomalyResultRequest) InjectSecurity(org.opensearch.commons.InjectSecurity) ResourceNotFoundException(org.opensearch.ad.common.exception.ResourceNotFoundException) AnomalyDetectionException(org.opensearch.ad.common.exception.AnomalyDetectionException) EndRunException(org.opensearch.ad.common.exception.EndRunException) IOException(java.io.IOException)

Example 2 with LockService

use of org.opensearch.jobscheduler.spi.utils.LockService in project anomaly-detection by opensearch-project.

the class AnomalyDetectorJobRunner method runJob.

@Override
public void runJob(ScheduledJobParameter scheduledJobParameter, JobExecutionContext context) {
    String detectorId = scheduledJobParameter.getName();
    log.info("Start to run AD job {}", detectorId);
    adTaskManager.refreshRealtimeJobRunTime(detectorId);
    if (!(scheduledJobParameter instanceof AnomalyDetectorJob)) {
        throw new IllegalArgumentException("Job parameter is not instance of AnomalyDetectorJob, type: " + scheduledJobParameter.getClass().getCanonicalName());
    }
    AnomalyDetectorJob jobParameter = (AnomalyDetectorJob) scheduledJobParameter;
    Instant executionStartTime = Instant.now();
    IntervalSchedule schedule = (IntervalSchedule) jobParameter.getSchedule();
    Instant detectionStartTime = executionStartTime.minus(schedule.getInterval(), schedule.getUnit());
    final LockService lockService = context.getLockService();
    Runnable runnable = () -> {
        if (jobParameter.getLockDurationSeconds() != null) {
            lockService.acquireLock(jobParameter, context, ActionListener.wrap(lock -> runAdJob(jobParameter, lockService, lock, detectionStartTime, executionStartTime), exception -> {
                indexAnomalyResultException(jobParameter, lockService, null, detectionStartTime, executionStartTime, exception, false);
                throw new IllegalStateException("Failed to acquire lock for AD job: " + detectorId);
            }));
        } else {
            log.warn("Can't get lock for AD job: " + detectorId);
        }
    };
    ExecutorService executor = threadPool.executor(AD_THREAD_POOL_NAME);
    executor.submit(runnable);
}
Also used : LockService(org.opensearch.jobscheduler.spi.utils.LockService) IntervalSchedule(org.opensearch.jobscheduler.spi.schedule.IntervalSchedule) Instant(java.time.Instant) ExecutorService(java.util.concurrent.ExecutorService) AnomalyDetectorJob(org.opensearch.ad.model.AnomalyDetectorJob)

Example 3 with LockService

use of org.opensearch.jobscheduler.spi.utils.LockService in project job-scheduler by opensearch-project.

the class SampleJobRunner method runJob.

@Override
public void runJob(ScheduledJobParameter jobParameter, JobExecutionContext context) {
    if (!(jobParameter instanceof SampleJobParameter)) {
        throw new IllegalStateException("Job parameter is not instance of SampleJobParameter, type: " + jobParameter.getClass().getCanonicalName());
    }
    if (this.clusterService == null) {
        throw new IllegalStateException("ClusterService is not initialized.");
    }
    if (this.threadPool == null) {
        throw new IllegalStateException("ThreadPool is not initialized.");
    }
    final LockService lockService = context.getLockService();
    Runnable runnable = () -> {
        if (jobParameter.getLockDurationSeconds() != null) {
            lockService.acquireLock(jobParameter, context, ActionListener.wrap(lock -> {
                if (lock == null) {
                    return;
                }
                SampleJobParameter parameter = (SampleJobParameter) jobParameter;
                StringBuilder msg = new StringBuilder();
                msg.append("Watching index ").append(parameter.getIndexToWatch()).append("\n");
                List<ShardRouting> shardRoutingList = this.clusterService.state().routingTable().allShards(parameter.getIndexToWatch());
                for (ShardRouting shardRouting : shardRoutingList) {
                    msg.append(shardRouting.shardId().getId()).append("\t").append(shardRouting.currentNodeId()).append("\t").append(shardRouting.active() ? "active" : "inactive").append("\n");
                }
                log.info(msg.toString());
                runTaskForIntegrationTests(parameter);
                runTaskForLockIntegrationTests(parameter);
                lockService.release(lock, ActionListener.wrap(released -> {
                    log.info("Released lock for job {}", jobParameter.getName());
                }, exception -> {
                    throw new IllegalStateException("Failed to release lock.");
                }));
            }, exception -> {
                throw new IllegalStateException("Failed to acquire lock.");
            }));
        }
    };
    threadPool.generic().submit(runnable);
}
Also used : Client(org.opensearch.client.Client) LockService(org.opensearch.jobscheduler.spi.utils.LockService) ThreadPool(org.opensearch.threadpool.ThreadPool) UUID(java.util.UUID) ScheduledJobParameter(org.opensearch.jobscheduler.spi.ScheduledJobParameter) Plugin(org.opensearch.plugins.Plugin) ShardRouting(org.opensearch.cluster.routing.ShardRouting) List(java.util.List) Logger(org.apache.logging.log4j.Logger) ClusterService(org.opensearch.cluster.service.ClusterService) XContentType(org.opensearch.common.xcontent.XContentType) ScheduledJobRunner(org.opensearch.jobscheduler.spi.ScheduledJobRunner) JobExecutionContext(org.opensearch.jobscheduler.spi.JobExecutionContext) ActionListener(org.opensearch.action.ActionListener) IndexRequest(org.opensearch.action.index.IndexRequest) LogManager(org.apache.logging.log4j.LogManager) LockService(org.opensearch.jobscheduler.spi.utils.LockService) ShardRouting(org.opensearch.cluster.routing.ShardRouting)

Example 4 with LockService

use of org.opensearch.jobscheduler.spi.utils.LockService in project job-scheduler by opensearch-project.

the class JobSweeperTests method setup.

@Before
public void setup() throws IOException {
    this.client = Mockito.mock(Client.class);
    this.threadPool = Mockito.mock(ThreadPool.class);
    this.scheduler = Mockito.mock(JobScheduler.class);
    this.jobRunner = Mockito.mock(ScheduledJobRunner.class);
    this.jobParser = Mockito.mock(ScheduledJobParser.class);
    // NamedXContentRegistry.Entry xContentRegistryEntry = new NamedXContentRegistry.Entry(ScheduledJobParameter.class,
    // new ParseField("JOB_TYPE"), this.jobParser);
    List<NamedXContentRegistry.Entry> namedXContentRegistryEntries = new ArrayList<>();
    // namedXContentRegistryEntries.add(xContentRegistryEntry);
    this.xContentRegistry = new NamedXContentRegistry(namedXContentRegistryEntries);
    this.settings = Settings.builder().build();
    this.discoveryNode = new DiscoveryNode("node", OpenSearchTestCase.buildNewFakeTransportAddress(), Version.CURRENT);
    Set<Setting<?>> settingSet = new HashSet<>();
    settingSet.addAll(ClusterSettings.BUILT_IN_CLUSTER_SETTINGS);
    settingSet.add(JobSchedulerSettings.REQUEST_TIMEOUT);
    settingSet.add(JobSchedulerSettings.SWEEP_PERIOD);
    settingSet.add(JobSchedulerSettings.SWEEP_BACKOFF_RETRY_COUNT);
    settingSet.add(JobSchedulerSettings.SWEEP_BACKOFF_MILLIS);
    settingSet.add(JobSchedulerSettings.SWEEP_PAGE_SIZE);
    settingSet.add(JobSchedulerSettings.JITTER_LIMIT);
    ClusterSettings clusterSettings = new ClusterSettings(this.settings, settingSet);
    ClusterService originClusterService = ClusterServiceUtils.createClusterService(this.threadPool, discoveryNode, clusterSettings);
    this.clusterService = Mockito.spy(originClusterService);
    ScheduledJobProvider jobProvider = new ScheduledJobProvider("JOB_TYPE", "job-index-name", this.jobParser, this.jobRunner);
    Map<String, ScheduledJobProvider> jobProviderMap = new HashMap<>();
    jobProviderMap.put("index-name", jobProvider);
    sweeper = new JobSweeper(settings, this.client, this.clusterService, this.threadPool, xContentRegistry, jobProviderMap, scheduler, new LockService(client, clusterService));
}
Also used : JobScheduler(org.opensearch.jobscheduler.scheduler.JobScheduler) ScheduledJobParser(org.opensearch.jobscheduler.spi.ScheduledJobParser) DiscoveryNode(org.opensearch.cluster.node.DiscoveryNode) ClusterSettings(org.opensearch.common.settings.ClusterSettings) LockService(org.opensearch.jobscheduler.spi.utils.LockService) HashMap(java.util.HashMap) Setting(org.opensearch.common.settings.Setting) ThreadPool(org.opensearch.threadpool.ThreadPool) ArrayList(java.util.ArrayList) ScheduledJobRunner(org.opensearch.jobscheduler.spi.ScheduledJobRunner) ClusterService(org.opensearch.cluster.service.ClusterService) ScheduledJobProvider(org.opensearch.jobscheduler.ScheduledJobProvider) Client(org.opensearch.client.Client) NamedXContentRegistry(org.opensearch.common.xcontent.NamedXContentRegistry) HashSet(java.util.HashSet) Before(org.junit.Before)

Example 5 with LockService

use of org.opensearch.jobscheduler.spi.utils.LockService in project job-scheduler by opensearch-project.

the class JobSchedulerPlugin method createComponents.

@Override
public Collection<Object> createComponents(Client client, ClusterService clusterService, ThreadPool threadPool, ResourceWatcherService resourceWatcherService, ScriptService scriptService, NamedXContentRegistry xContentRegistry, Environment environment, NodeEnvironment nodeEnvironment, NamedWriteableRegistry namedWriteableRegistry, IndexNameExpressionResolver indexNameExpressionResolver, Supplier<RepositoriesService> repositoriesServiceSupplier) {
    this.lockService = new LockService(client, clusterService);
    this.scheduler = new JobScheduler(threadPool, this.lockService);
    this.sweeper = initSweeper(environment.settings(), client, clusterService, threadPool, xContentRegistry, this.scheduler, this.lockService);
    clusterService.addListener(this.sweeper);
    clusterService.addLifecycleListener(this.sweeper);
    return Collections.emptyList();
}
Also used : JobScheduler(org.opensearch.jobscheduler.scheduler.JobScheduler) LockService(org.opensearch.jobscheduler.spi.utils.LockService)

Aggregations

LockService (org.opensearch.jobscheduler.spi.utils.LockService)6 ActionListener (org.opensearch.action.ActionListener)3 IndexRequest (org.opensearch.action.index.IndexRequest)3 AnomalyDetectorJob (org.opensearch.ad.model.AnomalyDetectorJob)3 Client (org.opensearch.client.Client)3 ScheduledJobRunner (org.opensearch.jobscheduler.spi.ScheduledJobRunner)3 ThreadPool (org.opensearch.threadpool.ThreadPool)3 Instant (java.time.Instant)2 ArrayList (java.util.ArrayList)2 HashSet (java.util.HashSet)2 List (java.util.List)2 ExecutorService (java.util.concurrent.ExecutorService)2 LogManager (org.apache.logging.log4j.LogManager)2 Logger (org.apache.logging.log4j.Logger)2 Before (org.junit.Before)2 GetRequest (org.opensearch.action.get.GetRequest)2 GetResponse (org.opensearch.action.get.GetResponse)2 DiscoveryNode (org.opensearch.cluster.node.DiscoveryNode)2 ClusterService (org.opensearch.cluster.service.ClusterService)2 NamedXContentRegistry (org.opensearch.common.xcontent.NamedXContentRegistry)2