debug.go 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254
  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. "encoding/json"
  14. "flag"
  15. "fmt"
  16. "net"
  17. "strings"
  18. "time"
  19. "devt.de/krotik/common/stringutil"
  20. "devt.de/krotik/ecal/interpreter"
  21. "devt.de/krotik/ecal/util"
  22. )
  23. /*
  24. CLIDebugInterpreter is a commandline interpreter with debug capabilities for ECAL.
  25. */
  26. type CLIDebugInterpreter struct {
  27. *CLIInterpreter
  28. // Parameter these can either be set programmatically or via CLI args
  29. DebugServerAddr *string // Debug server address
  30. RunDebugServer *bool // Run a debug server
  31. Interactive *bool // Flag if the interpreter should open a console in the current tty.
  32. }
  33. /*
  34. NewCLIDebugInterpreter wraps an existing CLIInterpreter object and adds capabilities.
  35. */
  36. func NewCLIDebugInterpreter(i *CLIInterpreter) *CLIDebugInterpreter {
  37. return &CLIDebugInterpreter{i, nil, nil, nil}
  38. }
  39. /*
  40. ParseArgs parses the command line arguments.
  41. */
  42. func (i *CLIDebugInterpreter) ParseArgs() bool {
  43. if i.Interactive != nil {
  44. return false
  45. }
  46. i.DebugServerAddr = flag.String("serveraddr", "localhost:33274", "Debug server address") // Think BERTA
  47. i.RunDebugServer = flag.Bool("server", false, "Run a debug server")
  48. i.Interactive = flag.Bool("interactive", true, "Run interactive console")
  49. return i.CLIInterpreter.ParseArgs()
  50. }
  51. /*
  52. Interpret starts the ECAL code interpreter with debug capabilities.
  53. */
  54. func (i *CLIDebugInterpreter) Interpret() error {
  55. if i.ParseArgs() {
  56. return nil
  57. }
  58. err := i.CreateRuntimeProvider("debug console")
  59. if err == nil {
  60. // Set custom messages
  61. i.CLIInterpreter.CustomWelcomeMessage = "Running in debug mode - "
  62. if *i.RunDebugServer {
  63. i.CLIInterpreter.CustomWelcomeMessage += fmt.Sprintf("with debug server on %v - ", *i.DebugServerAddr)
  64. }
  65. i.CLIInterpreter.CustomWelcomeMessage += "prefix debug commands with ##"
  66. i.CustomHelpString = " @dbg [glob] - List all available debug commands.\n"
  67. // Set debug object on the runtime provider
  68. i.RuntimeProvider.Debugger = interpreter.NewECALDebugger(i.GlobalVS)
  69. // Set this object as a custom handler to deal with input.
  70. i.CustomHandler = i
  71. if *i.RunDebugServer {
  72. debugServer := &debugTelnetServer{*i.DebugServerAddr, "ECALDebugServer: ",
  73. nil, true, i, i.RuntimeProvider.Logger}
  74. go debugServer.Run()
  75. time.Sleep(500 * time.Millisecond) // Too lazy to do proper signalling
  76. defer func() {
  77. if debugServer.listener != nil {
  78. debugServer.listen = false
  79. debugServer.listener.Close() // Attempt to cleanup
  80. }
  81. }()
  82. }
  83. err = i.CLIInterpreter.Interpret(*i.Interactive)
  84. }
  85. return err
  86. }
  87. /*
  88. CanHandle checks if a given string can be handled by this handler.
  89. */
  90. func (i *CLIDebugInterpreter) CanHandle(s string) bool {
  91. return strings.HasPrefix(s, "##") || strings.HasPrefix(s, "@dbg")
  92. }
  93. /*
  94. Handle handles a given input string.
  95. */
  96. func (i *CLIDebugInterpreter) Handle(ot OutputTerminal, line string) {
  97. if strings.HasPrefix(line, "@dbg") {
  98. args := strings.Fields(line)[1:]
  99. tabData := []string{"Debug command", "Description"}
  100. for name, f := range interpreter.DebugCommandsMap {
  101. ds := f.DocString()
  102. if len(args) > 0 && !matchesFulltextSearch(ot, fmt.Sprintf("%v %v", name, ds), args[0]) {
  103. continue
  104. }
  105. tabData = fillTableRow(tabData, name, ds)
  106. }
  107. if len(tabData) > 2 {
  108. ot.WriteString(stringutil.PrintGraphicStringTable(tabData, 2, 1,
  109. stringutil.SingleDoubleLineTable))
  110. }
  111. } else {
  112. res, err := i.RuntimeProvider.Debugger.HandleInput(strings.TrimSpace(line[2:]))
  113. if err == nil {
  114. var outBytes []byte
  115. outBytes, err = json.MarshalIndent(res, "", " ")
  116. if err == nil {
  117. ot.WriteString(fmt.Sprintln(string(outBytes)))
  118. }
  119. }
  120. if err != nil {
  121. ot.WriteString(fmt.Sprintf("Debugger Error: %v", err.Error()))
  122. }
  123. }
  124. }
  125. /*
  126. debugTelnetServer is a simple telnet server to send and receive debug data.
  127. */
  128. type debugTelnetServer struct {
  129. address string
  130. logPrefix string
  131. listener *net.TCPListener
  132. listen bool
  133. interpreter *CLIDebugInterpreter
  134. logger util.Logger
  135. }
  136. /*
  137. Run runs the debug server.
  138. */
  139. func (s *debugTelnetServer) Run() {
  140. tcpaddr, err := net.ResolveTCPAddr("tcp", s.address)
  141. if err == nil {
  142. if s.listener, err = net.ListenTCP("tcp", tcpaddr); err == nil {
  143. s.logger.LogInfo(s.logPrefix,
  144. "Running Debug Server on ", tcpaddr.String())
  145. for s.listen {
  146. var conn net.Conn
  147. if conn, err = s.listener.Accept(); err == nil {
  148. go s.HandleConnection(conn)
  149. } else if s.listen {
  150. s.logger.LogError(s.logPrefix, err)
  151. err = nil
  152. }
  153. }
  154. }
  155. }
  156. if s.listen && err != nil {
  157. s.logger.LogError(s.logPrefix, "Could not start debug server - ", err)
  158. }
  159. }
  160. /*
  161. HandleConnection handles an incoming connection.
  162. */
  163. func (s *debugTelnetServer) HandleConnection(conn net.Conn) {
  164. tid := s.interpreter.RuntimeProvider.NewThreadID()
  165. inputReader := bufio.NewReader(conn)
  166. outputTerminal := OutputTerminal(&bufioWriterShim{bufio.NewWriter(conn)})
  167. line := ""
  168. s.logger.LogDebug(s.logPrefix, "Connect ", conn.RemoteAddr())
  169. for {
  170. var err error
  171. if line, err = inputReader.ReadString('\n'); err == nil {
  172. line = strings.TrimSpace(line)
  173. if line == "exit" || line == "q" || line == "quit" || line == "bye" || line == "\x04" {
  174. break
  175. }
  176. s.interpreter.HandleInput(outputTerminal, line, tid)
  177. }
  178. if err != nil {
  179. s.logger.LogDebug(s.logPrefix, "Disconnect ", conn.RemoteAddr(), " - ", err)
  180. break
  181. }
  182. }
  183. conn.Close()
  184. }
  185. /*
  186. bufioWriterShim is a shim to allow a bufio.Writer to be used as an OutputTerminal.
  187. */
  188. type bufioWriterShim struct {
  189. writer *bufio.Writer
  190. }
  191. /*
  192. WriteString write a string to the writer.
  193. */
  194. func (shim *bufioWriterShim) WriteString(s string) {
  195. shim.writer.WriteString(s)
  196. shim.writer.Flush()
  197. }