awlsim-client 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229
  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. def main():
  90. opt_connect = (AwlSimServer.DEFAULT_HOST, AwlSimServer.DEFAULT_PORT)
  91. opt_timeout = 10.0
  92. opt_loglevel = Logging.LOG_WARNING
  93. opt_sshTunnel = False
  94. opt_sshPassphrase = None
  95. opt_sshUser = SSHTunnel.SSH_DEFAULT_USER
  96. opt_sshPort = SSHTunnel.SSH_PORT
  97. opt_sshLocalPort = None
  98. opt_sshExe = SSHTunnel.SSH_DEFAULT_EXECUTABLE
  99. actions = []
  100. try:
  101. (opts, args) = getopt.getopt(sys.argv[1:],
  102. "hc:t:L:sP:r:S",
  103. [ "help", "connect=", "timeout=", "loglevel=",
  104. "ssh-tunnel", "ssh-passphrase=", "ssh-user=", "ssh-port=", "ssh-localport=", "ssh-exe=",
  105. "runstate=", "stats", ])
  106. except getopt.GetoptError as e:
  107. printError(str(e))
  108. usage()
  109. return ExitCodes.EXIT_ERR_CMDLINE
  110. for (o, v) in opts:
  111. if o in ("-h", "--help"):
  112. usage()
  113. return ExitCodes.EXIT_OK
  114. if o in ("-c", "--connect"):
  115. try:
  116. host, port = parseNetAddress(v)
  117. if port is None:
  118. port = AwlSimServer.DEFAULT_PORT
  119. opt_connect = (host, port)
  120. except AwlSimError as e:
  121. printError("-c|--connect: %s" % e.message)
  122. sys.exit(1)
  123. if o in ("-t", "--timeout"):
  124. try:
  125. opt_timeout = float(v)
  126. except ValueError:
  127. printError("-t|--timeout: Invalid timeout value")
  128. sys.exit(1)
  129. if o in ("-L", "--loglevel"):
  130. try:
  131. opt_loglevel = int(v)
  132. except ValueError:
  133. printError("-L|--loglevel: Invalid log level")
  134. sys.exit(1)
  135. if o in ("-s", "--ssh-tunnel"):
  136. opt_sshTunnel = True
  137. if o in ("-P", "--ssh-passphrase"):
  138. opt_sshPassphrase = v
  139. if o == "--ssh-user":
  140. opt_sshUser = v
  141. if o == "--ssh-port":
  142. try:
  143. opt_sshPort = int(v)
  144. except ValueError:
  145. printError("--ssh-port: Invalid port number")
  146. sys.exit(1)
  147. if o == "--ssh-localport":
  148. try:
  149. if v.lower().strip() == "auto":
  150. opt_sshLocalPort = None
  151. else:
  152. opt_sshLocalPort = int(v)
  153. except ValueError:
  154. printError("--ssh-localport: Invalid port number")
  155. sys.exit(1)
  156. if o == "--ssh-exe":
  157. opt_sshExe = v
  158. if o in ("-r", "--runstate"):
  159. if v.upper().strip() in ("RUN", "1", "START"):
  160. actions.append(("runstate", True))
  161. elif v.upper().strip() in ("STOP", "0"):
  162. actions.append(("runstate", False))
  163. else:
  164. printError("-r|--runstate: Invalid run state")
  165. sys.exit(1)
  166. if o in ("-S", "--stats"):
  167. actions.append(("stats", None))
  168. if args:
  169. usage()
  170. return ExitCodes.EXIT_ERR_CMDLINE
  171. if not actions:
  172. usage()
  173. return ExitCodes.EXIT_ERR_CMDLINE
  174. client = None
  175. try:
  176. Logging.setLoglevel(opt_loglevel)
  177. host, port = opt_connect
  178. if opt_sshTunnel:
  179. printInfo("Establishing SSH tunnel...")
  180. tunnel = SSHTunnel(
  181. remoteHost=host,
  182. remotePort=port,
  183. localPort=opt_sshLocalPort,
  184. sshUser=opt_sshUser,
  185. sshPort=opt_sshPort,
  186. sshExecutable=opt_sshExe,
  187. sshPassphrase=opt_sshPassphrase
  188. )
  189. host, port = tunnel.connect()
  190. client = TextInterfaceAwlSimClient()
  191. client.connectToServer(host=host,
  192. port=port,
  193. timeout=opt_timeout)
  194. for action, actionValue in actions:
  195. if action == "runstate":
  196. client.setRunState(actionValue)
  197. elif action == "stats":
  198. printCpuStats(client.getCpuStats(sync=True))
  199. else:
  200. assert(0)
  201. except AwlSimError as e:
  202. printError(e.getReport())
  203. return ExitCodes.EXIT_ERR_SIM
  204. finally:
  205. if client:
  206. client.shutdown()
  207. return ExitCodes.EXIT_OK
  208. if __name__ == "__main__":
  209. sys.exit(main())