Compare commits

..

12 Commits

Author SHA1 Message Date
34387f129d Merge pull request #188 from unistack-org/proto
fix service names in proto
2023-02-21 13:28:13 +03:00
47075acb06 fix service names in proto
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2023-02-21 13:26:01 +03:00
09cb998ba4 fix service names in proto
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2023-02-21 13:18:03 +03:00
b9dbfb1cfc Merge pull request #187 from unistack-org/api-REMOVE
api: remove and regen
2023-02-21 02:12:47 +03:00
56efccc4cf api: remove and regen
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2023-02-21 02:10:24 +03:00
ce9f896287 Merge pull request #186 from unistack-org/structfs
util/structfs: import https://github.com/unistack-org/go-structfs
2023-02-19 23:38:31 +03:00
83d87a40e4 util/structfs: import https://github.com/unistack-org/go-structfs
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2023-02-19 23:35:39 +03:00
75fd1e43b9 Merge pull request #185 from unistack-org/server
server: add server.SetHandlerOption helper
2023-02-13 23:33:57 +03:00
395a3eed3d server: add server.SetHandlerOption helper
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2023-02-13 23:31:38 +03:00
3ba8cb7f9e Merge pull request #184 from unistack-org/duration
util/time: add Marshal/Unmarshal to own Duration
2023-02-13 14:05:16 +03:00
b07806b9a1 tmp
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2023-02-13 14:03:02 +03:00
0f583218d4 tmp
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2023-02-13 14:02:08 +03:00
21 changed files with 616 additions and 512 deletions

View File

@@ -1,182 +0,0 @@
package api // import "go.unistack.org/micro/v3/api"
import (
"errors"
"regexp"
"strings"
"go.unistack.org/micro/v3/metadata"
"go.unistack.org/micro/v3/register"
"go.unistack.org/micro/v3/server"
)
// nolint: revive
// Api interface
type Api interface {
// Initialise options
Init(...Option) error
// Get the options
Options() Options
// Register a http handler
Register(*Endpoint) error
// Register a route
Deregister(*Endpoint) error
// Implementation of api
String() string
}
// Options holds the options
type Options struct{}
// Option func signature
type Option func(*Options) error
// Endpoint is a mapping between an RPC method and HTTP endpoint
type Endpoint struct {
// Name Greeter.Hello
Name string
// Desciption for endpoint
Description string
// Handler e.g rpc, proxy
Handler string
// Body destination
// "*" or "" - top level message value
// "string" - inner message value
Body string
// Host e.g example.com
Host []string
// Method e.g GET, POST
Method []string
// Path e.g /greeter. Expect POSIX regex
Path []string
// Stream flag
Stream bool
}
// Service represents an API service
type Service struct {
// Name of service
Name string
// Endpoint for this service
Endpoint *Endpoint
// Services that provides service
Services []*register.Service
}
// Encode encodes an endpoint to endpoint metadata
func Encode(e *Endpoint) map[string]string {
if e == nil {
return nil
}
// endpoint map
ep := make(map[string]string)
// set vals only if they exist
set := func(k, v string) {
if len(v) == 0 {
return
}
ep[k] = v
}
set("endpoint", e.Name)
set("description", e.Description)
set("handler", e.Handler)
set("method", strings.Join(e.Method, ","))
set("path", strings.Join(e.Path, ","))
set("host", strings.Join(e.Host, ","))
set("body", e.Body)
return ep
}
// Decode decodes endpoint metadata into an endpoint
func Decode(e metadata.Metadata) *Endpoint {
if e == nil {
return nil
}
ep := &Endpoint{}
ep.Name, _ = e.Get("endpoint")
ep.Description, _ = e.Get("description")
epmethod, _ := e.Get("method")
ep.Method = []string{epmethod}
eppath, _ := e.Get("path")
ep.Path = []string{eppath}
ephost, _ := e.Get("host")
ep.Host = []string{ephost}
ep.Handler, _ = e.Get("handler")
ep.Body, _ = e.Get("body")
return ep
}
// Validate validates an endpoint to guarantee it won't blow up when being served
func Validate(e *Endpoint) error {
if e == nil {
return errors.New("endpoint is nil")
}
if len(e.Name) == 0 {
return errors.New("name required")
}
for _, p := range e.Path {
ps := p[0]
pe := p[len(p)-1]
switch {
case ps == '^' && pe == '$':
if _, err := regexp.CompilePOSIX(p); err != nil {
return err
}
case ps == '^' && pe != '$':
return errors.New("invalid path")
case ps != '^' && pe == '$':
return errors.New("invalid path")
}
}
if len(e.Handler) == 0 {
return errors.New("invalid handler")
}
return nil
}
/*
Design ideas
// Gateway is an api gateway interface
type Gateway interface {
// Register a http handler
Handle(pattern string, http.Handler)
// Register a route
RegisterRoute(r Route)
// Init initialises the command line.
// It also parses further options.
Init(...Option) error
// Run the gateway
Run() error
}
// NewGateway returns a new api gateway
func NewGateway() Gateway {
return newGateway()
}
*/
// WithEndpoint returns a server.HandlerOption with endpoint metadata set
//
// Usage:
//
// proto.RegisterHandler(service.Server(), new(Handler), api.WithEndpoint(
// &api.Endpoint{
// Name: "Greeter.Hello",
// Path: []string{"/greeter"},
// },
// ))
func WithEndpoint(e *Endpoint) server.HandlerOption {
return server.EndpointMetadata(e.Name, Encode(e))
}

