api.go 8.8 KB

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