awlsim-client 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. #
  4. # AWL simulator - Client interface
  5. #
  6. # Copyright 2013-2019 Michael Buesch <m@bues.ch>
  7. #
  8. # This program is free software; you can redistribute it and/or modify
  9. # it under the terms of the GNU General Public License as published by
  10. # the Free Software Foundation; either version 2 of the License, or
  11. # (at your option) any later version.
  12. #
  13. # This program is distributed in the hope that it will be useful,
  14. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. # GNU General Public License for more details.
  17. #
  18. # You should have received a copy of the GNU General Public License along
  19. # with this program; if not, write to the Free Software Foundation, Inc.,
  20. # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  21. #
  22. from __future__ import division, absolute_import, print_function, unicode_literals
  23. import sys
  24. import getopt
  25. from awlsim_loader.common import *
  26. from awlsim_loader.coreclient import *
  27. def printCpuStats(cpuStatsMsg):
  28. if not cpuStatsMsg:
  29. print("Failed to fetch CPU statistics.")
  30. return
  31. if cpuStatsMsg.insnPerSecond > 0.0:
  32. insnPerSecondStr = floatToHumanReadable(cpuStatsMsg.insnPerSecond)
  33. usPerInsnStr = "%.03f" % ((1.0 / cpuStatsMsg.insnPerSecond) * 1000000.0)
  34. else:
  35. insnPerSecondStr = "-/-"
  36. usPerInsnStr = "-/-"
  37. if (cpuStatsMsg.avgCycleTime <= 0.0 or
  38. cpuStatsMsg.minCycleTime <= 0.0 or
  39. cpuStatsMsg.maxCycleTime <= 0.0):
  40. avgCycleTimeStr = minCycleTimeStr = maxCycleTimeStr = "-/-"
  41. else:
  42. avgCycleTimeStr = "%.03f" % (cpuStatsMsg.avgCycleTime * 1000.0)
  43. minCycleTimeStr = "%.03f" % (cpuStatsMsg.minCycleTime * 1000.0)
  44. maxCycleTimeStr = "%.03f" % (cpuStatsMsg.maxCycleTime * 1000.0)
  45. if cpuStatsMsg.running:
  46. print("CPU RUN %.01f s (system uptime %.01f s)" % (
  47. cpuStatsMsg.runtime, cpuStatsMsg.uptime))
  48. else:
  49. print("CPU STOP (system uptime %.01f s)" % (
  50. cpuStatsMsg.uptime))
  51. print(" OB1: avg: %s ms min: %s ms max: %s ms" % (
  52. avgCycleTimeStr, minCycleTimeStr, maxCycleTimeStr))
  53. print(" Speed: %s stmt/s (= %s us/stmt) %.01f stmt/cycle" % (
  54. insnPerSecondStr, usPerInsnStr, cpuStatsMsg.insnPerCycle))
  55. class TextInterfaceAwlSimClient(AwlSimClient):
  56. pass
  57. def usage():
  58. print("awlsim-client version %s" % VERSION_STRING)
  59. print("")
  60. print("Usage: awlsim-client [OPTIONS] <ACTIONS>")
  61. print("")
  62. print("Options:")
  63. print(" -c|--connect HOST[:PORT] Connect to the server at HOST:PORT")
  64. print(" Defaults to %s:%d" % (
  65. AwlSimServer.DEFAULT_HOST, AwlSimServer.DEFAULT_PORT))
  66. print(" -t|--timeout 10.0 Set the connection timeout (default 10 s)")
  67. print(" -L|--loglevel LVL Set the client log level:")
  68. print(" 0: Log nothing")
  69. print(" 1: Log errors")
  70. print(" 2: Log errors and warnings (default)")
  71. print(" 3: Log errors, warnings and info messages")
  72. print(" 4: Verbose logging")
  73. print(" 5: Extremely verbose logging")
  74. print("")
  75. print(" -s|--ssh-tunnel Establish the connection via SSH tunnel.")
  76. print(" -P|--ssh-passphrase XYZ Use XYZ as SSH passphrase.")
  77. print(" Default: Ask user.")
  78. print(" --ssh-user %s SSH user. Default: %s" % (
  79. SSHTunnel.SSH_DEFAULT_USER, SSHTunnel.SSH_DEFAULT_USER))
  80. print(" --ssh-port %s SSH port. Default: %s" % (
  81. SSHTunnel.SSH_PORT, SSHTunnel.SSH_PORT))
  82. print(" --ssh-localport auto SSH localport number or 'auto'.")
  83. print(" --ssh-exe %s SSH client executable path. Default: %s" % (
  84. SSHTunnel.SSH_DEFAULT_EXECUTABLE, SSHTunnel.SSH_DEFAULT_EXECUTABLE))
  85. print("")
  86. print("Actions to be performed on the server:")
  87. print(" -r|--runstate RUN/STOP Set the run state of the CPU.")
  88. print(" -S|--stats Fetch and display CPU statistics.")
  89. print(" --meas-start Start instruction time measurements.")
  90. print(" --meas-stop Stop instruction time measurements.")
  91. print(" --shutdown Shutdown the core server system.")
  92. print(" --reboot Reboot the core server system.")
  93. def main():
  94. opt_connect = (AwlSimServer.DEFAULT_HOST, AwlSimServer.DEFAULT_PORT)
  95. opt_timeout = 10.0
  96. opt_loglevel = Logging.LOG_WARNING
  97. opt_sshTunnel = False
  98. opt_sshPassphrase = None
  99. opt_sshUser = SSHTunnel.SSH_DEFAULT_USER
  100. opt_sshPort = SSHTunnel.SSH_PORT
  101. opt_sshLocalPort = None
  102. opt_sshExe = SSHTunnel.SSH_DEFAULT_EXECUTABLE
  103. actions = []
  104. try:
  105. (opts, args) = getopt.getopt(sys.argv[1:],
  106. "hc:t:L:sP:r:S",
  107. [ "help", "connect=", "timeout=", "loglevel=",
  108. "ssh-tunnel", "ssh-passphrase=", "ssh-user=", "ssh-port=", "ssh-localport=", "ssh-exe=",
  109. "runstate=", "stats", "meas-start", "meas-stop", "shutdown", "reboot", ])
  110. except getopt.GetoptError as e:
  111. printError(str(e))
  112. usage()
  113. return ExitCodes.EXIT_ERR_CMDLINE
  114. for (o, v) in opts:
  115. if o in ("-h", "--help"):
  116. usage()
  117. return ExitCodes.EXIT_OK
  118. if o in ("-c", "--connect"):
  119. try:
  120. host, port = parseNetAddress(v)
  121. if port is None:
  122. port = AwlSimServer.DEFAULT_PORT
  123. opt_connect = (host, port)
  124. except AwlSimError as e:
  125. printError("-c|--connect: %s" % e.message)
  126. sys.exit(1)
  127. if o in ("-t", "--timeout"):
  128. try:
  129. opt_timeout = float(v)
  130. except ValueError:
  131. printError("-t|--timeout: Invalid timeout value")
  132. sys.exit(1)
  133. if o in ("-L", "--loglevel"):
  134. try:
  135. opt_loglevel = int(v)
  136. except ValueError:
  137. printError("-L|--loglevel: Invalid log level")
  138. sys.exit(1)
  139. if o in ("-s", "--ssh-tunnel"):
  140. opt_sshTunnel = True
  141. if o in ("-P", "--ssh-passphrase"):
  142. opt_sshPassphrase = v
  143. if o == "--ssh-user":
  144. opt_sshUser = v
  145. if o == "--ssh-port":
  146. try:
  147. opt_sshPort = int(v)
  148. except ValueError:
  149. printError("--ssh-port: Invalid port number")
  150. sys.exit(1)
  151. if o == "--ssh-localport":
  152. try:
  153. if v.lower().strip() == "auto":
  154. opt_sshLocalPort = None
  155. else:
  156. opt_sshLocalPort = int(v)
  157. except ValueError:
  158. printError("--ssh-localport: Invalid port number")
  159. sys.exit(1)
  160. if o == "--ssh-exe":
  161. opt_sshExe = v
  162. if o in ("-r", "--runstate"):
  163. if v.upper().strip() in ("RUN", "1", "START"):
  164. actions.append(("runstate", True))
  165. elif v.upper().strip() in ("STOP", "0"):
  166. actions.append(("runstate", False))
  167. else:
  168. printError("-r|--runstate: Invalid run state")
  169. sys.exit(1)
  170. if o in ("-S", "--stats"):
  171. actions.append(("stats", None))
  172. if o == "--meas-start":
  173. actions.append(("meas-start", None))
  174. if o == "--meas-stop":
  175. actions.append(("meas-stop", None))
  176. if o == "--shutdown":
  177. actions.append(("shutdown", None))
  178. if o == "--reboot":
  179. actions.append(("reboot", None))
  180. if args:
  181. usage()
  182. return ExitCodes.EXIT_ERR_CMDLINE
  183. if not actions:
  184. usage()
  185. return ExitCodes.EXIT_ERR_CMDLINE
  186. client = None
  187. try:
  188. Logging.setLoglevel(opt_loglevel)
  189. host, port = opt_connect
  190. if opt_sshTunnel:
  191. printInfo("Establishing SSH tunnel...")
  192. tunnel = SSHTunnel(
  193. remoteHost=host,
  194. remotePort=port,
  195. localPort=opt_sshLocalPort,
  196. sshUser=opt_sshUser,
  197. sshPort=opt_sshPort,
  198. sshExecutable=opt_sshExe,
  199. sshPassphrase=opt_sshPassphrase
  200. )
  201. host, port = tunnel.connect()
  202. client = TextInterfaceAwlSimClient()
  203. client.connectToServer(host=host,
  204. port=port,
  205. timeout=opt_timeout)
  206. for action, actionValue in actions:
  207. if action == "runstate":
  208. client.setRunState(actionValue)
  209. elif action == "stats":
  210. printCpuStats(client.getCpuStats(sync=True))
  211. elif action == "meas-start":
  212. if not client.measStart():
  213. printError("Failed to start measurements.")
  214. elif action == "meas-stop":
  215. reportData = client.measStop()
  216. if reportData:
  217. sys.stdout.write(reportData)
  218. sys.stdout.flush()
  219. else:
  220. printError("Measurement failed. No data.")
  221. elif action == "shutdown":
  222. client.shutdownCoreServerSystem()
  223. elif action == "reboot":
  224. client.rebootCoreServerSystem()
  225. else:
  226. assert(0)
  227. except AwlSimError as e:
  228. printError(e.getReport())
  229. return ExitCodes.EXIT_ERR_SIM
  230. finally:
  231. if client:
  232. client.shutdown()
  233. return ExitCodes.EXIT_OK
  234. if __name__ == "__main__":
  235. sys.exit(main())