user's can't set/unset site in Login Details without the proper authorization
[plstackapi.git] / planetstack / tools / get_instance_ip.py
1 #! /usr/bin/python
2
3 import json
4 import os
5 import requests
6 import sys
7
8 from operator import itemgetter, attrgetter
9
10 REST_API="http://alpha.opencloud.us:8000/plstackapi/"
11
12 NODES_API = REST_API + "nodes/"
13 SLICES_API = REST_API + "slices/"
14 SLIVERS_API = REST_API + "slivers/"
15 NETWORKSLIVERS_API = REST_API + "networkslivers/"
16
17 opencloud_auth=("demo@onlab.us", "demo")
18
19 def 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
23 def get_node_id(host_name):
24      r = requests.get(NODES_API)
25      nodes = r.json()
26      for node in nodes:
27          if node["name"].lower() == host_name.lower():
28              return node["id"]
29      print >> sys.stderr, "Error: failed to find node %s" % host_name
30      sys.exit(-1)
31
32 def get_slivers(slice_id=None, node_id=None):
33     queries = []
34     if slice_id:
35         queries.append("slice=%s" % str(slice_id))
36     if node_id:
37         queries.append("node=%s" % str(node_id))
38
39     if queries:
40         query_string = "?" + "&".join(queries)
41     else:
42         query_string = ""
43
44     r = requests.get(SLIVERS_API + query_string, auth=opencloud_auth)
45     return r.json()
46
47 def main():
48     global opencloud_auth
49
50     if len(sys.argv)!=5:
51         print >> sys.stderr, "syntax: get_instance_name.py <username>, <password>, <hostname> <slicename>"
52         sys.exit(-1)
53
54     username = sys.argv[1]
55     password = sys.argv[2]
56     hostname = sys.argv[3]
57     slice_name = sys.argv[4]
58
59     opencloud_auth=(username, password)
60
61     slice_id = get_slice_id(slice_name)
62     node_id = get_node_id(hostname)
63     slivers = get_slivers(slice_id, node_id)
64
65     # get (instance_name, ip) pairs for instances with names and ips
66
67     slivers = [x for x in slivers if x["instance_name"]]
68     slivers = sorted(slivers, key = lambda sliver: sliver["instance_name"])
69
70     # return the last one in the list (i.e. the newest one)
71
72     sliver_id = slivers[-1]["id"]
73
74     r = requests.get(NETWORKSLIVERS_API + "?sliver=%s" % sliver_id, auth=opencloud_auth)
75
76     networkSlivers = r.json()
77     ips = [x["ip"] for x in networkSlivers]
78
79     # XXX kinda hackish -- assumes private ips start with "10." and nat start with "172."
80
81     # print a public IP if there is one
82     for ip in ips:
83        if (not ip.startswith("10")) and (not ip.startswith("172")):
84            print ip
85            return
86
87     # otherwise print a privat ip
88     for ip in ips:
89        if (not ip.startswith("172")):
90            print ip
91            return
92
93     # otherwise just print the first one
94     print ips[0]
95
96 if __name__ == "__main__":
97     main()
98