ERP5ProjectUnitTestDistributor.py 20.8 KB
Newer Older
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 38 39
##############################################################################
# Copyright (c) 2013 Nexedi SA and Contributors. All Rights Reserved.
#          Sebastien Robin <seb@nexedi.com>
#
# 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 2
# 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
##############################################################################
from Products.ERP5Type.XMLObject import XMLObject
from Products.ERP5.Tool.TaskDistributionTool import TaskDistributionTool
from DateTime import DateTime
from datetime import datetime
import json
import sys
import itertools
from copy import deepcopy
import random
import string
from zLOG import LOG,INFO,ERROR
from AccessControl import ClassSecurityInfo
from Products.ERP5Type import Permissions
40
from Products.ZSQLCatalog.SQLCatalog import SimpleQuery
41
TEST_SUITE_MAX = 4
42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93
# Depending on the test suite priority, we will affect
# more or less cores
PRIORITY_MAPPING =  {
  # int_index: (min cores, max cores)
   1: ( 3,  3),
   2: ( 3,  3),
   3: ( 3,  6),
   4: ( 3,  6),
   5: ( 3,  6),
   6: ( 6,  9),
   7: ( 6,  9),
   8: ( 6,  9),
   9: ( 9, 15),
  }

class ERP5ProjectUnitTestDistributor(XMLObject):

  security = ClassSecurityInfo()
  security.declareObjectProtected(Permissions.AccessContentsInformation)

  security.declareProtected(Permissions.ManagePortal,
                            "cleanupInvalidatedTestNode")
  def cleanupInvalidatedTestNode(self, test_node):
    """
    When a test node is invalidated, the work will be distributed to
    other test nodes, so we should clean association to test suites.
    Like this, when this node will come back, we will not mess distribution
    with stuff already distributed in other places
    """
    if test_node.getAggregateList():
      test_node.setAggregateList([])

  def _cleanupTestNodeList(self,test_node_list, test_suite_list_to_remove):
    # Remove useless assigment of test suites. First remove from
    # nodes with highest number of test suites
    # test_suite_list_to_remove could be like ['foo','foo', 'bar']
    test_suite_list_to_remove.sort()
    while len(test_suite_list_to_remove):
      test_node_list.sort(key=lambda x: -len(x.getAggregateList()))
      current_test_suite = test_suite_list_to_remove[0]
      for test_node in test_node_list:
        test_suite_list = test_node.getAggregateList()
        if current_test_suite in test_suite_list:
          test_suite_list.remove(current_test_suite)
          test_node.setAggregateList(test_suite_list)
          test_suite_list_to_remove.remove(current_test_suite)
        if len(test_suite_list_to_remove):
          if test_suite_list_to_remove[0] != current_test_suite:
            break
        else:
          break

94
  def _checkCurrentConfiguration(self,test_node_list, test_suite_list_to_add, max_test_suite):
95 96 97 98 99 100 101 102
    """
    We look at what is already installed and then we remove from the list
    of test suite list to add what is already installed.
    We also build a list of installed test suites that should be removed
    """
    test_suite_list_to_remove = []
    for test_node in test_node_list:
      test_suite_list = test_node.getAggregateList()
103 104 105 106
      for index, test_suite in enumerate(test_suite_list, 1):
        if index > max_test_suite:
          test_suite_list_to_remove.append(test_suite)
          continue
107
        try:
108
          test_suite_list_to_add.remove(test_suite)
109
        except ValueError:
110
          test_suite_list_to_remove.append(test_suite)
111
    return test_suite_list_to_remove
Sebastien Robin's avatar
Sebastien Robin committed
112

113 114 115 116 117 118
  security.declareProtected(Permissions.ManagePortal, "optimizeConfiguration")
  def optimizeConfiguration(self):
    """
    We are going to add test suites to test nodes.
    First are completed test nodes with fewer test suites
    """
119 120
    self.serialize() # prevent parallel optimization to avoid conflict
                     # on nodes and possibly weird results
121 122 123 124 125 126
    portal = self.getPortalObject()
    test_node_module = self._getTestNodeModule()
    test_node_list = [
        x.getObject() for x in test_node_module.searchFolder(
        portal_type="Test Node", validation_state="validated",
        specialise_uid=self.getUid(), sort_on=[('title','ascending')])]
