Merge "Remove Compass from genesis."
[genesis.git] / opensteak / tools / opensteak / foreman_objects / itemHost.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 import base64
20 from string import Template
21 from opensteak.foreman_objects.item import ForemanItem
22
23
24 class ItemHost(ForemanItem):
25     """
26     ItemHostsGroup class
27     Represent the content of a foreman hostgroup as a dict
28     """
29
30     objName = 'hosts'
31     payloadObj = 'host'
32
33     def __init__(self, api, key, *args, **kwargs):
34         """ Function __init__
35         Represent the content of a foreman object as a dict
36
37         @param api: The foreman api
38         @param key: The object Key
39         @param *args, **kwargs: the dict representation
40         @return RETURN: Itself
41         """
42         ForemanItem.__init__(self, api, key,
43                              self.objName, self.payloadObj,
44                              *args, **kwargs)
45         self.update({'puppetclass_ids':
46                      self.api.list('{}/{}/puppetclass_ids'
47                                    .format(self.objName, key))})
48         self.update({'param_ids':
49                      list(self.api.list('{}/{}/parameters'
50                                         .format(self.objName, key),
51                                         only_id=True)
52                           .keys())})
53
54
55     def getStatus(self):
56         """ Function getStatus
57         Get the status of an host
58
59         @return RETURN: The host status
60         """
61         return self.api.get('hosts', self.key, 'status')['status']
62
63     def powerOn(self):
64         """ Function powerOn
65         Power on a host
66
67         @return RETURN: The API result
68         """
69         return self.api.set('hosts', self.key,
70                             {"power_action": "start"},
71                             'power', async=self.async)
72
73     def getParamFromEnv(self, var, default=''):
74         """ Function getParamFromEnv
75         Search a parameter in the host environment
76
77         @param var: the var name
78         @param hostgroup: the hostgroup item linked to this host
79         @param default: default value
80         @return RETURN: the value
81         """
82         if self.getParam(var):
83             return self.getParam(var)
84         if self.hostgroup:
85             if self.hostgroup.getParam(var):
86                 return self.hostgroup.getParam(var)
87         if self.domain.getParam('password'):
88             return self.domain.getParam('password')
89         else:
90             return default
91
92     def getUserData(self,
93                     hostgroup,
94                     domain,
95                     defaultPwd='',
96                     defaultSshKey='',
97                     proxyHostname='',
98                     tplFolder='templates_metadata/'):
99         """ Function getUserData
100         Generate a userdata script for metadata server from Foreman API
101
102         @param domain: the domain item linked to this host
103         @param hostgroup: the hostgroup item linked to this host
104         @param defaultPwd: the default password if no password is specified
105                            in the host>hostgroup>domain params
106         @param defaultSshKey: the default ssh key if no password is specified
107                               in the host>hostgroup>domain params
108         @param proxyHostname: hostname of the smartproxy
109         @param tplFolder: the templates folder
110         @return RETURN: the user data
111         """
112         if 'user-data' in self.keys():
113             return self['user-data']
114         else:
115             self.hostgroup = hostgroup
116             self.domain = domain
117             if proxyHostname == '':
118                 proxyHostname = 'foreman.' + domain
119             password = self.getParamFromEnv('password', defaultPwd)
120             sshauthkeys = self.getParamFromEnv('global_sshkey', defaultSshKey)
121             with open(tplFolder+'puppet.conf', 'rb') as puppet_file:
122                 p = MyTemplate(puppet_file.read())
123                 enc_puppet_file = base64.b64encode(p.substitute(
124                     foremanHostname=proxyHostname))
125             with open(tplFolder+'cloud-init.tpl', 'r') as content_file:
126                 s = MyTemplate(content_file.read())
127                 if sshauthkeys:
128                     sshauthkeys = ' - '+sshauthkeys
129                 self.userdata = s.substitute(
130                     password=password,
131                     fqdn=self['name'],
132                     sshauthkeys=sshauthkeys,
133                     foremanurlbuilt="http://{}/unattended/built"
134                                     .format(proxyHostname),
135                     puppet_conf_content=enc_puppet_file.decode('utf-8'))
136                 return self.userdata
137
138
139 class MyTemplate(Template):
140     delimiter = '%'
141     idpattern = r'[a-z][_a-z0-9]*'