View File

@@ -1,245 +0,0 @@
package api
import (
"strings"
"testing"
"go.unistack.org/micro/v3/metadata"
"go.unistack.org/micro/v3/server"
)
func TestDecode(t *testing.T) {
md := metadata.New(0)
md.Set("host", "localhost", "method", "GET", "path", "/")
ep := Decode(md)
if md == nil {
t.Fatalf("failed to decode md %#+v", md)
} else if len(ep.Host) != 1 || len(ep.Method) != 1 || len(ep.Path) != 1 {
t.Fatalf("ep invalid after decode %#+v", ep)
}
if ep.Host[0] != "localhost" || ep.Method[0] != "GET" || ep.Path[0] != "/" {
t.Fatalf("ep invalid after decode %#+v", ep)
}
}
//nolint:gocyclo
func TestEncode(t *testing.T) {
testData := []*Endpoint{
nil,
{
Name: "Foo.Bar",
Description: "A test endpoint",
Handler: "meta",
Host: []string{"foo.com"},
Method: []string{"GET"},
Path: []string{"/test"},
},
}
compare := func(expect, got []string) bool {
// no data to compare, return true
if len(expect) == 0 && len(got) == 0 {
return true
}
// no data expected but got some return false
if len(expect) == 0 && len(got) > 0 {
return false
}
// compare expected with what we got
for _, e := range expect {
var seen bool
for _, g := range got {
if e == g {
seen = true
break
}
}
if !seen {
return false
}
}
// we're done, return true
return true
}
for _, d := range testData {
// encode
e := Encode(d)
// decode
de := Decode(e)
// nil endpoint returns nil
if d == nil {
if e != nil {
t.Fatalf("expected nil got %v", e)
}
if de != nil {
t.Fatalf("expected nil got %v", de)
}
continue
}
// check encoded map
name := e["endpoint"]
desc := e["description"]
method := strings.Split(e["method"], ",")
path := strings.Split(e["path"], ",")
host := strings.Split(e["host"], ",")
handler := e["handler"]
if name != d.Name {
t.Fatalf("expected %v got %v", d.Name, name)
}
if desc != d.Description {
t.Fatalf("expected %v got %v", d.Description, desc)
}
if handler != d.Handler {
t.Fatalf("expected %v got %v", d.Handler, handler)
}
if ok := compare(d.Method, method); !ok {
t.Fatalf("expected %v got %v", d.Method, method)
}
if ok := compare(d.Path, path); !ok {
t.Fatalf("expected %v got %v", d.Path, path)
}
if ok := compare(d.Host, host); !ok {
t.Fatalf("expected %v got %v", d.Host, host)
}
if de.Name != d.Name {
t.Fatalf("expected %v got %v", d.Name, de.Name)
}
if de.Description != d.Description {
t.Fatalf("expected %v got %v", d.Description, de.Description)
}
if de.Handler != d.Handler {
t.Fatalf("expected %v got %v", d.Handler, de.Handler)
}
if ok := compare(d.Method, de.Method); !ok {
t.Fatalf("expected %v got %v", d.Method, de.Method)
}
if ok := compare(d.Path, de.Path); !ok {
t.Fatalf("expected %v got %v", d.Path, de.Path)
}
if ok := compare(d.Host, de.Host); !ok {
t.Fatalf("expected %v got %v", d.Host, de.Host)
}
}
}
func TestValidate(t *testing.T) {
epPcre := &Endpoint{
Name: "Foo.Bar",
Description: "A test endpoint",
Handler: "meta",
Host: []string{"foo.com"},
Method: []string{"GET"},
Path: []string{"^/test/?$"},
}
if err := Validate(epPcre); err != nil {
t.Fatal(err)
}
epGpath := &Endpoint{
Name: "Foo.Bar",
Description: "A test endpoint",
Handler: "meta",
Host: []string{"foo.com"},
Method: []string{"GET"},
Path: []string{"/test/{id}"},
}
if err := Validate(epGpath); err != nil {
t.Fatal(err)
}
epPcreInvalid := &Endpoint{
Name: "Foo.Bar",
Description: "A test endpoint",
Handler: "meta",
Host: []string{"foo.com"},
Method: []string{"GET"},
Path: []string{"/test/?$"},
}
if err := Validate(epPcreInvalid); err == nil {
t.Fatalf("invalid pcre %v", epPcreInvalid.Path[0])
}
}
func TestWithEndpoint(t *testing.T) {
ep := &Endpoint{
Name: "Foo.Bar",
Description: "A test endpoint",
Handler: "meta",
Host: []string{"foo.com"},
Method: []string{"GET"},
Path: []string{"/test/{id}"},
}
o := WithEndpoint(ep)
opts := server.NewHandlerOptions(o)
if opts.Metadata == nil {
t.Fatalf("WithEndpoint not works %#+v", opts)
}
md, ok := opts.Metadata[ep.Name]
if !ok {
t.Fatalf("WithEndpoint not works %#+v", opts)
}
if v, ok := md.Get("Endpoint"); !ok || v != "Foo.Bar" {
t.Fatalf("WithEndpoint not works %#+v", md)
}
}
func TestValidateNilErr(t *testing.T) {
var ep *Endpoint
if err := Validate(ep); err == nil {
t.Fatalf("Validate not works")
}
}
func TestValidateMissingNameErr(t *testing.T) {
ep := &Endpoint{}
if err := Validate(ep); err == nil {
t.Fatalf("Validate not works")
}
}
func TestValidateMissingHandlerErr(t *testing.T) {
ep := &Endpoint{Name: "test"}
if err := Validate(ep); err == nil {
t.Fatalf("Validate not works")
}
}
func TestValidateRegexpStartErr(t *testing.T) {
ep := &Endpoint{Name: "test", Handler: "test"}
ep.Path = []string{"^/"}
if err := Validate(ep); err == nil {
t.Fatalf("Validate not works")
}
}
func TestValidateRegexpEndErr(t *testing.T) {
ep := &Endpoint{Name: "test", Handler: "test", Path: []string{""}}
ep.Path[0] = "/$"
if err := Validate(ep); err == nil {
t.Fatalf("Validate not works")
}
}
func TestValidateRegexpNonErr(t *testing.T) {
ep := &Endpoint{Name: "test", Handler: "test", Path: []string{""}}
ep.Path[0] = "^/(.*)$"
if err := Validate(ep); err != nil {
t.Fatalf("Validate not works")
}
}
func TestValidateRegexpErr(t *testing.T) {
ep := &Endpoint{Name: "test", Handler: "test", Path: []string{""}}
ep.Path[0] = "^/(.$"
if err := Validate(ep); err == nil {
t.Fatalf("Validate not works")
}
}

