Skip to content

feat: basic server functionality #3

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jul 7, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
71 changes: 69 additions & 2 deletions cmd/chnsd/main.go
Original file line number Diff line number Diff line change
@@ -1,9 +1,76 @@
// Copyright 2023 Blink Labs, LLC.
//
//
// Use of this source code is governed by an MIT-style
// license that can be found in the LICENSE file or at
// https://opensource.org/licenses/MIT.

package main

func main() {}
import (
"flag"
"fmt"
"net/http"
_ "net/http/pprof"
"os"

"github.com/blinklabs-io/chnsd/internal/config"
"github.com/blinklabs-io/chnsd/internal/dns"
"github.com/blinklabs-io/chnsd/internal/logging"
)

var cmdlineFlags struct {
configFile string
}

func main() {
flag.StringVar(&cmdlineFlags.configFile, "config", "", "path to config file to load")
flag.Parse()

// Load config
cfg, err := config.Load(cmdlineFlags.configFile)
if err != nil {
fmt.Printf("Failed to load config: %s\n", err)
os.Exit(1)
}

// Configure logging
logging.Setup()
logger := logging.GetLogger()
// Sync logger on exit
defer func() {
if err := logger.Sync(); err != nil {
// We don't actually care about the error here, but we have to do something
// to appease the linter
return
}
}()

/*
// Test node connection
if oConn, err := node.GetConnection(); err != nil {
logger.Fatalf("failed to connect to node: %s", err)
} else {
oConn.Close()
}
*/

// Start debug listener
if cfg.Debug.ListenPort > 0 {
logger.Infof("starting debug listener on %s:%d", cfg.Debug.ListenAddress, cfg.Debug.ListenPort)
go func() {
err := http.ListenAndServe(fmt.Sprintf("%s:%d", cfg.Debug.ListenAddress, cfg.Debug.ListenPort), nil)
if err != nil {
logger.Fatalf("failed to start debug listener: %s", err)
}
}()
}

// Start DNS listener
logger.Infof("starting DNS listener on %s:%d", cfg.Dns.ListenAddress, cfg.Dns.ListenPort)
if err := dns.Start(); err != nil {
logger.Fatalf("failed to start DNS listener: %s", err)
}

// Wait forever
select {}
}
22 changes: 22 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
@@ -1,3 +1,25 @@
module github.com/blinklabs-io/chnsd

go 1.19

require (
github.com/blinklabs-io/gouroboros v0.47.0
github.com/kelseyhightower/envconfig v1.4.0
github.com/miekg/dns v1.1.55
go.uber.org/zap v1.24.0
gopkg.in/yaml.v2 v2.4.0
)

