api.go 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303
  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. "fmt"
  20. "io/fs"
  21. "net"
  22. "net/http"
  23. _ "net/http/pprof"
  24. "strings"
  25. "time"
  26. "github.com/libp2p/go-libp2p-core/network"
  27. "github.com/libp2p/go-libp2p-core/peer"
  28. "github.com/miekg/dns"
  29. apiTypes "github.com/mudler/edgevpn/api/types"
  30. "github.com/labstack/echo/v4"
  31. "github.com/mudler/edgevpn/pkg/node"
  32. "github.com/mudler/edgevpn/pkg/protocol"
  33. "github.com/mudler/edgevpn/pkg/services"
  34. "github.com/mudler/edgevpn/pkg/types"
  35. )
  36. //go:embed public
  37. var embededFiles embed.FS
  38. func getFileSystem() http.FileSystem {
  39. fsys, err := fs.Sub(embededFiles, "public")
  40. if err != nil {
  41. panic(err)
  42. }
  43. return http.FS(fsys)
  44. }
  45. const (
  46. MachineURL = "/api/machines"
  47. UsersURL = "/api/users"
  48. ServiceURL = "/api/services"
  49. BlockchainURL = "/api/blockchain"
  50. LedgerURL = "/api/ledger"
  51. SummaryURL = "/api/summary"
  52. FileURL = "/api/files"
  53. NodesURL = "/api/nodes"
  54. DNSURL = "/api/dns"
  55. PeerstoreURL = "/api/peerstore"
  56. )
  57. func API(ctx context.Context, l string, defaultInterval, timeout time.Duration, e *node.Node, debugMode bool) error {
  58. ledger, _ := e.Ledger()
  59. ec := echo.New()
  60. if strings.HasPrefix(l, "unix://") {
  61. unixListener, err := net.Listen("unix", strings.ReplaceAll(l, "unix://", ""))
  62. if err != nil {
  63. return err
  64. }
  65. ec.Listener = unixListener
  66. }
  67. assetHandler := http.FileServer(getFileSystem())
  68. if debugMode {
  69. ec.GET("/debug/pprof/*", echo.WrapHandler(http.DefaultServeMux))
  70. }
  71. // Get data from ledger
  72. ec.GET(FileURL, func(c echo.Context) error {
  73. list := []*types.File{}
  74. for _, v := range ledger.CurrentData()[protocol.FilesLedgerKey] {
  75. machine := &types.File{}
  76. v.Unmarshal(machine)
  77. list = append(list, machine)
  78. }
  79. return c.JSON(http.StatusOK, list)
  80. })
  81. ec.GET(SummaryURL, func(c echo.Context) error {
  82. files := len(ledger.CurrentData()[protocol.FilesLedgerKey])
  83. machines := len(ledger.CurrentData()[protocol.MachinesLedgerKey])
  84. users := len(ledger.CurrentData()[protocol.UsersLedgerKey])
  85. services := len(ledger.CurrentData()[protocol.ServicesLedgerKey])
  86. peers, err := e.MessageHub.ListPeers()
  87. if err != nil {
  88. return err
  89. }
  90. onChainNodes := len(peers)
  91. p2pPeers := len(e.Host().Network().Peerstore().Peers())
  92. nodeID := e.Host().ID().String()
  93. blockchain := ledger.Index()
  94. return c.JSON(http.StatusOK, types.Summary{
  95. Files: files,
  96. Machines: machines,
  97. Users: users,
  98. Services: services,
  99. BlockChain: blockchain,
  100. OnChainNodes: onChainNodes,
  101. Peers: p2pPeers,
  102. NodeID: nodeID,
  103. })
  104. })
  105. ec.GET(MachineURL, func(c echo.Context) error {
  106. list := []*apiTypes.Machine{}
  107. for _, v := range ledger.CurrentData()[protocol.MachinesLedgerKey] {
  108. machine := &types.Machine{}
  109. v.Unmarshal(machine)
  110. m := &apiTypes.Machine{Machine: *machine}
  111. if e.Host().Network().Connectedness(peer.ID(machine.PeerID)) == network.Connected {
  112. m.Connected = true
  113. }
  114. peers, err := e.MessageHub.ListPeers()
  115. if err != nil {
  116. return err
  117. }
  118. for _, p := range peers {
  119. if p.String() == machine.PeerID {
  120. m.OnChain = true
  121. }
  122. }
  123. list = append(list, m)
  124. }
  125. return c.JSON(http.StatusOK, list)
  126. })
  127. ec.GET(NodesURL, func(c echo.Context) error {
  128. list := []apiTypes.Peer{}
  129. peers, err := e.MessageHub.ListPeers()
  130. if err != nil {
  131. return err
  132. }
  133. // Sum up state also from services
  134. online := services.AvailableNodes(ledger, 10*time.Minute)
  135. p := map[string]interface{}{}
  136. for _, v := range online {
  137. p[v] = nil
  138. }
  139. for _, v := range peers {
  140. _, exists := p[v.String()]
  141. if !exists {
  142. p[v.String()] = nil
  143. }
  144. }
  145. for id, _ := range p {
  146. list = append(list, apiTypes.Peer{ID: id, Online: true})
  147. }
  148. return c.JSON(http.StatusOK, list)
  149. })
  150. ec.GET(PeerstoreURL, func(c echo.Context) error {
  151. list := []apiTypes.Peer{}
  152. for _, v := range e.Host().Network().Peerstore().Peers() {
  153. list = append(list, apiTypes.Peer{ID: v.String()})
  154. }
  155. return c.JSON(http.StatusOK, list)
  156. })
  157. ec.GET(UsersURL, func(c echo.Context) error {
  158. user := []*types.User{}
  159. for _, v := range ledger.CurrentData()[protocol.UsersLedgerKey] {
  160. u := &types.User{}
  161. v.Unmarshal(u)
  162. user = append(user, u)
  163. }
  164. return c.JSON(http.StatusOK, user)
  165. })
  166. ec.GET(ServiceURL, func(c echo.Context) error {
  167. list := []*types.Service{}
  168. for _, v := range ledger.CurrentData()[protocol.ServicesLedgerKey] {
  169. srvc := &types.Service{}
  170. v.Unmarshal(srvc)
  171. list = append(list, srvc)
  172. }
  173. return c.JSON(http.StatusOK, list)
  174. })
  175. ec.GET("/*", echo.WrapHandler(http.StripPrefix("/", assetHandler)))
  176. ec.GET(BlockchainURL, func(c echo.Context) error {
  177. return c.JSON(http.StatusOK, ledger.LastBlock())
  178. })
  179. ec.GET(LedgerURL, func(c echo.Context) error {
  180. return c.JSON(http.StatusOK, ledger.CurrentData())
  181. })
  182. ec.GET(fmt.Sprintf("%s/:bucket/:key", LedgerURL), func(c echo.Context) error {
  183. bucket := c.Param("bucket")
  184. key := c.Param("key")
  185. return c.JSON(http.StatusOK, ledger.CurrentData()[bucket][key])
  186. })
  187. ec.GET(fmt.Sprintf("%s/:bucket", LedgerURL), func(c echo.Context) error {
  188. bucket := c.Param("bucket")
  189. return c.JSON(http.StatusOK, ledger.CurrentData()[bucket])
  190. })
  191. announcing := struct{ State string }{"Announcing"}
  192. // Store arbitrary data
  193. ec.PUT(fmt.Sprintf("%s/:bucket/:key/:value", LedgerURL), func(c echo.Context) error {
  194. bucket := c.Param("bucket")
  195. key := c.Param("key")
  196. value := c.Param("value")
  197. ledger.Persist(context.Background(), defaultInterval, timeout, bucket, key, value)
  198. return c.JSON(http.StatusOK, announcing)
  199. })
  200. ec.GET(DNSURL, func(c echo.Context) error {
  201. res := []apiTypes.DNS{}
  202. for r, e := range ledger.CurrentData()[protocol.DNSKey] {
  203. var t types.DNS
  204. e.Unmarshal(&t)
  205. d := map[string]string{}
  206. for k, v := range t {
  207. d[dns.TypeToString[uint16(k)]] = v
  208. }
  209. res = append(res,
  210. apiTypes.DNS{
  211. Regex: r,
  212. Records: d,
  213. })
  214. }
  215. return c.JSON(http.StatusOK, res)
  216. })
  217. // Announce dns
  218. ec.POST(DNSURL, func(c echo.Context) error {
  219. d := new(apiTypes.DNS)
  220. if err := c.Bind(d); err != nil {
  221. return echo.NewHTTPError(http.StatusBadRequest, err.Error())
  222. }
  223. entry := make(types.DNS)
  224. for r, e := range d.Records {
  225. entry[dns.Type(dns.StringToType[r])] = e
  226. }
  227. services.PersistDNSRecord(context.Background(), ledger, defaultInterval, timeout, d.Regex, entry)
  228. return c.JSON(http.StatusOK, announcing)
  229. })
  230. // Delete data from ledger
  231. ec.DELETE(fmt.Sprintf("%s/:bucket", LedgerURL), func(c echo.Context) error {
  232. bucket := c.Param("bucket")
  233. ledger.AnnounceDeleteBucket(context.Background(), defaultInterval, timeout, bucket)
  234. return c.JSON(http.StatusOK, announcing)
  235. })
  236. ec.DELETE(fmt.Sprintf("%s/:bucket/:key", LedgerURL), func(c echo.Context) error {
  237. bucket := c.Param("bucket")
  238. key := c.Param("key")
  239. ledger.AnnounceDeleteBucketKey(context.Background(), defaultInterval, timeout, bucket, key)
  240. return c.JSON(http.StatusOK, announcing)
  241. })
  242. ec.HideBanner = true
  243. if err := ec.Start(l); err != nil && err != http.ErrServerClosed {
  244. return err
  245. }
  246. go func() {
  247. <-ctx.Done()
  248. ct, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  249. ec.Shutdown(ct)
  250. cancel()
  251. }()
  252. return nil
  253. }