Sebastien Robin's avatar
Sebastien Robin committed
127

128
    test_node_list_len = len(test_node_list)
129
    max_test_suite = self.getMaxTestSuite(TEST_SUITE_MAX)
130 131
    def _optimizeConfiguration(test_suite_list_to_add, level=0,
                               test_node_list_to_optimize=None,
132
                               test_suite_max=max_test_suite):
133 134
      if test_node_list_to_optimize is None:
        test_node_list_to_optimize = [x for x in test_node_list]
135 136
      if test_suite_list_to_add:
        test_node_list_to_remove = []
137
        for test_node in test_node_list_to_optimize:
138
          # We can no longer add more test suite on this test node
139
          if test_suite_max < (level + 1):
140 141 142 143 144 145 146 147 148 149 150 151
            test_node_list_to_remove.append(test_node)
            continue
          test_suite_list = test_node.getAggregateList()
          if len(test_suite_list) == level:
            for test_suite in test_suite_list_to_add:
              if not(test_suite in test_suite_list):
                test_node.setAggregateList([test_suite] + test_suite_list)
                test_suite_list_to_add.remove(test_suite)
                break
            if len(test_suite_list_to_add) == 0:
              break
        for test_node in test_node_list_to_remove:
152 153 154 155 156
          test_node_list_to_optimize.remove(test_node)
      if test_suite_list_to_add and test_node_list_to_optimize:
        _optimizeConfiguration(test_suite_list_to_add, level=level+1,
                      test_node_list_to_optimize=test_node_list_to_optimize,
                      test_suite_max=test_suite_max)
157

158 159
    test_suite_score, test_suite_list_to_add = self._getSortedNodeTestSuiteList()
    average_quantity = float(len(test_suite_list_to_add)) / (test_node_list_len or 1)
160
    test_suite_list_to_remove = self._checkCurrentConfiguration(test_node_list,
161
      test_suite_list_to_add, max_test_suite)
162 163
    self._cleanupTestNodeList(test_node_list, test_suite_list_to_remove)
    _optimizeConfiguration(test_suite_list_to_add)
164 165 166 167 168 169 170 171 172 173 174 175 176 177 178
    # once we removed useless test suite and added needed ones,
    # we check if we can move some test suites to testnodes that are
    # more idle than others. We try to move first test suites using
    # more test nodes, this reduce risk of moving a test suite assigned
    # on a single test node (to avoid waiting building)
    overloaded_test_node_list = []
    lazy_test_node_list = []
    int_average_quantity = int(average_quantity)
    # Find testnode which can accept more work
    for test_node in test_node_list:
      aggregate_len = len(test_node.getAggregateList())
      if aggregate_len <= (average_quantity - 1):
        lazy_test_node_list.append(test_node)
    # check on most overloaded test nodes first if we can move some work to lazy
    # test nodes
179
    for aggregate_quantity in range(max_test_suite, int_average_quantity, -1):
180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198
      if len(lazy_test_node_list) == 0:
        break
      overloaded_test_node_list = [x for x in test_node_list if len(x.getAggregateList()) == aggregate_quantity]
      for test_node in overloaded_test_node_list:
        test_suite_list = test_node.getAggregateList()
        test_suite_list.sort(key=lambda x: (-test_suite_score[x][-1],
                                            portal.unrestrictedTraverse(x).getTitle()))
        for test_suite in test_suite_list:
          test_suite_list_to_move = [test_suite]
          _optimizeConfiguration(test_suite_list_to_move,
                                 test_node_list_to_optimize=lazy_test_node_list,
                                 test_suite_max=int_average_quantity)
          if len(test_suite_list_to_move) == 0:
            # This means we were able to affect the test suite to another test node
            test_suite_list.remove(test_suite)
            test_node.setAggregateList(test_suite_list)
            break
        if len(lazy_test_node_list) == 0:
          break
