blob: c227e2e4933b407d68d702f822c86f50e685f6eb [file] [log] [blame]
Scott Bakere53b6b22014-08-11 19:21:14 -07001#! /usr/bin/python
2
3import json
4import os
5import requests
6import sys
7
8from operator import itemgetter, attrgetter
9
10REST_API="http://alpha.opencloud.us:8000/plstackapi/"
11
12NODES_API = REST_API + "nodes/"
13SLICES_API = REST_API + "slices/"
14SLIVERS_API = REST_API + "slivers/"
Scott Bakerf2ddddf2014-08-12 18:14:34 -070015NETWORKSLIVERS_API = REST_API + "networkslivers/"
Scott Bakere53b6b22014-08-11 19:21:14 -070016
17opencloud_auth=("demo@onlab.us", "demo")
18
19def get_slice_id(slice_name):
20 r = requests.get(SLICES_API + "?name=%s" % slice_name, auth=opencloud_auth)
21 return r.json()[0]["id"]
22
23def get_node_id(host_name):
24 r = requests.get(NODES_API + "?name=%s" % host_name, auth=opencloud_auth)
25 return r.json()[0]["id"]
26
27def get_slivers(slice_id=None, node_id=None):
28 queries = []
29 if slice_id:
30 queries.append("slice=%s" % str(slice_id))
31 if node_id:
32 queries.append("node=%s" % str(node_id))
33
34 if queries:
35 query_string = "?" + "&".join(queries)
36 else:
37 query_string = ""
38
39 r = requests.get(SLIVERS_API + query_string, auth=opencloud_auth)
40 return r.json()
41
42def main():
43 global opencloud_auth
44
45 if len(sys.argv)!=5:
46 print >> sys.stderr, "syntax: get_instance_name.py <username>, <password>, <hostname> <slicename>"
47 sys.exit(-1)
48
49 username = sys.argv[1]
50 password = sys.argv[2]
51 hostname = sys.argv[3]
52 slice_name = sys.argv[4]
53
54 opencloud_auth=(username, password)
55
56 slice_id = get_slice_id(slice_name)
57 node_id = get_node_id(hostname)
58 slivers = get_slivers(slice_id, node_id)
59
60 # get (instance_name, ip) pairs for instances with names and ips
61
Scott Baker4a69ab92014-08-20 12:33:26 -070062 slivers = [x for x in slivers if x["instance_name"]]
Scott Bakere53b6b22014-08-11 19:21:14 -070063 slivers = sorted(slivers, key = lambda sliver: sliver["instance_name"])
64
65 # return the last one in the list (i.e. the newest one)
66
Scott Bakerf2ddddf2014-08-12 18:14:34 -070067 sliver_id = slivers[-1]["id"]
68
69 r = requests.get(NETWORKSLIVERS_API + "?sliver=%s" % sliver_id, auth=opencloud_auth)
70
71 networkSlivers = r.json()
72 ips = [x["ip"] for x in networkSlivers]
73
74 # XXX kinda hackish -- assumes private ips start with "10." and nat start with "172."
75
76 # print a public IP if there is one
77 for ip in ips:
78 if (not ip.startswith("10")) and (not ip.startswith("172")):
79 print ip
80 return
81
82 # otherwise print a privat ip
83 for ip in ips:
84 if (not ip.startswith("172")):
85 print ip
86 return
87
88 # otherwise just print the first one
89 print ips[0]
Scott Bakere53b6b22014-08-11 19:21:14 -070090
91if __name__ == "__main__":
92 main()
93