Debian Codegraph @

examples/qemu-networking/qemunetworkstrategy.py

raw symbols SCIP
1 # Copyright 2023 by Garmin Ltd. or its subsidiaries
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain 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,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
14
15 import enum
16
17 import attr
18
19 from labgrid import target_factory, step
20 from labgrid.strategy import Strategy, StrategyError, never_retry
21 from labgrid.util import get_free_port
22
23
24 class Status(enum.Enum):
25 unknown = 0
26 off = 1
27 shell = 2
28
29
30 @target_factory.reg_driver
31 @attr.s(eq=False)
32 class QEMUNetworkStrategy(Strategy):
33 bindings = {
34 "qemu": "QEMUDriver",
35 "shell": "ShellDriver",
36 "ssh": "SSHDriver",
37 }
38
39 status = attr.ib(default=Status.unknown)
40
41 def __attrs_post_init__(self):
42 super().__attrs_post_init__()
43 self.__port_forward = None
44 self.__remote_port = self.ssh.networkservice.port
45
46 @step(result=True)
47 def get_remote_address(self):
48 return str(self.shell.get_ip_addresses()[0].ip)
49
50 @step()
51 def update_network_service(self):
52 new_address = self.get_remote_address()
53 networkservice = self.ssh.networkservice
54
55 if networkservice.address != new_address:
56 self.target.deactivate(self.ssh)
57
58 if "user" in self.qemu.nic.split(","):
59 if self.__port_forward is not None:
60 self.qemu.remove_port_forward(*self.__port_forward)
61
62 local_port = get_free_port()
63 local_address = "127.0.0.1"
64
65 self.qemu.add_port_forward(
66 "tcp",
67 local_address,
68 local_port,
69 new_address,
70 self.__remote_port,
71 )
72 self.__port_forward = ("tcp", local_address, local_port)
73
74 networkservice.address = local_address
75 networkservice.port = local_port
76 else:
77 networkservice.address = new_address
78 networkservice.port = self.__remote_port
79
80 @never_retry
81 @step(args=["state"])
82 def transition(self, state, *, step):
83 if not isinstance(state, Status):
84 state = Status[state]
85
86 if state == Status.unknown:
87 raise StrategyError(f"can not transition to {state}")
88
89 elif self.status == state:
90 step.skip("nothing to do")
91 return
92
93 if state == Status.off:
94 self.target.activate(self.qemu)
95 self.qemu.off()
96
97 elif state == Status.shell:
98 self.target.activate(self.qemu)
99 self.qemu.on()
100 self.target.activate(self.shell)
101 self.update_network_service()
102
103 self.status = state