199 200 201 202 203 204 205

  def _getSortedNodeTestSuiteList(self):
    """
    We build the list of test suite instances. If a test suite
    can be installed on at most 2 test nodes, it will be twice
    in the returned list. We give a score for every wished test suites.
    The lower score, the better chance it has to be installed.
206 207 208

    A test_suite_score is also returned allowing to quickly identify
    which test suite migh be removed on test node with too many test suites
209 210 211 212 213 214
  """
    test_suite_module = self._getTestSuiteModule()
    portal = self.getPortalObject()
    test_suite_list = test_suite_module.searchFolder(validation_state="validated",
                                               specialise_uid=self.getUid())
    all_test_suite_list = []
215
    test_suite_score = {}
216 217 218 219 220 221 222 223 224 225
    for test_suite in test_suite_list:
      test_suite = test_suite.getObject()
      test_suite_url = test_suite.getRelativeUrl()
      title = test_suite.getTitle()
      # suites required
      int_index = test_suite.getIntIndex()
      # we divide per 3 because we have 3 cores per node
      node_quantity_min = PRIORITY_MAPPING[int_index][0]/3
      node_quantity_max = PRIORITY_MAPPING[int_index][1]/3
      for x in xrange(0, node_quantity_min):
226 227 228
        score = float(x)/(x+1)
        all_test_suite_list.append((score, test_suite_url, title))
        test_suite_score.setdefault(test_suite_url, []).append(score)
229 230 231
      # additional suites, lower score
      for x in xrange(0, node_quantity_max -
                   node_quantity_min ):
232
        score = float(1) + x/(x+1)
233
        all_test_suite_list.append((1 + x/(x+1), test_suite_url, title))
234
        test_suite_score.setdefault(test_suite_url, []).append(score)
235
    all_test_suite_list.sort(key=lambda x: (x[0], x[2]))
236
    return test_suite_score, [x[1] for x in all_test_suite_list]
237 238 239 240 241 242 243 244 245 246 247 248 249

  def _getTestNodeModule(self):
    return self.getPortalObject().test_node_module

  def _getTestSuiteModule(self):
    return self.getPortalObject().test_suite_module

  def getMemcachedDict(self):
    portal = self.getPortalObject()
    memcached_dict = portal.portal_memcached.getMemcachedDict(
                            "task_distribution", "default_memcached_plugin")
    return memcached_dict

250 251 252 253 254 255 256 257 258 259 260 261 262 263 264
  security.declarePublic("getTestType")
  def getTestType(self, batch_mode=0):
    """
    getTestType : return a string defining the test type
    """
    return 'UnitTest'

  security.declarePublic("subscribeNode")
  def subscribeNode(self,title,computer_guid,batch_mode=0):
    """
    subscribeNode doc
    """
    test_node_module = self._getTestNodeModule()
    portal = self.getPortalObject()

Łukasz Nowak's avatar
Łukasz Nowak committed
265
    config = {}
266 267
    tag = "%s_%s" % (self.getRelativeUrl(), title)
    if portal.portal_activities.countMessageWithTag(tag) == 0:
268 269 270 271
      test_node_list = test_node_module.searchFolder(
        portal_type="Test Node",
        title=SimpleQuery(comparison_operator='=', title=title),
      )
Łukasz Nowak's avatar
Łukasz Nowak committed
272 273
      if getattr(self, 'getProcessTimeout', None) is not None:
        config['process_timeout'] = self.getProcessTimeout()
274 275 276 277 278 279 280 281 282 283 284 285 286 287 288
      assert len(test_node_list) in (0, 1), "Unable to find testnode : %s" % title
      test_node = None
      if len(test_node_list) == 1:
        test_node = test_node_list[0].getObject()
        if test_node.getValidationState() != 'validated':
           try:
            test_node.validate()
           except e:
             LOG('Test Node Validate',ERROR,'%s' %e)
      if test_node is None:
        test_node = test_node_module.newContent(portal_type="Test Node", title=title, computer_guid=computer_guid,
                                      specialise=self.getRelativeUrl(),
                                      activate_kw={'tag': tag})
        self.activate(after_tag=tag).optimizeConfiguration()
      test_node.setPingDate()
Łukasz Nowak's avatar
Łukasz Nowak committed
289 290 291
    if batch_mode:
      return config
    return json.dumps(config)
292

