Ambari自定义服务开发-常用函数
[toc]
自定义开发服务时,经常会用到的函数汇总
# 判断某个rpm是否安装
# 如果rpm存在则卸载
def remove_rpm(self,rpm_name):
if self.rpm_install_status(rpm_name):
cmd = 'rpm -qa | grep "{0}" | xargs rpm -e'.format(rpm_name)
Execute(cmd)
# 判断某个rpm是否安装
def rpm_install_status(self, rpm_name):
cmd = 'rpm -qa | grep -q "{0}" && echo "True" || echo "False"'.format(rpm_name)
result = subprocess.check_output(cmd ,
stderr=subprocess.STDOUT,
shell=True,
universal_newlines=True).strip()
if result == 'True':
return True
else:
return False
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# 根据PID判断某个进程是否存在
# 根据PID查询进程是否存在
def process_exist(self, pid):
try:
# kill 0 并不会真实kill进程
os.kill(pid, 0)
logger.info("process already exists! ")
process_is_exist = True
except OSError:
logger.error("Process with pid {0} is not running.".format(pid))
process_is_exist = False
return process_is_exist
1
2
3
4
5
6
7
8
9
10
11
2
3
4
5
6
7
8
9
10
11
# 根据进程名称查找某一个进程是否存在
def find_hugegraph_pid(self, env):
import params
env.set_params(params)
cmd = "ps -ef | grep \'{0}\' | grep -v grep | awk \'{ {print $2}}\'".format('com.xxx')
result = subprocess.check_output(cmd, stderr=subprocess.STDOUT, shell=True, universal_newlines=True).strip()
if result.isdigit():
return result
else:
return -1
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
返回:
- -1:进程不存在
- 其他:进程ID
# 以某个用户执行sh文件
try:
# 启动HugeGraph服务,并打印启动输出内容
print subprocess.check_output(format('sudo -i -u '+params.hugegraph_user+' {hugegraph_base_dir}/bin/start-hugegraph.sh'),
stderr=subprocess.STDOUT,
shell=True,
universal_newlines=True)
except subprocess.CalledProcessError as e:
error_output = e.output
print(error_output)
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
# 删除目录
# 删除pid目录
Directory([params.hubble_pid_dir],
action="delete")
1
2
3
2
3
# 创建目录
# 创建pid目录
Directory([params.hubble_log_dir, params.hubble_pid_dir],
mode=0755,
cd_access='a',
owner=params.hugegraph_user,
group=params.user_group,
create_parents=True
)
1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
# 判断文件是否存在
# 判断文件是否存在
def fileExists(self,file_path):
# 1代表不存在,0代表文件存在
cmd = format('[ -f "{0}" ] && echo 0 || echo 1'.format(file_path))
print cmd
result = subprocess.check_output(cmd,
stderr=subprocess.STDOUT,
shell=True,
universal_newlines=True)
if int(result.strip()) == 1:
return False
else:
return True
1
2
3
4
5
6
7
8
9
10
11
12
13
2
3
4
5
6
7
8
9
10
11
12
13
上次更新: 2024/04/08, 16:09:09