View File

@@ -8,6 +8,7 @@ import (
)
func TestDeps(t *testing.T) {
t.Skip()
d := &dag.AcyclicGraph{}
v0 := d.Add(&node{"v0"})

View File

@@ -10,7 +10,7 @@ import (
)
// guard to fail early
var _ MeterServer = &Handler{}
var _ MeterServiceServer = &Handler{}
type Handler struct {
opts Options

View File

@@ -7,7 +7,7 @@ import "api/annotations.proto";
import "openapiv3/annotations.proto";
import "codec/frame.proto";
service Meter {
service MeterService {
rpc Metrics(micro.codec.Frame) returns (micro.codec.Frame) {
option (micro.openapiv3.openapiv3_operation) = {
operation_id: "Metrics";

View File

@@ -1,32 +1,29 @@
// Code generated by protoc-gen-go-micro. DO NOT EDIT.
// protoc-gen-go-micro version: v3.5.3
// versions:
// - protoc-gen-go-micro v3.5.3
// - protoc v3.21.12
// source: handler.proto
package handler
import (
context "context"
api "go.unistack.org/micro/v3/api"
codec "go.unistack.org/micro/v3/codec"
http "net/http"
)
var (
MeterName = "Meter"
MeterEndpoints = []api.Endpoint{
{
Name: "Meter.Metrics",
Path: []string{"/metrics"},
Method: []string{"GET"},
Handler: "rpc",
MeterServiceName = "MeterService"
)
var (
MeterServiceServerEndpoints = map[string]map[string]string{
"/metrics": map[string]string{
"Method": http.MethodGet,
"Stream": "false",
},
}
)
func NewMeterEndpoints() []api.Endpoint {
return MeterEndpoints
}
type MeterServer interface {
type MeterServiceServer interface {
Metrics(ctx context.Context, req *codec.Frame, rsp *codec.Frame) error
}

View File

@@ -6,30 +6,27 @@ package handler
import (
context "context"
api "go.unistack.org/micro/v3/api"
v3 "go.unistack.org/micro-server-http/v3"
codec "go.unistack.org/micro/v3/codec"
server "go.unistack.org/micro/v3/server"
)
type meterServer struct {
MeterServer
type meterServiceServer struct {
MeterServiceServer
}
func (h *meterServer) Metrics(ctx context.Context, req *codec.Frame, rsp *codec.Frame) error {
return h.MeterServer.Metrics(ctx, req, rsp)
func (h *meterServiceServer) Metrics(ctx context.Context, req *codec.Frame, rsp *codec.Frame) error {
return h.MeterServiceServer.Metrics(ctx, req, rsp)
}
func RegisterMeterServer(s server.Server, sh MeterServer, opts ...server.HandlerOption) error {
type meter interface {
Metrics(ctx context.Context, req *codec.Frame, rsp *codec.Frame) error
func RegisterMeterServiceServer(s server.Server, sh MeterServiceServer, opts ...server.HandlerOption) error {
type meterService interface {
}
type Meter struct {
meter
type MeterService struct {
meterService
}
h := &meterServer{sh}
h := &meterServiceServer{sh}
var nopts []server.HandlerOption
for _, endpoint := range MeterEndpoints {
nopts = append(nopts, api.WithEndpoint(&endpoint))
}
return s.Handle(s.NewHandler(&Meter{h}, append(nopts, opts...)...))
nopts = append(nopts, v3.HandlerMetadata(MeterServiceServerEndpoints))
return s.Handle(s.NewHandler(&MeterService{h}, append(nopts, opts...)...))
}

View File

@@ -3,7 +3,6 @@ package register
import (
"context"
"fmt"
"os"
"sync"
"testing"
"time"
@@ -207,9 +206,9 @@ func TestMemoryRegistryTTLConcurrent(t *testing.T) {
}
}
if len(os.Getenv("IN_TRAVIS_CI")) == 0 {
t.Logf("test will wait %v, then check TTL timeouts", waitTime)
}
//if len(os.Getenv("IN_TRAVIS_CI")) == 0 {
// t.Logf("test will wait %v, then check TTL timeouts", waitTime)
//}
errChan := make(chan error, concurrency)
syncChan := make(chan struct{})

View File

@@ -42,3 +42,13 @@ func SetSubscriberOption(k, v interface{}) SubscriberOption {
o.Context = context.WithValue(o.Context, k, v)
}
}
// SetHandlerOption returns a function to setup a context with given value
func SetHandlerOption(k, v interface{}) HandlerOption {
return func(o *HandlerOptions) {
if o.Context == nil {
o.Context = context.Background()
}
o.Context = context.WithValue(o.Context, k, v)
}
}

View File

@@ -7,7 +7,7 @@ import (
"go.unistack.org/micro/v3/errors"
)
var _ HealthServer = &Handler{}
var _ HealthServiceServer = &Handler{}
type Handler struct {
opts Options

View File

@@ -7,7 +7,7 @@ import "api/annotations.proto";
import "openapiv3/annotations.proto";
import "codec/frame.proto";
service Health {
service HealthService {
rpc Live(micro.codec.Frame) returns (micro.codec.Frame) {
option (micro.openapiv3.openapiv3_operation) = {
operation_id: "Live";

View File

@@ -1,45 +1,38 @@
// Code generated by protoc-gen-go-micro. DO NOT EDIT.
// protoc-gen-go-micro version: v3.5.3
// versions:
// - protoc-gen-go-micro v3.5.3
// - protoc v3.21.12
// source: health.proto
package health
import (
context "context"
api "go.unistack.org/micro/v3/api"
codec "go.unistack.org/micro/v3/codec"
http "net/http"
)
var (
HealthName = "Health"
HealthEndpoints = []api.Endpoint{
{
Name: "Health.Live",
Path: []string{"/live"},
Method: []string{"GET"},
Handler: "rpc",
HealthServiceName = "HealthService"
)
var (
HealthServiceServerEndpoints = map[string]map[string]string{
"/live": map[string]string{
"Method": http.MethodGet,
"Stream": "false",
},
{
Name: "Health.Ready",
Path: []string{"/ready"},
Method: []string{"GET"},
Handler: "rpc",
"/ready": map[string]string{
"Method": http.MethodGet,
"Stream": "false",
},
{
Name: "Health.Version",
Path: []string{"/version"},
Method: []string{"GET"},
Handler: "rpc",
"/version": map[string]string{
"Method": http.MethodGet,
"Stream": "false",
},
}
)
func NewHealthEndpoints() []api.Endpoint {
return HealthEndpoints
}
type HealthServer interface {
type HealthServiceServer interface {
Live(ctx context.Context, req *codec.Frame, rsp *codec.Frame) error
Ready(ctx context.Context, req *codec.Frame, rsp *codec.Frame) error
Version(ctx context.Context, req *codec.Frame, rsp *codec.Frame) error

View File

@@ -6,40 +6,35 @@ package health
import (
context "context"
api "go.unistack.org/micro/v3/api"
v3 "go.unistack.org/micro-server-http/v3"
codec "go.unistack.org/micro/v3/codec"
server "go.unistack.org/micro/v3/server"
)
type healthServer struct {
HealthServer
type healthServiceServer struct {
HealthServiceServer
}
func (h *healthServer) Live(ctx context.Context, req *codec.Frame, rsp *codec.Frame) error {
return h.HealthServer.Live(ctx, req, rsp)
func (h *healthServiceServer) Live(ctx context.Context, req *codec.Frame, rsp *codec.Frame) error {
return h.HealthServiceServer.Live(ctx, req, rsp)
}
func (h *healthServer) Ready(ctx context.Context, req *codec.Frame, rsp *codec.Frame) error {
return h.HealthServer.Ready(ctx, req, rsp)
func (h *healthServiceServer) Ready(ctx context.Context, req *codec.Frame, rsp *codec.Frame) error {
return h.HealthServiceServer.Ready(ctx, req, rsp)
}
func (h *healthServer) Version(ctx context.Context, req *codec.Frame, rsp *codec.Frame) error {
return h.HealthServer.Version(ctx, req, rsp)
func (h *healthServiceServer) Version(ctx context.Context, req *codec.Frame, rsp *codec.Frame) error {
return h.HealthServiceServer.Version(ctx, req, rsp)
}
func RegisterHealthServer(s server.Server, sh HealthServer, opts ...server.HandlerOption) error {
type health interface {
Live(ctx context.Context, req *codec.Frame, rsp *codec.Frame) error
Ready(ctx context.Context, req *codec.Frame, rsp *codec.Frame) error
Version(ctx context.Context, req *codec.Frame, rsp *codec.Frame) error
func RegisterHealthServiceServer(s server.Server, sh HealthServiceServer, opts ...server.HandlerOption) error {
type healthService interface {
}
type Health struct {
health
type HealthService struct {
healthService
}
h := &healthServer{sh}
h := &healthServiceServer{sh}
var nopts []server.HandlerOption
for _, endpoint := range HealthEndpoints {
nopts = append(nopts, api.WithEndpoint(&endpoint))
}
return s.Handle(s.NewHandler(&Health{h}, append(nopts, opts...)...))
nopts = append(nopts, v3.HandlerMetadata(HealthServiceServerEndpoints))
return s.Handle(s.NewHandler(&HealthService{h}, append(nopts, opts...)...))
}

View File

@@ -322,7 +322,7 @@ type HandlerOption func(*HandlerOptions)
type HandlerOptions struct {
// Context holds external options
Context context.Context
// Metadata for hondler
// Metadata for handler
Metadata map[string]metadata.Metadata
}

3
util/structfs/README.md Normal file
View File

@@ -0,0 +1,3 @@
# go-structfs
Expose struct data via http.FileServer

View File

@@ -0,0 +1,67 @@
package structfs
import (
"encoding/json"
"net/http"
"strings"
"time"
)
type DigitalOceanMetadata struct {
Metadata struct {
V1 struct {
DropletID int64 `json:"droplet_id"`
Hostname string `json:"hostname"`
VendorData string `json:"vendor_data"`
PublicKeys []string `json:"public_keys"`
Region string `json:"region"`
Interfaces struct {
Private []struct {
IPv4 struct {
Address string `json:"ip_address"`
Netmask string `json:"netmask"`
Gateway string `json:"gateway"`
}
Mac string `json:"mac"`
Type string `json:"type"`
} `json:"private"`
Public []struct {
IPv4 struct {
Address string `json:"ip_address"`
Netmask string `json:"netmask"`
Gateway string `json:"gateway"`
} `json:"ipv4"`
IPv6 struct {
Address string `json:"ip_address"`
CIDR int `json:"cidr"`
Gateway string `json:"gateway"`
} `json:"ipv6"`
Mac string `json:"mac"`
Type string `json:"type"`
} `json:"public"`
} `json:"interfaces"`
FloatingIP struct {
IPv4 struct {
Active bool `json:"active"`
} `json:"ipv4"`
} `json:"floating_ip"`
DNS struct {
Nameservers []string `json:"nameservers"`
} `json:"dns"`
Features map[string]interface{} `json:"features"`
} `json:"v1"`
} `json:"metadata"`
}
func (stfs *DigitalOceanMetadata) ServeHTTP(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
case "/metadata/v1.json":
json.NewEncoder(w).Encode(stfs.Metadata.V1)
default:
fs := FileServer(stfs, "json", time.Now())
idx := strings.Index(r.URL.Path[1:], "/")
r.URL.Path = strings.Replace(r.URL.Path[idx+1:], "/metadata/v1/", "", 1)
r.RequestURI = r.URL.Path
fs.ServeHTTP(w, r)
}
}

View File

@@ -0,0 +1,30 @@
package structfs
type EC2Metadata struct {
Latest struct {
Metadata struct {
AMIID int `json:"ami-id"`
AMILaunchIndex int `json:"ami-launch-index"`
AMIManifestPath string `json:"ami-manifest-path"`
AncestorAMIIDs []int `json:"ancestor-ami-ids"`
BlockDeviceMapping []string `json:"block-device-mapping"`
InstanceID int `json:"instance-id"`
InstanceType string `json:"instance-type"`
LocalHostname string `json:"local-hostname"`
LocalIPv4 string `json:"local-ipv4"`
kernelID int `json:"kernel-id"`
Placement string `json:"placement"`
AvailabilityZone string `json:"availability-zone"`
ProductCodes string `json:"product-codes"`
PublicHostname string `json:"public-hostname"`
PublicIPv4 string `json:"public-ipv4"`
PublicKeys []struct {
Key []string `json:"-"`
} `json:"public-keys"`
RamdiskID int `json:"ramdisk-id"`
ReservationID int `json:"reservation-id"`
SecurityGroups []string `json:"security-groups"`
} `json:"meta-data"`
Userdata string `json:"user-data"`
} `json:"latest"`
}

245
util/structfs/structfs.go Normal file
View File

@@ -0,0 +1,245 @@
package structfs
import (
"fmt"
"io"
"net/http"
"os"
"reflect"
"strings"
"time"
)
// FileServer creates new file server from the struct iface with specific tag and specific modtime
func FileServer(iface interface{}, tag string, modtime time.Time) http.Handler {
if modtime.IsZero() {
modtime = time.Now()
}
return &fs{iface: iface, tag: tag, modtime: modtime}
}
func (fs *fs) ServeHTTP(w http.ResponseWriter, r *http.Request) {
upath := r.URL.Path
if !strings.HasPrefix(upath, "/") {
upath = "/" + upath
r.URL.Path = upath
}
f, err := fs.Open(r.URL.Path)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte(err.Error()))
return
}
w.Header().Set("Content-Type", "application/octet-stream")
http.ServeContent(w, r, r.URL.Path, fs.modtime, f)
}
type fs struct {
iface interface{}
tag string
modtime time.Time
}
type file struct {
name string
offset int64
data []byte
modtime time.Time
}
type fileInfo struct {
name string
size int64
modtime time.Time
}
func (fi *fileInfo) Sys() interface{} {
return nil
}
func (fi *fileInfo) Size() int64 {
return fi.size
}
func (fi *fileInfo) Name() string {
return fi.name
}
func (fi *fileInfo) Mode() os.FileMode {
if strings.HasSuffix(fi.name, "/") {
return os.FileMode(0755) | os.ModeDir
}
return os.FileMode(0644)
}
func (fi *fileInfo) IsDir() bool {
// disables additional open /index.html
return false
}
func (fi *fileInfo) ModTime() time.Time {
return fi.modtime
}
func (f *file) Close() error {
return nil
}
func (f *file) Read(b []byte) (int, error) {
var err error
var n int
if f.offset >= int64(len(f.data)) {
return 0, io.EOF
}
if len(f.data) > 0 {
n = copy(b, f.data[f.offset:])
}
if n < len(b) {
err = io.EOF
}
f.offset += int64(n)
return n, err
}
func (f *file) Readdir(count int) ([]os.FileInfo, error) {
return nil, nil
}
func (f *file) Seek(offset int64, whence int) (int64, error) {
// log.Printf("seek %d %d %s\n", offset, whence, f.name)
switch whence {
case os.SEEK_SET:
f.offset = offset
case os.SEEK_CUR:
f.offset += offset
case os.SEEK_END:
f.offset = int64(len(f.data)) + offset
}
return f.offset, nil
}
func (f *file) Stat() (os.FileInfo, error) {
return &fileInfo{name: f.name, size: int64(len(f.data)), modtime: f.modtime}, nil
}
func (fs *fs) Open(path string) (http.File, error) {
return newFile(path, fs.iface, fs.tag, fs.modtime)
}
func newFile(name string, iface interface{}, tag string, modtime time.Time) (*file, error) {
var err error
f := &file{name: name, modtime: modtime}
f.data, err = structItem(name, iface, tag)
if err != nil {
return nil, err
}
return f, nil
}
func structItem(path string, iface interface{}, tag string) ([]byte, error) {
var buf []byte
var err error
var curiface interface{}
if path == "/" {
return getNames(iface, tag)
}
idx := strings.Index(path[1:], "/")
switch {
case idx > 0:
curiface, err = getStruct(path[1:idx+1], iface, tag)
if err != nil {
return nil, err
}
buf, err = structItem(path[idx+1:], curiface, tag)
case idx == 0:
return getNames(iface, tag)
case idx < 0:
return getValue(path[1:], iface, tag)
}
return buf, err
}
func getNames(iface interface{}, tag string) ([]byte, error) {
var lines []string
s := reflectValue(iface)
typeOf := s.Type()
for i := 0; i < s.NumField(); i++ {
value := typeOf.Field(i).Tag.Get(tag)
if value != "" {
lines = append(lines, value)
}
}
if len(lines) > 0 {
return []byte(strings.Join(lines, "\n")), nil
}
return nil, fmt.Errorf("failed to find names")
}
func getStruct(name string, iface interface{}, tag string) (interface{}, error) {
s := reflectValue(iface)
typeOf := s.Type()
for i := 0; i < s.NumField(); i++ {
if typeOf.Field(i).Tag.Get(tag) == name {
return s.Field(i).Interface(), nil
}
}
return nil, fmt.Errorf("failed to find iface %T with name %s", iface, name)
}
func getValue(name string, iface interface{}, tag string) ([]byte, error) {
s := reflectValue(iface)
typeOf := s.Type()
switch typeOf.Kind() {
case reflect.Map:
return []byte(fmt.Sprintf("%v", s.MapIndex(reflect.ValueOf(name)).Interface())), nil
default:
for i := 0; i < s.NumField(); i++ {
if typeOf.Field(i).Tag.Get(tag) != name {
continue
}
ifs := s.Field(i).Interface()
switch s.Field(i).Kind() {
case reflect.Slice:
var lines []string
for k := 0; k < s.Field(i).Len(); k++ {
lines = append(lines, fmt.Sprintf("%v", s.Field(i).Index(k)))
}
return []byte(strings.Join(lines, "\n")), nil
default:
return []byte(fmt.Sprintf("%v", ifs)), nil
}
}
}
return nil, fmt.Errorf("failed to find %s in interface %T", name, iface)
}
func hasValidType(obj interface{}, types []reflect.Kind) bool {
for _, t := range types {
if reflect.TypeOf(obj).Kind() == t {
return true
}
}
return false
}
func reflectValue(obj interface{}) reflect.Value {
var val reflect.Value
if reflect.TypeOf(obj).Kind() == reflect.Ptr {
val = reflect.ValueOf(obj).Elem()
} else {
val = reflect.ValueOf(obj)
}
return val
}

View File

@@ -0,0 +1,133 @@
package structfs
import (
"encoding/json"
"io/ioutil"
"net/http"
"reflect"
"testing"
"time"
)
var doOrig = []byte(`{
"droplet_id":2756294,
"hostname":"sample-droplet",
"vendor_data":"#cloud-config\ndisable_root: false\nmanage_etc_hosts: true\n\ncloud_config_modules:\n - ssh\n - set_hostname\n - [ update_etc_hosts, once-per-instance ]\n\ncloud_final_modules:\n - scripts-vendor\n - scripts-per-once\n - scripts-per-boot\n - scripts-per-instance\n - scripts-user\n",
"public_keys":["ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCcbi6cygCUmuNlB0KqzBpHXf7CFYb3VE4pDOf/RLJ8OFDjOM+fjF83a24QktSVIpQnHYpJJT2pQMBxD+ZmnhTbKv+OjwHSHwAfkBullAojgZKzz+oN35P4Ea4J78AvMrHw0zp5MknS+WKEDCA2c6iDRCq6/hZ13Mn64f6c372JK99X29lj/B4VQpKCQyG8PUSTFkb5DXTETGbzuiVft+vM6SF+0XZH9J6dQ7b4yD3sOder+M0Q7I7CJD4VpdVD/JFa2ycOS4A4dZhjKXzabLQXdkWHvYGgNPGA5lI73TcLUAueUYqdq3RrDRfaQ5Z0PEw0mDllCzhk5dQpkmmqNi0F sammy@digitalocean.com"],
"region":"nyc3",
"interfaces":{
"private":[
{
"ipv4":{
"ip_address":"10.132.255.113",
"netmask":"255.255.0.0",
"gateway":"10.132.0.1"
},
"mac":"04:01:2a:0f:2a:02",
"type":"private"
}
],
"public":[
{
"ipv4":{
"ip_address":"104.131.20.105",
"netmask":"255.255.192.0",
"gateway":"104.131.0.1"
},
"ipv6":{
"ip_address":"2604:A880:0800:0010:0000:0000:017D:2001",
"cidr":64,
"gateway":"2604:A880:0800:0010:0000:0000:0000:0001"
},
"mac":"04:01:2a:0f:2a:01",
"type":"public"}
]
},
"floating_ip": {
"ipv4": {
"active": false
}
},
"dns":{
"nameservers":[
"2001:4860:4860::8844",
"2001:4860:4860::8888",
"8.8.8.8"
]
},
"features":{
"dhcp_enabled": true
}
}
`)
func server(t *testing.T) {
stfs := DigitalOceanMetadata{}
err := json.Unmarshal(doOrig, &stfs.Metadata.V1)
if err != nil {
t.Fatal(err)
}
http.Handle("/metadata/v1/", FileServer(&stfs, "json", time.Now()))
http.Handle("/metadata/v1.json", &stfs)
go func() {
t.Fatal(http.ListenAndServe("127.0.0.1:8080", nil))
}()
time.Sleep(2 * time.Second)
}
func get(path string) ([]byte, error) {
res, err := http.Get(path)
if err != nil {
return nil, err
}
defer res.Body.Close()
return ioutil.ReadAll(res.Body)
}
func TestAll(t *testing.T) {
server(t)
var tests = []struct {
in string
out string
}{
{"http://127.0.0.1:8080/metadata/v1/", "droplet_id\nhostname\nvendor_data\npublic_keys\nregion\ninterfaces\nfloating_ip\ndns\nfeatures"},
{"http://127.0.0.1:8080/metadata/v1/droplet_id", "2756294"},
{"http://127.0.0.1:8080/metadata/v1/dns/", "nameservers"},
{"http://127.0.0.1:8080/metadata/v1/dns/nameservers", "2001:4860:4860::8844\n2001:4860:4860::8888\n8.8.8.8"},
{"http://127.0.0.1:8080/metadata/v1/features/dhcp_enabled", "true"},
}
for _, tt := range tests {
buf, err := get(tt.in)
if err != nil {
t.Fatal(err)
}
if string(buf) != tt.out {
t.Errorf("req %s output %s not match requested %s", tt.in, string(buf), tt.out)
}
}
doTest, err := get("http://127.0.0.1:8080/metadata/v1.json")
if err != nil {
t.Fatal(err)
}
oSt := DigitalOceanMetadata{}
err = json.Unmarshal(doOrig, &oSt.Metadata.V1)
if err != nil {
t.Fatal(err)
}
nSt := DigitalOceanMetadata{}
err = json.Unmarshal(doTest, &nSt.Metadata.V1)
if err != nil {
t.Fatal(err)
}
if !reflect.DeepEqual(oSt, nSt) {
t.Fatalf("%v not match %v", oSt, nSt)
}
}

View File

@@ -1,6 +1,7 @@
package time
import (
"encoding/json"
"fmt"
"time"
)
@@ -46,3 +47,36 @@ func ParseDuration(s string) (time.Duration, error) {
return td, err
}
func (d Duration) MarshalJSON() ([]byte, error) {
return json.Marshal(time.Duration(d).String())
}
func (d *Duration) UnmarshalJSON(b []byte) error {
var v interface{}
if err := json.Unmarshal(b, &v); err != nil {
return err
}
switch value := v.(type) {
case float64:
*d = Duration(time.Duration(value))
return nil
case string:
dv, err := time.ParseDuration(value)
if err != nil {
return err
}
*d = Duration(dv)
return nil
default:
return fmt.Errorf("invalid duration")
}
}
/*
func (d Duration) MarshalYAML() (interface{}, error) {
return nil, nil
}
func (d Duration) UnmarshalYAML(fn func(interface{}) error) error
*/

View File

@@ -1,10 +1,37 @@
package time
import (
"bytes"
"encoding/json"
"testing"
"time"
)
func TestMarshalJSON(t *testing.T) {
d := Duration(10000000)
buf, err := json.Marshal(d)
if err != nil {
t.Fatal(err)
}
if !bytes.Equal(buf, []byte(`"10ms"`)) {
t.Fatalf("invalid duration: %s != %s", buf, `"10ms"`)
}
}
func TestUnmarshalJSON(t *testing.T) {
type str struct {
TTL Duration `json:"ttl"`
}
v := &str{}
err := json.Unmarshal([]byte(`{"ttl":"10ms"}`), v)
if err != nil {
t.Fatal(err)
} else if v.TTL != 10000000 {
t.Fatalf("invalid duration %v != 10000000", v.TTL)
}
}
func TestParseDuration(t *testing.T) {
var td time.Duration
var err error