Merge "Remove Compass from genesis."
[genesis.git] / opensteak / tools / opensteak / foreman_objects / freeip.py
1 #!/usr/bin/python3
2 # -*- coding: utf-8 -*-
3 # Licensed under the Apache License, Version 2.0 (the "License"); you may
4 # not use this file except in compliance with the License. You may obtain
5 # a copy of the License at
6 #
7 #      http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11 # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12 # License for the specific language governing permissions and limitations
13 # under the License.
14 #
15 # Authors:
16 # @author: David Blaisonneau <david.blaisonneau@orange.com>
17 # @author: Arnaud Morin <arnaud1.morin@orange.com>
18
19 #~ from foreman.api import Api
20 import requests
21 from bs4 import BeautifulSoup
22 import sys
23 import json
24
25 class FreeIP:
26     """ FreeIP return an available IP in the targeted network """
27
28     def __init__ (self, login, password):
29         """ Init: get authenticity token """
30         with requests.session() as self.session:
31             try:
32                 #~ 1/ Get login token and authentify
33                 payload = {}
34                 log_soup = BeautifulSoup(self.session.get('https://127.0.0.1/users/login', verify=False).text)
35                 payload['utf8'] = log_soup.findAll('input',attrs={'name':'utf8'})[0].get('value')
36                 payload['authenticity_token'] = log_soup.findAll('input',attrs={'name':'authenticity_token'})[0].get('value')
37                 if payload['authenticity_token'] == None:
38                     raise requests.exceptions.RequestException("Bad catch of authenticity_token")
39                 payload['commit']='Login'
40                 payload['login[login]'] = login
41                 payload['login[password]'] = password
42                 #~ 2/ Log in
43                 r = self.session.post('https://127.0.0.1/users/login', verify=False, data=payload)
44                 if r.status_code != 200:
45                     raise requests.exceptions.RequestException("Bad login or password")
46                 #~ Get token for host creation
47                 log_soup = BeautifulSoup(self.session.get('https://127.0.0.1/hosts/new', verify=False).text)
48                 self.authenticity_token = log_soup.findAll('input',attrs={'name':'authenticity_token'})[0].get('value')
49                 if payload['authenticity_token'] == None:
50                     raise requests.exceptions.RequestException("Bad catch of authenticity_token")
51             except requests.exceptions.RequestException as e:
52                 print("Error connection Foreman to get a free ip")
53                 print(e)
54                 sys.exit(1)
55         pass
56
57     def get(self, subnet, mac = ""):
58         payload = {"host_mac": mac, "subnet_id": subnet}
59         payload['authenticity_token'] = self.authenticity_token
60         try:
61             self.last_ip = json.loads(self.session.post('https://127.0.0.1/subnets/freeip', verify=False, data=payload).text)['ip']
62             if payload['authenticity_token'] == None:
63                 raise requests.exceptions.RequestException("Error getting free IP")
64         except requests.exceptions.RequestException as e:
65             print("Error connection Foreman to get a free ip")
66             print(e)
67             sys.exit(1)
68         return self.last_ip
69
70
71
72 if __name__ == "__main__":
73     import pprint
74     import sys
75     if len(sys.argv) == 4:
76         f = FreeIP(sys.argv[1], sys.argv[2])
77         print(f.get(sys.argv[3]))
78     else:
79         print('Error: Usage\npython {} foreman_user foreman_password subnet'.format(sys.argv[0]))