api.go 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241
  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/http"
  21. "time"
  22. "github.com/libp2p/go-libp2p-core/network"
  23. "github.com/libp2p/go-libp2p-core/peer"
  24. "github.com/miekg/dns"
  25. apiTypes "github.com/mudler/edgevpn/api/types"
  26. "github.com/labstack/echo/v4"
  27. "github.com/mudler/edgevpn/pkg/node"
  28. "github.com/mudler/edgevpn/pkg/protocol"
  29. "github.com/mudler/edgevpn/pkg/services"
  30. "github.com/mudler/edgevpn/pkg/types"
  31. )
  32. //go:embed public
  33. var embededFiles embed.FS
  34. func getFileSystem() http.FileSystem {
  35. fsys, err := fs.Sub(embededFiles, "public")
  36. if err != nil {
  37. panic(err)
  38. }
  39. return http.FS(fsys)
  40. }
  41. func API(ctx context.Context, l string, defaultInterval, timeout time.Duration, e *node.Node) error {
  42. ledger, _ := e.Ledger()
  43. ec := echo.New()
  44. assetHandler := http.FileServer(getFileSystem())
  45. // Get data from ledger
  46. ec.GET("/api/files", func(c echo.Context) error {
  47. list := []*types.File{}
  48. for _, v := range ledger.CurrentData()[protocol.FilesLedgerKey] {
  49. machine := &types.File{}
  50. v.Unmarshal(machine)
  51. list = append(list, machine)
  52. }
  53. return c.JSON(http.StatusOK, list)
  54. })
  55. ec.GET("/api/summary", func(c echo.Context) error {
  56. files := len(ledger.CurrentData()[protocol.FilesLedgerKey])
  57. machines := len(ledger.CurrentData()[protocol.MachinesLedgerKey])
  58. users := len(ledger.CurrentData()[protocol.UsersLedgerKey])
  59. services := len(ledger.CurrentData()[protocol.ServicesLedgerKey])
  60. onChainNodes := len(e.HubRoom.Topic.ListPeers())
  61. p2pPeers := len(e.Host().Network().Peerstore().Peers())
  62. nodeID := e.Host().ID().String()
  63. blockchain := ledger.Index()
  64. return c.JSON(http.StatusOK, struct {
  65. Files, Machines, Users, Services, BlockChain, OnChainNodes, Peers int
  66. NodeID string
  67. }{files, machines, users, services, blockchain, onChainNodes, p2pPeers, nodeID})
  68. })
  69. ec.GET("/api/machines", func(c echo.Context) error {
  70. list := []*apiTypes.Machine{}
  71. for _, v := range ledger.CurrentData()[protocol.MachinesLedgerKey] {
  72. machine := &types.Machine{}
  73. v.Unmarshal(machine)
  74. m := &apiTypes.Machine{Machine: *machine}
  75. if e.Host().Network().Connectedness(peer.ID(machine.PeerID)) == network.Connected {
  76. m.Connected = true
  77. }
  78. for _, p := range e.HubRoom.Topic.ListPeers() {
  79. if p.String() == machine.PeerID {
  80. m.OnChain = true
  81. }
  82. }
  83. list = append(list, m)
  84. }
  85. return c.JSON(http.StatusOK, list)
  86. })
  87. ec.GET("/api/nodes", func(c echo.Context) error {
  88. list := []apiTypes.Peer{}
  89. for _, v := range e.HubRoom.Topic.ListPeers() {
  90. list = append(list, apiTypes.Peer{ID: v.String()})
  91. }
  92. return c.JSON(http.StatusOK, list)
  93. })
  94. ec.GET("/api/peerstore", func(c echo.Context) error {
  95. list := []apiTypes.Peer{}
  96. for _, v := range e.Host().Network().Peerstore().Peers() {
  97. list = append(list, apiTypes.Peer{ID: v.String()})
  98. }
  99. e.HubRoom.Topic.ListPeers()
  100. return c.JSON(http.StatusOK, list)
  101. })
  102. ec.GET("/api/users", func(c echo.Context) error {
  103. user := []*types.User{}
  104. for _, v := range ledger.CurrentData()[protocol.UsersLedgerKey] {
  105. u := &types.User{}
  106. v.Unmarshal(u)
  107. user = append(user, u)
  108. }
  109. return c.JSON(http.StatusOK, user)
  110. })
  111. ec.GET("/api/services", func(c echo.Context) error {
  112. list := []*types.Service{}
  113. for _, v := range ledger.CurrentData()[protocol.ServicesLedgerKey] {
  114. srvc := &types.Service{}
  115. v.Unmarshal(srvc)
  116. list = append(list, srvc)
  117. }
  118. return c.JSON(http.StatusOK, list)
  119. })
  120. ec.GET("/*", echo.WrapHandler(http.StripPrefix("/", assetHandler)))
  121. ec.GET("/api/blockchain", func(c echo.Context) error {
  122. return c.JSON(http.StatusOK, ledger.LastBlock())
  123. })
  124. ec.GET("/api/ledger", func(c echo.Context) error {
  125. return c.JSON(http.StatusOK, ledger.CurrentData())
  126. })
  127. ec.GET("/api/ledger/:bucket/:key", func(c echo.Context) error {
  128. bucket := c.Param("bucket")
  129. key := c.Param("key")
  130. return c.JSON(http.StatusOK, ledger.CurrentData()[bucket][key])
  131. })
  132. ec.GET("/api/ledger/:bucket", func(c echo.Context) error {
  133. bucket := c.Param("bucket")
  134. return c.JSON(http.StatusOK, ledger.CurrentData()[bucket])
  135. })
  136. announcing := struct{ State string }{"Announcing"}
  137. // Store arbitrary data
  138. ec.PUT("/api/ledger/:bucket/:key/:value", func(c echo.Context) error {
  139. bucket := c.Param("bucket")
  140. key := c.Param("key")
  141. value := c.Param("value")
  142. ledger.Persist(context.Background(), defaultInterval, timeout, bucket, key, value)
  143. return c.JSON(http.StatusOK, announcing)
  144. })
  145. ec.GET("/api/dns", func(c echo.Context) error {
  146. res := []apiTypes.DNS{}
  147. for r, e := range ledger.CurrentData()[protocol.DNSKey] {
  148. var t types.DNS
  149. e.Unmarshal(&t)
  150. d := map[string]string{}
  151. for k, v := range t {
  152. d[dns.TypeToString[uint16(k)]] = v
  153. }
  154. res = append(res,
  155. apiTypes.DNS{
  156. Regex: r,
  157. Records: d,
  158. })
  159. }
  160. return c.JSON(http.StatusOK, res)
  161. })
  162. // Announce dns
  163. ec.POST("/api/dns", func(c echo.Context) error {
  164. d := new(apiTypes.DNS)
  165. if err := c.Bind(d); err != nil {
  166. return echo.NewHTTPError(http.StatusBadRequest, err.Error())
  167. }
  168. entry := make(types.DNS)
  169. for r, e := range d.Records {
  170. entry[dns.Type(dns.StringToType[r])] = e
  171. }
  172. services.PersistDNSRecord(context.Background(), ledger, defaultInterval, timeout, d.Regex, entry)
  173. return c.JSON(http.StatusOK, announcing)
  174. })
  175. // Delete data from ledger
  176. ec.DELETE("/api/ledger/:bucket", func(c echo.Context) error {
  177. bucket := c.Param("bucket")
  178. ledger.AnnounceDeleteBucket(context.Background(), defaultInterval, timeout, bucket)
  179. return c.JSON(http.StatusOK, announcing)
  180. })
  181. ec.DELETE("/api/ledger/:bucket/:key", func(c echo.Context) error {
  182. bucket := c.Param("bucket")
  183. key := c.Param("key")
  184. ledger.AnnounceDeleteBucketKey(context.Background(), defaultInterval, timeout, bucket, key)
  185. return c.JSON(http.StatusOK, announcing)
  186. })
  187. ec.HideBanner = true
  188. if err := ec.Start(l); err != nil && err != http.ErrServerClosed {
  189. return err
  190. }
  191. go func() {
  192. <-ctx.Done()
  193. ec.Shutdown(ctx)
  194. }()
  195. return nil
  196. }