Add --pass option
[ci.git] / htest / vm / controller.py
blobcf36eaa56b6712088ba3639dc496316b313e721e
1 #!/usr/bin/env python3
4 # Copyright (c) 2018 Vojtech Horky
5 # All rights reserved.
7 # Redistribution and use in source and binary forms, with or without
8 # modification, are permitted provided that the following conditions
9 # are met:
11 # - Redistributions of source code must retain the above copyright
12 # notice, this list of conditions and the following disclaimer.
13 # - Redistributions in binary form must reproduce the above copyright
14 # notice, this list of conditions and the following disclaimer in the
15 # documentation and/or other materials provided with the distribution.
16 # - The name of the author may not be used to endorse or promote products
17 # derived from this software without specific prior written permission.
19 # THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
20 # IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
21 # OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
22 # IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
23 # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
24 # NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25 # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26 # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27 # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
28 # THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31 import os
32 import subprocess
34 class VMManager:
35 """
36 Keeps track of running virtual machines.
37 """
39 def __init__(self, controller, architecture, boot_image, memory_amount, extra_opts):
40 self.controller_class = controller
41 self.architecture = architecture
42 self.boot_image = boot_image
43 self.memory_amount = memory_amount
44 self.extra_options = extra_opts
45 self.instances = {}
46 self.last = None
48 def create(self, name):
49 if name in self.instances:
50 raise Exception("Duplicate machine name {}.".format(name))
51 self.instances[name] = self.controller_class(self.architecture, name, self.boot_image)
52 self.instances[name].memory = self.memory_amount
53 self.instances[name].extra_options = self.extra_options
54 self.last = name
55 return self.instances[name]
57 def get(self, name=None):
58 if name is None:
59 name = self.last
60 if name is None:
61 return None
62 if name in self.instances:
63 self.last = name
64 return self.instances[name]
65 else:
66 return None
68 def terminate(self, vterm_dump_filename, last_screenshot_filename):
69 for i in self.instances:
70 self.instances[i].terminate()
71 if vterm_dump_filename is not None:
72 with open(vterm_dump_filename, 'w') as f:
73 for i in self.instances:
74 lines = '\n'.join(self.instances[i].full_vterm)
75 print(lines, file=f)
76 if last_screenshot_filename is not None:
77 for i in self.instances:
78 filename = self.instances[i].screenshot_filename
79 if filename is not None:
80 proc = subprocess.Popen(['convert', filename, last_screenshot_filename])
81 proc.wait()
82 if proc.returncode != 0:
83 raise Exception("Saving screenshot failed.")
85 class VMController:
86 """
87 Base class for controllers of specific virtual machine emulators.
88 """
90 def __init__(self, provider):
91 self.provider_name = provider
92 # Patched by VMManager
93 self.name = 'XXX'
94 self.screenshot_filename = None
95 # All lines seen in the terminal
96 # (do not reset unless you know what you are doing).
97 self.full_vterm = []
98 # Used to keep track of new-lines
99 self.vterm = []
100 # Amount of memory (MB) (patched by VMM manager)
101 self.memory = 0
102 # Extra command-line options (patched by VMM manager)
103 self.extra_options = []
104 pass
106 def is_supported(self, arch):
108 Tells whether this controller supports given architecture.
110 return False
112 def boot(self, **kwargs):
114 Bring the machine up.
116 pass
118 def terminate(self):
120 Shutdown the VM.
122 pass
124 def type(self, what):
126 Type given text into vterm.
128 print("type('{}') @ {}".format(what, self.provider_name))
129 pass
131 def same_vterm_tail(self, lines):
132 lines_count = len(lines)
133 for i in range(-1, -lines_count - 1, -1):
134 if i != -1:
135 if lines[i] != self.full_vterm[i]:
136 return False
137 else:
138 a = lines[-1].replace("_", " ").strip()
139 b = self.full_vterm[-1].replace("_", " ").strip()
140 if not a.startswith(b):
141 return False
142 return True
144 def capture_vterm(self):
146 Capture contents of current terminal window and updates self.vterm
149 # Read everything from the terminal and get rid of completely empty
150 # lines (for first commands when the screen is empty).
151 lines = self.capture_vterm_impl()
152 lines = [l.strip() for l in lines]
153 while (len(lines) > 0) and (lines[-1].strip() == ""):
154 lines = lines[0:-1]
155 if (len(lines) == 0):
156 return
158 # When this is the very first screen, we simply copy it.
159 if len(self.full_vterm) == 0:
160 for l in lines:
161 self.full_vterm.append(l)
162 self.vterm.append(l)
163 else:
164 # Otherwise, we find whether there is some overlap, i.e. whether
165 # we are capturing a rolling screen.
166 lines_count = len(lines)
167 same_lines = 0
168 for i in range(lines_count, 0, -1):
169 if self.same_vterm_tail(lines[0:i]):
170 same_lines = i
171 break
172 # If there is no overlap, we might have missed some lines.
173 if same_lines == 0:
174 self.full_vterm.append("!!!!!! WARNING: probably missed some lines here !!!!!")
175 else:
176 # Otherwise, update the last line (last capture might have
177 # missed some characters).
178 if len(self.full_vterm) > 0:
179 self.full_vterm = self.full_vterm[0:-1]
180 if len(self.vterm) > 0:
181 self.vterm = self.vterm[0:-1]
182 same_lines = same_lines - 1
183 # Add the new lines.
184 for i in range(same_lines, lines_count):
185 self.full_vterm.append(lines[i])
186 self.vterm.append(lines[i])
188 def capture_vterm_impl(self):
190 Do not call but reimplement in subclass.
192 return []
194 def get_temp(self, id):
196 Get temporary file name.
198 os.makedirs('tmp-vm-python', exist_ok=True)
199 return 'tmp-vm-python/tmp-' + self.name + '-' + id