293 294 295 296 297 298 299 300 301 302 303 304 305 306
  def _getSortedNodeTestSuiteToRun(self, test_node):
    """
    Returned ordered list of test suites of a test node. More the
    latest test result is old, more it will have priority. Like this
    we try to run first test suites that have no results since a long
    time
    """
    portal = self.getPortalObject()
    test_suite_list = test_node.getAggregateValueList()
    # Do not take results older than one month to avoid killing the
    # sql server
    now = DateTime()
    from_date = now - 30
    def getTestSuiteSortKey(test_suite):
307
      test_result_list = portal.portal_catalog(portal_type="Test Result",
308 309 310 311 312
                                          title=SimpleQuery(title=test_suite.getTitle()),
                                          creation_date=SimpleQuery(
                                            creation_date=from_date,
                                            comparison_operator='>=',
                                          ),
313 314
                                          sort_on=[("modification_date", "descending")],
                                          limit=1)
315 316 317 318 319 320 321 322 323 324
      if len(test_result_list):
        test_result = test_result_list[0].getObject()
        key = test_result.getModificationDate().timeTime()
        # if a test result has all it's tests already ongoing, it is not a
        # priority at all to process it, therefore push it at the end of the list
        if test_result.getSimulationState() == "started":
          result_line_list = test_result.objectValues(portal_type="Test Result Line")
          if len(result_line_list):
            if len([x for x in result_line_list if x.getSimulationState() == "draft"]) == 0:
              key = now.timeTime()
325 326 327 328 329 330
      else:
        key = random.random()
      return key
    test_suite_list.sort(key=getTestSuiteSortKey)
    return test_suite_list

331
  security.declarePublic("startTestSuite")
332
  def startTestSuite(self,title, computer_guid=None, batch_mode=0):
333 334 335 336 337 338 339 340 341
    """
    startTestSuite doc
    """
    test_node_module = self._getTestNodeModule()
    test_suite_module =  self._getTestSuiteModule()
    portal = self.getPortalObject()
    config_list = []
    tag = "%s_%s" % (self.getRelativeUrl(), title)
    if portal.portal_activities.countMessageWithTag(tag) == 0:
342 343 344 345
      test_node_list = test_node_module.searchFolder(
        portal_type="Test Node",
        title=SimpleQuery(comparison_operator='=', title=title),
      )
346 347 348 349 350
      assert len(test_node_list) in (0, 1), "Unable to find testnode : %s" % title
      test_node = None
      if len(test_node_list) == 1:
        test_node = test_node_list[0].getObject()
        if test_node.getValidationState() != 'validated':
351
          test_node.validate()
352 353 354 355 356 357
      if test_node is None:
        test_node = test_node_module.newContent(portal_type="Test Node", title=title,
                                      specialise=self.getRelativeUrl(),
                                      activate_kw={'tag': tag})
        self.activate(after_tag=tag).optimizeConfiguration()
      test_node.setPingDate()
358
      choice_list = self._getSortedNodeTestSuiteToRun(test_node)
359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385
      for test_suite in choice_list:
        config = {}
        config["project_title"] = test_suite.getSourceProjectTitle()
        config["test_suite"] = test_suite.getTestSuite()
        config["test_suite_title"] = test_suite.getTitle()
        config["additional_bt5_repository_id"] = test_suite.getAdditionalBt5RepositoryId()
        config["test_suite_reference"] = test_suite.getReference()
        vcs_repository_list = []
        #In this case objectValues is faster than searchFolder
        for repository in test_suite.objectValues(portal_type="Test Suite Repository"):
          repository_dict = {}
          for property_name in ["git_url", "profile_path", "buildout_section_id", "branch"]:
            property_value = repository.getProperty(property_name)
            # the property name url returns the object's url, so it is mandatory use another name.
            if property_name == "git_url":
              property_name="url"
            if property_value is not None:
              repository_dict[property_name] = property_value
          vcs_repository_list.append(repository_dict)
        config["vcs_repository_list"] = vcs_repository_list
        to_delete_key_list = [x for x,y in config.items() if y==None]
        [config.pop(x) for x in to_delete_key_list]
        config_list.append(config)
    LOG('ERP5ProjectUnitTestDistributor.startTestSuite, config_list',INFO,config_list)
    if batch_mode:
      return config_list
    return json.dumps(config_list)
