Blame view

slapos/grid/promise/generic.py 17 KB
Alain Takoudjou committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
# -*- coding: utf-8 -*-
# vim: set et sts=2:
##############################################################################
#
# Copyright (c) 2018 Vifib SARL and Contributors.
# All Rights Reserved.
#
# WARNING: This program as such is intended to be used by professional
# programmers who take the whole responsibility of assessing all potential
# consequences resulting from its eventual inadequacies and bugs
# End users who are looking for a ready-to-use solution with commercial
# guarantees and support are strongly advised to contract a Free Software
# Service Company
#
# This program is Free Software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 3
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
#
##############################################################################

import os
import logging
import re
import time
import random
import traceback
import slapos.slap
Bryton Lacquement committed
38
from slapos.util import bytes2str, mkdir_p
Alain Takoudjou committed
39
from abc import ABCMeta, abstractmethod
Bryton Lacquement committed
40 41
import six
from six import PY3, with_metaclass
Alain Takoudjou committed
42 43 44 45 46
from datetime import datetime, timedelta

PROMISE_STATE_FOLDER_NAME = '.slapgrid/promise'
PROMISE_RESULT_FOLDER_NAME = '.slapgrid/promise/result'
PROMISE_LOG_FOLDER_NAME = '.slapgrid/promise/log'
Rafael Monnerat committed
47
PROMISE_HISTORY_RESULT_FOLDER_NAME = '.slapgrid/promise/history'
Alain Takoudjou committed
48 49
PROMISE_PARAMETER_NAME = 'extra_config_dict'

Julien Muchembled committed
50
LOGLINE_RE = r"(\d{4}-\d{2}-\d{2}\s+\d{2}:\d{2}:\d{2})\s+\-?\s*(\w+)\s+\-?\s+(\d+\-\d{3})\s+\-?\s*(.*)"
Bryton Lacquement committed
51 52 53
matchLogStr = re.compile(LOGLINE_RE).match
matchLogBytes = re.compile(LOGLINE_RE.encode()).match if PY3 else matchLogStr

Julien Muchembled committed
54 55
ERROR_LEVEL = 'CRITICAL', 'ERROR'

Alain Takoudjou committed
56 57 58
class BaseResult(object):
  def __init__(self, problem=False, message=None, date=None):
    self.__problem = problem
Alain Takoudjou committed
59 60 61
    # The promise message should be very short,
    # a huge message size can freeze the process Pipe
    # XXX this is important to prevent process deadlock
Alain Takoudjou committed
62
    if message is not None and len(message) > 5000:
Alain Takoudjou committed
63
      message = '...%s' % message[-5000:]
Alain Takoudjou committed
64 65 66 67 68 69 70 71
    self.__message = message
    self.__date = date
    if self.__date is None:
      self.__date = datetime.utcnow()

  def hasFailed(self):
    return self.__problem

Alain Takoudjou committed
72 73
  @staticmethod
  def type():
Alain Takoudjou committed
74 75 76 77 78 79 80 81 82 83 84 85
    return "Base Result"

  @property
  def message(self):
    return self.__message

  @property
  def date(self):
    return self.__date

class TestResult(BaseResult):

Alain Takoudjou committed
86 87
  @staticmethod
  def type():
Alain Takoudjou committed
88 89 90 91
    return "Test Result"

class AnomalyResult(BaseResult):

Alain Takoudjou committed
92 93
  @staticmethod
  def type():
Alain Takoudjou committed
94 95
    return "Anomaly Result"

Alain Takoudjou committed
96 97 98 99 100 101 102 103 104
class EmptyResult(BaseResult):

  def __init__(self):
    BaseResult.__init__(self, False, None, None)

  @staticmethod
  def type():
    return "Empty Result"

Alain Takoudjou committed
105 106
class PromiseQueueResult(object):

Alain Takoudjou committed
107 108
  def __init__(self, path=None, name=None, title=None,
               item=None, execution_time=0):
Alain Takoudjou committed
109 110 111 112 113
    self.path = path
    self.name = name
    self.item = item
    self.title = title
    self.execution_time = execution_time