require (
github.com/fxamacker/cbor/v2 v2.4.0 // indirect
github.com/jinzhu/copier v0.3.5 // indirect
github.com/pkg/errors v0.9.1 // indirect
github.com/x448/float16 v0.8.4 // indirect
go.uber.org/atomic v1.7.0 // indirect
go.uber.org/multierr v1.6.0 // indirect
golang.org/x/crypto v0.10.0 // indirect
golang.org/x/mod v0.9.0 // indirect
golang.org/x/net v0.10.0 // indirect
golang.org/x/sys v0.9.0 // indirect
golang.org/x/tools v0.7.0 // indirect
)
46 changes: 46 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
github.com/benbjohnson/clock v1.1.0 h1:Q92kusRqC1XV2MjkWETPvjJVqKetz1OzxZB7mHJLju8=
github.com/blinklabs-io/gouroboros v0.47.0 h1:N8SoWoT6h6m+w60OU5qNGNyAHj/MxJzSZaw6cnR1Dc8=
github.com/blinklabs-io/gouroboros v0.47.0/go.mod h1:J3Zf9Fx65LoLldIZB4+dZZpsUsGfwXMQQKQOhNBNlwY=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/fxamacker/cbor/v2 v2.4.0 h1:ri0ArlOR+5XunOP8CRUowT0pSJOwhW098ZCUyskZD88=
github.com/fxamacker/cbor/v2 v2.4.0/go.mod h1:TA1xS00nchWmaBnEIxPSE5oHLuJBAVvqrtAnWBwBCVo=
github.com/jinzhu/copier v0.3.5 h1:GlvfUwHk62RokgqVNvYsku0TATCF7bAHVwEXoBh3iJg=
github.com/jinzhu/copier v0.3.5/go.mod h1:DfbEm0FYsaqBcKcFuvmOZb218JkPGtvSHsKg8S8hyyg=
github.com/kelseyhightower/envconfig v1.4.0 h1:Im6hONhd3pLkfDFsbRgu68RDNkGF1r3dvMUtDTo2cv8=
github.com/kelseyhightower/envconfig v1.4.0/go.mod h1:cccZRl6mQpaq41TPp5QxidR+Sa3axMbJDNb//FQX6Gg=
github.com/miekg/dns v1.1.55 h1:GoQ4hpsj0nFLYe+bWiCToyrBEJXkQfOOIvFGFy0lEgo=
github.com/miekg/dns v1.1.55/go.mod h1:uInx36IzPl7FYnDcMeVWxj9byh7DutNykX4G9Sj60FY=
github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
github.com/stretchr/testify v1.8.0 h1:pSgiaMZlXftHpm5L7V1+rVB+AZJydKsMxsQBIJw4PKk=
github.com/x448/float16 v0.8.4 h1:qLwI1I70+NjRFUR3zs1JPUCgaCXSh3SW62uAKT1mSBM=
github.com/x448/float16 v0.8.4/go.mod h1:14CWIYCyZA/cWjXOioeEpHeN/83MdbZDRQHoFcYsOfg=
go.uber.org/atomic v1.7.0 h1:ADUqmZGgLDDfbSL9ZmPxKTybcoEYHgpYfELNoN+7hsw=
go.uber.org/atomic v1.7.0/go.mod h1:fEN4uk6kAWBTFdckzkM89CLk9XfWZrxpCo0nPH17wJc=
go.uber.org/goleak v1.1.11 h1:wy28qYRKZgnJTxGxvye5/wgWr1EKjmUDGYox5mGlRlI=
go.uber.org/multierr v1.6.0 h1:y6IPFStTAIT5Ytl7/XYmHvzXQ7S3g/IeZW9hyZ5thw4=
go.uber.org/multierr v1.6.0/go.mod h1:cdWPpRnG4AhwMwsgIHip0KRBQjJy5kYEpYjJxpXp9iU=
go.uber.org/zap v1.24.0 h1:FiJd5l1UOLj0wCgbSE0rwwXHzEdAZS6hiiSnxJN/D60=
go.uber.org/zap v1.24.0/go.mod h1:2kMP+WWQ8aoFoedH3T2sq6iJ2yDWpHbP0f6MQbS9Gkg=
golang.org/x/crypto v0.10.0 h1:LKqV2xt9+kDzSTfOhx4FrkEBcMrAgHSYgzywV9zcGmM=
golang.org/x/crypto v0.10.0/go.mod h1:o4eNf7Ede1fv+hwOwZsTHl9EsPFO6q6ZvYR8vYfY45I=
golang.org/x/mod v0.9.0 h1:KENHtAZL2y3NLMYZeHY9DW8HW8V+kQyJsY/V9JlKvCs=
golang.org/x/mod v0.9.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
golang.org/x/net v0.10.0 h1:X2//UzNDwYmtCLn7To6G58Wr6f5ahEAQgKNzv9Y951M=
golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg=
golang.org/x/sync v0.1.0 h1:wsuoTGHzEhffawBOhz5CYhcrV4IdKZbEyZjBMuTp12o=
golang.org/x/sys v0.9.0 h1:KS/R3tvhPqvJvwcKfnBHJwwthS11LRhmM5D59eEXa0s=
golang.org/x/sys v0.9.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/tools v0.7.0 h1:W4OVu8VVOaIO0yzWMNdepAulS7YfoS3Zabrm8DOXXU4=
golang.org/x/tools v0.7.0/go.mod h1:4pg6aUX35JBAogB10C9AtvVL+qowtN4pT3CGSQex14s=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY=
gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
105 changes: 105 additions & 0 deletions internal/config/config.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
package config

import (
"fmt"
"os"

ouroboros "github.com/blinklabs-io/gouroboros"
"github.com/kelseyhightower/envconfig"
"gopkg.in/yaml.v2"
)

type Config struct {
Logging LoggingConfig `yaml:"logging"`
Metrics MetricsConfig `yaml:"metrics"`
Dns DnsConfig `yaml:"dns"`
Debug DebugConfig `yaml:"debug"`
Node NodeConfig `yaml:"node"`
}

type LoggingConfig struct {
Healthchecks bool `yaml:"healthchecks" envconfig:"LOGGING_HEALTHCHECKS"`
Level string `yaml:"level" envconfig:"LOGGING_LEVEL"`
}

type DnsConfig struct {
ListenAddress string `yaml:"address" envconfig:"DNS_LISTEN_ADDRESS"`
ListenPort uint `yaml:"port" envconfig:"DNS_LISTEN_PORT"`
}

type DebugConfig struct {
ListenAddress string `yaml:"address" envconfig:"DEBUG_ADDRESS"`
ListenPort uint `yaml:"port" envconfig:"DEBUG_PORT"`
}

type MetricsConfig struct {
ListenAddress string `yaml:"address" envconfig:"METRICS_LISTEN_ADDRESS"`
ListenPort uint `yaml:"port" envconfig:"METRICS_LISTEN_PORT"`
}

type NodeConfig struct {
Network string `yaml:"network" envconfig:"CARDANO_NETWORK"`
NetworkMagic uint32 `yaml:"networkMagic" envconfig:"CARDANO_NODE_NETWORK_MAGIC"`
Address string `yaml:"address" envconfig:"CARDANO_NODE_SOCKET_TCP_HOST"`
Port uint `yaml:"port" envconfig:"CARDANO_NODE_SOCKET_TCP_PORT"`
SocketPath string `yaml:"socketPath" envconfig:"CARDANO_NODE_SOCKET_PATH"`
}