Sebastien Robin's avatar
Sebastien Robin committed
386

387 388 389 390 391 392 393 394
  security.declarePublic("createTestResult")
  def createTestResult(self, name, revision, test_name_list, allow_restart,
                       test_title=None, node_title=None, project_title=None):
    """
    Here this is only a proxy to the task distribution tool
    """
    LOG('ERP5ProjectUnitTestDistributor.createTestResult', 0, (node_title, test_title))
    portal = self.getPortalObject()
395 396 397
    if node_title:
      test_node = self._getTestNodeFromTitle(node_title)
      test_node.setPingDate()
398
    test_suite = self._getTestSuiteFromTitle(test_title)
399
    if test_suite is not None:
400 401 402 403 404 405 406 407 408 409
      if not allow_restart and test_suite.isEnabled():
        # in case if allow_restart is not enforced by client and test_node
        # periodicity is enabled control the restartability based on test_suite
        # periodicity
        current_date = DateTime()
        alarm_date = test_suite.getAlarmDate()
        if alarm_date is None or alarm_date <= current_date:
          allow_restart = True
          test_suite.setAlarmDate(
            test_suite.getNextPeriodicalDate(current_date, alarm_date))
410
      test_suite.setPingDate()
411
      return portal.portal_task_distribution.createTestResult(name,
412
           revision, test_name_list, allow_restart,
413
           test_title=test_title, node_title=node_title,
414 415 416 417
           project_title=project_title)

  def _getTestNodeFromTitle(self, node_title):
    test_node_list = self._getTestNodeModule().searchFolder(
418 419 420
      portal_type="Test Node",
      title=SimpleQuery(comparison_operator='=', title=node_title),
    )
421 422 423 424 425 426 427
    assert len(test_node_list) == 1, "We found %i test nodes for %s" % (
                                      len(test_node_list), node_title)
    test_node = test_node_list[0].getObject()
    return test_node

  def _getTestSuiteFromTitle(self, suite_title):
    test_suite_list = self._getTestSuiteModule().searchFolder(
428 429 430
      portal_type='Test Suite',
      title=SimpleQuery(comparison_operator='=', title=suite_title),
      validation_state='validated')
431
    assert len(test_suite_list) <= 1, "We found %i test suite for %s" % (
432
                                      len(test_suite_list), suite_title)
433 434 435
    test_suite = None
    if len(test_suite_list):
      test_suite = test_suite_list[0].getObject()
436
    return test_suite
437 438 439 440 441 442 443 444

  security.declarePublic("startUnitTest")
  def startUnitTest(self,test_result_path,exclude_list=()):
    """
    Here this is only a proxy to the task distribution tool
    """
    LOG('ERP5ProjectUnitTestDistributor.startUnitTest', 0, test_result_path)
    portal = self.getPortalObject()
445
    return portal.portal_task_distribution.startUnitTest(test_result_path,exclude_list)
446 447 448 449 450 451 452 453

  security.declarePublic("stopUnitTest")
  def stopUnitTest(self,test_path,status_dict):
    """
    Here this is only a proxy to the task distribution tool
    """
    LOG('ERP5ProjectUnitTestDistributor.stop_unit_test', 0, test_path)
    portal = self.getPortalObject()
454
    return portal.portal_task_distribution.stopUnitTest(test_path, status_dict)
455 456 457 458 459 460 461 462 463

  security.declarePublic("generateConfiguration")
  def generateConfiguration(self, test_suite_title, batch_mode=0):
    """
    return the list of configuration to create instances, in the case of ERP5 unit tests,
    we will have only one configuration (unlike scalability tests). But for API consistency,
    always return a list.
    """
    test_suite = self._getTestSuiteFromTitle(test_suite_title)
464 465 466 467 468 469 470
    generated_configuration = {"configuration_list": [{}]}
    if test_suite is not None:
      cluster_configuration = test_suite.getClusterConfiguration() or '{}'
      try:
        generated_configuration = {"configuration_list": [json.loads(cluster_configuration)]}
      except ValueError:
        pass
471 472 473
    if batch_mode:
      return generated_configuration
    return json.dumps(generated_configuration)