Alain Takoudjou committed
114 115 116
    if self.item is None:
      # if no result set, then set EmptyResult
      self.item = EmptyResult()
Alain Takoudjou committed
117 118 119 120 121 122 123 124

  def serialize(self):
    return {
      'title': self.title,
      'name': self.name,
      'path': self.path,
      'execution-time': self.execution_time,
      'result': {
Alain Takoudjou committed
125
        'type': self.item.type(),
Alain Takoudjou committed
126
        'failed': self.item.hasFailed(),
Alain Takoudjou committed
127
        'date': self.item.date.strftime('%Y-%m-%dT%H:%M:%S+0000'),
Alain Takoudjou committed
128 129 130 131
        'message': self.item.message
      }
    }

Alain Takoudjou committed
132 133 134 135 136
  def load(self, data):
    if data['result']['type'] == AnomalyResult.type():
      self.item = AnomalyResult(
        problem=data['result']['failed'],
        message=data['result']['message'],
Alain Takoudjou committed
137
        date=datetime.strptime(data['result']['date'], '%Y-%m-%dT%H:%M:%S+0000'))
Alain Takoudjou committed
138 139 140 141
    elif data['result']['type'] == TestResult.type():
      self.item = TestResult(
        problem=data['result']['failed'],
        message=data['result']['message'],
Alain Takoudjou committed
142
        date=datetime.strptime(data['result']['date'], '%Y-%m-%dT%H:%M:%S+0000'))
Alain Takoudjou committed
143 144 145 146 147 148 149 150
    else:
      raise ValueError('Unknown result type: %r' % data['result']['type'])

    self.title = data['title']
    self.name = data['name']
    self.path = data['path']
    self.execution_time = data['execution-time']

Bryton Lacquement committed
151
class GenericPromise(with_metaclass(ABCMeta, object)):
Alain Takoudjou committed
152 153 154 155 156 157 158 159 160 161 162

  def __init__(self, config):
    self.__config = config

    self.__log_folder = self.__config.pop('log-folder', None)
    self.__partition_folder = self.__config.pop('partition-folder', None)
    self.__debug = self.__config.pop('debug', True)
    self.__name = self.__config.pop('name', None)
    self.__promise_path = self.__config.pop('path', None)
    self.__queue = self.__config.pop('queue', None)
    self.__logger_buffer = None
Alain Takoudjou committed
163
    self.setPeriodicity(self.__config.pop('periodicity', 2))
Alain Takoudjou committed
164 165

    self.__transaction_id = '%s-%s' % (int(time.time()), random.randint(100, 999))
Alain Takoudjou committed
166 167 168
    self.__is_tested = True
    # XXX - JP asked to use __is_anomaly_detected = True, but __is_anomaly_less seems more convenient
    self.__is_anomaly_detected = True
Alain Takoudjou committed
169 170 171 172 173 174 175 176 177

    self._validateConf()
    self._configureLogger()

  def _configureLogger(self):
    self.logger = logging.getLogger(self.__name)
    for handler in self.logger.handlers:
      self.logger.removeHandler(handler)
    if self.__log_folder is None:
Bryton Lacquement committed
178
      self.__logger_buffer = six.StringIO()
Alain Takoudjou committed
179 180 181
      logger_handler = logging.StreamHandler(self.__logger_buffer)
      self.__log_file = None
    else:
Alain Takoudjou committed
182
      mkdir_p(self.__log_folder)
