AMBARI-20634. Cleanup unused files and data in ambari-agent code (aonishuk)
Project: http://git-wip-us.apache.org/repos/asf/ambari/repo Commit: http://git-wip-us.apache.org/repos/asf/ambari/commit/c28b797d Tree: http://git-wip-us.apache.org/repos/asf/ambari/tree/c28b797d Diff: http://git-wip-us.apache.org/repos/asf/ambari/diff/c28b797d Branch: refs/heads/branch-feature-AMBARI-14714 Commit: c28b797d2723ee11725db2b68c7ae0cabda5bc25 Parents: 5b36cdf Author: Andrew Onishuk <[email protected]> Authored: Tue Oct 3 16:14:20 2017 +0300 Committer: Andrew Onishuk <[email protected]> Committed: Tue Oct 3 16:14:20 2017 +0300 ---------------------------------------------------------------------- .../main/python/ambari_agent/AmbariConfig.py | 74 +------- .../main/python/ambari_agent/ProcessHelper.py | 71 -------- .../src/main/python/ambari_agent/StatusCheck.py | 142 --------------- .../src/main/python/ambari_agent/main.py | 12 +- .../src/test/python/ambari_agent/TestMain.py | 8 +- .../python/ambari_agent/TestProcessHelper.py | 70 -------- .../test/python/ambari_agent/TestStatusCheck.py | 180 ------------------- 7 files changed, 14 insertions(+), 543 deletions(-) ---------------------------------------------------------------------- http://git-wip-us.apache.org/repos/asf/ambari/blob/c28b797d/ambari-agent/src/main/python/ambari_agent/AmbariConfig.py ---------------------------------------------------------------------- diff --git a/ambari-agent/src/main/python/ambari_agent/AmbariConfig.py b/ambari-agent/src/main/python/ambari_agent/AmbariConfig.py index 95e4712..fcbc21c 100644 --- a/ambari-agent/src/main/python/ambari_agent/AmbariConfig.py +++ b/ambari-agent/src/main/python/ambari_agent/AmbariConfig.py @@ -30,6 +30,9 @@ from ambari_commons.os_family_impl import OsFamilyFuncImpl, OsFamilyImpl logger = logging.getLogger(__name__) +""" +The below config is necessary only for unit tests. +""" content = """ [server] @@ -75,77 +78,6 @@ log_command_executes = 0 """.format(ps=os.sep) -servicesToPidNames = { - 'GLUSTERFS': 'glusterd.pid$', - 'NAMENODE': 'hadoop-{USER}-namenode.pid$', - 'SECONDARY_NAMENODE': 'hadoop-{USER}-secondarynamenode.pid$', - 'DATANODE': 'hadoop-{USER}-datanode.pid$', - 'JOBTRACKER': 'hadoop-{USER}-jobtracker.pid$', - 'TASKTRACKER': 'hadoop-{USER}-tasktracker.pid$', - 'RESOURCEMANAGER': 'yarn-{USER}-resourcemanager.pid$', - 'NODEMANAGER': 'yarn-{USER}-nodemanager.pid$', - 'HISTORYSERVER': 'mapred-{USER}-historyserver.pid$', - 'JOURNALNODE': 'hadoop-{USER}-journalnode.pid$', - 'ZKFC': 'hadoop-{USER}-zkfc.pid$', - 'OOZIE_SERVER': 'oozie.pid', - 'ZOOKEEPER_SERVER': 'zookeeper_server.pid', - 'FLUME_SERVER': 'flume-node.pid', - 'TEMPLETON_SERVER': 'templeton.pid', - 'HBASE_MASTER': 'hbase-{USER}-master.pid', - 'HBASE_REGIONSERVER': 'hbase-{USER}-regionserver.pid', - 'HCATALOG_SERVER': 'webhcat.pid', - 'KERBEROS_SERVER': 'kadmind.pid', - 'HIVE_SERVER': 'hive-server.pid', - 'HIVE_METASTORE': 'hive.pid', - 'HIVE_SERVER_INTERACTIVE': 'hive-interactive.pid', - 'MYSQL_SERVER': 'mysqld.pid', - 'HUE_SERVER': '/var/run/hue/supervisor.pid', - 'WEBHCAT_SERVER': 'webhcat.pid', -} - -# Each service, which's pid depends on user should provide user mapping -servicesToLinuxUser = { - 'NAMENODE': 'hdfs_user', - 'SECONDARY_NAMENODE': 'hdfs_user', - 'DATANODE': 'hdfs_user', - 'JOURNALNODE': 'hdfs_user', - 'ZKFC': 'hdfs_user', - 'JOBTRACKER': 'mapred_user', - 'TASKTRACKER': 'mapred_user', - 'RESOURCEMANAGER': 'yarn_user', - 'NODEMANAGER': 'yarn_user', - 'HISTORYSERVER': 'mapred_user', - 'HBASE_MASTER': 'hbase_user', - 'HBASE_REGIONSERVER': 'hbase_user', -} - -pidPathVars = [ - {'var': 'glusterfs_pid_dir_prefix', - 'defaultValue': '/var/run'}, - {'var': 'hadoop_pid_dir_prefix', - 'defaultValue': '/var/run/hadoop'}, - {'var': 'hadoop_pid_dir_prefix', - 'defaultValue': '/var/run/hadoop'}, - {'var': 'hbase_pid_dir', - 'defaultValue': '/var/run/hbase'}, - {'var': 'zk_pid_dir', - 'defaultValue': '/var/run/zookeeper'}, - {'var': 'oozie_pid_dir', - 'defaultValue': '/var/run/oozie'}, - {'var': 'hcat_pid_dir', - 'defaultValue': '/var/run/webhcat'}, - {'var': 'hive_pid_dir', - 'defaultValue': '/var/run/hive'}, - {'var': 'mysqld_pid_dir', - 'defaultValue': '/var/run/mysqld'}, - {'var': 'hcat_pid_dir', - 'defaultValue': '/var/run/webhcat'}, - {'var': 'yarn_pid_dir_prefix', - 'defaultValue': '/var/run/hadoop-yarn'}, - {'var': 'mapred_pid_dir_prefix', - 'defaultValue': '/var/run/hadoop-mapreduce'}, -] - class AmbariConfig: TWO_WAY_SSL_PROPERTY = "security.server.two_way_ssl" http://git-wip-us.apache.org/repos/asf/ambari/blob/c28b797d/ambari-agent/src/main/python/ambari_agent/ProcessHelper.py ---------------------------------------------------------------------- diff --git a/ambari-agent/src/main/python/ambari_agent/ProcessHelper.py b/ambari-agent/src/main/python/ambari_agent/ProcessHelper.py deleted file mode 100644 index bc2f827..0000000 --- a/ambari-agent/src/main/python/ambari_agent/ProcessHelper.py +++ /dev/null @@ -1,71 +0,0 @@ -#!/usr/bin/env python - -''' -Licensed to the Apache Software Foundation (ASF) under one -or more contributor license agreements. See the NOTICE file -distributed with this work for additional information -regarding copyright ownership. The ASF licenses this file -to you 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. -''' - -import os -import logging -import traceback -import sys -from ambari_commons.shell import getTempFiles - -logger = logging.getLogger() - -if 'AMBARI_PID_DIR' in os.environ: - piddir = os.environ['AMBARI_PID_DIR'] -else: - piddir = "/var/run/ambari-agent" - -pidfile = os.path.join(piddir, "ambari-agent.pid") - - -def _clean(): - logger.info("Removing pid file") - try: - os.unlink(pidfile) - except Exception as ex: - traceback.print_exc() - logger.warn("Unable to remove pid file: %s", ex) - - logger.info("Removing temp files") - for f in getTempFiles(): - if os.path.exists(f): - try: - os.unlink(f) - except Exception as ex: - traceback.print_exc() - logger.warn("Unable to remove: %s, %s", f, ex) - - -def stopAgent(): - _clean() - sys.exit(0) - - -def restartAgent(): - _clean() - - executable = sys.executable - args = sys.argv[:] - args.insert(0, executable) - - logger.info("Restarting self: %s %s", executable, args) - - os.execvp(executable, args) - - http://git-wip-us.apache.org/repos/asf/ambari/blob/c28b797d/ambari-agent/src/main/python/ambari_agent/StatusCheck.py ---------------------------------------------------------------------- diff --git a/ambari-agent/src/main/python/ambari_agent/StatusCheck.py b/ambari-agent/src/main/python/ambari_agent/StatusCheck.py deleted file mode 100644 index 5231f72..0000000 --- a/ambari-agent/src/main/python/ambari_agent/StatusCheck.py +++ /dev/null @@ -1,142 +0,0 @@ -#!/usr/bin/env python - -''' -Licensed to the Apache Software Foundation (ASF) under one -or more contributor license agreements. See the NOTICE file -distributed with this work for additional information -regarding copyright ownership. The ASF licenses this file -to you 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. -''' - -import logging -import os -import re -import string -from ambari_commons.shell import shellRunner - - -logger = logging.getLogger() - - -class StatusCheck: - - USER_PATTERN='{USER}' - firstInit = True - - def listFiles(self, dir): - basedir = dir - logger.debug("Files in " + os.path.abspath(dir) + ": ") - subdirlist = [] - try: - if os.path.isdir(dir): - for item in os.listdir(dir): - if os.path.isfile(item) and item.endswith('.pid'): - self.pidFilesDict[item.split(os.sep).pop()] = os.getcwd() + os.sep + item - else: - subdirlist.append(os.path.join(basedir, item)) - for subdir in subdirlist: - self.listFiles(subdir) - else: - if dir.endswith('.pid'): - self.pidFilesDict[dir.split(os.sep).pop()] = dir - except OSError as e: - logger.info(e.strerror + ' to ' + e.filename) - - def fillDirValues(self): - try: - for pidVar in self.pidPathVars: - pidVarName = pidVar['var'] - pidDefaultvalue = pidVar['defaultValue'] - if self.globalConfig.has_key(pidVarName): - self.pidPathes.append(self.globalConfig[pidVarName]) - else: - self.pidPathes.append(pidDefaultvalue) - except Exception as e: - logger.error("Error while filling directories values " + str(e)) - - def __init__(self, serviceToPidDict, pidPathVars, globalConfig, - servicesToLinuxUser): - - self.serToPidDict = serviceToPidDict.copy() - self.pidPathVars = pidPathVars - self.pidPathes = [] - self.sh = shellRunner() - self.pidFilesDict = {} - self.globalConfig = globalConfig - self.servicesToLinuxUser = servicesToLinuxUser - - self.fillDirValues() - - for pidPath in self.pidPathes: - self.listFiles(pidPath) - - for service, pid in self.serToPidDict.items(): - if self.servicesToLinuxUser.has_key(service): - linuxUserKey = self.servicesToLinuxUser[service] - if self.globalConfig.has_key(linuxUserKey): - self.serToPidDict[service] = string.replace(pid, self.USER_PATTERN, - self.globalConfig[linuxUserKey]) - else: - if self.USER_PATTERN in pid: - logger.error('There is no linux user mapping for component: ' + service) - - if StatusCheck.firstInit: - logger.info('Service to pid dictionary: ' + str(self.serToPidDict)) - StatusCheck.firstInit = False - else: - logger.debug('Service to pid dictionary: ' + str(self.serToPidDict)) - - def getIsLive(self, pidPath): - - if not pidPath: - return False - - isLive = False - pid = -1 - try: - pidFile = open(pidPath, 'r') - pid = int(pidFile.readline()) - except IOError, e: - logger.warn("Can not open file " + str(pidPath) + " due to " + str(e)) - return isLive - res = self.sh.run(['ps -p', str(pid), '-f']) - lines = res['output'].strip().split(os.linesep) - try: - procInfo = lines[1] - isLive = not procInfo == None - except IndexError: - logger.info("Process is dead. Checking " + str(pidPath)) - return isLive - - def getStatus(self, serviceCode): - try: - pidPath = None - pidPattern = self.serToPidDict[serviceCode] - logger.debug('pidPattern: ' + pidPattern) - except KeyError as e: - logger.warn('There is no mapping for ' + serviceCode) - return None - try: - for pidFile in self.pidFilesDict.keys(): - if re.match(pidPattern, pidFile): - pidPath = self.pidFilesDict[pidFile] - logger.debug('pidPath: ' + str(pidPath)) - result = self.getIsLive(pidPath) - return result - except KeyError: - logger.info('Pid file was not found') - return False - - def getSerToPidDict(self): - return self.serToPidDict - http://git-wip-us.apache.org/repos/asf/ambari/blob/c28b797d/ambari-agent/src/main/python/ambari_agent/main.py ---------------------------------------------------------------------- diff --git a/ambari-agent/src/main/python/ambari_agent/main.py b/ambari-agent/src/main/python/ambari_agent/main.py index 19c92b0..5fcd051 100644 --- a/ambari-agent/src/main/python/ambari_agent/main.py +++ b/ambari-agent/src/main/python/ambari_agent/main.py @@ -89,7 +89,6 @@ import time import locale import platform import ConfigParser -import ProcessHelper import resource from logging.handlers import SysLogHandler from Controller import Controller @@ -118,6 +117,9 @@ agentPid = os.getpid() # Global variables to be set later. home_dir = "" +agent_piddir = os.environ['AMBARI_PID_DIR'] if 'AMBARI_PID_DIR' in os.environ else "/var/run/ambari-agent" +agent_pidfile = os.path.join(agent_piddir, "ambari-agent.pid") + config = AmbariConfig.AmbariConfig() # TODO AMBARI-18733, remove this global variable and calculate it based on home_dir once it is set. @@ -260,8 +262,8 @@ def perform_prestart_checks(expected_hostname): logger.error(msg) sys.exit(1) # Check if there is another instance running - if os.path.isfile(ProcessHelper.pidfile) and not OSCheck.get_os_family() == OSConst.WINSRV_FAMILY: - print("%s already exists, exiting" % ProcessHelper.pidfile) + if os.path.isfile(agent_pidfile) and not OSCheck.get_os_family() == OSConst.WINSRV_FAMILY: + print("%s already exists, exiting" % agent_pidfile) sys.exit(1) # check if ambari prefix exists elif config.has_option('agent', 'prefix') and not os.path.isdir(os.path.abspath(config.get('agent', 'prefix'))): @@ -281,14 +283,14 @@ def perform_prestart_checks(expected_hostname): def daemonize(): pid = str(os.getpid()) - file(ProcessHelper.pidfile, 'w').write(pid) + file(agent_pidfile, 'w').write(pid) def stop_agent(): # stop existing Ambari agent pid = -1 runner = shellRunner() try: - with open(ProcessHelper.pidfile, 'r') as f: + with open(agent_pidfile, 'r') as f: pid = f.read() pid = int(pid) http://git-wip-us.apache.org/repos/asf/ambari/blob/c28b797d/ambari-agent/src/test/python/ambari_agent/TestMain.py ---------------------------------------------------------------------- diff --git a/ambari-agent/src/test/python/ambari_agent/TestMain.py b/ambari-agent/src/test/python/ambari_agent/TestMain.py index a04b85d..504ca08 100644 --- a/ambari-agent/src/test/python/ambari_agent/TestMain.py +++ b/ambari-agent/src/test/python/ambari_agent/TestMain.py @@ -224,14 +224,14 @@ class TestMain(unittest.TestCase): def test_daemonize_and_stop(self, exists_mock, sleep_mock): from ambari_commons.shell import shellRunnerLinux - oldpid = ProcessHelper.pidfile + oldpid = main.agent_pidfile pid = str(os.getpid()) _, tmpoutfile = tempfile.mkstemp() - ProcessHelper.pidfile = tmpoutfile + main.agent_pidfile = tmpoutfile # Test daemonization main.daemonize() - saved = open(ProcessHelper.pidfile, 'r').read() + saved = open(main.agent_pidfile, 'r').read() self.assertEqual(pid, saved) main.GRACEFUL_STOP_TRIES = 1 @@ -269,7 +269,7 @@ class TestMain(unittest.TestCase): call(['ambari-sudo.sh', 'kill', '-9', pid])]) # Restore - ProcessHelper.pidfile = oldpid + main.pidfile = oldpid os.remove(tmpoutfile) @patch("os.rmdir") http://git-wip-us.apache.org/repos/asf/ambari/blob/c28b797d/ambari-agent/src/test/python/ambari_agent/TestProcessHelper.py ---------------------------------------------------------------------- diff --git a/ambari-agent/src/test/python/ambari_agent/TestProcessHelper.py b/ambari-agent/src/test/python/ambari_agent/TestProcessHelper.py deleted file mode 100644 index f30d45d..0000000 --- a/ambari-agent/src/test/python/ambari_agent/TestProcessHelper.py +++ /dev/null @@ -1,70 +0,0 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- - -''' -Licensed to the Apache Software Foundation (ASF) under one -or more contributor license agreements. See the NOTICE file -distributed with this work for additional information -regarding copyright ownership. The ASF licenses this file -to you 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. -''' - -import os -import tempfile -import unittest -from mock.mock import patch, MagicMock -from ambari_agent import ProcessHelper - -from only_for_platform import not_for_platform, PLATFORM_WINDOWS - -@not_for_platform(PLATFORM_WINDOWS) -class TestProcessHelper(unittest.TestCase): - - @patch.object(ProcessHelper, "getTempFiles") - def test_clean(self, getTempFilesMock): - - tf1 = tempfile.NamedTemporaryFile(delete=False) - tf2 = tempfile.NamedTemporaryFile(delete=False) - tf3 = tempfile.NamedTemporaryFile(delete=False) - - getTempFilesMock.return_value = [tf2.name, tf3.name] - ProcessHelper.pidfile = tf1.name - ProcessHelper.logger = MagicMock() - - ProcessHelper._clean() - - self.assertFalse(os.path.exists(tf1.name)) - self.assertFalse(os.path.exists(tf2.name)) - self.assertFalse(os.path.exists(tf3.name)) - - - @patch("sys.exit") - @patch.object(ProcessHelper, "_clean") - def test_stopAgent(self, _clean_mock, sys_exit_mock): - - ProcessHelper.stopAgent() - self.assertTrue(_clean_mock.called) - self.assertTrue(sys_exit_mock.called) - - - @patch("os.execvp") - @patch.object(ProcessHelper, "_clean") - def test_restartAgent(self, _clean_mock, execMock): - - ProcessHelper.logger = MagicMock() - ProcessHelper.restartAgent() - - self.assertTrue(_clean_mock.called) - self.assertTrue(execMock.called) - self.assertEqual(2, len(execMock.call_args_list[0])) - http://git-wip-us.apache.org/repos/asf/ambari/blob/c28b797d/ambari-agent/src/test/python/ambari_agent/TestStatusCheck.py ---------------------------------------------------------------------- diff --git a/ambari-agent/src/test/python/ambari_agent/TestStatusCheck.py b/ambari-agent/src/test/python/ambari_agent/TestStatusCheck.py deleted file mode 100644 index 34c57cc..0000000 --- a/ambari-agent/src/test/python/ambari_agent/TestStatusCheck.py +++ /dev/null @@ -1,180 +0,0 @@ -#!/usr/bin/env python - -''' -Licensed to the Apache Software Foundation (ASF) under one -or more contributor license agreements. See the NOTICE file -distributed with this work for additional information -regarding copyright ownership. The ASF licenses this file -to you 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. -''' -import string -import random -import os -from unittest import TestCase -from ambari_commons import OSCheck -from ambari_agent.StatusCheck import StatusCheck -import logging - -from mock.mock import patch -from mock.mock import MagicMock - -from only_for_platform import os_distro_value - -USERNAME_LENGTH=10 -USERNAME_CHARS=string.ascii_uppercase +string.ascii_lowercase + string.digits + '-_' - -PID_DIR='/pids_dir' - -COMPONENT_LIVE = 'LIVE_COMPONENT' -COMPONENT_LIVE_PID = 'live_' + StatusCheck.USER_PATTERN + '_comp.pid' - -COMPONENT_DEAD = 'DEAD_COMPONENT' -COMPONENT_DEAD_PID = 'dead_' + StatusCheck.USER_PATTERN + '_comp.pid' - -class TestStatusCheck(TestCase): - - logger = logging.getLogger() - - def generateUserName(self): - return ''.join(random.choice(USERNAME_CHARS) for x in range(USERNAME_LENGTH)) - - def setUp(self): - - self.pidPathVars = [ - {'var' : '', - 'defaultValue' : PID_DIR} - ] - - self.serviceToPidDict = { - COMPONENT_LIVE : COMPONENT_LIVE_PID, - COMPONENT_DEAD : COMPONENT_DEAD_PID - } - - live_user = self.generateUserName() - self.logger.info('Live user: ' + live_user) - self.live_pid_file_name = string.replace(COMPONENT_LIVE_PID, StatusCheck.USER_PATTERN, live_user) - self.live_pid_full_path = PID_DIR + os.sep + self.live_pid_file_name - - dead_user = self.generateUserName() - self.logger.info('Dead user: ' + live_user) - self.dead_pid_file_name = string.replace(COMPONENT_DEAD_PID, StatusCheck.USER_PATTERN, dead_user) - self.dead_pid_full_path = PID_DIR + os.sep + self.dead_pid_file_name - - self.pidFilesDict = {self.live_pid_file_name : self.live_pid_full_path, - self.dead_pid_file_name : self.dead_pid_full_path} - - self.is_live_values = {self.live_pid_full_path : True, - self.dead_pid_full_path : False} - - self.servicesToLinuxUser = {COMPONENT_LIVE : 'live_user', - COMPONENT_DEAD : 'dead_user'} - - self.globalConfig = {'live_user' : live_user, - 'dead_user' : dead_user} - - - # Ensure that status checker return True for running process - @patch.object(OSCheck, "os_distribution", new = MagicMock(return_value = os_distro_value)) - @patch.object(StatusCheck, 'getIsLive') - def test_live(self, get_is_live_mock): - - statusCheck = StatusCheck(self.serviceToPidDict, self.pidPathVars, - self.globalConfig, self.servicesToLinuxUser) - - self.assertTrue(StatusCheck.USER_PATTERN in self.serviceToPidDict[COMPONENT_LIVE]) - self.assertTrue(StatusCheck.USER_PATTERN in self.serviceToPidDict[COMPONENT_DEAD]) - - statusCheck.pidFilesDict = self.pidFilesDict - - get_is_live_mock.side_effect = lambda pid_path : self.is_live_values[pid_path] - - status = statusCheck.getStatus(COMPONENT_LIVE) - self.assertEqual(status, True) - - @patch.object(OSCheck, "os_distribution", new = MagicMock(return_value = os_distro_value)) - @patch.object(logger, 'info') - def test_dont_relog_serToPidDict(self, logger_info_mock): - TestStatusCheck.timesLogged = 0 - - def my_side_effect(*args, **kwargs): - TestStatusCheck.timesLogged += args[0].find('Service to pid dictionary: ')+1 - - - logger_info_mock.side_effect = my_side_effect - - # call this three times - statusCheck = StatusCheck(self.serviceToPidDict, self.pidPathVars, - self.globalConfig, self.servicesToLinuxUser) - statusCheck = StatusCheck(self.serviceToPidDict, self.pidPathVars, - self.globalConfig, self.servicesToLinuxUser) - statusCheck = StatusCheck(self.serviceToPidDict, self.pidPathVars, - self.globalConfig, self.servicesToLinuxUser) - # logged not more then once - self.assert_(TestStatusCheck.timesLogged <= 1, "test_dont_relog_serToPidDict logged more then once") - - # Ensure that status checker return True for running process even if multiple - # pids for a service component exist - @patch.object(OSCheck, "os_distribution", new = MagicMock(return_value = os_distro_value)) - @patch.object(StatusCheck, 'getIsLive') - def test_live_if_multiple_pids(self, get_is_live_mock): - - one_more_pid_file_name = string.replace(COMPONENT_LIVE_PID, StatusCheck.USER_PATTERN, - 'any_other_linux_user') - one_more_pid_full_path = PID_DIR + os.sep + one_more_pid_file_name - - self.pidFilesDict[one_more_pid_file_name] = one_more_pid_full_path - self.is_live_values[one_more_pid_full_path] = False - - statusCheck = StatusCheck(self.serviceToPidDict, self.pidPathVars, - self.globalConfig, self.servicesToLinuxUser) - - statusCheck.pidFilesDict = self.pidFilesDict - - get_is_live_mock.side_effect = lambda pid_path : self.is_live_values[pid_path] - - status = statusCheck.getStatus(COMPONENT_LIVE) - self.assertEqual(status, True) - - # Ensure that status checker prints error message if there is no linux user - # for service, which pid depends on user - @patch.object(OSCheck, "os_distribution", new = MagicMock(return_value = os_distro_value)) - @patch.object(StatusCheck, 'getIsLive') - @patch.object(logger, "error") - def test_no_user_mapping(self, error_mock, get_is_live_mock): - - - badServiceToPidDict = self.serviceToPidDict.copy() - badServiceToPidDict['BAD_COMPONENT'] = 'prefix' + StatusCheck.USER_PATTERN - - statusCheck = StatusCheck(badServiceToPidDict, self.pidPathVars, - self.globalConfig, self.servicesToLinuxUser) - - statusCheck.pidFilesDict = self.pidFilesDict - - get_is_live_mock.side_effect = lambda pid_path : self.is_live_values[pid_path] - - status = statusCheck.getStatus(COMPONENT_LIVE) - self.assertTrue(error_mock.called) - - # Ensure that status checker return False for dead process - @patch.object(OSCheck, "os_distribution", new = MagicMock(return_value = os_distro_value)) - @patch.object(StatusCheck, 'getIsLive') - def test_dead(self, get_is_live_mock): - statusCheck = StatusCheck(self.serviceToPidDict, self.pidPathVars, - self.globalConfig, self.servicesToLinuxUser) - - statusCheck.pidFilesDict = self.pidFilesDict - - get_is_live_mock.side_effect = lambda pid_path : self.is_live_values[pid_path] - status = statusCheck.getStatus(COMPONENT_DEAD) - self.assertEqual(status, False)
