Skip to content
Snippets Groups Projects
Unverified Commit f6cd7aca authored by capossele's avatar capossele
Browse files

:recycle: Refactor for PR

parent 9c70f5e6
No related tags found
No related merge requests found
......@@ -7,8 +7,7 @@ import (
)
const (
routeFindByID = "message/findById"
routeSendPayload = "message/sendPayload"
routeFindByID = "message/findById"
)
// FindMessageByID finds messages by the given base58 encoded IDs. The messages are returned in the same order as
......@@ -27,14 +26,3 @@ func (api *GoShimmerAPI) FindMessageByID(base58EncodedIDs []string) (*webapi_mes
return res, nil
}
func (api *GoShimmerAPI) SendPayload(payload []byte) (string, error) {
res := &webapi_message.MessageResponse{}
if err := api.do(http.MethodPost, routeSendPayload,
&webapi_message.MessageRequest{Payload: payload}, res); err != nil {
return "", err
}
return res.ID, nil
}
......@@ -5,7 +5,6 @@ import (
analysisclient "github.com/iotaledger/goshimmer/plugins/analysis/client"
analysisdashboard "github.com/iotaledger/goshimmer/plugins/analysis/dashboard"
analysisserver "github.com/iotaledger/goshimmer/plugins/analysis/server"
"github.com/iotaledger/goshimmer/plugins/prometheus"
"github.com/iotaledger/goshimmer/plugins/remotelog"
"github.com/iotaledger/hive.go/node"
)
......@@ -15,6 +14,5 @@ var PLUGINS = node.Plugins(
analysisserver.Plugin,
analysisclient.Plugin,
analysisdashboard.Plugin,
prometheus.Plugin,
networkdelay.App,
)
package prometheus
import (
"os"
"path/filepath"
"github.com/iotaledger/goshimmer/plugins/config"
"github.com/iotaledger/goshimmer/plugins/database"
"github.com/prometheus/client_golang/prometheus"
)
var (
dataSizes *prometheus.GaugeVec
)
func init() {
dataSizes = prometheus.NewGaugeVec(
prometheus.GaugeOpts{
Name: "iota_data_sizes_bytes",
Help: "Data sizes in bytes.",
},
[]string{"name"},
)
registry.MustRegister(dataSizes)
addCollect(colectData)
}
func colectData() {
dataSizes.Reset()
dbSize, err := directorySize(config.Node.GetString(database.CfgDatabaseDir))
if err == nil {
dataSizes.WithLabelValues("database").Set(float64(dbSize))
}
}
func directorySize(path string) (int64, error) {
var size int64
err := filepath.Walk(path, func(_ string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if !info.IsDir() {
size += info.Size()
}
return err
})
return size, err
}
package prometheus
import (
"github.com/iotaledger/goshimmer/plugins/banner"
"github.com/prometheus/client_golang/prometheus"
)
var (
infoApp *prometheus.GaugeVec
infoTips prometheus.Gauge
)
func init() {
infoApp = prometheus.NewGaugeVec(
prometheus.GaugeOpts{
Name: "iota_info_app",
Help: "Node software name and version.",
},
[]string{"name", "version"},
)
infoTips = prometheus.NewGauge(prometheus.GaugeOpts{
Name: "iota_info_tips",
Help: "Number of tips.",
})
infoApp.WithLabelValues(banner.AppName, banner.AppVersion).Set(1)
registry.MustRegister(infoApp)
registry.MustRegister(infoTips)
addCollect(collectInfo)
}
func collectInfo() {
// Tips
infoTips.Set(0)
}
package prometheus
import (
"github.com/iotaledger/goshimmer/plugins/metrics"
"github.com/prometheus/client_golang/prometheus"
)
var (
messagesPerSecond prometheus.Gauge
)
func init() {
messagesPerSecond = prometheus.NewGauge(prometheus.GaugeOpts{
Name: "iota_messages_per_second",
Help: "Number of messages per second.",
})
registry.MustRegister(messagesPerSecond)
addCollect(collectServer)
}
func collectServer() {
messagesPerSecond.Set(float64(metrics.ReceivedMessagesPerSecond()))
}
package prometheus
import (
flag "github.com/spf13/pflag"
)
const (
// CfgPrometheusGoMetrics defines the config flag to enable/disable go metrics.
CfgPrometheusGoMetrics = "prometheus.goMetrics"
// CfgPrometheusProcessMetrics defines the config flag to enable/disable process metrics.
CfgPrometheusProcessMetrics = "prometheus.processMetrics"
// CfgPrometheusPromhttpMetrics defines the config flag to enable/disable promhttp metrics.
CfgPrometheusPromhttpMetrics = "prometheus.promhttpMetrics"
// CfgPrometheusBindAddress defines the config flag of the bind address on which the Prometheus exporter listens on.
CfgPrometheusBindAddress = "prometheus.bindAddress"
)
func init() {
flag.String(CfgPrometheusBindAddress, "localhost:9311", "the bind address on which the Prometheus exporter listens on")
flag.Bool(CfgPrometheusGoMetrics, false, "include go metrics")
flag.Bool(CfgPrometheusProcessMetrics, false, "include process metrics")
flag.Bool(CfgPrometheusPromhttpMetrics, false, "include promhttp metrics")
}
package prometheus
import (
"context"
"net/http"
"time"
"github.com/gin-gonic/gin"
"github.com/iotaledger/goshimmer/packages/shutdown"
"github.com/iotaledger/goshimmer/plugins/config"
"github.com/iotaledger/hive.go/daemon"
"github.com/iotaledger/hive.go/logger"
"github.com/iotaledger/hive.go/node"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
)
// Plugin Prometheus
var (
Plugin = node.NewPlugin("Prometheus", node.Disabled, configure, run)
log *logger.Logger
server *http.Server
registry = prometheus.NewRegistry()
collects []func()
)
func configure(plugin *node.Plugin) {
log = logger.NewLogger(plugin.Name)
if config.Node.GetBool(CfgPrometheusGoMetrics) {
registry.MustRegister(prometheus.NewGoCollector())
}
if config.Node.GetBool(CfgPrometheusProcessMetrics) {
registry.MustRegister(prometheus.NewProcessCollector(prometheus.ProcessCollectorOpts{}))
}
}
func addCollect(collect func()) {
collects = append(collects, collect)
}
func run(plugin *node.Plugin) {
log.Info("Starting Prometheus exporter ...")
if err := daemon.BackgroundWorker("Prometheus exporter", func(shutdownSignal <-chan struct{}) {
log.Info("Starting Prometheus exporter ... done")
engine := gin.New()
engine.Use(gin.Recovery())
engine.GET("/metrics", func(c *gin.Context) {
for _, collect := range collects {
collect()
}
handler := promhttp.HandlerFor(
registry,
promhttp.HandlerOpts{
EnableOpenMetrics: true,
},
)
if config.Node.GetBool(CfgPrometheusPromhttpMetrics) {
handler = promhttp.InstrumentMetricHandler(registry, handler)
}
handler.ServeHTTP(c.Writer, c.Request)
})
bindAddr := config.Node.GetString(CfgPrometheusBindAddress)
server = &http.Server{Addr: bindAddr, Handler: engine}
go func() {
log.Infof("You can now access the Prometheus exporter using: http://%s/metrics", bindAddr)
if err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed {
log.Error("Stopping Prometheus exporter due to an error ... done")
}
}()
<-shutdownSignal
log.Info("Stopping Prometheus exporter ...")
if server != nil {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
err := server.Shutdown(ctx)
if err != nil {
log.Error(err.Error())
}
cancel()
}
log.Info("Stopping Prometheus exporter ... done")
}, shutdown.PriorityPrometheus); err != nil {
log.Panic(err)
}
}
......@@ -23,7 +23,6 @@ var (
func configure(plugin *node.Plugin) {
log = logger.NewLogger(PluginName)
webapi.Server.POST("message/findById", findMessageByID)
webapi.Server.POST("message/sendPayload", sendPayload)
}
// findMessageByID returns the array of messages for the
......
package message
import (
"net/http"
"github.com/iotaledger/goshimmer/packages/binary/messagelayer/payload"
"github.com/iotaledger/goshimmer/plugins/issuer"
"github.com/labstack/echo"
)
// sendPayload creates a message of the given payload and
// broadcasts it to the node's neighbors. It returns the message ID if successful.
func sendPayload(c echo.Context) error {
var request MessageRequest
if err := c.Bind(&request); err != nil {
log.Info(err.Error())
return c.JSON(http.StatusBadRequest, MessageResponse{Error: err.Error()})
}
//TODO: to check max payload size allowed, if exceeding return an error
parsedPayload, _, err := payload.FromBytes(request.Payload)
if err != nil {
return c.JSON(http.StatusBadRequest, MessageResponse{Error: "not a valid payload"})
}
msg, err := issuer.IssuePayload(parsedPayload)
if err != nil {
return c.JSON(http.StatusBadRequest, MessageResponse{Error: err.Error()})
}
return c.JSON(http.StatusOK, MessageResponse{ID: msg.Id().String()})
}
// MessageResponse contains the ID of the message sent.
type MessageResponse struct {
ID string `json:"id,omitempty"`
Error string `json:"error,omitempty"`
}
// MessageRequest contains the message to send.
type MessageRequest struct {
Payload []byte `json:"payload"`
}
scrape_configs:
- job_name: peer_master
scrape_interval: 5s
static_configs:
- targets:
- peer_master:9311
\ No newline at end of file
package main
import (
"fmt"
"net/http"
"time"
"github.com/iotaledger/goshimmer/client"
"github.com/iotaledger/goshimmer/dapps/valuetransfers/packages/address"
"github.com/iotaledger/goshimmer/dapps/valuetransfers/packages/address/signaturescheme"
"github.com/iotaledger/goshimmer/dapps/valuetransfers/packages/balance"
valuepayload "github.com/iotaledger/goshimmer/dapps/valuetransfers/packages/payload"
"github.com/iotaledger/goshimmer/dapps/valuetransfers/packages/transaction"
"github.com/iotaledger/goshimmer/dapps/valuetransfers/packages/wallet"
"github.com/mr-tron/base58"
)
func main() {
client := client.NewGoShimmerAPI("http://localhost:8080", http.Client{Timeout: 30 * time.Second})
// genesis wallet
genesisSeedBytes, err := base58.Decode("7R1itJx5hVuo9w9hjg5cwKFmek4HMSoBDgJZN8hKGxih")
if err != nil {
fmt.Println(err)
}
const genesisBalance = 1000000000
genesisWallet := wallet.New(genesisSeedBytes)
genesisAddr := genesisWallet.Seed().Address(0)
genesisOutputID := transaction.NewOutputID(genesisAddr, transaction.GenesisID)
// issue transactions which spend the same genesis output in all partitions
conflictingTxs := make([]*transaction.Transaction, 2)
conflictingTxIDs := make([]string, 2)
receiverSeeds := make([]*wallet.Seed, 2)
for i := range conflictingTxs {
// create a new receiver wallet for the given conflict
receiverSeeds[i] = wallet.NewSeed()
destAddr := receiverSeeds[i].Address(0)
tx := transaction.New(
transaction.NewInputs(genesisOutputID),
transaction.NewOutputs(map[address.Address][]*balance.Balance{
destAddr: {
{Value: genesisBalance, Color: balance.ColorIOTA},
},
}))
tx = tx.Sign(signaturescheme.ED25519(*genesisWallet.Seed().KeyPair(0)))
conflictingTxs[i] = tx
valueObject := valuepayload.New(valuepayload.GenesisID, valuepayload.GenesisID, tx)
// issue the value object
txID, err := client.SendPayload(valueObject.Bytes())
if err != nil {
fmt.Println(err)
}
conflictingTxIDs[i] = txID
fmt.Printf("issued conflict transaction %s\n", txID)
//time.Sleep(7 * time.Second)
}
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment