blob: 9c797d94c55f639447ca6a27bee131f759c3d20b [file] [log] [blame]
Adriana Kobylak4c60e5e2016-01-10 15:22:45 -06001#!/usr/bin/python -u
2
3import gobject
4import dbus
5import dbus.service
6import dbus.mainloop.glib
Adriana Kobylak41a925e2016-01-28 16:44:27 -06007import os
8import os.path as path
Adriana Kobylak256be782016-08-24 15:43:16 -05009import sys
Lei YU1d8b7cd2016-12-21 11:01:28 +080010from obmc.dbuslib.bindings import DbusProperties, DbusObjectManager, get_dbus
Vishwanatha Subbanna5b090c62016-09-21 15:49:26 +053011from IPy import IP
Adriana Kobylak256be782016-08-24 15:43:16 -050012
Brad Bishop966fcd52016-09-29 09:22:32 -040013settings_file_path = os.path.join(
14 sys.prefix,
15 'share',
16 'phosphor-settings')
Adriana Kobylak256be782016-08-24 15:43:16 -050017sys.path.insert(1, settings_file_path)
Adriana Kobylak4c60e5e2016-01-10 15:22:45 -060018import settings_file as s
Vishwanatha Subbanna5b090c62016-09-21 15:49:26 +053019import re
Sergey Solomin62b55f32016-10-13 10:40:27 -050020import obmc.mapper
Adriana Kobylak4c60e5e2016-01-10 15:22:45 -060021
22DBUS_NAME = 'org.openbmc.settings.Host'
Adriana Kobylak4c60e5e2016-01-10 15:22:45 -060023CONTROL_INTF = 'org.openbmc.Settings'
24
Sergey Solomin4a2433f2016-10-03 10:22:57 -050025def walk_nest(d, keys =()):
26 """Arrange dictionary keys and values.
27
28 Walk the dictionary and establish every possible path
29 returned to and processed by 'create_object' below
30 """
31 if isinstance(d, dict):
32 for k, v in d.iteritems():
33 for rv in walk_nest(v, keys + (k, )):
34 yield rv
35 else:
36 yield keys, d
37
38def create_object(settings):
39 """Create and format objects.
40
Sergey Solomin62b55f32016-10-13 10:40:27 -050041 Parse dictionary file and return all objects and settings
42 in the following format: {obj_name {settings}}
Sergey Solomin4a2433f2016-10-03 10:22:57 -050043 """
Sergey Solominf68b8642016-11-14 16:26:17 -060044 bus = get_dbus()
Sergey Solomin62b55f32016-10-13 10:40:27 -050045 mapper = obmc.mapper.Mapper(bus)
Sergey Solomin4a2433f2016-10-03 10:22:57 -050046 allobjects = {}
Sergey Solomin62b55f32016-10-13 10:40:27 -050047 queries = {}
Sergey Solomin4a2433f2016-10-03 10:22:57 -050048 for compound_key, val in walk_nest(settings):
49 obj_name = compound_key[0].lower()
50 obj_name = obj_name.replace(".","/")
51 obj_name = "/" + obj_name + "0"
52
Sergey Solomin62b55f32016-10-13 10:40:27 -050053 for i in compound_key[2:len(compound_key)-2]:
Sergey Solomin4a2433f2016-10-03 10:22:57 -050054 obj_name = obj_name + "/" + i
55
56 setting = compound_key[len(compound_key) - 2]
57 attribute = compound_key[len(compound_key) - 1]
Sergey Solomin62b55f32016-10-13 10:40:27 -050058 if settings.get(compound_key[0], {}).get('query', {}):
59 q = queries.setdefault(obj_name, {})
60 s = q.setdefault(
61 setting, {'name': None, 'type': None, 'default': None})
62 else:
63 o = allobjects.setdefault(obj_name, {})
64 s = o.setdefault(
65 setting, {'name': None, 'type': None, 'default': None})
Sergey Solomin4a2433f2016-10-03 10:22:57 -050066 s[attribute] = val
Sergey Solomin62b55f32016-10-13 10:40:27 -050067 for settings in queries.itervalues():
68 for setting in settings.itervalues():
69 if setting['type'] is not 'instance_query':
70 continue
Lei YU1d8b7cd2016-12-21 11:01:28 +080071 paths = mapper.get_subtree_paths(setting['subtree'], 0,
72 retries=10, interval=0.1)
Matt Spinler371dd022016-12-15 12:48:04 -060073
74 if setting['keyregex'] == 'host':
75 # Always create at least one host object.
76 paths = set(paths + ['/org/openbmc/control/host0'])
77
Sergey Solomin62b55f32016-10-13 10:40:27 -050078 for path in paths:
79 m = re.search(setting['matchregex'], path)
80 if not m:
81 continue
82 allobjects.setdefault(
83 "/org/openbmc/settings/" + m.group(1), settings)
Sergey Solomin4a2433f2016-10-03 10:22:57 -050084 return allobjects
Brad Bishop2a9fe662016-08-31 12:37:35 -040085
Lei YU1d8b7cd2016-12-21 11:01:28 +080086class HostSettingsObject(DbusProperties, DbusObjectManager):
Adriana Kobylak41a925e2016-01-28 16:44:27 -060087 def __init__(self, bus, name, settings, path):
Brad Bishopc1e5e9f2016-09-29 09:40:01 -040088 super(HostSettingsObject, self).__init__(
89 conn=bus,
90 object_path=name,
91 validator=self.input_validator)
Vishwanatha Subbanna5b090c62016-09-21 15:49:26 +053092 self.bus = bus
Adriana Kobylak41a925e2016-01-28 16:44:27 -060093 self.path = path
Sergey Solomin4a2433f2016-10-03 10:22:57 -050094 self.name = name
95 self.settings = settings
Yi Li5ebab482016-11-22 16:34:18 +080096 self.fname = name[name.rfind("/")+1:] + '-'
Sergey Solomin4a2433f2016-10-03 10:22:57 -050097
Vishwanatha Subbanna5b090c62016-09-21 15:49:26 +053098 # Needed to ignore the validation on default networkconfig values as
99 # opposed to user giving the same.
100 self.adminmode = True
101
Adriana Kobylak41a925e2016-01-28 16:44:27 -0600102 if not os.path.exists(path):
103 os.mkdir(path)
Adriana Kobylak4c60e5e2016-01-10 15:22:45 -0600104
105 # Listen to changes in the property values and sync them to the BMC
Brad Bishop2a9fe662016-08-31 12:37:35 -0400106 bus.add_signal_receiver(
107 self.settings_signal_handler,
108 dbus_interface="org.freedesktop.DBus.Properties",
109 signal_name="PropertiesChanged",
Sergey Solomin4a2433f2016-10-03 10:22:57 -0500110 path=name)
Adriana Kobylak4c60e5e2016-01-10 15:22:45 -0600111
112 # Create the dbus properties
Sergey Solomin4a2433f2016-10-03 10:22:57 -0500113 for setting in settings.itervalues():
Sergey Solomin62b55f32016-10-13 10:40:27 -0500114 if setting['type'] is 'instance_query':
115 continue
116 self.set_settings_property(
Yi Li5ebab482016-11-22 16:34:18 +0800117 setting['name'], setting['type'], setting['default'],
118 self.fname)
Vishwanatha Subbanna5b090c62016-09-21 15:49:26 +0530119 # Done with consuming factory settings.
120 self.adminmode = False
Adriana Kobylak4c60e5e2016-01-10 15:22:45 -0600121
Sergey Solomin62b55f32016-10-13 10:40:27 -0500122 def get_bmc_value(self, name, fname):
Adriana Kobylak4c60e5e2016-01-10 15:22:45 -0600123 try:
Sergey Solomin62b55f32016-10-13 10:40:27 -0500124 with open(path.join(self.path, fname + name), 'r') as f:
Adriana Kobylak41a925e2016-01-28 16:44:27 -0600125 return f.read()
Adriana Kobylak4c60e5e2016-01-10 15:22:45 -0600126 except (IOError):
127 pass
Adriana Kobylak41a925e2016-01-28 16:44:27 -0600128 return None
Adriana Kobylak4c60e5e2016-01-10 15:22:45 -0600129
Brad Bishop2a9fe662016-08-31 12:37:35 -0400130 # Create dbus properties based on bmc value.
131 # This will be either a value previously set,
132 # or the default file value if the BMC value
133 # does not exist.
Sergey Solomin62b55f32016-10-13 10:40:27 -0500134 def set_settings_property(self, attr_name, attr_type, value, fname):
135 bmcv = self.get_bmc_value(attr_name, fname)
Adriana Kobylak41a925e2016-01-28 16:44:27 -0600136 if bmcv:
137 value = bmcv
Sergey Solomin4a2433f2016-10-03 10:22:57 -0500138 if attr_type == "i":
139 self.Set(DBUS_NAME, attr_name, int(value))
140 elif attr_type == "s":
141 self.Set(DBUS_NAME, attr_name, str(value))
142 elif attr_type == "b":
143 self.Set(DBUS_NAME, attr_name, bool(value))
Adriana Kobylak4c60e5e2016-01-10 15:22:45 -0600144
145 # Save the settings to the BMC. This will write the settings value in
146 # individual files named by the property name to the BMC.
Sergey Solomin62b55f32016-10-13 10:40:27 -0500147 def set_system_settings(self, name, value, fname):
148 bmcv = self.get_bmc_value(name, fname)
Adriana Kobylak41a925e2016-01-28 16:44:27 -0600149 if bmcv != value:
Sergey Solomin62b55f32016-10-13 10:40:27 -0500150 filepath = path.join(self.path, fname + name)
Adriana Kobylak4c60e5e2016-01-10 15:22:45 -0600151 with open(filepath, 'w') as f:
Adriana Kobylak41a925e2016-01-28 16:44:27 -0600152 f.write(str(value))
Adriana Kobylak4c60e5e2016-01-10 15:22:45 -0600153
154 # Signal handler for when one ore more settings properties were updated.
155 # This will sync the changes to the BMC.
Brad Bishop2a9fe662016-08-31 12:37:35 -0400156 def settings_signal_handler(
Yi Li5ebab482016-11-22 16:34:18 +0800157 self, interface_name, changed_properties, invalidated_properties):
Adriana Kobylak41a925e2016-01-28 16:44:27 -0600158 for name, value in changed_properties.items():
Yi Li5ebab482016-11-22 16:34:18 +0800159 self.set_system_settings(name, value, self.fname)
Adriana Kobylak4c60e5e2016-01-10 15:22:45 -0600160
161 # Placeholder signal. Needed to register the settings interface.
Adriana Kobylak41a925e2016-01-28 16:44:27 -0600162 @dbus.service.signal(DBUS_NAME, signature='s')
163 def SettingsUpdated(self, sname):
Adriana Kobylak4c60e5e2016-01-10 15:22:45 -0600164 pass
165
Vishwanatha Subbanna5b090c62016-09-21 15:49:26 +0530166 def validate_regex(self, regex, value):
167 if not re.compile(regex).search(value):
Brad Bishopc1e5e9f2016-09-29 09:40:01 -0400168 raise ValueError("Invalid input. Data does not satisfy regex")
Vishwanatha Subbanna5b090c62016-09-21 15:49:26 +0530169
170 def validate_range(self, min, max, value):
171 if value not in range(min, max):
Brad Bishopc1e5e9f2016-09-29 09:40:01 -0400172 raise ValueError("Invalid input. Data not in allowed range")
Vishwanatha Subbanna5b090c62016-09-21 15:49:26 +0530173
Vishwanatha Subbannaeb1bea82017-01-12 16:42:44 +0530174 def validate_list(self, lst, value):
175 if value not in map(lambda val: val, lst):
Brad Bishopc1e5e9f2016-09-29 09:40:01 -0400176 raise ValueError("Invalid input. Data not in allowed values")
Vishwanatha Subbanna5b090c62016-09-21 15:49:26 +0530177
178 # validate host network configuration
179 # need "ipaddress=,prefix=,gateway=,mac=,addr_type="
180 # Must be able to handle any order
181 def validate_net_config(self, value):
182 if self.adminmode:
183 return
184
185 # Need all of these to be given by the user.
186 user_config = []
187 all_config = ['ipaddress', 'prefix', 'gateway', 'mac', 'addr_type']
188
189 # This has a hard data format mentioned above so no blanks allowed.
190 if value.count(" ") or value.count("=") != 5:
Brad Bishopc1e5e9f2016-09-29 09:40:01 -0400191 raise ValueError("Invalid Network Data. No white spaces allowed")
Vishwanatha Subbanna5b090c62016-09-21 15:49:26 +0530192
193 config = value.split(',')
194 for key_value in config:
Brad Bishopc1e5e9f2016-09-29 09:40:01 -0400195 key, value = key_value.split('=')
Vishwanatha Subbanna5b090c62016-09-21 15:49:26 +0530196 if not key or not value:
Brad Bishopc1e5e9f2016-09-29 09:40:01 -0400197 raise ValueError("Invalid key or Data")
Vishwanatha Subbanna5b090c62016-09-21 15:49:26 +0530198
199 # Add the current key seen so we can compare at the end to see
200 # if all values have been given
201 user_config.append(key.lower())
202
203 if key.lower() == 'ipaddress' or key.lower() == 'gateway':
Brad Bishopc1e5e9f2016-09-29 09:40:01 -0400204 IP(value)
Vishwanatha Subbanna5b090c62016-09-21 15:49:26 +0530205
206 elif key.lower() == 'mac':
207 regex = '([a-fA-F0-9]{2}[:|\-]?){6}'
208 self.validate_regex(regex, value)
209
210 elif key.lower() == 'prefix':
211 self.validate_range(0, 33, int(value))
212
213 elif key.lower() == 'addr_type':
214 allowed = ["STATIC", "DYNAMIC"]
Vishwanatha Subbannaeb1bea82017-01-12 16:42:44 +0530215 self.validate_list(allowed, value)
Vishwanatha Subbanna5b090c62016-09-21 15:49:26 +0530216
217 # Did user pass everything ??
218 if set(all_config) - set(user_config):
Brad Bishopc1e5e9f2016-09-29 09:40:01 -0400219 raise ValueError(
220 "Invalid Network Data. All information is mandatory")
Vishwanatha Subbanna5b090c62016-09-21 15:49:26 +0530221
222 # Validate to see if the changes are in order
223 def input_validator(self, iface, proprty, value):
Vishwanatha Subbanna5b090c62016-09-21 15:49:26 +0530224 # User entered key is not present
Sergey Solomin4a2433f2016-10-03 10:22:57 -0500225 shk = None
226 for attr in self.settings.itervalues():
227 if attr['name'] == proprty:
228 shk = attr
229
230 if shk is None:
Brad Bishopc1e5e9f2016-09-29 09:40:01 -0400231 raise KeyError("Invalid Property")
Vishwanatha Subbanna5b090c62016-09-21 15:49:26 +0530232
Sergey Solomin4a2433f2016-10-03 10:22:57 -0500233 validation = shk.get('validation', None)
234
235 if validation == 'list':
Vishwanatha Subbannaeb1bea82017-01-12 16:42:44 +0530236 self.validate_list(shk['allowed'], value)
Vishwanatha Subbanna5b090c62016-09-21 15:49:26 +0530237
Sergey Solomin4a2433f2016-10-03 10:22:57 -0500238 elif validation == 'range':
Vishwanatha Subbanna5b090c62016-09-21 15:49:26 +0530239 self.validate_range(shk['min'], shk['max']+1, value)
240
Sergey Solomin4a2433f2016-10-03 10:22:57 -0500241 elif validation == 'regex':
Vishwanatha Subbanna5b090c62016-09-21 15:49:26 +0530242 self.validate_regex(shk['regex'], value)
243
Sergey Solomin4a2433f2016-10-03 10:22:57 -0500244 elif validation == 'custom':
Brad Bishopc1e5e9f2016-09-29 09:40:01 -0400245 getattr(self, shk['method'])(value)
Vishwanatha Subbanna5b090c62016-09-21 15:49:26 +0530246
Adriana Kobylak4c60e5e2016-01-10 15:22:45 -0600247if __name__ == '__main__':
248 dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)
249
Brad Bishop5ef7fe62016-05-17 08:39:17 -0400250 bus = get_dbus()
Sergey Solomin4a2433f2016-10-03 10:22:57 -0500251 allobjects = create_object(s.SETTINGS)
252 lastobject = None
253 objs = []
254 for o, settings in allobjects.iteritems():
255 objs.append(HostSettingsObject(bus, o, settings, "/var/lib/obmc/"))
256 objs[-1].unmask_signals()
Sergey Solomin4a2433f2016-10-03 10:22:57 -0500257 mainloop = gobject.MainLoop()
Brad Bishop2cbef3d2016-08-31 12:40:13 -0400258 name = dbus.service.BusName(DBUS_NAME, bus)
Adriana Kobylak4c60e5e2016-01-10 15:22:45 -0600259 print "Running HostSettingsService"
260 mainloop.run()
Brad Bishop31c42f02016-09-29 09:35:32 -0400261
262# vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4