blob: d2dca3bee977e460411f88d78b3b4fde6246e129 [file] [log] [blame]
Sapan Bhatiafe16ae42016-01-14 11:44:43 -05001#!/usr/bin/env python
2import jinja2
3import tempfile
4import os
5import json
6import pdb
7import string
8import random
9import re
10import traceback
11import subprocess
12from xos.config import Config, XOS_DIR
Scott Baker0ae266e2016-01-14 15:30:20 -080013from xos.logger import observer_logger
Sapan Bhatiafe16ae42016-01-14 11:44:43 -050014
15try:
16 step_dir = Config().observer_steps_dir
17 sys_dir = Config().observer_sys_dir
18except:
Sapan Bhatia298f44c2016-01-18 09:19:42 -050019 step_dir = XOS_DIR + '/synchronizers/openstack/steps'
Sapan Bhatiafe16ae42016-01-14 11:44:43 -050020 sys_dir = '/opt/opencloud'
21
22os_template_loader = jinja2.FileSystemLoader( searchpath=step_dir)
23os_template_env = jinja2.Environment(loader=os_template_loader)
24
25def parse_output(msg):
26 lines = msg.splitlines()
27 results = []
28
29 observer_logger.info(msg)
30
31 for l in lines:
32 magic_str = 'ok: [127.0.0.1] => '
33 magic_str2 = 'changed: [127.0.0.1] => '
34 if (l.startswith(magic_str)):
35 w = len(magic_str)
36 str = l[w:]
37 d = json.loads(str)
38 results.append(d)
39 elif (l.startswith(magic_str2)):
40 w = len(magic_str2)
41 str = l[w:]
42 d = json.loads(str)
43 results.append(d)
44
45
46 return results
47
48def parse_unreachable(msg):
49 total_unreachable=0
50 total_failed=0
51 for l in msg.splitlines():
52 x = re.findall('ok=([0-9]+).*changed=([0-9]+).*unreachable=([0-9]+).*failed=([0-9]+)', l)
53 if x:
54 (ok, changed, unreachable, failed) = x[0]
55 ok=int(ok)
56 changed=int(changed)
57 unreachable=int(unreachable)
58 failed=int(failed)
59
60 total_unreachable += unreachable
61 total_failed += failed
62 return {'unreachable':total_unreachable,'failed':total_failed}
63
64
65def id_generator(size=6, chars=string.ascii_uppercase + string.digits):
66 return ''.join(random.choice(chars) for _ in range(size))
67
68def shellquote(s):
69 return "'" + s.replace("'", "'\\''") + "'"
70
71def get_playbook_fn(opts, path):
72 if not opts.get("ansible_tag", None):
73 # if no ansible_tag is in the options, then generate a unique one
74 objname= id_generator()
75 opts = opts.copy()
76 opts["ansible_tag"] = objname
77
78 objname = opts["ansible_tag"]
79
80 os.system('mkdir -p %s' % os.path.join(sys_dir, path))
81 return (opts, os.path.join(sys_dir,path,objname))
82
83def run_template(name, opts, path='', expected_num=None, ansible_config=None, ansible_hosts=None, run_ansible_script=None):
84 template = os_template_env.get_template(name)
85 buffer = template.render(opts)
86
87 (opts, fqp) = get_playbook_fn(opts, path)
88
89 f = open(fqp,'w')
90 f.write(buffer)
91 f.flush()
92
93 # This is messy -- there's no way to specify ansible config file from
94 # the command line, but we can specify it using the environment.
95 env = os.environ.copy()
96 if ansible_config:
97 env["ANSIBLE_CONFIG"] = ansible_config
98 if ansible_hosts:
99 env["ANSIBLE_HOSTS"] = ansible_hosts
100
101 if (not Config().observer_pretend):
102 if not run_ansible_script:
Scott Baker35dcea52016-01-20 15:57:30 -0800103 run_ansible_script = os.path.join(XOS_DIR, "synchronizers/base/run_ansible")
Sapan Bhatiafe16ae42016-01-14 11:44:43 -0500104
105 process = subprocess.Popen("%s %s" % (run_ansible_script, shellquote(fqp)), shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env)
106 msg = process.stdout.read()
107 err_msg = process.stderr.read()
108
109 if getattr(Config(), "observer_save_ansible_output", False):
110 try:
111 open(fqp+".out","w").write(msg)
112 open(fqp+".err","w").write(err_msg)
113 except:
114 # fail silently
115 pass
116
117 else:
118 msg = open(fqp+'.out').read()
119
120 try:
121 ok_results = parse_output(msg)
122 if (expected_num is not None) and (len(ok_results) != expected_num):
123 raise ValueError('Unexpected num %s!=%d' % (str(expected_num), len(ok_results)) )
124
125 parsed = parse_unreachable(msg)
126 total_unreachable = parsed['unreachable']
127 failed = parsed['failed']
128 if (failed):
129 raise ValueError('Ansible playbook failed.')
130
131 if (total_unreachable > 0):
132 raise ValueError("Unreachable results in ansible recipe")
133 except ValueError,e:
134 all_fatal = [e.message] + re.findall(r'^msg: (.*)',msg,re.MULTILINE)
135 all_fatal2 = re.findall(r'^ERROR: (.*)',msg,re.MULTILINE)
136
137 all_fatal.extend(all_fatal2)
138 try:
139 error = ' // '.join(all_fatal)
140 except:
141 pass
142 raise Exception(error)
143
144 return ok_results
145
146def run_template_ssh(name, opts, path='', expected_num=None):
147 instance_name = opts["instance_name"]
148 hostname = opts["hostname"]
149 private_key = opts["private_key"]
150 baremetal_ssh = opts.get("baremetal_ssh",False)
151 if baremetal_ssh:
152 # no instance_id or nat_ip for baremetal
153 # we never proxy to baremetal
154 proxy_ssh = False
155 else:
156 instance_id = opts["instance_id"]
157 nat_ip = opts["nat_ip"]
158 try:
159 proxy_ssh = Config().observer_proxy_ssh
160 except:
161 proxy_ssh = True
162
163 (opts, fqp) = get_playbook_fn(opts, path)
164 private_key_pathname = fqp + ".key"
165 config_pathname = fqp + ".config"
166 hosts_pathname = fqp + ".hosts"
167
168 f = open(private_key_pathname, "w")
169 f.write(private_key)
170 f.close()
171
172 f = open(config_pathname, "w")
173 f.write("[ssh_connection]\n")
174 if proxy_ssh:
175 proxy_command = "ProxyCommand ssh -q -i %s -o StrictHostKeyChecking=no %s@%s" % (private_key_pathname, instance_id, hostname)
176 f.write('ssh_args = -o "%s"\n' % proxy_command)
177 f.write('scp_if_ssh = True\n')
178 f.write('pipelining = True\n')
179 f.write('\n[defaults]\n')
180 f.write('host_key_checking = False\n')
181 f.close()
182
183 f = open(hosts_pathname, "w")
184 f.write("[%s]\n" % instance_name)
185 if proxy_ssh or baremetal_ssh:
186 f.write("%s ansible_ssh_private_key_file=%s\n" % (hostname, private_key_pathname))
187 else:
188 # acb: Login user is hardcoded, this is not great
189 f.write("%s ansible_ssh_private_key_file=%s ansible_ssh_user=ubuntu\n" % (nat_ip, private_key_pathname))
190 f.close()
191
192 # SSH will complain if private key is world or group readable
193 os.chmod(private_key_pathname, 0600)
194
195 print "ANSIBLE_CONFIG=%s" % config_pathname
196 print "ANSIBLE_HOSTS=%s" % hosts_pathname
197
Srikanth Vavilapalliae1acd62016-01-25 20:06:43 -0500198 return run_template(name, opts, path, ansible_config = config_pathname, ansible_hosts = hosts_pathname, run_ansible_script="/opt/xos/synchronizers/base/run_ansible_verbose")
Sapan Bhatiafe16ae42016-01-14 11:44:43 -0500199
200
201
202def main():
203 run_template('ansible/sync_user_deployments.yaml',{ "endpoint" : "http://172.31.38.128:5000/v2.0/",
204 "name" : "Sapan Bhatia",
205 "email": "gwsapan@gmail.com",
206 "password": "foobar",
207 "admin_user":"admin",
208 "admin_password":"6a789bf69dd647e2",
209 "admin_tenant":"admin",
210 "tenant":"demo",
211 "roles":['user','admin'] })