Alain Takoudjou committed
183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239
      self.__log_file = os.path.join(
        self.__log_folder,
        '%s.log' % self.__title
      )
      logger_handler = logging.FileHandler(self.__log_file)

    self.logger.setLevel(logging.DEBUG if self.__debug else logging.INFO)
    logger_handler.setFormatter(
      fmt=logging.Formatter("%(asctime)s - %(levelname)s - " +
          self.__transaction_id + " - %(message)s",
        datefmt="%Y-%m-%d %H:%M:%S")
    )
    self.logger.addHandler(logger_handler)

  def _validateConf(self):
    if self.__queue is None:
      raise ValueError("Queue object is not set in configuration")
    if self.__name is None:
      raise ValueError("Monitor name is not set in configuration")
    self.__title = os.path.splitext(self.__name)[0]
    if self.__promise_path is None:
      raise ValueError("Promise path is not set in configuration")
    if self.__partition_folder is None:
      raise ValueError("Monitor partition folder is not set in configuration")

  def getConfig(self, key, default=None):
    return self.__config.get(key, default)

  def setConfig(self, key, value):
    self.__config[key] = value

  def getTitle(self):
    return self.__title

  def getName(self):
    return self.__name

  def getLogFile(self):
    return self.__log_file

  def getLogFolder(self):
    return self.__log_folder

  def getPartitionFolder(self):
    return self.__partition_folder

  def getPromiseFile(self):
    return self.__promise_path

  def setPeriodicity(self, minute):
    if minute <= 0:
      raise ValueError("Cannot set promise periodicity to a value less than 1")
    self.__periodicity = minute

  def getPeriodicity(self):
    return self.__periodicity

Alain Takoudjou committed
240 241 242 243 244 245 246 247 248 249 250 251 252 253 254
  def setTestLess(self):
    """
      Ask to skip test method. Only Anomaly will run
    """
    self.__is_tested = False

  def isTested(self):
    return self.__is_tested

  def setAnomalyLess(self):
    """
      Ask to skip anomaly method. Only Test will run
    """
    self.__is_anomaly_detected = False

Alain Takoudjou committed
255
  def isAnomalyDetected(self):
Alain Takoudjou committed
256 257
    return self.__is_anomaly_detected

Alain Takoudjou committed
258 259 260 261
  def __bang(self, message):
    """
      Call bang if requested
    """
Bryton Lacquement committed
262
    if 'master-url' in self.__config and \
Julien Muchembled committed
263
       'partition-id' in self.__config and \
Bryton Lacquement committed
264
       'computer-id' in self.__config:
Alain Takoudjou committed
265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285

      slap = slapos.slap.slap()
      slap.initializeConnection(
          self.__config['master-url'],
          self.__config.get('partition-key'),
          self.__config.get('partition-cert'),
      )
      computer_partition = slap.registerComputerPartition(
          self.__config['computer-id'],
          self.__config['partition-id'],
      )
      computer_partition.bang(message)
      self.logger.info("Bang with message %r." % message)

  def __getResultFromString(self, result_string, only_failure=False):
    line_list = result_string.split('\n')
    result_list = []
    line_part = ""
    for line in line_list:
      if not line:
        continue
Bryton Lacquement committed
286
      match = matchLogStr(line)
Alain Takoudjou committed
287
      if match is not None:
Julien Muchembled committed
288 289
        date, level, tid, msg = match.groups()
        if not only_failure or level in ERROR_LEVEL:
Alain Takoudjou committed
290
          result_list.append({
Julien Muchembled committed
291 292 293
            'date': datetime.strptime(date, '%Y-%m-%d %H:%M:%S'),
            'status': level,
            'message': (msg + line_part).strip(),
Alain Takoudjou committed
294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327
          })
        line_part = ""
      else:
        line_part += '\n' + line

    return [result_list]

  def getLastPromiseResultList(self, latest_minute=0, result_count=1,
      only_failure=False):
    """
      Return the latest log result of the promise starting from the most recent

      @param last_minute: the number of minutes in the past. If last_minute is
        1, it will return the log of the latest minute execution. 0 => disabled
      @param only_failure: only return the lines which contain failures.
      @param result_count: maximum number of promise result to check, will not
        exceed the `latest_minute`
      @return Return a list of logs. The format is
        [[{"date": "DATE", "status": "STATUS", "message": MESSAGE}, ...], ...]
    """

    if self.__log_file is None:
      if self.__logger_buffer is not None:
        return self.__getResultFromString(self.__logger_buffer.getvalue(),
                                          only_failure)
      else:
        return []

    if not os.path.exists(self.__log_file):
      return []

    if latest_minute > 0:
      date = datetime.now() - timedelta(minutes=latest_minute)
      max_date_string = date.strftime('%Y-%m-%d %H:%M:%S')