// Singleton config instance with default values
var globalConfig = &Config{
Logging: LoggingConfig{
Level: "info",
Healthchecks: false,
},
Dns: DnsConfig{
ListenAddress: "",
ListenPort: 8053,
},
Debug: DebugConfig{
ListenAddress: "localhost",
ListenPort: 0,
},
Metrics: MetricsConfig{
ListenAddress: "",
ListenPort: 8081,
},
Node: NodeConfig{
Network: "mainnet",
SocketPath: "/node-ipc/node.socket",
},
}

func Load(configFile string) (*Config, error) {
// Load config file as YAML if provided
if configFile != "" {
buf, err := os.ReadFile(configFile)
if err != nil {
return nil, fmt.Errorf("error reading config file: %s", err)
}
err = yaml.Unmarshal(buf, globalConfig)
if err != nil {
return nil, fmt.Errorf("error parsing config file: %s", err)
}
}
// Load config values from environment variables
// We use "dummy" as the app name here to (mostly) prevent picking up env
// vars that we hadn't explicitly specified in annotations above
err := envconfig.Process("dummy", globalConfig)
if err != nil {
return nil, fmt.Errorf("error processing environment: %s", err)
}
// Populate network magic value from network name
if globalConfig.Node.Network != "" {
network := ouroboros.NetworkByName(globalConfig.Node.Network)
if network == ouroboros.NetworkInvalid {
return nil, fmt.Errorf("unknown network: %s", globalConfig.Node.Network)
}
globalConfig.Node.NetworkMagic = network.NetworkMagic
}
return globalConfig, nil
}

// Config returns the global config instance
func GetConfig() *Config {
return globalConfig
}
54 changes: 54 additions & 0 deletions internal/dns/dns.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
package dns

import (
"fmt"

"github.com/blinklabs-io/chnsd/internal/config"
"github.com/blinklabs-io/chnsd/internal/logging"

"github.com/miekg/dns"
)

func Start() error {
cfg := config.GetConfig()
listenAddr := fmt.Sprintf("%s:%d", cfg.Dns.ListenAddress, cfg.Dns.ListenPort)
// Setup handler
dns.HandleFunc(".", handleTest)
// UDP listener
serverUdp := &dns.Server{Addr: listenAddr, Net: "udp", TsigSecret: nil, ReusePort: true}
go startListener(serverUdp)
// TCP listener
serverTcp := &dns.Server{Addr: listenAddr, Net: "tcp", TsigSecret: nil, ReusePort: true}
go startListener(serverTcp)
return nil
}

func startListener(server *dns.Server) {
if err := server.ListenAndServe(); err != nil {
logging.GetLogger().Fatalf("failed to start DNS listener: %s", err)
}
}

func handleTest(w dns.ResponseWriter, r *dns.Msg) {
logger := logging.GetLogger()
m := new(dns.Msg)
m.SetReply(r)

queryStr := fmt.Sprintf(
"%s %s",
dns.Type(r.Question[0].Qtype).String(),
r.Question[0].Name,
)

logger.Infof("request: %s", queryStr)

t := &dns.TXT{
Hdr: dns.RR_Header{Name: "test.zone.", Rrtype: dns.TypeTXT, Class: dns.ClassINET, Ttl: 0},
Txt: []string{queryStr},
}

m.Answer = append(m.Answer, t)
if err := w.WriteMsg(m); err != nil {
logger.Errorf("failed to write response: %s", err)
}
}
54 changes: 54 additions & 0 deletions internal/logging/logging.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
package logging

import (
"log"
"time"

"github.com/blinklabs-io/chnsd/internal/config"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
)

type Logger = zap.SugaredLogger

var globalLogger *Logger

func Setup() {
cfg := config.GetConfig()
// Build our custom logging config
loggerConfig := zap.NewProductionConfig()
// Change timestamp key name
loggerConfig.EncoderConfig.TimeKey = "timestamp"
// Use a human readable time format
loggerConfig.EncoderConfig.EncodeTime = zapcore.TimeEncoderOfLayout(time.RFC3339)

// Set level
if cfg.Logging.Level != "" {
level, err := zapcore.ParseLevel(cfg.Logging.Level)
if err != nil {
log.Fatalf("error configuring logger: %s", err)
}
loggerConfig.Level.SetLevel(level)
}

// Create the logger
l, err := loggerConfig.Build()
if err != nil {
log.Fatal(err)
}

// Store the "sugared" version of the logger
globalLogger = l.Sugar()
}

func GetLogger() *zap.SugaredLogger {
return globalLogger
}

func GetDesugaredLogger() *zap.Logger {
return globalLogger.Desugar()
}

func GetAccessLogger() *zap.Logger {
return globalLogger.Desugar().With(zap.String("type", "access")).WithOptions(zap.WithCaller(false))
}