debug.go 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312
  1. /*
  2. * ECAL
  3. *
  4. * Copyright 2020 Matthias Ladkau. All rights reserved.
  5. *
  6. * This Source Code Form is subject to the terms of the MIT
  7. * License, If a copy of the MIT License was not distributed with this
  8. * file, You can obtain one at https://opensource.org/licenses/MIT.
  9. */
  10. package tool
  11. import (
  12. "bufio"
  13. "bytes"
  14. "encoding/base64"
  15. "encoding/json"
  16. "flag"
  17. "fmt"
  18. "net"
  19. "strings"
  20. "time"
  21. "devt.de/krotik/common/errorutil"
  22. "devt.de/krotik/common/stringutil"
  23. "devt.de/krotik/ecal/interpreter"
  24. "devt.de/krotik/ecal/util"
  25. )
  26. /*
  27. CLIDebugInterpreter is a commandline interpreter with debug capabilities for ECAL.
  28. */
  29. type CLIDebugInterpreter struct {
  30. *CLIInterpreter
  31. // Parameter these can either be set programmatically or via CLI args
  32. DebugServerAddr *string // Debug server address
  33. RunDebugServer *bool // Run a debug server
  34. EchoDebugServer *bool // Echo all input and output of the debug server
  35. Interactive *bool // Flag if the interpreter should open a console in the current tty.
  36. }
  37. /*
  38. NewCLIDebugInterpreter wraps an existing CLIInterpreter object and adds capabilities.
  39. */
  40. func NewCLIDebugInterpreter(i *CLIInterpreter) *CLIDebugInterpreter {
  41. return &CLIDebugInterpreter{i, nil, nil, nil, nil}
  42. }
  43. /*
  44. ParseArgs parses the command line arguments.
  45. */
  46. func (i *CLIDebugInterpreter) ParseArgs() bool {
  47. if i.Interactive != nil {
  48. return false
  49. }
  50. i.DebugServerAddr = flag.String("serveraddr", "localhost:33274", "Debug server address") // Think BERTA
  51. i.RunDebugServer = flag.Bool("server", false, "Run a debug server")
  52. i.EchoDebugServer = flag.Bool("echo", false, "Echo all i/o of the debug server")
  53. i.Interactive = flag.Bool("interactive", true, "Run interactive console")
  54. return i.CLIInterpreter.ParseArgs()
  55. }
  56. /*
  57. Interpret starts the ECAL code interpreter with debug capabilities.
  58. */
  59. func (i *CLIDebugInterpreter) Interpret() error {
  60. if i.ParseArgs() {
  61. return nil
  62. }
  63. err := i.CreateRuntimeProvider("debug console")
  64. if err == nil {
  65. // Set custom messages
  66. i.CLIInterpreter.CustomWelcomeMessage = "Running in debug mode - "
  67. if *i.RunDebugServer {
  68. i.CLIInterpreter.CustomWelcomeMessage += fmt.Sprintf("with debug server on %v - ", *i.DebugServerAddr)
  69. }
  70. i.CLIInterpreter.CustomWelcomeMessage += "prefix debug commands with ##"
  71. i.CustomHelpString = " @dbg [glob] - List all available debug commands.\n"
  72. // Set debug object on the runtime provider
  73. i.RuntimeProvider.Debugger = interpreter.NewECALDebugger(i.GlobalVS)
  74. // Set this object as a custom handler to deal with input.
  75. i.CustomHandler = i
  76. if *i.RunDebugServer {
  77. debugServer := &debugTelnetServer{*i.DebugServerAddr, "ECALDebugServer: ",
  78. nil, true, *i.EchoDebugServer, i, i.RuntimeProvider.Logger}
  79. go debugServer.Run()
  80. time.Sleep(500 * time.Millisecond) // Too lazy to do proper signalling
  81. defer func() {
  82. if debugServer.listener != nil {
  83. debugServer.listen = false
  84. debugServer.listener.Close() // Attempt to cleanup
  85. }
  86. }()
  87. }
  88. err = i.CLIInterpreter.Interpret(*i.Interactive)
  89. }
  90. return err
  91. }
  92. /*
  93. CanHandle checks if a given string can be handled by this handler.
  94. */
  95. func (i *CLIDebugInterpreter) CanHandle(s string) bool {
  96. return strings.HasPrefix(s, "##") || strings.HasPrefix(s, "@dbg")
  97. }
  98. /*
  99. Handle handles a given input string.
  100. */
  101. func (i *CLIDebugInterpreter) Handle(ot OutputTerminal, line string) {
  102. if strings.HasPrefix(line, "@dbg") {
  103. args := strings.Fields(line)[1:]
  104. tabData := []string{"Debug command", "Description"}
  105. for name, f := range interpreter.DebugCommandsMap {
  106. ds := f.DocString()
  107. if len(args) > 0 && !matchesFulltextSearch(ot, fmt.Sprintf("%v %v", name, ds), args[0]) {
  108. continue
  109. }
  110. tabData = fillTableRow(tabData, name, ds)
  111. }
  112. if len(tabData) > 2 {
  113. ot.WriteString(stringutil.PrintGraphicStringTable(tabData, 2, 1,
  114. stringutil.SingleDoubleLineTable))
  115. }
  116. ot.WriteString(fmt.Sprintln(fmt.Sprintln()))
  117. } else {
  118. res, err := i.RuntimeProvider.Debugger.HandleInput(strings.TrimSpace(line[2:]))
  119. if err == nil {
  120. var outBytes []byte
  121. outBytes, err = json.MarshalIndent(res, "", " ")
  122. if err == nil {
  123. ot.WriteString(fmt.Sprintln(fmt.Sprintln(string(outBytes))))
  124. }
  125. }
  126. if err != nil {
  127. var outBytes []byte
  128. outBytes, err = json.MarshalIndent(map[string]interface{}{
  129. "DebuggerError": err.Error(),
  130. }, "", " ")
  131. errorutil.AssertOk(err)
  132. ot.WriteString(fmt.Sprintln(fmt.Sprintln(string(outBytes))))
  133. }
  134. }
  135. }
  136. /*
  137. debugTelnetServer is a simple telnet server to send and receive debug data.
  138. */
  139. type debugTelnetServer struct {
  140. address string
  141. logPrefix string
  142. listener *net.TCPListener
  143. listen bool
  144. echo bool
  145. interpreter *CLIDebugInterpreter
  146. logger util.Logger
  147. }
  148. /*
  149. Run runs the debug server.
  150. */
  151. func (s *debugTelnetServer) Run() {
  152. tcpaddr, err := net.ResolveTCPAddr("tcp", s.address)
  153. if err == nil {
  154. if s.listener, err = net.ListenTCP("tcp", tcpaddr); err == nil {
  155. s.logger.LogInfo(s.logPrefix,
  156. "Running Debug Server on ", tcpaddr.String())
  157. for s.listen {
  158. var conn net.Conn
  159. if conn, err = s.listener.Accept(); err == nil {
  160. go s.HandleConnection(conn)
  161. } else if s.listen {
  162. s.logger.LogError(s.logPrefix, err)
  163. err = nil
  164. }
  165. }
  166. }
  167. }
  168. if s.listen && err != nil {
  169. s.logger.LogError(s.logPrefix, "Could not start debug server - ", err)
  170. }
  171. }
  172. /*
  173. HandleConnection handles an incoming connection.
  174. */
  175. func (s *debugTelnetServer) HandleConnection(conn net.Conn) {
  176. tid := s.interpreter.RuntimeProvider.NewThreadID()
  177. inputReader := bufio.NewReader(conn)
  178. outputTerminal := OutputTerminal(&bufioWriterShim{fmt.Sprint(conn.RemoteAddr()), bufio.NewWriter(conn), s.echo})
  179. line := ""
  180. s.logger.LogDebug(s.logPrefix, "Connect ", conn.RemoteAddr())
  181. if s.echo {
  182. fmt.Println(fmt.Sprintf("%v : Connected", conn.RemoteAddr()))
  183. }
  184. for {
  185. var outBytes []byte
  186. var err error
  187. if line, err = inputReader.ReadString('\n'); err == nil {
  188. line = strings.TrimSpace(line)
  189. if s.echo {
  190. fmt.Println(fmt.Sprintf("%v > %v", conn.RemoteAddr(), line))
  191. }
  192. if line == "exit" || line == "q" || line == "quit" || line == "bye" || line == "\x04" {
  193. break
  194. }
  195. isHelpTable := strings.HasPrefix(line, "@")
  196. if !s.interpreter.CanHandle(line) || isHelpTable {
  197. buffer := bytes.NewBuffer(nil)
  198. s.interpreter.HandleInput(&bufioWriterShim{"tmpbuffer", bufio.NewWriter(buffer), false}, line, tid)
  199. if isHelpTable {
  200. // Special case we have tables which should be transformed
  201. r := strings.NewReplacer("═", "*", "│", "*", "╪", "*", "╒", "*",
  202. "╕", "*", "╘", "*", "╛", "*", "╤", "*", "╞", "*", "╡", "*", "╧", "*")
  203. outBytes = []byte(r.Replace(buffer.String()))
  204. } else {
  205. outBytes = buffer.Bytes()
  206. }
  207. outBytes, err = json.MarshalIndent(map[string]interface{}{
  208. "EncodedOutput": base64.StdEncoding.EncodeToString(outBytes),
  209. }, "", " ")
  210. errorutil.AssertOk(err)
  211. outputTerminal.WriteString(fmt.Sprintln(fmt.Sprintln(string(outBytes))))
  212. } else {
  213. s.interpreter.HandleInput(outputTerminal, line, tid)
  214. }
  215. }
  216. if err != nil {
  217. if s.echo {
  218. fmt.Println(fmt.Sprintf("%v : Disconnected", conn.RemoteAddr()))
  219. }
  220. s.logger.LogDebug(s.logPrefix, "Disconnect ", conn.RemoteAddr(), " - ", err)
  221. break
  222. }
  223. }
  224. conn.Close()
  225. }
  226. /*
  227. bufioWriterShim is a shim to allow a bufio.Writer to be used as an OutputTerminal.
  228. */
  229. type bufioWriterShim struct {
  230. id string
  231. writer *bufio.Writer
  232. echo bool
  233. }
  234. /*
  235. WriteString write a string to the writer.
  236. */
  237. func (shim *bufioWriterShim) WriteString(s string) {
  238. if shim.echo {
  239. fmt.Println(fmt.Sprintf("%v < %v", shim.id, s))
  240. }
  241. shim.writer.WriteString(s)
  242. shim.writer.Flush()
  243. }