Bryton Lacquement committed
328 329
    else:
      max_date_string = ""
Alain Takoudjou committed
330 331 332 333 334

    line_list = []
    result_list = []
    transaction_id = None
    transaction_count = 0
Bryton Lacquement committed
335
    with open(self.__log_file, 'rb') as f:
Alain Takoudjou committed
336
      f.seek(0, 2)
Bryton Lacquement committed
337 338 339 340
      offset = f.tell()
      line = b""
      line_part = ""
      while offset:
Alain Takoudjou committed
341
        offset -= 1
Bryton Lacquement committed
342
        f.seek(offset)
Alain Takoudjou committed
343
        char = f.read(1)
Bryton Lacquement committed
344
        if char != b'\n':
Alain Takoudjou committed
345
          line = char + line
Bryton Lacquement committed
346
          if offset:
Alain Takoudjou committed
347
            continue
Bryton Lacquement committed
348 349
        if line:
            result = matchLogBytes(line)
Alain Takoudjou committed
350
            if result is not None:
Bryton Lacquement committed
351 352
              date, level, tid, msg = map(bytes2str, result.groups())
              if max_date_string and date <= max_date_string:
Alain Takoudjou committed
353
                break
Bryton Lacquement committed
354
              if transaction_id != tid:
Alain Takoudjou committed
355 356 357 358 359 360 361
                if transaction_id is not None:
                  # append new result
                  result_list.append(line_list)
                  line_list = []
                transaction_count += 1
                if transaction_count > result_count:
                  break
Bryton Lacquement committed
362
                transaction_id = tid
Julien Muchembled committed
363
              if not only_failure or level in ERROR_LEVEL:
Alain Takoudjou committed
364
                line_list.insert(0, {
Bryton Lacquement committed
365
                  'date': datetime.strptime(date,
Alain Takoudjou committed
366
                                            '%Y-%m-%d %H:%M:%S'),
Bryton Lacquement committed
367 368
                  'status': level,
                  'message': (msg + line_part).strip(),
Alain Takoudjou committed
369
                })
Bryton Lacquement committed
370
              line_part = ""
Alain Takoudjou committed
371
            else:
Bryton Lacquement committed
372 373
              line_part = '\n' + bytes2str(line) + line_part
            line = b""
Alain Takoudjou committed
374 375 376 377 378 379 380 381 382

    if len(line_list):
      result_list.append(line_list)
    return result_list

  def __readResultList(self, result_list):
    failed = False
    message = ""
    for result in result_list:
Julien Muchembled committed
383
      if result['status'] in ERROR_LEVEL:
Alain Takoudjou committed
384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418
        failed = True
      message += "\n%s" % result['message']
    return failed, message.strip()

  def __checkPromiseResult(self, result_count=1, failure_amount=1,
      latest_minute=0, is_anomaly=False):
    """
      Test if the latest messages contain `failure_amount` failures.

      @param result_count: maximum number of promise result to check, will not
        exceed the `latest_minute`
      @param latest_minute: test the result from now to the latest X minutes in
        the past.
      @param failure_amount: fail is this amount of failure is found in result
      @param is_anomaly: Say if the result is an AnomalyResult of TestResult
    """

    module = TestResult if not is_anomaly else AnomalyResult
    latest_result_list = self.getLastPromiseResultList(
      result_count=result_count,
      latest_minute=latest_minute,
      only_failure=False
    )
    result_size = len(latest_result_list)
    if result_size == 0:
      return module(problem=False, message="No result found!")
    problem, message = self.__readResultList(latest_result_list[0])
    if not problem:
      # latest execution is OK
      return module(problem=False, message=message)

    i = 1
    failure_found = 1
    while i < result_size and failure_found < failure_amount:
      for result in latest_result_list[i]:
Julien Muchembled committed
419
        if result['status'] in ERROR_LEVEL:
