7 import salt.client as sclient
9 from vstf.common import cmds
11 log = logging.getLogger(__name__)
20 self.cur_path = os.path.abspath(os.path.dirname(inspect.stack()[1][1]))
21 self.salt_conf = "/etc/salt/master"
22 if not os.path.exists(self.salt_conf):
23 raise Exception("this python must be run on the salt master.")
24 self.pillar_path = str(
25 cmds.execute("grep '^pillar_roots' \
26 /etc/salt/master -A 2 | sed 1,2d | awk '{print $2}'") + '/')
27 if self.pillar_path == "":
28 log.warning("pillar path not found, make sure the pillar_roots configed")
30 os.system("mkdir -p " + self.pillar_path)
32 self.state_path = str(cmds.execute("grep '^file_roots' \
33 /etc/salt/master -A 2 | sed 1,2d | awk '{print $2}'") + '/')
34 if self.state_path == "":
35 log.warning("state path not found, make sure the file_roots configed")
37 os.system("mkdir -p " + self.state_path)
39 self.salt = sclient.LocalClient()
41 def slave_exists(self, host):
42 pslave = "/etc/salt/pki/master/minions/" + host
43 if os.path.exists(pslave):
48 def __is_dir_or_file(self, src):
49 if not os.path.exists(src):
51 if os.path.isdir(src):
53 elif os.path.isfile(src):
58 def __copy_target(self, target, flag=""):
59 if not os.path.exists(target):
60 log.error("target %(d)s not exists.", {'d': target})
64 dst = self.pillar_path
68 log.error("this file or dir not pillar or state, can not support now.")
71 if self.IS_FILE == self.__is_dir_or_file(target):
72 os.system('cp ' + target + ' ' + dst)
74 os.system("cp -r " + target + ' ' + dst)
77 def copy(self, host, src, dst):
78 """copy file or dir to slave.
80 :dst if src is a file, the dst must be like this /home/xx.py, not /home
83 '''check if the host exists on the master'''
84 if not self.slave_exists(host):
85 log.error("the host %(h)s is not held by master, please check.")
88 '''copy file to salt's file_roots'''
89 if not self.__copy_target(src, "state"):
92 if self.IS_DIR == self.__is_dir_or_file(src):
93 dir_name = os.path.basename(src)
94 self.salt.cmd(host, "cp.get_dir", ["salt://" + dir_name, dst])
95 elif self.IS_FILE == self.__is_dir_or_file(src):
96 file_name = os.path.basename(src)
97 print self.salt.cmd(host, "cp.get_file", ["salt://" + file_name, dst])
99 log.error("not file and not dir, what is it")
103 def __luxuriant_line(self, str, color):
105 return "\033[22;35;40m" + str + "\033[0m"
106 elif "green" == color:
107 return "\033[22;32;40m" + str + "\033[0m"
111 def result_check(self, ret, host):
116 for key in ret[host].keys():
117 if True == ret[host][key]['result']:
121 msg = msg + self.__luxuriant_line("Failed %d:\n" % num_f, "red")
122 msg = msg + "\t" + key + '\n'
123 msg = msg + self.__luxuriant_line("\t%s\n" % ret[host][key]['comment'], "red")
124 if True == ret[host][key]['changes'].has_key('retcode'):
125 msg = msg + "RETCODE: %s\n" % (ret[host][key]['changes']['retcode'])
126 if True == ret[host][key]['changes'].has_key('stderr'):
127 msg = msg + "STDERR: %s\n" % (ret[host][key]['changes']['stderr'])
128 if True == ret[host][key]['changes'].has_key('stdout'):
129 msg = msg + "STDOUT: %s\n" % (ret[host][key]['changes']['stdout'])
130 msg = msg + self.__luxuriant_line("total success: %d\n" % num_s, "green")
131 msg = msg + self.__luxuriant_line("failed: %d\n" % num_f, "red")
132 except Exception as e:
133 log.error("sorry, thy to check result happend error, <%(e)s>.\nret:%(ret)s",
134 {'e': e, 'ret': ret})
136 log.info(':\n' + msg)
139 def run_state(self, host, fstate, ext_pillar={}, care_result=True):
141 log.info("salt " + host + " state.sls " +
142 fstate + ' pillar=\'' + str(ext_pillar) + '\'')
143 ret = self.salt.cmd(host, 'state.sls', [fstate, 'pillar=' + str(ext_pillar)], 180, 'list')
144 except Exception as e:
145 log.error("try to init host %(host)s happend error: <%(e)s>.",
146 {'host': host, 'e': e})
147 if True == care_result:
150 if 0 != self.result_check(ret, host) and care_result:
154 def salt_cmd(self, host, cmd):
157 logging.info("Begin to run cmd %s on %s" % (host, cmd))
160 ret = self.salt.cmd(host, 'cmd.run', [cmd])
162 log.error("Remote salt execute failed.")
165 def copy_by_state(self, host, src, state_cmd, **kwargs):
166 '''the src must be a dir, and the state.sls
167 must be the name of the dir name'''
169 if not self.slave_exists(host):
170 log.error("the host %(h)s is not held by master, please check.")
173 if not self.__copy_target(src, "state"):
176 return self.run_state(host, state_cmd, kwargs, care_result=True)
178 def get_master_ip(self, host=None):
180 ret = cmds.execute("grep '^interface:' /etc/salt/master | awk '{print $2}'").strip()
183 ret = self.salt.cmd(host, "grains.item", ["master"])[host]['master']
185 log.error("salt happened error when get master ip")