RIFT OSM R1 Initial Submission
[osm/SO.git] / rwcal / plugins / vala / rwcal_openstack / rift / rwcal / openstack / prepare_vm.py
1 #!/usr/bin/env python3
2
3 #
4 # Copyright 2016 RIFT.IO Inc
5 #
6 # Licensed under the Apache License, Version 2.0 (the "License");
7 # you may not use this file except in compliance with the License.
8 # You may obtain a copy of the License at
9 #
10 # http://www.apache.org/licenses/LICENSE-2.0
11 #
12 # Unless required by applicable law or agreed to in writing, software
13 # distributed under the License is distributed on an "AS IS" BASIS,
14 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 # See the License for the specific language governing permissions and
16 # limitations under the License.
17 #
18
19 import rift.rwcal.openstack as openstack_drv
20 import logging
21 import argparse
22 import sys, os, time
23 import rwlogger
24
25 logging.basicConfig(level=logging.DEBUG)
26 logger = logging.getLogger()
27
28 rwlog_handler = rwlogger.RwLogger(category="rw-cal-log",
29 subcategory="openstack",)
30 logger.addHandler(rwlog_handler)
31 #logger.setLevel(logging.DEBUG)
32
33
34 def assign_floating_ip_address(drv, argument):
35 if not argument.floating_ip:
36 return
37
38 server = drv.nova_server_get(argument.server_id)
39 logger.info("Assigning the floating_ip: %s to VM: %s" %(argument.floating_ip, server['name']))
40
41 for i in range(120):
42 server = drv.nova_server_get(argument.server_id)
43 for network_name,network_info in server['addresses'].items():
44 if network_info:
45 if network_name == argument.mgmt_network:
46 for n_info in network_info:
47 if 'OS-EXT-IPS:type' in n_info and n_info['OS-EXT-IPS:type'] == 'fixed':
48 management_ip = n_info['addr']
49 drv.nova_floating_ip_assign(argument.server_id,
50 argument.floating_ip,
51 management_ip)
52 logger.info("Assigned floating_ip: %s to management_ip: %s" %(argument.floating_ip, management_ip))
53 return
54 logger.info("Waiting for management_ip to be assigned to server: %s" %(server['name']))
55 time.sleep(1)
56 else:
57 logger.info("No management_ip IP available to associate floating_ip for server: %s" %(server['name']))
58 return
59
60
61 def create_port_metadata(drv, argument):
62 if argument.port_metadata == False:
63 return
64
65 ### Get Management Network ID
66 network_list = drv.neutron_network_list()
67 mgmt_network_id = [net['id'] for net in network_list if net['name'] == argument.mgmt_network][0]
68 port_list = [ port for port in drv.neutron_port_list(**{'device_id': argument.server_id})
69 if port['network_id'] != mgmt_network_id ]
70 meta_data = {}
71
72 meta_data['rift-meta-ports'] = str(len(port_list))
73 port_id = 0
74 for port in port_list:
75 info = []
76 info.append('"port_name":"'+port['name']+'"')
77 if 'mac_address' in port:
78 info.append('"hw_addr":"'+port['mac_address']+'"')
79 if 'network_id' in port:
80 #info.append('"network_id":"'+port['network_id']+'"')
81 net_name = [net['name'] for net in network_list if net['id'] == port['network_id']]
82 if net_name:
83 info.append('"network_name":"'+net_name[0]+'"')
84 if 'fixed_ips' in port:
85 ip_address = port['fixed_ips'][0]['ip_address']
86 info.append('"ip":"'+ip_address+'"')
87
88 meta_data['rift-meta-port-'+str(port_id)] = '{' + ','.join(info) + '}'
89 port_id += 1
90
91 nvconn = drv.nova_drv._get_nova_connection()
92 nvconn.servers.set_meta(argument.server_id, meta_data)
93
94
95 def prepare_vm_after_boot(drv,argument):
96 ### Important to call create_port_metadata before assign_floating_ip_address
97 ### since assign_floating_ip_address can wait thus delaying port_metadata creation
98
99 ### Wait for 2 minute for server to come up -- Needs fine tuning
100 wait_time = 120
101 sleep_time = 1
102 for i in range(int(wait_time/sleep_time)):
103 server = drv.nova_server_get(argument.server_id)
104 if server['status'] == 'ACTIVE':
105 logger.info("Server %s to reached active state" %(server['name']))
106 break
107 elif server['status'] == 'BUILD':
108 logger.info("Waiting for server: %s to build. Current state: %s" %(server['name'], server['status']))
109 time.sleep(sleep_time)
110 else:
111 logger.info("Server %s reached state: %s" %(server['name'], server['status']))
112 sys.exit(3)
113 else:
114 logger.error("Server %s did not reach active state in %d seconds. Current state: %s" %(server['name'], wait_time, server['status']))
115 sys.exit(4)
116
117 #create_port_metadata(drv, argument)
118 assign_floating_ip_address(drv, argument)
119
120
121 def main():
122 """
123 Main routine
124 """
125 parser = argparse.ArgumentParser(description='Script to create openstack resources')
126 parser.add_argument('--auth_url',
127 action = "store",
128 dest = "auth_url",
129 type = str,
130 help='Keystone Auth URL')
131
132 parser.add_argument('--username',
133 action = "store",
134 dest = "username",
135 type = str,
136 help = "Username for openstack installation")
137
138 parser.add_argument('--password',
139 action = "store",
140 dest = "password",
141 type = str,
142 help = "Password for openstack installation")
143
144 parser.add_argument('--tenant_name',
145 action = "store",
146 dest = "tenant_name",
147 type = str,
148 help = "Tenant name openstack installation")
149
150 parser.add_argument('--mgmt_network',
151 action = "store",
152 dest = "mgmt_network",
153 type = str,
154 help = "mgmt_network")
155
156 parser.add_argument('--server_id',
157 action = "store",
158 dest = "server_id",
159 type = str,
160 help = "Server ID on which boot operations needs to be performed")
161
162 parser.add_argument('--floating_ip',
163 action = "store",
164 dest = "floating_ip",
165 type = str,
166 help = "Floating IP to be assigned")
167
168 parser.add_argument('--port_metadata',
169 action = "store_true",
170 dest = "port_metadata",
171 default = False,
172 help = "Create Port Metadata")
173
174 argument = parser.parse_args()
175
176 if not argument.auth_url:
177 logger.error("ERROR: AuthURL is not configured")
178 sys.exit(1)
179 else:
180 logger.info("Using AuthURL: %s" %(argument.auth_url))
181
182 if not argument.username:
183 logger.error("ERROR: Username is not configured")
184 sys.exit(1)
185 else:
186 logger.info("Using Username: %s" %(argument.username))
187
188 if not argument.password:
189 logger.error("ERROR: Password is not configured")
190 sys.exit(1)
191 else:
192 logger.info("Using Password: %s" %(argument.password))
193
194 if not argument.tenant_name:
195 logger.error("ERROR: Tenant Name is not configured")
196 sys.exit(1)
197 else:
198 logger.info("Using Tenant Name: %s" %(argument.tenant_name))
199
200 if not argument.mgmt_network:
201 logger.error("ERROR: Management Network Name is not configured")
202 sys.exit(1)
203 else:
204 logger.info("Using Management Network: %s" %(argument.mgmt_network))
205
206 if not argument.server_id:
207 logger.error("ERROR: Server ID is not configured")
208 sys.exit(1)
209 else:
210 logger.info("Using Server ID : %s" %(argument.server_id))
211
212
213 try:
214 pid = os.fork()
215 if pid > 0:
216 # exit for parent
217 sys.exit(0)
218 except OSError as e:
219 logger.error("fork failed: %d (%s)\n" % (e.errno, e.strerror))
220 sys.exit(2)
221
222 drv = openstack_drv.OpenstackDriver(username = argument.username,
223 password = argument.password,
224 auth_url = argument.auth_url,
225 tenant_name = argument.tenant_name,
226 mgmt_network = argument.mgmt_network)
227 prepare_vm_after_boot(drv, argument)
228 sys.exit(0)
229
230 if __name__ == "__main__":
231 main()
232
233