<commit_before>/*
 * Copyright 2014 Netflix, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License")
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.netflix.spinnaker.orca.batch.adapters

import com.netflix.spectator.api.ExtendedRegistry
import com.netflix.spectator.api.Id
import com.netflix.spinnaker.orca.*
import com.netflix.spinnaker.orca.batch.BatchStepStatus
import com.netflix.spinnaker.orca.batch.ExecutionContextManager
import com.netflix.spinnaker.orca.batch.exceptions.ExceptionHandler
import com.netflix.spinnaker.orca.pipeline.model.Execution
import com.netflix.spinnaker.orca.pipeline.model.OrchestrationStage
import com.netflix.spinnaker.orca.pipeline.model.PipelineStage
import com.netflix.spinnaker.orca.pipeline.model.Stage
import com.netflix.spinnaker.orca.pipeline.model.Task as TaskModel
import com.netflix.spinnaker.orca.pipeline.persistence.ExecutionRepository
import com.netflix.spinnaker.security.AuthenticatedRequest
import com.netflix.spinnaker.security.User
import groovy.transform.CompileStatic
import groovy.util.logging.Slf4j
import org.slf4j.LoggerFactory
import org.springframework.batch.core.ExitStatus
import org.springframework.batch.core.StepContribution
import org.springframework.batch.core.scope.context.ChunkContext
import org.springframework.batch.core.step.tasklet.Tasklet
import org.springframework.batch.repeat.RepeatStatus

@Slf4j
@CompileStatic
class TaskTasklet implements Tasklet {
  private static final String METRIC_NAME = "task.invocations"

  private final Task task
  private final ExecutionRepository executionRepository
  private final List<ExceptionHandler> exceptionHandlers
  private final ExtendedRegistry extendedRegistry

  TaskTasklet(Task task,
              ExecutionRepository executionRepository,
              List<ExceptionHandler> exceptionHandlers,
              ExtendedRegistry extendedRegistry) {
    this.task = task
    this.executionRepository = executionRepository
    this.exceptionHandlers = exceptionHandlers
    this.extendedRegistry = extendedRegistry
  }

  Class<? extends Task> getTaskType() {
    task.getClass()
  }

  @Override
  RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext) {
    def stage = currentStage(chunkContext)
    def task = currentTask(chunkContext)

    try {
      if (stage.execution.canceled) {
        setStopStatus(chunkContext, ExitStatus.STOPPED, ExecutionStatus.CANCELED)
        return cancel(stage)
      } else if (task.status.complete) {
        // no-op
        log.warn "Skipping task $task.name because its status is $task.status"
        chunkContext.stepContext.stepExecution.executionContext.put("orcaTaskStatus", task.status)
        return RepeatStatus.FINISHED
      } else {
        def result = executeTask(stage, chunkContext)
        logResult(result, stage, chunkContext)

        // we should reload the execution now, in case it has been affected
        // by a parallel process
        long scheduledTime = stage.scheduledTime
        stage = currentStage(chunkContext)
        // Setting the scheduledTime if it has been set by the task
        stage.scheduledTime = scheduledTime

        if (result.status == ExecutionStatus.TERMINAL) {
          setStopStatus(chunkContext, ExitStatus.FAILED, result.status)
        }

        def stageOutputs = new HashMap(result.stageOutputs)
        if (result.status.complete) {
          stageOutputs.put('batch.task.id.' + taskName(chunkContext), chunkContext.stepContext.stepExecution.id)
        }

        storeExecutionResults(new DefaultTaskResult(result.status, stageOutputs, result.globalOutputs), stage,
                              chunkContext)

        def batchStepStatus = BatchStepStatus.mapResult(result)
        chunkContext.stepContext.stepExecution.with {
          executionContext.put("orcaTaskStatus", result.status)
          status = batchStepStatus.batchStatus
          jobExecution.status = batchStepStatus.batchStatus
        }
        contribution.exitStatus = batchStepStatus.exitStatus
        stage.endTime = !batchStepStatus.repeatStatus.continuable ? System.currentTimeMillis() : null

        return batchStepStatus.repeatStatus
      }
    } finally {
      save(stage)
    }
  }

  private RepeatStatus cancel(Stage stage) {
    if (task instanceof CancellableTask) {
      CancellableTask cancellableTask = (CancellableTask) task
      cancellableTask.cancel(stage)
    }
    stage.status = ExecutionStatus.CANCELED
    stage.endTime = System.currentTimeMillis()
    stage.tasks.findAll { !it.status.complete }.each { it.status = ExecutionStatus.CANCELED }
    return RepeatStatus.FINISHED
  }

  private void save(Stage stage) {
    if (stage.self instanceof OrchestrationStage) {
      executionRepository.storeStage(stage.self as OrchestrationStage)
    } else if (stage.self instanceof PipelineStage) {
      executionRepository.storeStage(stage.self as PipelineStage)
    }
  }

  private static void setStopStatus(ChunkContext chunkContext, ExitStatus exitStatus, ExecutionStatus executionStatus) {
    chunkContext.stepContext.stepExecution.with {
      setTerminateOnly()
      executionContext.put("orcaTaskStatus", executionStatus)
      it.exitStatus = exitStatus
    }
  }

  protected TaskResult doExecuteTask(Stage stage, ChunkContext chunkContext) {
    return task.execute(stage)
  }

  private TaskResult executeTask(Stage stage, ChunkContext chunkContext) {
    try {
      def currentUser = new User(
        stage.execution?.authentication?.user, null, null, [], stage.execution?.authentication?.allowedAccounts
      )<commit_msg>Added log message whenever a pipeline is canceled<commit_after>/*
 * Copyright 2014 Netflix, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License")
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.netflix.spinnaker.orca.batch.adapters

import com.netflix.spectator.api.ExtendedRegistry
import com.netflix.spectator.api.Id
import com.netflix.spinnaker.orca.*
import com.netflix.spinnaker.orca.batch.BatchStepStatus
import com.netflix.spinnaker.orca.batch.ExecutionContextManager
import com.netflix.spinnaker.orca.batch.exceptions.ExceptionHandler
import com.netflix.spinnaker.orca.pipeline.model.Execution
import com.netflix.spinnaker.orca.pipeline.model.OrchestrationStage
import com.netflix.spinnaker.orca.pipeline.model.PipelineStage
import com.netflix.spinnaker.orca.pipeline.model.Stage
import com.netflix.spinnaker.orca.pipeline.model.Task as TaskModel
import com.netflix.spinnaker.orca.pipeline.persistence.ExecutionRepository
import com.netflix.spinnaker.security.AuthenticatedRequest
import com.netflix.spinnaker.security.User
import groovy.transform.CompileStatic
import groovy.util.logging.Slf4j
import org.slf4j.LoggerFactory
import org.springframework.batch.core.ExitStatus
import org.springframework.batch.core.StepContribution
import org.springframework.batch.core.scope.context.ChunkContext
import org.springframework.batch.core.step.tasklet.Tasklet
import org.springframework.batch.repeat.RepeatStatus

@Slf4j
@CompileStatic
class TaskTasklet implements Tasklet {
  private static final String METRIC_NAME = "task.invocations"

  private final Task task
  private final ExecutionRepository executionRepository
  private final List<ExceptionHandler> exceptionHandlers
  private final ExtendedRegistry extendedRegistry

  TaskTasklet(Task task,
              ExecutionRepository executionRepository,
              List<ExceptionHandler> exceptionHandlers,
              ExtendedRegistry extendedRegistry) {
    this.task = task
    this.executionRepository = executionRepository
    this.exceptionHandlers = exceptionHandlers
    this.extendedRegistry = extendedRegistry
  }

  Class<? extends Task> getTaskType() {
    task.getClass()
  }

  @Override
  RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext) {
    def stage = currentStage(chunkContext)
    def task = currentTask(chunkContext)

    try {
      if (stage.execution.canceled) {
        setStopStatus(chunkContext, ExitStatus.STOPPED, ExecutionStatus.CANCELED)
        return cancel(stage)
      } else if (task.status.complete) {
        // no-op
        log.warn "Skipping task $task.name because its status is $task.status"
        chunkContext.stepContext.stepExecution.executionContext.put("orcaTaskStatus", task.status)
        return RepeatStatus.FINISHED
      } else {
        def result = executeTask(stage, chunkContext)
        logResult(result, stage, chunkContext)

        // we should reload the execution now, in case it has been affected
        // by a parallel process
        long scheduledTime = stage.scheduledTime
        stage = currentStage(chunkContext)
        // Setting the scheduledTime if it has been set by the task
        stage.scheduledTime = scheduledTime

        if (result.status == ExecutionStatus.TERMINAL) {
          setStopStatus(chunkContext, ExitStatus.FAILED, result.status)
        }

        def stageOutputs = new HashMap(result.stageOutputs)
        if (result.status.complete) {
          stageOutputs.put('batch.task.id.' + taskName(chunkContext), chunkContext.stepContext.stepExecution.id)
        }

        storeExecutionResults(new DefaultTaskResult(result.status, stageOutputs, result.globalOutputs), stage,
                              chunkContext)

        def batchStepStatus = BatchStepStatus.mapResult(result)
        chunkContext.stepContext.stepExecution.with {
          executionContext.put("orcaTaskStatus", result.status)
          status = batchStepStatus.batchStatus
          jobExecution.status = batchStepStatus.batchStatus
        }
        contribution.exitStatus = batchStepStatus.exitStatus
        stage.endTime = !batchStepStatus.repeatStatus.continuable ? System.currentTimeMillis() : null

        return batchStepStatus.repeatStatus
      }
    } finally {
      save(stage)
    }
  }

  private RepeatStatus cancel(Stage stage) {
    if (task instanceof CancellableTask) {
      CancellableTask cancellableTask = (CancellableTask) task
      cancellableTask.cancel(stage)
    }
    stage.status = ExecutionStatus.CANCELED
    stage.endTime = System.currentTimeMillis()
    stage.tasks.findAll { !it.status.complete }.each { it.status = ExecutionStatus.CANCELED }

    log.info("${stage.execution.class.simpleName} ${stage.execution.id} was canceled")
    return RepeatStatus.FINISHED
  }

  private void save(Stage stage) {
    if (stage.self instanceof OrchestrationStage) {
      executionRepository.storeStage(stage.self as OrchestrationStage)
    } else if (stage.self instanceof PipelineStage) {
      executionRepository.storeStage(stage.self as PipelineStage)
    }
  }

  private static void setStopStatus(ChunkContext chunkContext, ExitStatus exitStatus, ExecutionStatus executionStatus) {
    chunkContext.stepContext.stepExecution.with {
      setTerminateOnly()
      executionContext.put("orcaTaskStatus", executionStatus)
      it.exitStatus = exitStatus
    }
  }

  protected TaskResult doExecuteTask(Stage stage, ChunkContext chunkContext) {
    return task.execute(stage)
  }

  private TaskResult executeTask(Stage stage, ChunkContext chunkContext) {
    try {
      def currentUser = new User(
        stage.execution?.authentication?.user, null, null, [], stage.execution?.authentication?.allowedAccounts
      )
{'fraction_non_alphanumeric': 0.07757496740547588, 'fraction_numerical': 0.0017926988265971316, 'mean_word_length': 3.7477756286266923, 'pattern_counts': {'":': 0, '<': 9, '<?xml version=': 0, '>': 9, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '263364', 'n_tokens_mistral': 3331, 'n_tokens_neox': 3266, 'n_words': 773}