1#!/usr/bin/env python3

2# Copyright 2021 Canonical Ltd.

3# All rights reserved.

4#

5# Written by:

6# Maciej Kisielewski <maciej.kisielewski@canonical.com>

7"""Check if hotplugging works on an ethernet port."""

8

9 import sys

10 import time

11

12

13 def has_cable(iface):

14 """Check if cable is inserted in the ethernet port identified by iface."""

15 path = "/sys/class/net/{}/carrier".format(iface)

16 with open(path) as carrier:

17 return carrier.read()[0] == "1"

18

19

20 def main():

21 """Entry point to the program."""

22 if len(sys.argv) != 2:

23 raise SystemExit("Usage {} INTERFACE_NAME".format(sys.argv[0]))

24 iface = sys.argv[1]

25 # sanity check of the interface path

26 try:

27 has_cable(iface)

28 except Exception as exc:

29 msg = "Could not check the cable for '{}': {}".format(iface, exc)

30 raise SystemExit(msg) from exc

31 print(

32 (

33 "Press enter and unplug the ethernet cable "

34 "from the port {} of the System."

35 ).format(iface)

36 )

37 print("After 15 seconds plug it back in.")

38 print("Checkbox session may be interrupted but it should come back up.")

39 input()

40 print("Waiting for cable to get disconnected.")

41 elapsed = 0

42 while elapsed < 60:

43 if not has_cable(sys.argv[1]):

44 break

45 time.sleep(1)

46 print(".", flush=True, end="")

47 elapsed += 1

48 else:

49 raise SystemExit("Failed to detect unplugging!")

50 print("Cable unplugged!")

51 print("Waiting for the cable to get connected.")

52 elapsed = 0

53 while elapsed < 60:

54 if has_cable(sys.argv[1]):

55 break

56 time.sleep(1)

57 print(".", flush=True, end="")

58 elapsed += 1

59 else:

60 raise SystemExit("Failed to detect plugging it back!")

61 print("Cable detected!")

62

63

64 if __name__ == "__main__":

65 main()