blob: 449a4cfa5c43132dba0ac5d80db31398c2fe7201 [file] [log] [blame]
Simran Basia9f41032012-05-11 14:21:58 -07001# Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
Todd Broche505b8d2011-03-21 18:19:54 -07002# Use of this source code is governed by a BSD-style license that can be
3# found in the LICENSE file.
4"""Servo Server."""
Simran Basia9f41032012-05-11 14:21:58 -07005import fnmatch
Todd Broche505b8d2011-03-21 18:19:54 -07006import imp
7import logging
Simran Basia9f41032012-05-11 14:21:58 -07008import os
9import shutil
Todd Broche505b8d2011-03-21 18:19:54 -070010import SimpleXMLRPCServer
Simran Basia9f41032012-05-11 14:21:58 -070011import subprocess
12import tempfile
Todd Broch7a91c252012-02-03 12:37:45 -080013import time
Simran Basia9f41032012-05-11 14:21:58 -070014import urllib
Todd Broche505b8d2011-03-21 18:19:54 -070015
16# TODO(tbroch) deprecate use of relative imports
Todd Broche505b8d2011-03-21 18:19:54 -070017import ftdigpio
18import ftdii2c
Todd Brochdbb09982011-10-02 07:14:26 -070019import ftdi_common
Todd Broch47c43f42011-05-26 15:11:31 -070020import ftdiuart
Todd Broche505b8d2011-03-21 18:19:54 -070021
22MAX_I2C_CLOCK_HZ = 100000
23
Todd Brochdbb09982011-10-02 07:14:26 -070024
Todd Broche505b8d2011-03-21 18:19:54 -070025class ServodError(Exception):
26 """Exception class for servod."""
27
28class Servod(object):
29 """Main class for Servo debug/controller Daemon."""
Simran Basia9f41032012-05-11 14:21:58 -070030 _USB_DETECTION_DELAY = 10
31 _HTTP_PREFIX = "http://"
32
Todd Brochdbb09982011-10-02 07:14:26 -070033 def __init__(self, config, vendor, product, serialname=None, interfaces=None):
Todd Broche505b8d2011-03-21 18:19:54 -070034 """Servod constructor.
35
36 Args:
37 config: instance of SystemConfig containing all controls for
38 particular Servod invocation
39 vendor: usb vendor id of FTDI device
40 product: usb product id of FTDI device
Todd Brochad034442011-05-25 15:05:29 -070041 serialname: string of device serialname/number as defined in FTDI eeprom.
Todd Brochdbb09982011-10-02 07:14:26 -070042 interfaces: list of strings of interface types the server will instantiate
43
44 Raises:
45 ServodError: if unable to locate init method for particular interface
Todd Broche505b8d2011-03-21 18:19:54 -070046 """
47 self._logger = logging.getLogger("Servod")
48 self._logger.debug("")
49 self._vendor = vendor
50 self._product = product
Todd Brochad034442011-05-25 15:05:29 -070051 self._serialname = serialname
Todd Broche505b8d2011-03-21 18:19:54 -070052 self._syscfg = config
53 # list of objects (Fi2c, Fgpio) to physical interfaces (gpio, i2c) that ftdi
54 # interfaces are mapped to
55 self._interface_list = []
56 # Dict of Dict to map control name, function name to to tuple (params, drv)
57 # Ex) _drv_dict[name]['get'] = (params, drv)
58 self._drv_dict = {}
59
Todd Brochdbb09982011-10-02 07:14:26 -070060 # Note, interface i is (i - 1) in list
61 if not interfaces:
62 interfaces = ftdi_common.INTERFACE_DEFAULTS[vendor][product]
63
64 for i, name in enumerate(interfaces):
Todd Broch8a77a992012-01-27 09:46:08 -080065 # servos with multiple FTDI are guaranteed to have contiguous USB PIDs
66 if i and ((i % ftdi_common.MAX_FTDI_INTERFACES_PER_DEVICE) == 0):
67 self._product += 1
68 self._logger.info("Changing to next FTDI part @ pid = 0x%04x",
69 self._product)
70
Todd Brochdbb09982011-10-02 07:14:26 -070071 self._logger.info("Initializing FTDI interface %d to %s", i + 1, name)
72 try:
73 func = getattr(self, '_init_%s' % name)
74 except AttributeError:
75 raise ServodError("Unable to locate init for interface %s" % name)
Todd Brocha9c74692012-01-24 22:54:22 -080076 result = func((i % ftdi_common.MAX_FTDI_INTERFACES_PER_DEVICE) + 1)
Todd Broch888da782011-10-07 14:29:09 -070077 if isinstance(result, tuple):
78 self._interface_list.extend(result)
79 else:
80 self._interface_list.append(result)
Todd Broche505b8d2011-03-21 18:19:54 -070081
Todd Brochb3048492012-01-15 21:52:41 -080082 def _init_dummy(self, interface):
83 """Initialize dummy interface.
84
85 Dummy interface is just a mechanism to reserve that interface for non servod
86 interaction. Typically the interface will be managed by external
87 third-party tools like openOCD or urjtag for JTAG or flashrom for SPI
88 interfaces.
89
90 TODO(tbroch): Investigate merits of incorporating these third-party
91 interfaces into servod or creating a communication channel between them
92
93 Returns: None
94 """
95 return None
96
Todd Broche505b8d2011-03-21 18:19:54 -070097 def _init_gpio(self, interface):
98 """Initialize gpio driver interface and open for use.
99
100 Args:
101 interface: interface number of FTDI device to use.
102
103 Returns:
104 Instance object of interface.
Todd Broch6de9dc62012-04-09 15:23:53 -0700105
106 Raises:
107 ServodError: If init fails
Todd Broche505b8d2011-03-21 18:19:54 -0700108 """
Todd Brochad034442011-05-25 15:05:29 -0700109 fobj = ftdigpio.Fgpio(self._vendor, self._product, interface,
110 self._serialname)
Todd Broch6de9dc62012-04-09 15:23:53 -0700111 try:
112 fobj.open()
113 except ftdigpio.FgpioError as e:
114 raise ServodError('Opening gpio interface. %s ( %d )' % (e.msg, e.value))
115
Todd Broche505b8d2011-03-21 18:19:54 -0700116 return fobj
117
118 def _init_i2c(self, interface):
119 """Initialize i2c interface and open for use.
120
121 Args:
122 interface: interface number of FTDI device to use
123
124 Returns:
125 Instance object of interface
Todd Broch6de9dc62012-04-09 15:23:53 -0700126
127 Raises:
128 ServodError: If init fails
Todd Broche505b8d2011-03-21 18:19:54 -0700129 """
Todd Brochad034442011-05-25 15:05:29 -0700130 fobj = ftdii2c.Fi2c(self._vendor, self._product, interface,
131 self._serialname)
Todd Broch6de9dc62012-04-09 15:23:53 -0700132 try:
133 fobj.open()
134 except ftdii2c.Fi2cError as e:
135 raise ServodError('Opening i2c interface. %s ( %d )' % (e.msg, e.value))
136
Todd Broche505b8d2011-03-21 18:19:54 -0700137 # Set the frequency of operation of the i2c bus.
138 # TODO(tbroch) make configureable
139 fobj.setclock(MAX_I2C_CLOCK_HZ)
Todd Broch6de9dc62012-04-09 15:23:53 -0700140
Todd Broche505b8d2011-03-21 18:19:54 -0700141 return fobj
142
Todd Broch47c43f42011-05-26 15:11:31 -0700143 def _init_uart(self, interface):
144 """Initialize uart inteface and open for use
145
146 Note, the uart runs in a separate thread (pthreads). Users wishing to
147 interact with it will query control for the pty's pathname and connect
148 with there favorite console program. For example:
149 cu -l /dev/pts/22
150
151 Args:
152 interface: interface number of FTDI device to use
153
154 Returns:
155 Instance object of interface
Todd Broch6de9dc62012-04-09 15:23:53 -0700156
157 Raises:
158 ServodError: If init fails
Todd Broch47c43f42011-05-26 15:11:31 -0700159 """
160 fobj = ftdiuart.Fuart(self._vendor, self._product, interface)
Todd Broch6de9dc62012-04-09 15:23:53 -0700161 try:
162 fobj.run()
163 except ftdiuart.FuartError as e:
164 raise ServodError('Running uart interface. %s ( %d )' % (e.msg, e.value))
165
Todd Broch47c43f42011-05-26 15:11:31 -0700166 self._logger.info("%s" % fobj.get_pty())
167 return fobj
168
Todd Broch888da782011-10-07 14:29:09 -0700169 def _init_gpiouart(self, interface):
170 """Initialize special gpio + uart interface and open for use
171
172 Note, the uart runs in a separate thread (pthreads). Users wishing to
173 interact with it will query control for the pty's pathname and connect
174 with there favorite console program. For example:
175 cu -l /dev/pts/22
176
177 Args:
178 interface: interface number of FTDI device to use
179
180 Returns:
181 Instance objects of interface
Todd Broch6de9dc62012-04-09 15:23:53 -0700182
183 Raises:
184 ServodError: If init fails
Todd Broch888da782011-10-07 14:29:09 -0700185 """
186 fgpio = self._init_gpio(interface)
187 fuart = ftdiuart.Fuart(self._vendor, self._product, interface, fgpio._fc)
Todd Broch6de9dc62012-04-09 15:23:53 -0700188 try:
189 fuart.run()
190 except ftdiuart.FuartError as e:
191 raise ServodError('Running uart interface. %s ( %d )' % (e.msg, e.value))
192
Todd Broch888da782011-10-07 14:29:09 -0700193 self._logger.info("uart pty: %s" % fuart.get_pty())
194 return fgpio, fuart
195
Tom Wai-Hong Tam28f0a5f2012-08-21 12:49:57 +0800196 def _camel_case(self, string):
197 output = ''
198 for s in string.split('_'):
199 if output:
200 output += s.capitalize()
201 else:
202 output = s
203 return output
204
Todd Broche505b8d2011-03-21 18:19:54 -0700205 def _get_param_drv(self, control_name, is_get=True):
206 """Get access to driver for a given control.
207
208 Note, some controls have different parameter dictionaries for 'getting' the
209 control's value versus 'setting' it. Boolean is_get distinguishes which is
210 being requested.
211
212 Args:
213 control_name: string name of control
214 is_get: boolean to determine
215
216 Returns:
217 tuple (param, drv) where:
218 param: param dictionary for control
219 drv: instance object of driver for particular control
220
221 Raises:
222 ServodError: Error occurred while examining params dict
223 """
224 self._logger.debug("")
225 # if already setup just return tuple from driver dict
226 if control_name in self._drv_dict:
227 if is_get and ('get' in self._drv_dict[control_name]):
228 return self._drv_dict[control_name]['get']
229 if not is_get and ('set' in self._drv_dict[control_name]):
230 return self._drv_dict[control_name]['set']
231
232 params = self._syscfg.lookup_control_params(control_name, is_get)
233 if 'drv' not in params:
234 self._logger.error("Unable to determine driver for %s" % control_name)
235 raise ServodError("'drv' key not found in params dict")
236 if 'interface' not in params:
237 self._logger.error("Unable to determine interface for %s" %
238 control_name)
239
240 raise ServodError("'interface' key not found in params dict")
241 index = int(params['interface']) - 1
242 interface = self._interface_list[index]
243 servo_pkg = imp.load_module('servo', *imp.find_module('servo'))
244 drv_pkg = imp.load_module('drv',
245 *imp.find_module('drv', servo_pkg.__path__))
246 drv_name = params['drv']
247 drv_module = getattr(drv_pkg, drv_name)
Tom Wai-Hong Tam28f0a5f2012-08-21 12:49:57 +0800248 drv_class = getattr(drv_module, self._camel_case(drv_name))
Todd Broche505b8d2011-03-21 18:19:54 -0700249 drv = drv_class(interface, params)
250 if control_name not in self._drv_dict:
251 self._drv_dict[control_name] = {}
252 if is_get:
253 self._drv_dict[control_name]['get'] = (params, drv)
254 else:
255 self._drv_dict[control_name]['set'] = (params, drv)
256 return (params, drv)
257
258 def doc_all(self):
259 """Return all documenation for controls.
260
261 Returns:
262 string of <doc> text in config file (xml) and the params dictionary for
263 all controls.
264
265 For example:
266 warm_reset :: Reset the device warmly
267 ------------------------> {'interface': '1', 'map': 'onoff_i', ... }
268 """
269 return self._syscfg.display_config()
270
271 def doc(self, name):
272 """Retreive doc string in system config file for given control name.
273
274 Args:
275 name: name string of control to get doc string
276
277 Returns:
278 doc string of name
279
280 Raises:
281 NameError: if fails to locate control
282 """
283 self._logger.debug("name(%s)" % (name))
284 if self._syscfg.is_control(name):
285 return self._syscfg.get_control_docstring(name)
286 else:
287 raise NameError("No control %s" %name)
288
Simran Basia9f41032012-05-11 14:21:58 -0700289 def _get_usb_port_set(self):
290 """Gets a set of USB disks currently connected to the system
291
292 Returns:
293 A set of USB disk paths.
294 """
295 usb_set = fnmatch.filter(os.listdir("/dev/"), "sd[a-z]")
296 return set(["/dev/" + dev for dev in usb_set])
297
298 def _probe_host_usb_dev(self):
299 """Probe the USB disk device plugged in the servo from the host side.
300
301 Method can fail by:
302 1) Having multiple servos connected and returning incorrect /dev/sdX of
303 another servo.
304 2) Finding multiple /dev/sdX and returning None.
305
306 Returns:
307 USB disk path if one and only one USB disk path is found, otherwise None.
308 """
309 original_value = self.get("usb_mux_sel1")
310 # Make the host unable to see the USB disk.
311 if original_value != "dut_sees_usbkey":
312 self.set("usb_mux_sel1", "dut_sees_usbkey")
313 time.sleep(self._USB_DETECTION_DELAY)
314
315 no_usb_set = self._get_usb_port_set()
316 # Make the host able to see the USB disk.
317 self.set("usb_mux_sel1", "servo_sees_usbkey")
318 time.sleep(self._USB_DETECTION_DELAY)
319
320 has_usb_set = self._get_usb_port_set()
321 # Back to its original value.
322 if original_value != "servo_sees_usbkey":
323 self.set("usb_mux_sel1", original_value)
324 time.sleep(self._USB_DETECTION_DELAY)
325 # Subtract the two sets to find the usb device.
326 diff_set = has_usb_set - no_usb_set
327 if len(diff_set) == 1:
328 return diff_set.pop()
329 else:
330 return None
331
332 def download_image_to_usb(self, image_path):
333 """Download image and save to the USB device found by probe_host_usb_dev.
334 If the image_path is a URL, it will download this url to the USB path;
335 otherwise it will simply copy the image_path's contents to the USB path.
336
337 Args:
338 image_path: path or url to the recovery image.
339
340 Returns:
341 True|False: True if process completed successfully, False if error
342 occurred.
343 Can't return None because XMLRPC doesn't allow it. PTAL at tbroch's
344 comment at the end of set().
345 """
346 self._logger.debug("image_path(%s)" % image_path)
347 self._logger.debug("Detecting USB stick device...")
348 usb_dev = self._probe_host_usb_dev()
349 if not usb_dev:
350 self._logger.error("No usb device connected to servo")
351 return False
352
353 try:
354 if image_path.startswith(self._HTTP_PREFIX):
355 self._logger.debug("Image path is a URL, downloading image")
356 urllib.urlretrieve(image_path, usb_dev)
357 else:
358 shutil.copyfile(image_path, usb_dev)
359 except IOError as e:
360 self._logger.error("Failed to transfer image to USB device: %s ( %d ) ",
361 e.strerror, e.errno)
362 return False
363 except urllib.ContentTooShortError:
364 self._logger.error("Failed to download URL: %s to USB device: %s",
365 image_path, usb_dev)
366 return False
367 except BaseException as e:
368 self._logger.error("Unexpected exception downloading %s to %s: %s",
369 image_path, usb_dev, str(e))
370 return False
371 return True
372
373 def make_image_noninteractive(self):
374 """Makes the recovery image noninteractive.
375
376 A noninteractive image will reboot automatically after installation
377 instead of waiting for the USB device to be removed to initiate a system
378 reboot.
379
380 Mounts partition 1 of the image stored on usb_dev and creates a file
381 called "non_interactive" so that the image will become noninteractive.
382
383 Returns:
384 True|False: True if process completed successfully, False if error
385 occurred.
386 """
387 result = True
388 usb_dev = self._probe_host_usb_dev()
389 if not usb_dev:
390 self._logger.error("No usb device connected to servo")
391 return False
392 # Create TempDirectory
393 tmpdir = tempfile.mkdtemp()
394 if tmpdir:
395 # Mount drive to tmpdir.
396 partition_1 = "%s1" % usb_dev
397 rc = subprocess.call(["mount", partition_1, tmpdir])
398 if rc == 0:
399 # Create file 'non_interactive'
400 non_interactive_file = os.path.join(tmpdir, "non_interactive")
401 try:
402 open(non_interactive_file, "w").close()
403 except IOError as e:
404 self._logger.error("Failed to create file %s : %s ( %d )",
405 non_interactive_file, e.strerror, e.errno)
406 result = False
407 except BaseException as e:
408 self._logger.error("Unexpected Exception creating file %s : %s",
409 non_interactive_file, str(e))
410 result = False
411 # Unmount drive regardless if file creation worked or not.
412 rc = subprocess.call(["umount", partition_1])
413 if rc != 0:
414 self._logger.error("Failed to unmount USB Device")
415 result = False
416 else:
417 self._logger.error("Failed to mount USB Device")
418 result = False
419
420 # Delete tmpdir. May throw exception if 'umount' failed.
421 try:
422 os.rmdir(tmpdir)
423 except OSError as e:
424 self._logger.error("Failed to remove temp directory %s : %s",
425 tmpdir, str(e))
426 return False
427 except BaseException as e:
428 self._logger.error("Unexpected Exception removing tempdir %s : %s",
429 tmpdir, str(e))
430 return False
431 else:
432 self._logger.error("Failed to create temp directory.")
433 return False
434 return result
435
Todd Broche505b8d2011-03-21 18:19:54 -0700436 def get(self, name):
437 """Get control value.
438
439 Args:
440 name: name string of control
441
442 Returns:
443 Response from calling drv get method. Value is reformatted based on
444 control's dictionary parameters
445
446 Raises:
447 HwDriverError: Error occurred while using drv
448 """
449 self._logger.debug("name(%s)" % (name))
450 (param, drv) = self._get_param_drv(name)
451 try:
452 val = drv.get()
453 rd_val = self._syscfg.reformat_val(param, val)
Todd Brochb042e7a2011-12-14 17:41:36 -0800454 self._logger.debug("%s = %s" % (name, rd_val))
Todd Broche505b8d2011-03-21 18:19:54 -0700455 return rd_val
Todd Brochfbc499d2011-06-16 16:09:58 -0700456 except AttributeError, error:
457 self._logger.error("Getting %s: %s" % (name, error))
458 raise
Todd Broche505b8d2011-03-21 18:19:54 -0700459 except drv.hw_driver.HwDriverError:
460 self._logger.error("Getting %s" % (name))
461 raise
Todd Brochd6061672012-05-11 15:52:47 -0700462
Todd Broche505b8d2011-03-21 18:19:54 -0700463 def get_all(self, verbose):
464 """Get all controls values.
465
466 Args:
467 verbose: Boolean on whether to return doc info as well
468
469 Returns:
470 string creating from trying to get all values of all controls. In case of
471 error attempting access to control, response is 'ERR'.
472 """
473 rsp = ""
474 for name in self._syscfg.syscfg_dict['control']:
475 self._logger.debug("name = %s" %name)
476 try:
477 value = self.get(name)
478 except Exception:
479 value = "ERR"
480 pass
481 if verbose:
482 rsp += "GET %s = %s :: %s\n" % (name, value, self.doc(name))
483 else:
484 rsp += "%s:%s\n" % (name, value)
485 return rsp
486
487 def set(self, name, wr_val_str):
488 """Set control.
489
490 Args:
491 name: name string of control
492 wr_val_str: value string to write. Can be integer, float or a
493 alpha-numerical that is mapped to a integer or float.
494
495 Raises:
496 HwDriverError: Error occurred while using driver
497 """
Todd Broch7a91c252012-02-03 12:37:45 -0800498 if name == 'sleep':
499 time.sleep(float(wr_val_str))
500 return True
501
Todd Broche505b8d2011-03-21 18:19:54 -0700502 self._logger.debug("name(%s) wr_val(%s)" % (name, wr_val_str))
503 (params, drv) = self._get_param_drv(name, False)
504 wr_val = self._syscfg.resolve_val(params, wr_val_str)
505 try:
506 drv.set(wr_val)
507 except drv.hw_driver.HwDriverError:
508 self._logger.error("Setting %s -> %s" % (name, wr_val_str))
509 raise
510 # TODO(tbroch) Figure out why despite allow_none=True for both xmlrpc server
511 # & client I still have to return something to appease the
512 # marshall/unmarshall
513 return True
514
Todd Brochd6061672012-05-11 15:52:47 -0700515 def hwinit(self, verbose=False):
516 """Initialize all controls.
517
518 These values are part of the system config XML files of the form
519 init=<value>. This command should be used by clients wishing to return the
520 servo and DUT its connected to a known good/safe state.
521
522 Args:
523 verbose: boolean, if True prints info about control initialized.
524 Otherwise prints nothing.
525 """
526 for control_name, value in self._syscfg.hwinit():
527 self.set(control_name, value)
528 if verbose:
529 self._logger.info('Initialized %s to %s', control_name, value)
530
531 return True
532
Todd Broche505b8d2011-03-21 18:19:54 -0700533 def echo(self, echo):
534 """Dummy echo function for testing/examples.
535
536 Args:
537 echo: string to echo back to client
538 """
539 self._logger.debug("echo(%s)" % (echo))
540 return "ECH0ING: %s" % (echo)
541
Todd Brochdbb09982011-10-02 07:14:26 -0700542
Todd Broche505b8d2011-03-21 18:19:54 -0700543def test():
544 """Integration testing.
545
546 TODO(tbroch) Enhance integration test and add unittest (see mox)
547 """
548 logging.basicConfig(level=logging.DEBUG,
549 format="%(asctime)s - %(name)s - " +
550 "%(levelname)s - %(message)s")
551 # configure server & listen
552 servod_obj = Servod(1)
553 # 4 == number of interfaces on a FT4232H device
554 for i in xrange(4):
555 if i == 1:
556 # its an i2c interface ... see __init__ for details and TODO to make
557 # this configureable
558 servod_obj._interface_list[i].wr_rd(0x21, [0], 1)
559 else:
560 # its a gpio interface
561 servod_obj._interface_list[i].wr_rd(0)
562
563 server = SimpleXMLRPCServer.SimpleXMLRPCServer(("localhost", 9999),
564 allow_none=True)
565 server.register_introspection_functions()
566 server.register_multicall_functions()
567 server.register_instance(servod_obj)
568 logging.info("Listening on localhost port 9999")
569 server.serve_forever()
570
571if __name__ == "__main__":
572 test()
573
574 # simple client transaction would look like
575 """
576 remote_uri = 'http://localhost:9999'
577 client = xmlrpclib.ServerProxy(remote_uri, verbose=False)
578 send_str = "Hello_there"
579 print "Sent " + send_str + ", Recv " + client.echo(send_str)
580 """