api.go 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252
  1. // Copyright © 2021-2022 Ettore Di Giacinto <[email protected]>
  2. //
  3. // This program is free software; you can redistribute it and/or modify
  4. // it under the terms of the GNU General Public License as published by
  5. // the Free Software Foundation; either version 2 of the License, or
  6. // (at your option) any later version.
  7. //
  8. // This program is distributed in the hope that it will be useful,
  9. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. // GNU General Public License for more details.
  12. //
  13. // You should have received a copy of the GNU General Public License along
  14. // with this program; if not, see <http://www.gnu.org/licenses/>.
  15. package api
  16. import (
  17. "context"
  18. "embed"
  19. "io/fs"
  20. "net"
  21. "net/http"
  22. "strings"
  23. "time"
  24. "github.com/libp2p/go-libp2p-core/network"
  25. "github.com/libp2p/go-libp2p-core/peer"
  26. "github.com/miekg/dns"
  27. apiTypes "github.com/mudler/edgevpn/api/types"
  28. "github.com/labstack/echo/v4"
  29. "github.com/mudler/edgevpn/pkg/node"
  30. "github.com/mudler/edgevpn/pkg/protocol"
  31. "github.com/mudler/edgevpn/pkg/services"
  32. "github.com/mudler/edgevpn/pkg/types"
  33. )
  34. //go:embed public
  35. var embededFiles embed.FS
  36. func getFileSystem() http.FileSystem {
  37. fsys, err := fs.Sub(embededFiles, "public")
  38. if err != nil {
  39. panic(err)
  40. }
  41. return http.FS(fsys)
  42. }
  43. func API(ctx context.Context, l string, defaultInterval, timeout time.Duration, e *node.Node) error {
  44. ledger, _ := e.Ledger()
  45. ec := echo.New()
  46. if strings.HasPrefix(l, "unix://") {
  47. unixListener, err := net.Listen("unix", strings.ReplaceAll(l, "unix://", ""))
  48. if err != nil {
  49. return err
  50. }
  51. ec.Listener = unixListener
  52. }
  53. assetHandler := http.FileServer(getFileSystem())
  54. // Get data from ledger
  55. ec.GET("/api/files", func(c echo.Context) error {
  56. list := []*types.File{}
  57. for _, v := range ledger.CurrentData()[protocol.FilesLedgerKey] {
  58. machine := &types.File{}
  59. v.Unmarshal(machine)
  60. list = append(list, machine)
  61. }
  62. return c.JSON(http.StatusOK, list)
  63. })
  64. ec.GET("/api/summary", func(c echo.Context) error {
  65. files := len(ledger.CurrentData()[protocol.FilesLedgerKey])
  66. machines := len(ledger.CurrentData()[protocol.MachinesLedgerKey])
  67. users := len(ledger.CurrentData()[protocol.UsersLedgerKey])
  68. services := len(ledger.CurrentData()[protocol.ServicesLedgerKey])
  69. onChainNodes := len(e.HubRoom.Topic.ListPeers())
  70. p2pPeers := len(e.Host().Network().Peerstore().Peers())
  71. nodeID := e.Host().ID().String()
  72. blockchain := ledger.Index()
  73. return c.JSON(http.StatusOK, struct {
  74. Files, Machines, Users, Services, BlockChain, OnChainNodes, Peers int
  75. NodeID string
  76. }{files, machines, users, services, blockchain, onChainNodes, p2pPeers, nodeID})
  77. })
  78. ec.GET("/api/machines", func(c echo.Context) error {
  79. list := []*apiTypes.Machine{}
  80. for _, v := range ledger.CurrentData()[protocol.MachinesLedgerKey] {
  81. machine := &types.Machine{}
  82. v.Unmarshal(machine)
  83. m := &apiTypes.Machine{Machine: *machine}
  84. if e.Host().Network().Connectedness(peer.ID(machine.PeerID)) == network.Connected {
  85. m.Connected = true
  86. }
  87. for _, p := range e.HubRoom.Topic.ListPeers() {
  88. if p.String() == machine.PeerID {
  89. m.OnChain = true
  90. }
  91. }
  92. list = append(list, m)
  93. }
  94. return c.JSON(http.StatusOK, list)
  95. })
  96. ec.GET("/api/nodes", func(c echo.Context) error {
  97. list := []apiTypes.Peer{}
  98. for _, v := range e.HubRoom.Topic.ListPeers() {
  99. list = append(list, apiTypes.Peer{ID: v.String()})
  100. }
  101. return c.JSON(http.StatusOK, list)
  102. })
  103. ec.GET("/api/peerstore", func(c echo.Context) error {
  104. list := []apiTypes.Peer{}
  105. for _, v := range e.Host().Network().Peerstore().Peers() {
  106. list = append(list, apiTypes.Peer{ID: v.String()})
  107. }
  108. e.HubRoom.Topic.ListPeers()
  109. return c.JSON(http.StatusOK, list)
  110. })
  111. ec.GET("/api/users", func(c echo.Context) error {
  112. user := []*types.User{}
  113. for _, v := range ledger.CurrentData()[protocol.UsersLedgerKey] {
  114. u := &types.User{}
  115. v.Unmarshal(u)
  116. user = append(user, u)
  117. }
  118. return c.JSON(http.StatusOK, user)
  119. })
  120. ec.GET("/api/services", func(c echo.Context) error {
  121. list := []*types.Service{}
  122. for _, v := range ledger.CurrentData()[protocol.ServicesLedgerKey] {
  123. srvc := &types.Service{}
  124. v.Unmarshal(srvc)
  125. list = append(list, srvc)
  126. }
  127. return c.JSON(http.StatusOK, list)
  128. })
  129. ec.GET("/*", echo.WrapHandler(http.StripPrefix("/", assetHandler)))
  130. ec.GET("/api/blockchain", func(c echo.Context) error {
  131. return c.JSON(http.StatusOK, ledger.LastBlock())
  132. })
  133. ec.GET("/api/ledger", func(c echo.Context) error {
  134. return c.JSON(http.StatusOK, ledger.CurrentData())
  135. })
  136. ec.GET("/api/ledger/:bucket/:key", func(c echo.Context) error {
  137. bucket := c.Param("bucket")
  138. key := c.Param("key")
  139. return c.JSON(http.StatusOK, ledger.CurrentData()[bucket][key])
  140. })
  141. ec.GET("/api/ledger/:bucket", func(c echo.Context) error {
  142. bucket := c.Param("bucket")
  143. return c.JSON(http.StatusOK, ledger.CurrentData()[bucket])
  144. })
  145. announcing := struct{ State string }{"Announcing"}
  146. // Store arbitrary data
  147. ec.PUT("/api/ledger/:bucket/:key/:value", func(c echo.Context) error {
  148. bucket := c.Param("bucket")
  149. key := c.Param("key")
  150. value := c.Param("value")
  151. ledger.Persist(context.Background(), defaultInterval, timeout, bucket, key, value)
  152. return c.JSON(http.StatusOK, announcing)
  153. })
  154. ec.GET("/api/dns", func(c echo.Context) error {
  155. res := []apiTypes.DNS{}
  156. for r, e := range ledger.CurrentData()[protocol.DNSKey] {
  157. var t types.DNS
  158. e.Unmarshal(&t)
  159. d := map[string]string{}
  160. for k, v := range t {
  161. d[dns.TypeToString[uint16(k)]] = v
  162. }
  163. res = append(res,
  164. apiTypes.DNS{
  165. Regex: r,
  166. Records: d,
  167. })
  168. }
  169. return c.JSON(http.StatusOK, res)
  170. })
  171. // Announce dns
  172. ec.POST("/api/dns", func(c echo.Context) error {
  173. d := new(apiTypes.DNS)
  174. if err := c.Bind(d); err != nil {
  175. return echo.NewHTTPError(http.StatusBadRequest, err.Error())
  176. }
  177. entry := make(types.DNS)
  178. for r, e := range d.Records {
  179. entry[dns.Type(dns.StringToType[r])] = e
  180. }
  181. services.PersistDNSRecord(context.Background(), ledger, defaultInterval, timeout, d.Regex, entry)
  182. return c.JSON(http.StatusOK, announcing)
  183. })
  184. // Delete data from ledger
  185. ec.DELETE("/api/ledger/:bucket", func(c echo.Context) error {
  186. bucket := c.Param("bucket")
  187. ledger.AnnounceDeleteBucket(context.Background(), defaultInterval, timeout, bucket)
  188. return c.JSON(http.StatusOK, announcing)
  189. })
  190. ec.DELETE("/api/ledger/:bucket/:key", func(c echo.Context) error {
  191. bucket := c.Param("bucket")
  192. key := c.Param("key")
  193. ledger.AnnounceDeleteBucketKey(context.Background(), defaultInterval, timeout, bucket, key)
  194. return c.JSON(http.StatusOK, announcing)
  195. })
  196. ec.HideBanner = true
  197. if err := ec.Start(l); err != nil && err != http.ErrServerClosed {
  198. return err
  199. }
  200. go func() {
  201. <-ctx.Done()
  202. ec.Shutdown(ctx)
  203. }()
  204. return nil
  205. }