<commit_before>'use strict';
// TODO abstract to a base poller

const _ = require('lodash');
const eventmesh = require('../../data-access-layer/eventmesh');
const CONST = require('../../common/constants');
const logger = require('../../common/logger');
const catalog = require('../../common/models').catalog;
const config = require('../../common/config');
const RestoreService = require('./');
const utils = require('../../common/utils');
const EventLogInterceptor = require('../../common/EventLogInterceptor');

class RestoreTaskPoller {

  static start() {
    function poller(object, interval) {
      // TODO handle HA scenario
      const response = JSON.parse(_.get(object.status, 'response'));
      const changedOptions = JSON.parse(object.spec.options);
      logger.info('Getting restore status with the following options and response:', changedOptions, response);
      const plan = catalog.getPlan(changedOptions.plan_id);
      const restore_opts = {
        context: changedOptions.context,
        agent_ip: response.agent_ip,
        instance_guid: changedOptions.instance_guid,
        restore_guid: changedOptions.restore_guid
      };
      return RestoreService.createService(plan)
        .then(restoreService => restoreService
          .getRestoreOperationState(restore_opts)
          .then(operationStatusResponse => {
            logger.info(`Got restore operation response for guid ${changedOptions.restore_guid}`, operationStatusResponse);
            return Promise
              .try(() => eventmesh.apiServerClient.patchResource({
                resourceGroup: CONST.APISERVER.RESOURCE_GROUPS.RESTORE,
                resourceType: CONST.APISERVER.RESOURCE_TYPES.DEFAULT_RESTORE,
                resourceId: changedOptions.restore_guid,
                status: {
                  'state': operationStatusResponse.state,
                  response: operationStatusResponse
                }
              }))
              .then(() => {
                if (_.includes([CONST.APISERVER.RESOURCE_STATE.SUCCEEDED, CONST.APISERVER.RESOURCE_STATE.FAILED], operationStatusResponse.state)) {
                  // cancel the poller and clear the array
                  clearInterval(interval);
                  RestoreTaskPoller.pollers[object.metadata.name] = false;
                }
              })
              .then(() => {
                if (utils.isServiceFabrikOperationFinished(operationStatusResponse.state)) {
                  return this._logEvent(restore_opts, CONST.OPERATION_TYPE.RESTORE, operationStatusResponse);
                }
              });
          })
          .catch(e => logger.error('Caught error in poller', e))
        );
    }

    function startPoller(event) {
      logger.debug('Received Restore Event: ', event);
      if ((event.type === CONST.API_SERVER.WATCH_EVENT.ADDED || event.type === CONST.API_SERVER.WATCH_EVENT.MODIFIED) && !RestoreTaskPoller.pollers[event.object.metadata.name]) {
        logger.info(`Starting poller for restore: ${event.object.metadata.name} with interval ${CONST.RESTORE_RESOURCE_POLLER_INTERVAL}`);
        const interval = setInterval(() => poller(event.object, interval), CONST.RESTORE_RESOURCE_POLLER_INTERVAL);
        RestoreTaskPoller.pollers[event.object.metadata.name] = true;
      }
    }
    const queryString = `state in (${CONST.APISERVER.RESOURCE_STATE.IN_PROGRESS})`;<commit_msg>Clear poller on abort<commit_after>'use strict';
// TODO abstract to a base poller

const _ = require('lodash');
const Promise = require('bluebird');
const eventmesh = require('../../data-access-layer/eventmesh');
const CONST = require('../../common/constants');
const logger = require('../../common/logger');
const catalog = require('../../common/models').catalog;
const config = require('../../common/config');
const RestoreService = require('./');
const utils = require('../../common/utils');
const EventLogInterceptor = require('../../common/EventLogInterceptor');

class RestoreTaskPoller {

  static start() {
    function poller(object, interval) {
      // TODO handle HA scenario
      const response = JSON.parse(_.get(object.status, 'response'));
      const changedOptions = JSON.parse(object.spec.options);
      logger.info('Getting restore status with the following options and response:', changedOptions, response);
      const plan = catalog.getPlan(changedOptions.plan_id);
      const restore_opts = {
        context: changedOptions.context,
        agent_ip: response.agent_ip,
        instance_guid: changedOptions.instance_guid,
        restore_guid: changedOptions.restore_guid
      };
      return RestoreService.createService(plan)
        .then(restoreService => restoreService
          .getRestoreOperationState(restore_opts)
          .then(operationStatusResponse => {
            logger.info(`Got restore operation response for guid ${changedOptions.restore_guid}`, operationStatusResponse);
            return Promise
              .try(() => eventmesh.apiServerClient.patchResource({
                resourceGroup: CONST.APISERVER.RESOURCE_GROUPS.RESTORE,
                resourceType: CONST.APISERVER.RESOURCE_TYPES.DEFAULT_RESTORE,
                resourceId: changedOptions.restore_guid,
                status: {
                  'state': operationStatusResponse.state,
                  response: operationStatusResponse
                }
              }))
              .then(() => {
                if (_.includes([CONST.APISERVER.RESOURCE_STATE.SUCCEEDED, CONST.APISERVER.RESOURCE_STATE.ABORTED], operationStatusResponse.state)) {
                  logger.debug('Cancel the poller:', object.metadata.name);
                  clearInterval(interval);
                  RestoreTaskPoller.pollers[object.metadata.name] = false;
                }
              })
              .then(() => {
                if (utils.isServiceFabrikOperationFinished(operationStatusResponse.state)) {
                  return RestoreTaskPoller._logEvent(restore_opts, CONST.OPERATION_TYPE.RESTORE, operationStatusResponse);
                }
              });
          })
          .catch(e => logger.error('Caught error in poller', e))
        );
    }

    function startPoller(event) {
      logger.debug('Received Restore Event: ', event);
      if ((event.type === CONST.API_SERVER.WATCH_EVENT.ADDED || event.type === CONST.API_SERVER.WATCH_EVENT.MODIFIED) && !RestoreTaskPoller.pollers[event.object.metadata.name]) {
        logger.info(`Starting poller for restore: ${event.object.metadata.name} with interval ${CONST.RESTORE_RESOURCE_POLLER_INTERVAL}`);
        const interval = setInterval(() => poller(event.object, interval), CONST.RESTORE_RESOURCE_POLLER_INTERVAL);
        RestoreTaskPoller.pollers[event.object.metadata.name] = true;
      }
    }
    const queryString = `state in (${CONST.APISERVER.RESOURCE_STATE.IN_PROGRESS})`;
{'fraction_non_alphanumeric': 0.12179487179487179, 'fraction_numerical': 0.0, 'mean_word_length': 2.7088060507833602, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 17, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, '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': '3304565', 'n_tokens_mistral': 1854, 'n_tokens_neox': 1798, 'n_words': 334}