Alain Takoudjou committed
420 421 422 423 424 425 426 427
          failure_found += 1
          break
      i += 1

    if failure_found != failure_amount:
      return module(problem=False, message=message)
    return module(problem=True, message=message)

Alain Takoudjou committed
428 429 430 431 432 433 434
  def __sendResult(self, result_item, retry_amount=3):
    """Send result to queue, retry if error (non blocking)"""
    error = None
    for i in range(0, retry_amount):
      try:
        self.__queue.put_nowait(result_item)
        break
Bryton Lacquement committed
435
      except Queue.Full as e:
Alain Takoudjou committed
436 437 438 439 440
        error = e
        time.sleep(0.5)
    if error:
      raise error

Alain Takoudjou committed
441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481
  def _test(self, result_count=1, failure_amount=1, latest_minute=0):
    """
      Default promise test method
    """
    return self.__checkPromiseResult(
      result_count=result_count,
      failure_amount=failure_amount,
      latest_minute=latest_minute,
      is_anomaly=False
    )

  def _anomaly(self, result_count=1, failure_amount=1, latest_minute=0):
    """
      Default anomaly check method
    """
    return self.__checkPromiseResult(
      result_count=result_count,
      failure_amount=failure_amount,
      latest_minute=latest_minute,
      is_anomaly=True
    )

  @abstractmethod
  def sense(self):
    """Run the promise code and log the result"""

  def anomaly(self):
    """Called to detect if there is an anomaly which require to bang."""
    return self._anomaly()

  def test(self):
    """Test promise and say if problem is detected or not"""
    return self._test()

  def run(self, check_anomaly=False, can_bang=True):
    """
      Method called to run the Promise
      @param check_anomaly: Say if anomaly method should be called
      @param can_bang: Set to True if bang can be called, this parameter should
        be set to False if bang is already called by another promise.
    """
Alain Takoudjou committed
482 483 484 485
    if not self.__is_tested and not self.__is_anomaly_detected:
      message = "It's not allowed to disable both Test and Anomaly in promise!"
      if check_anomaly:
        result = AnomalyResult(problem=True, message=message)
Alain Takoudjou committed
486
      else:
Alain Takoudjou committed
487 488 489 490 491 492 493 494 495 496
        result = TestResult(problem=True, message=message)
      self.__sendResult(PromiseQueueResult(
        path=self.__promise_path,
        name=self.__name,
        title=self.__title,
        item=result
      ))
    elif (not self.__is_tested and not check_anomaly) or \
        (not self.__is_anomaly_detected and check_anomaly):
      # Anomaly or Test is disabled on this promise, send empty result
Alain Takoudjou committed
497 498 499 500 501
      if self.getConfig('slapgrid-version', '') <= '1.4.17':
        # old version cannot send EmptyResult
        self.__sendResult(PromiseQueueResult(item=TestResult()))
      else:
        self.__sendResult(PromiseQueueResult())
Alain Takoudjou committed
502 503
    else:
      try:
Alain Takoudjou committed
504
        self.sense()
Bryton Lacquement committed
505
      except Exception as e:
Alain Takoudjou committed
506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537
        # log the result
        self.logger.error(str(e))
      if check_anomaly:
        # run sense, anomaly
        try:
          result = self.anomaly()
          if result is None:
            raise ValueError("Promise anomaly method returned 'None'")
        except Exception as e:
          result = AnomalyResult(problem=True, message=str(e))
        else:
          if isinstance(result, AnomalyResult) and result.hasFailed() and can_bang:
            try:
              self.__bang("Promise %s is failing" % self.__title)
            except:
              self.logger.warning(traceback.format_exc())
      else:
        # run sense, test
        try:
          result = self.test()
          if result is None:
            raise ValueError("Promise test method returned 'None'")
        except Exception as e:
          result = TestResult(problem=True, message=str(e))

      # send the result of this promise
      self.__sendResult(PromiseQueueResult(
        path=self.__promise_path,
        name=self.__name,
        title=self.__title,
        item=result
      ))
Alain Takoudjou committed
538 539 540

    if self.__logger_buffer is not None:
      self.__logger_buffer.close()