mirror of
https://github.com/go-micro/go-micro.git
synced 2025-09-16 08:36:30 +02:00
fix: some linting issues (#2563)
This commit is contained in:
@@ -17,7 +17,7 @@ func init() {
|
||||
}
|
||||
}
|
||||
|
||||
// AppendPrivateBlocks append private network blocks
|
||||
// AppendPrivateBlocks append private network blocks.
|
||||
func AppendPrivateBlocks(bs ...string) {
|
||||
for _, b := range bs {
|
||||
if _, block, err := net.ParseCIDR(b); err == nil {
|
||||
@@ -36,7 +36,7 @@ func isPrivateIP(ipAddr string) bool {
|
||||
return false
|
||||
}
|
||||
|
||||
// IsLocal tells us whether an ip is local
|
||||
// IsLocal tells us whether an ip is local.
|
||||
func IsLocal(addr string) bool {
|
||||
// extract the host
|
||||
host, _, err := net.SplitHostPort(addr)
|
||||
@@ -59,7 +59,7 @@ func IsLocal(addr string) bool {
|
||||
return false
|
||||
}
|
||||
|
||||
// Extract returns a real ip
|
||||
// Extract returns a real ip.
|
||||
func Extract(addr string) (string, error) {
|
||||
// if addr specified then its returned
|
||||
if len(addr) > 0 && (addr != "0.0.0.0" && addr != "[::]" && addr != "::") {
|
||||
@@ -71,7 +71,6 @@ func Extract(addr string) (string, error) {
|
||||
return "", fmt.Errorf("Failed to get interfaces! Err: %v", err)
|
||||
}
|
||||
|
||||
//nolint:prealloc
|
||||
var addrs []net.Addr
|
||||
var loAddrs []net.Addr
|
||||
for _, iface := range ifaces {
|
||||
@@ -132,7 +131,7 @@ func Extract(addr string) (string, error) {
|
||||
return "", fmt.Errorf("No IP address found, and explicit IP not provided")
|
||||
}
|
||||
|
||||
// IPs returns all known ips
|
||||
// IPs returns all known ips.
|
||||
func IPs() []string {
|
||||
ifaces, err := net.Interfaces()
|
||||
if err != nil {
|
||||
|
@@ -49,12 +49,10 @@ func TestExtractor(t *testing.T) {
|
||||
if ip == nil {
|
||||
t.Error("Unexpected nil IP")
|
||||
}
|
||||
|
||||
} else if addr != d.expect {
|
||||
t.Errorf("Expected %s got %s", d.expect, addr)
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
func TestAppendPrivateBlocks(t *testing.T) {
|
||||
|
@@ -29,7 +29,7 @@ import (
|
||||
type Cmd interface {
|
||||
// The cli app within this cmd
|
||||
App() *cli.App
|
||||
// Adds options, parses flags and initialise
|
||||
// Adds options, parses flags and initialize
|
||||
// exits on error
|
||||
Init(opts ...Option) error
|
||||
// Options set within this command
|
||||
|
@@ -58,21 +58,21 @@ type Options struct {
|
||||
Context context.Context
|
||||
}
|
||||
|
||||
// Command line Name
|
||||
// Command line Name.
|
||||
func Name(n string) Option {
|
||||
return func(o *Options) {
|
||||
o.Name = n
|
||||
}
|
||||
}
|
||||
|
||||
// Command line Description
|
||||
// Command line Description.
|
||||
func Description(d string) Option {
|
||||
return func(o *Options) {
|
||||
o.Description = d
|
||||
}
|
||||
}
|
||||
|
||||
// Command line Version
|
||||
// Command line Version.
|
||||
func Version(v string) Option {
|
||||
return func(o *Options) {
|
||||
o.Version = v
|
||||
@@ -157,84 +157,84 @@ func Profile(p *profile.Profile) Option {
|
||||
}
|
||||
}
|
||||
|
||||
// New broker func
|
||||
// New broker func.
|
||||
func NewBroker(name string, b func(...broker.Option) broker.Broker) Option {
|
||||
return func(o *Options) {
|
||||
o.Brokers[name] = b
|
||||
}
|
||||
}
|
||||
|
||||
// New cache func
|
||||
// New cache func.
|
||||
func NewCache(name string, c func(...cache.Option) cache.Cache) Option {
|
||||
return func(o *Options) {
|
||||
o.Caches[name] = c
|
||||
}
|
||||
}
|
||||
|
||||
// New client func
|
||||
// New client func.
|
||||
func NewClient(name string, b func(...client.Option) client.Client) Option {
|
||||
return func(o *Options) {
|
||||
o.Clients[name] = b
|
||||
}
|
||||
}
|
||||
|
||||
// New registry func
|
||||
// New registry func.
|
||||
func NewRegistry(name string, r func(...registry.Option) registry.Registry) Option {
|
||||
return func(o *Options) {
|
||||
o.Registries[name] = r
|
||||
}
|
||||
}
|
||||
|
||||
// New selector func
|
||||
// New selector func.
|
||||
func NewSelector(name string, s func(...selector.Option) selector.Selector) Option {
|
||||
return func(o *Options) {
|
||||
o.Selectors[name] = s
|
||||
}
|
||||
}
|
||||
|
||||
// New server func
|
||||
// New server func.
|
||||
func NewServer(name string, s func(...server.Option) server.Server) Option {
|
||||
return func(o *Options) {
|
||||
o.Servers[name] = s
|
||||
}
|
||||
}
|
||||
|
||||
// New transport func
|
||||
// New transport func.
|
||||
func NewTransport(name string, t func(...transport.Option) transport.Transport) Option {
|
||||
return func(o *Options) {
|
||||
o.Transports[name] = t
|
||||
}
|
||||
}
|
||||
|
||||
// New runtime func
|
||||
// New runtime func.
|
||||
func NewRuntime(name string, r func(...runtime.Option) runtime.Runtime) Option {
|
||||
return func(o *Options) {
|
||||
o.Runtimes[name] = r
|
||||
}
|
||||
}
|
||||
|
||||
// New tracer func
|
||||
// New tracer func.
|
||||
func NewTracer(name string, t func(...trace.Option) trace.Tracer) Option {
|
||||
return func(o *Options) {
|
||||
o.Tracers[name] = t
|
||||
}
|
||||
}
|
||||
|
||||
// New auth func
|
||||
// New auth func.
|
||||
func NewAuth(name string, t func(...auth.Option) auth.Auth) Option {
|
||||
return func(o *Options) {
|
||||
o.Auths[name] = t
|
||||
}
|
||||
}
|
||||
|
||||
// New config func
|
||||
// New config func.
|
||||
func NewConfig(name string, t func(...config.Option) (config.Config, error)) Option {
|
||||
return func(o *Options) {
|
||||
o.Configs[name] = t
|
||||
}
|
||||
}
|
||||
|
||||
// New profile func
|
||||
// New profile func.
|
||||
func NewProfile(name string, t func(...profile.Option) profile.Profile) Option {
|
||||
return func(o *Options) {
|
||||
o.Profiles[name] = t
|
||||
|
@@ -12,7 +12,7 @@ import (
|
||||
proto "go-micro.dev/v4/util/file/proto"
|
||||
)
|
||||
|
||||
// Client is the client interface to access files
|
||||
// Client is the client interface to access files.
|
||||
type File interface {
|
||||
Open(filename string, truncate bool) (int64, error)
|
||||
Stat(filename string) (*proto.StatResponse, error)
|
||||
@@ -26,7 +26,7 @@ type File interface {
|
||||
DownloadAt(filename, saveFile string, blockId int) error
|
||||
}
|
||||
|
||||
// NewClient returns a new Client which uses a micro Client
|
||||
// NewClient returns a new Client which uses a micro Client.
|
||||
func New(service string, c client.Client) File {
|
||||
return &fc{proto.NewFileService(service, c)}
|
||||
}
|
||||
|
@@ -2,7 +2,7 @@ package file
|
||||
|
||||
import "os"
|
||||
|
||||
// Exists returns true if the path is existing
|
||||
// Exists returns true if the path is existing.
|
||||
func Exists(path string) (bool, error) {
|
||||
_, err := os.Stat(path)
|
||||
if err == nil {
|
||||
|
@@ -14,7 +14,7 @@ import (
|
||||
proto "go-micro.dev/v4/util/file/proto"
|
||||
)
|
||||
|
||||
// NewHandler is a handler that can be registered with a micro Server
|
||||
// NewHandler is a handler that can be registered with a micro Server.
|
||||
func NewHandler(readDir string) proto.FileHandler {
|
||||
return &handler{
|
||||
readDir: readDir,
|
||||
@@ -25,7 +25,7 @@ func NewHandler(readDir string) proto.FileHandler {
|
||||
}
|
||||
}
|
||||
|
||||
// RegisterHandler is a convenience method for registering a handler
|
||||
// RegisterHandler is a convenience method for registering a handler.
|
||||
func RegisterHandler(s server.Server, readDir string) {
|
||||
proto.RegisterFileHandler(s, NewHandler(readDir))
|
||||
}
|
||||
|
@@ -9,7 +9,7 @@ import (
|
||||
// Input:
|
||||
// Foo.Bar, /Foo/Bar, /package.Foo/Bar, /a.package.Foo/Bar
|
||||
// Output:
|
||||
// [Foo, Bar]
|
||||
// [Foo, Bar].
|
||||
func ServiceMethod(m string) (string, string, error) {
|
||||
if len(m) == 0 {
|
||||
return "", "", fmt.Errorf("malformed method name: %q", m)
|
||||
@@ -40,7 +40,7 @@ func ServiceMethod(m string) (string, string, error) {
|
||||
}
|
||||
|
||||
// ServiceFromMethod returns the service
|
||||
// /service.Foo/Bar => service
|
||||
// /service.Foo/Bar => service.
|
||||
func ServiceFromMethod(m string) string {
|
||||
if len(m) == 0 {
|
||||
return m
|
||||
|
@@ -13,7 +13,7 @@ import (
|
||||
"go-micro.dev/v4/selector"
|
||||
)
|
||||
|
||||
// Write sets the status and body on a http ResponseWriter
|
||||
// Write sets the status and body on a http ResponseWriter.
|
||||
func Write(w http.ResponseWriter, contentType string, status int, body string) {
|
||||
w.Header().Set("Content-Length", fmt.Sprintf("%v", len(body)))
|
||||
w.Header().Set("Content-Type", contentType)
|
||||
@@ -21,7 +21,7 @@ func Write(w http.ResponseWriter, contentType string, status int, body string) {
|
||||
fmt.Fprintf(w, `%v`, body)
|
||||
}
|
||||
|
||||
// WriteBadRequestError sets a 400 status code
|
||||
// WriteBadRequestError sets a 400 status code.
|
||||
func WriteBadRequestError(w http.ResponseWriter, err error) {
|
||||
rawBody, err := json.Marshal(map[string]string{
|
||||
"error": err.Error(),
|
||||
@@ -33,7 +33,7 @@ func WriteBadRequestError(w http.ResponseWriter, err error) {
|
||||
Write(w, "application/json", 400, string(rawBody))
|
||||
}
|
||||
|
||||
// WriteInternalServerError sets a 500 status code
|
||||
// WriteInternalServerError sets a 500 status code.
|
||||
func WriteInternalServerError(w http.ResponseWriter, err error) {
|
||||
rawBody, err := json.Marshal(map[string]string{
|
||||
"error": err.Error(),
|
||||
|
@@ -77,5 +77,4 @@ func TestRoundTripper(t *testing.T) {
|
||||
if string(b) != "hello world" {
|
||||
t.Fatal("response is", string(b))
|
||||
}
|
||||
|
||||
}
|
||||
|
@@ -34,7 +34,7 @@ func (r *rwc) Close() error {
|
||||
return r.socket.Close()
|
||||
}
|
||||
|
||||
// NewRWC returns a new ReadWriteCloser
|
||||
// NewRWC returns a new ReadWriteCloser.
|
||||
func NewRWC(sock transport.Socket) io.ReadWriteCloser {
|
||||
return &rwc{sock}
|
||||
}
|
||||
|
@@ -10,7 +10,7 @@ var (
|
||||
r = rand.New(rand.NewSource(time.Now().UnixNano()))
|
||||
)
|
||||
|
||||
// Do returns a random time to jitter with max cap specified
|
||||
// Do returns a random time to jitter with max cap specified.
|
||||
func Do(d time.Duration) time.Duration {
|
||||
v := r.Float64() * float64(d.Nanoseconds())
|
||||
return time.Duration(v)
|
||||
|
@@ -21,49 +21,49 @@ type testcase struct {
|
||||
type assertFn func(req *http.Request) bool
|
||||
|
||||
var tests = []testcase{
|
||||
testcase{
|
||||
{
|
||||
ReqFn: func(opts *Options) *Request {
|
||||
return NewRequest(opts).Get().Resource("service")
|
||||
},
|
||||
Method: "GET",
|
||||
URI: "/api/v1/namespaces/default/services/",
|
||||
},
|
||||
testcase{
|
||||
{
|
||||
ReqFn: func(opts *Options) *Request {
|
||||
return NewRequest(opts).Get().Resource("service").Name("foo")
|
||||
},
|
||||
Method: "GET",
|
||||
URI: "/api/v1/namespaces/default/services/foo",
|
||||
},
|
||||
testcase{
|
||||
{
|
||||
ReqFn: func(opts *Options) *Request {
|
||||
return NewRequest(opts).Get().Resource("service").Namespace("test").Name("bar")
|
||||
},
|
||||
Method: "GET",
|
||||
URI: "/api/v1/namespaces/test/services/bar",
|
||||
},
|
||||
testcase{
|
||||
{
|
||||
ReqFn: func(opts *Options) *Request {
|
||||
return NewRequest(opts).Get().Resource("deployment").Name("foo")
|
||||
},
|
||||
Method: "GET",
|
||||
URI: "/apis/apps/v1/namespaces/default/deployments/foo",
|
||||
},
|
||||
testcase{
|
||||
{
|
||||
ReqFn: func(opts *Options) *Request {
|
||||
return NewRequest(opts).Get().Resource("deployment").Namespace("test").Name("foo")
|
||||
},
|
||||
Method: "GET",
|
||||
URI: "/apis/apps/v1/namespaces/test/deployments/foo",
|
||||
},
|
||||
testcase{
|
||||
{
|
||||
ReqFn: func(opts *Options) *Request {
|
||||
return NewRequest(opts).Get().Resource("pod").Params(&Params{LabelSelector: map[string]string{"foo": "bar"}})
|
||||
},
|
||||
Method: "GET",
|
||||
URI: "/api/v1/namespaces/default/pods/?labelSelector=foo%3Dbar",
|
||||
},
|
||||
testcase{
|
||||
{
|
||||
ReqFn: func(opts *Options) *Request {
|
||||
return NewRequest(opts).Post().Resource("service").Name("foo").Body(map[string]string{"foo": "bar"})
|
||||
},
|
||||
@@ -71,7 +71,7 @@ var tests = []testcase{
|
||||
URI: "/api/v1/namespaces/default/services/foo",
|
||||
Body: map[string]string{"foo": "bar"},
|
||||
},
|
||||
testcase{
|
||||
{
|
||||
ReqFn: func(opts *Options) *Request {
|
||||
return NewRequest(opts).Post().Resource("deployment").Namespace("test").Name("foo").Body(map[string]string{"foo": "bar"})
|
||||
},
|
||||
@@ -79,7 +79,7 @@ var tests = []testcase{
|
||||
URI: "/apis/apps/v1/namespaces/test/deployments/foo",
|
||||
Body: map[string]string{"foo": "bar"},
|
||||
},
|
||||
testcase{
|
||||
{
|
||||
ReqFn: func(opts *Options) *Request {
|
||||
return NewRequest(opts).Put().Resource("endpoint").Name("baz").Body(map[string]string{"bam": "bar"})
|
||||
},
|
||||
@@ -87,7 +87,7 @@ var tests = []testcase{
|
||||
URI: "/api/v1/namespaces/default/endpoints/baz",
|
||||
Body: map[string]string{"bam": "bar"},
|
||||
},
|
||||
testcase{
|
||||
{
|
||||
ReqFn: func(opts *Options) *Request {
|
||||
return NewRequest(opts).Patch().Resource("endpoint").Name("baz").Body(map[string]string{"bam": "bar"})
|
||||
},
|
||||
@@ -95,7 +95,7 @@ var tests = []testcase{
|
||||
URI: "/api/v1/namespaces/default/endpoints/baz",
|
||||
Body: map[string]string{"bam": "bar"},
|
||||
},
|
||||
testcase{
|
||||
{
|
||||
ReqFn: func(opts *Options) *Request {
|
||||
return NewRequest(opts).Patch().Resource("endpoint").Name("baz").SetHeader("foo", "bar")
|
||||
},
|
||||
@@ -103,7 +103,7 @@ var tests = []testcase{
|
||||
URI: "/api/v1/namespaces/default/endpoints/baz",
|
||||
Header: map[string]string{"foo": "bar"},
|
||||
},
|
||||
testcase{
|
||||
{
|
||||
ReqFn: func(opts *Options) *Request {
|
||||
return NewRequest(opts).Patch().Resource("deployment").Name("baz").SetHeader("foo", "bar")
|
||||
},
|
||||
@@ -111,7 +111,7 @@ var tests = []testcase{
|
||||
URI: "/apis/apps/v1/namespaces/default/deployments/baz",
|
||||
Header: map[string]string{"foo": "bar"},
|
||||
},
|
||||
testcase{
|
||||
{
|
||||
ReqFn: func(opts *Options) *Request {
|
||||
return NewRequest(opts).
|
||||
Get().
|
||||
|
@@ -40,7 +40,7 @@ type Params struct {
|
||||
Additional map[string]string
|
||||
}
|
||||
|
||||
// verb sets method
|
||||
// verb sets method.
|
||||
func (r *Request) verb(method string) *Request {
|
||||
r.method = method
|
||||
return r
|
||||
@@ -50,32 +50,32 @@ func (r *Request) Context(ctx context.Context) {
|
||||
r.context = ctx
|
||||
}
|
||||
|
||||
// Get request
|
||||
// Get request.
|
||||
func (r *Request) Get() *Request {
|
||||
return r.verb("GET")
|
||||
}
|
||||
|
||||
// Post request
|
||||
// Post request.
|
||||
func (r *Request) Post() *Request {
|
||||
return r.verb("POST")
|
||||
}
|
||||
|
||||
// Put request
|
||||
// Put request.
|
||||
func (r *Request) Put() *Request {
|
||||
return r.verb("PUT")
|
||||
}
|
||||
|
||||
// Patch request
|
||||
// Patch request.
|
||||
func (r *Request) Patch() *Request {
|
||||
return r.verb("PATCH")
|
||||
}
|
||||
|
||||
// Delete request
|
||||
// Delete request.
|
||||
func (r *Request) Delete() *Request {
|
||||
return r.verb("DELETE")
|
||||
}
|
||||
|
||||
// Namespace is to set the namespace to operate on
|
||||
// Namespace is to set the namespace to operate on.
|
||||
func (r *Request) Namespace(s string) *Request {
|
||||
if len(s) > 0 {
|
||||
r.namespace = s
|
||||
@@ -84,26 +84,26 @@ func (r *Request) Namespace(s string) *Request {
|
||||
}
|
||||
|
||||
// Resource is the type of resource the operation is
|
||||
// for, such as "services", "endpoints" or "pods"
|
||||
// for, such as "services", "endpoints" or "pods".
|
||||
func (r *Request) Resource(s string) *Request {
|
||||
r.resource = s
|
||||
return r
|
||||
}
|
||||
|
||||
// SubResource sets a subresource on a resource,
|
||||
// e.g. pods/log for pod logs
|
||||
// e.g. pods/log for pod logs.
|
||||
func (r *Request) SubResource(s string) *Request {
|
||||
r.subResource = &s
|
||||
return r
|
||||
}
|
||||
|
||||
// Name is for targeting a specific resource by id
|
||||
// Name is for targeting a specific resource by id.
|
||||
func (r *Request) Name(s string) *Request {
|
||||
r.resourceName = &s
|
||||
return r
|
||||
}
|
||||
|
||||
// Body pass in a body to set, this is for POST, PUT and PATCH requests
|
||||
// Body pass in a body to set, this is for POST, PUT and PATCH requests.
|
||||
func (r *Request) Body(in interface{}) *Request {
|
||||
b := new(bytes.Buffer)
|
||||
// if we're not sending YAML request, we encode to JSON
|
||||
@@ -132,7 +132,6 @@ func (r *Request) Body(in interface{}) *Request {
|
||||
return r
|
||||
}
|
||||
|
||||
// Params isused to set paramters on a request
|
||||
func (r *Request) Params(p *Params) *Request {
|
||||
for k, v := range p.LabelSelector {
|
||||
// create new key=value pair
|
||||
@@ -152,13 +151,13 @@ func (r *Request) Params(p *Params) *Request {
|
||||
}
|
||||
|
||||
// SetHeader sets a header on a request with
|
||||
// a `key` and `value`
|
||||
// a `key` and `value`.
|
||||
func (r *Request) SetHeader(key, value string) *Request {
|
||||
r.header.Add(key, value)
|
||||
return r
|
||||
}
|
||||
|
||||
// request builds the http.Request from the options
|
||||
// request builds the http.Request from the options.
|
||||
func (r *Request) request() (*http.Request, error) {
|
||||
var url string
|
||||
switch r.resource {
|
||||
@@ -204,7 +203,7 @@ func (r *Request) request() (*http.Request, error) {
|
||||
return req, nil
|
||||
}
|
||||
|
||||
// Do builds and triggers the request
|
||||
// Do builds and triggers the request.
|
||||
func (r *Request) Do() *Response {
|
||||
if r.err != nil {
|
||||
return &Response{
|
||||
@@ -231,7 +230,7 @@ func (r *Request) Do() *Response {
|
||||
return newResponse(res, err)
|
||||
}
|
||||
|
||||
// Raw performs a Raw HTTP request to the Kubernetes API
|
||||
// Raw performs a Raw HTTP request to the Kubernetes API.
|
||||
func (r *Request) Raw() (*http.Response, error) {
|
||||
req, err := r.request()
|
||||
if err != nil {
|
||||
@@ -253,7 +252,7 @@ type Options struct {
|
||||
Client *http.Client
|
||||
}
|
||||
|
||||
// NewRequest creates a k8s api request
|
||||
// NewRequest creates a k8s api request.
|
||||
func NewRequest(opts *Options) *Request {
|
||||
req := &Request{
|
||||
header: make(http.Header),
|
||||
|
@@ -33,17 +33,17 @@ type Response struct {
|
||||
body []byte
|
||||
}
|
||||
|
||||
// Error returns an error
|
||||
// Error returns an error.
|
||||
func (r *Response) Error() error {
|
||||
return r.err
|
||||
}
|
||||
|
||||
// StatusCode returns status code for response
|
||||
// StatusCode returns status code for response.
|
||||
func (r *Response) StatusCode() int {
|
||||
return r.res.StatusCode
|
||||
}
|
||||
|
||||
// Into decode body into `data`
|
||||
// Into decode body into `data`.
|
||||
func (r *Response) Into(data interface{}) error {
|
||||
if r.err != nil {
|
||||
return r.err
|
||||
|
@@ -17,13 +17,13 @@ import (
|
||||
)
|
||||
|
||||
var (
|
||||
// path to kubernetes service account token
|
||||
// path to kubernetes service account token.
|
||||
serviceAccountPath = "/var/run/secrets/kubernetes.io/serviceaccount"
|
||||
// ErrReadNamespace is returned when the names could not be read from service account
|
||||
// ErrReadNamespace is returned when the names could not be read from service account.
|
||||
ErrReadNamespace = errors.New("could not read namespace from service account secret")
|
||||
// DefaultImage is default micro image
|
||||
// DefaultImage is default micro image.
|
||||
DefaultImage = "micro/go-micro"
|
||||
// DefaultNamespace is the default k8s namespace
|
||||
// DefaultNamespace is the default k8s namespace.
|
||||
DefaultNamespace = "default"
|
||||
)
|
||||
|
||||
@@ -32,7 +32,7 @@ type client struct {
|
||||
opts *api.Options
|
||||
}
|
||||
|
||||
// Kubernetes client
|
||||
// Kubernetes client.
|
||||
type Client interface {
|
||||
// Create creates new API resource
|
||||
Create(*Resource, ...CreateOption) error
|
||||
@@ -50,7 +50,7 @@ type Client interface {
|
||||
Watch(*Resource, ...WatchOption) (Watcher, error)
|
||||
}
|
||||
|
||||
// Create creates new API object
|
||||
// Create creates new API object.
|
||||
func (c *client) Create(r *Resource, opts ...CreateOption) error {
|
||||
options := CreateOptions{
|
||||
Namespace: c.opts.Namespace,
|
||||
@@ -79,12 +79,12 @@ var (
|
||||
)
|
||||
|
||||
// SerializeResourceName removes all spacial chars from a string so it
|
||||
// can be used as a k8s resource name
|
||||
// can be used as a k8s resource name.
|
||||
func SerializeResourceName(ns string) string {
|
||||
return nameRegex.ReplaceAllString(ns, "-")
|
||||
}
|
||||
|
||||
// Get queries API objects and stores the result in r
|
||||
// Get queries API objects and stores the result in r.
|
||||
func (c *client) Get(r *Resource, opts ...GetOption) error {
|
||||
options := GetOptions{
|
||||
Namespace: c.opts.Namespace,
|
||||
@@ -102,7 +102,7 @@ func (c *client) Get(r *Resource, opts ...GetOption) error {
|
||||
Into(r.Value)
|
||||
}
|
||||
|
||||
// Log returns logs for a pod
|
||||
// Log returns logs for a pod.
|
||||
func (c *client) Log(r *Resource, opts ...LogOption) (io.ReadCloser, error) {
|
||||
options := LogOptions{
|
||||
Namespace: c.opts.Namespace,
|
||||
@@ -133,7 +133,7 @@ func (c *client) Log(r *Resource, opts ...LogOption) (io.ReadCloser, error) {
|
||||
return resp.Body, nil
|
||||
}
|
||||
|
||||
// Update updates API object
|
||||
// Update updates API object.
|
||||
func (c *client) Update(r *Resource, opts ...UpdateOption) error {
|
||||
options := UpdateOptions{
|
||||
Namespace: c.opts.Namespace,
|
||||
@@ -164,7 +164,7 @@ func (c *client) Update(r *Resource, opts ...UpdateOption) error {
|
||||
return resp.Error()
|
||||
}
|
||||
|
||||
// Delete removes API object
|
||||
// Delete removes API object.
|
||||
func (c *client) Delete(r *Resource, opts ...DeleteOption) error {
|
||||
options := DeleteOptions{
|
||||
Namespace: c.opts.Namespace,
|
||||
@@ -182,7 +182,7 @@ func (c *client) Delete(r *Resource, opts ...DeleteOption) error {
|
||||
return resp.Error()
|
||||
}
|
||||
|
||||
// List lists API objects and stores the result in r
|
||||
// List lists API objects and stores the result in r.
|
||||
func (c *client) List(r *Resource, opts ...ListOption) error {
|
||||
options := ListOptions{
|
||||
Namespace: c.opts.Namespace,
|
||||
@@ -194,7 +194,7 @@ func (c *client) List(r *Resource, opts ...ListOption) error {
|
||||
return c.Get(r, GetNamespace(options.Namespace))
|
||||
}
|
||||
|
||||
// Watch returns an event stream
|
||||
// Watch returns an event stream.
|
||||
func (c *client) Watch(r *Resource, opts ...WatchOption) (Watcher, error) {
|
||||
options := WatchOptions{
|
||||
Namespace: c.opts.Namespace,
|
||||
@@ -225,7 +225,7 @@ func (c *client) Watch(r *Resource, opts ...WatchOption) (Watcher, error) {
|
||||
return newWatcher(req)
|
||||
}
|
||||
|
||||
// NewService returns default micro kubernetes service definition
|
||||
// NewService returns default micro kubernetes service definition.
|
||||
func NewService(name, version, typ, namespace string) *Service {
|
||||
if logger.V(logger.TraceLevel, logger.DefaultLogger) {
|
||||
logger.Logf(logger.TraceLevel, "kubernetes default service: name: %s, version: %s", name, version)
|
||||
@@ -268,7 +268,7 @@ func NewService(name, version, typ, namespace string) *Service {
|
||||
}
|
||||
}
|
||||
|
||||
// NewService returns default micro kubernetes deployment definition
|
||||
// NewService returns default micro kubernetes deployment definition.
|
||||
func NewDeployment(name, version, typ, namespace string) *Deployment {
|
||||
if logger.V(logger.TraceLevel, logger.DefaultLogger) {
|
||||
logger.Logf(logger.TraceLevel, "kubernetes default deployment: name: %s, version: %s", name, version)
|
||||
@@ -333,7 +333,7 @@ func NewDeployment(name, version, typ, namespace string) *Deployment {
|
||||
}
|
||||
}
|
||||
|
||||
// NewLocalClient returns a client that can be used with `kubectl proxy`
|
||||
// NewLocalClient returns a client that can be used with `kubectl proxy`.
|
||||
func NewLocalClient(hosts ...string) *client {
|
||||
if len(hosts) == 0 {
|
||||
hosts[0] = "http://localhost:8001"
|
||||
|
@@ -36,70 +36,70 @@ type ListOption func(*ListOptions)
|
||||
type LogOption func(*LogOptions)
|
||||
type WatchOption func(*WatchOptions)
|
||||
|
||||
// LogParams provides additional params for logs
|
||||
// LogParams provides additional params for logs.
|
||||
func LogParams(p map[string]string) LogOption {
|
||||
return func(l *LogOptions) {
|
||||
l.Params = p
|
||||
}
|
||||
}
|
||||
|
||||
// WatchParams used for watch params
|
||||
// WatchParams used for watch params.
|
||||
func WatchParams(p map[string]string) WatchOption {
|
||||
return func(w *WatchOptions) {
|
||||
w.Params = p
|
||||
}
|
||||
}
|
||||
|
||||
// CreateNamespace sets the namespace for creating a resource
|
||||
// CreateNamespace sets the namespace for creating a resource.
|
||||
func CreateNamespace(ns string) CreateOption {
|
||||
return func(o *CreateOptions) {
|
||||
o.Namespace = SerializeResourceName(ns)
|
||||
}
|
||||
}
|
||||
|
||||
// GetNamespace sets the namespace for getting a resource
|
||||
// GetNamespace sets the namespace for getting a resource.
|
||||
func GetNamespace(ns string) GetOption {
|
||||
return func(o *GetOptions) {
|
||||
o.Namespace = SerializeResourceName(ns)
|
||||
}
|
||||
}
|
||||
|
||||
// GetLabels sets the labels for when getting a resource
|
||||
// GetLabels sets the labels for when getting a resource.
|
||||
func GetLabels(ls map[string]string) GetOption {
|
||||
return func(o *GetOptions) {
|
||||
o.Labels = ls
|
||||
}
|
||||
}
|
||||
|
||||
// UpdateNamespace sets the namespace for updating a resource
|
||||
// UpdateNamespace sets the namespace for updating a resource.
|
||||
func UpdateNamespace(ns string) UpdateOption {
|
||||
return func(o *UpdateOptions) {
|
||||
o.Namespace = SerializeResourceName(ns)
|
||||
}
|
||||
}
|
||||
|
||||
// DeleteNamespace sets the namespace for deleting a resource
|
||||
// DeleteNamespace sets the namespace for deleting a resource.
|
||||
func DeleteNamespace(ns string) DeleteOption {
|
||||
return func(o *DeleteOptions) {
|
||||
o.Namespace = SerializeResourceName(ns)
|
||||
}
|
||||
}
|
||||
|
||||
// ListNamespace sets the namespace for listing resources
|
||||
// ListNamespace sets the namespace for listing resources.
|
||||
func ListNamespace(ns string) ListOption {
|
||||
return func(o *ListOptions) {
|
||||
o.Namespace = SerializeResourceName(ns)
|
||||
}
|
||||
}
|
||||
|
||||
// LogNamespace sets the namespace for logging a resource
|
||||
// LogNamespace sets the namespace for logging a resource.
|
||||
func LogNamespace(ns string) LogOption {
|
||||
return func(o *LogOptions) {
|
||||
o.Namespace = SerializeResourceName(ns)
|
||||
}
|
||||
}
|
||||
|
||||
// WatchNamespace sets the namespace for watching a resource
|
||||
// WatchNamespace sets the namespace for watching a resource.
|
||||
func WatchNamespace(ns string) WatchOption {
|
||||
return func(o *WatchOptions) {
|
||||
o.Namespace = SerializeResourceName(ns)
|
||||
|
@@ -9,7 +9,7 @@ var templates = map[string]string{
|
||||
}
|
||||
|
||||
// stripped image pull policy always
|
||||
// imagePullPolicy: Always
|
||||
// imagePullPolicy: Always.
|
||||
var deploymentTmpl = `
|
||||
apiVersion: apps/v1
|
||||
kind: Deployment
|
||||
|
@@ -1,6 +1,6 @@
|
||||
package client
|
||||
|
||||
// ContainerPort
|
||||
// ContainerPort.
|
||||
type ContainerPort struct {
|
||||
Name string `json:"name,omitempty"`
|
||||
HostPort int `json:"hostPort,omitempty"`
|
||||
@@ -8,7 +8,7 @@ type ContainerPort struct {
|
||||
Protocol string `json:"protocol,omitempty"`
|
||||
}
|
||||
|
||||
// EnvVar is environment variable
|
||||
// EnvVar is environment variable.
|
||||
type EnvVar struct {
|
||||
Name string `json:"name"`
|
||||
Value string `json:"value,omitempty"`
|
||||
@@ -20,7 +20,7 @@ type Condition struct {
|
||||
Message string `json:"message,omitempty"`
|
||||
}
|
||||
|
||||
// Container defined container runtime values
|
||||
// Container defined container runtime values.
|
||||
type Container struct {
|
||||
Name string `json:"name"`
|
||||
Image string `json:"image"`
|
||||
@@ -30,14 +30,14 @@ type Container struct {
|
||||
Ports []ContainerPort `json:"ports,omitempty"`
|
||||
}
|
||||
|
||||
// DeploymentSpec defines micro deployment spec
|
||||
// DeploymentSpec defines micro deployment spec.
|
||||
type DeploymentSpec struct {
|
||||
Replicas int `json:"replicas,omitempty"`
|
||||
Selector *LabelSelector `json:"selector"`
|
||||
Template *Template `json:"template,omitempty"`
|
||||
}
|
||||
|
||||
// DeploymentCondition describes the state of deployment
|
||||
// DeploymentCondition describes the state of deployment.
|
||||
type DeploymentCondition struct {
|
||||
LastUpdateTime string `json:"lastUpdateTime"`
|
||||
Type string `json:"type"`
|
||||
@@ -45,7 +45,7 @@ type DeploymentCondition struct {
|
||||
Message string `json:"message,omitempty"`
|
||||
}
|
||||
|
||||
// DeploymentStatus is returned when querying deployment
|
||||
// DeploymentStatus is returned when querying deployment.
|
||||
type DeploymentStatus struct {
|
||||
Replicas int `json:"replicas,omitempty"`
|
||||
UpdatedReplicas int `json:"updatedReplicas,omitempty"`
|
||||
@@ -55,20 +55,20 @@ type DeploymentStatus struct {
|
||||
Conditions []DeploymentCondition `json:"conditions,omitempty"`
|
||||
}
|
||||
|
||||
// Deployment is Kubernetes deployment
|
||||
// Deployment is Kubernetes deployment.
|
||||
type Deployment struct {
|
||||
Metadata *Metadata `json:"metadata"`
|
||||
Spec *DeploymentSpec `json:"spec,omitempty"`
|
||||
Status *DeploymentStatus `json:"status,omitempty"`
|
||||
}
|
||||
|
||||
// DeploymentList
|
||||
// DeploymentList.
|
||||
type DeploymentList struct {
|
||||
Items []Deployment `json:"items"`
|
||||
}
|
||||
|
||||
// LabelSelector is a label query over a set of resources
|
||||
// NOTE: we do not support MatchExpressions at the moment
|
||||
// NOTE: we do not support MatchExpressions at the moment.
|
||||
type LabelSelector struct {
|
||||
MatchLabels map[string]string `json:"matchLabels,omitempty"`
|
||||
}
|
||||
@@ -82,7 +82,7 @@ type LoadBalancerStatus struct {
|
||||
Ingress []LoadBalancerIngress `json:"ingress,omitempty"`
|
||||
}
|
||||
|
||||
// Metadata defines api object metadata
|
||||
// Metadata defines api object metadata.
|
||||
type Metadata struct {
|
||||
Name string `json:"name,omitempty"`
|
||||
Namespace string `json:"namespace,omitempty"`
|
||||
@@ -91,25 +91,25 @@ type Metadata struct {
|
||||
Annotations map[string]string `json:"annotations,omitempty"`
|
||||
}
|
||||
|
||||
// PodSpec is a pod
|
||||
// PodSpec is a pod.
|
||||
type PodSpec struct {
|
||||
Containers []Container `json:"containers"`
|
||||
ServiceAccountName string `json:"serviceAccountName"`
|
||||
}
|
||||
|
||||
// PodList
|
||||
// PodList.
|
||||
type PodList struct {
|
||||
Items []Pod `json:"items"`
|
||||
}
|
||||
|
||||
// Pod is the top level item for a pod
|
||||
// Pod is the top level item for a pod.
|
||||
type Pod struct {
|
||||
Metadata *Metadata `json:"metadata"`
|
||||
Spec *PodSpec `json:"spec,omitempty"`
|
||||
Status *PodStatus `json:"status"`
|
||||
}
|
||||
|
||||
// PodStatus
|
||||
// PodStatus.
|
||||
type PodStatus struct {
|
||||
Conditions []PodCondition `json:"conditions,omitempty"`
|
||||
Containers []ContainerStatus `json:"containerStatuses"`
|
||||
@@ -118,7 +118,7 @@ type PodStatus struct {
|
||||
Reason string `json:"reason"`
|
||||
}
|
||||
|
||||
// PodCondition describes the state of pod
|
||||
// PodCondition describes the state of pod.
|
||||
type PodCondition struct {
|
||||
Type string `json:"type"`
|
||||
Reason string `json:"reason,omitempty"`
|
||||
@@ -135,21 +135,21 @@ type ContainerState struct {
|
||||
Waiting *Condition `json:"waiting"`
|
||||
}
|
||||
|
||||
// Resource is API resource
|
||||
// Resource is API resource.
|
||||
type Resource struct {
|
||||
Name string
|
||||
Kind string
|
||||
Value interface{}
|
||||
}
|
||||
|
||||
// ServicePort configures service ports
|
||||
// ServicePort configures service ports.
|
||||
type ServicePort struct {
|
||||
Name string `json:"name,omitempty"`
|
||||
Port int `json:"port"`
|
||||
Protocol string `json:"protocol,omitempty"`
|
||||
}
|
||||
|
||||
// ServiceSpec provides service configuration
|
||||
// ServiceSpec provides service configuration.
|
||||
type ServiceSpec struct {
|
||||
ClusterIP string `json:"clusterIP"`
|
||||
Type string `json:"type,omitempty"`
|
||||
@@ -157,52 +157,52 @@ type ServiceSpec struct {
|
||||
Ports []ServicePort `json:"ports,omitempty"`
|
||||
}
|
||||
|
||||
// ServiceStatus
|
||||
// ServiceStatus.
|
||||
type ServiceStatus struct {
|
||||
LoadBalancer LoadBalancerStatus `json:"loadBalancer,omitempty"`
|
||||
}
|
||||
|
||||
// Service is kubernetes service
|
||||
// Service is kubernetes service.
|
||||
type Service struct {
|
||||
Metadata *Metadata `json:"metadata"`
|
||||
Spec *ServiceSpec `json:"spec,omitempty"`
|
||||
Status *ServiceStatus `json:"status,omitempty"`
|
||||
}
|
||||
|
||||
// ServiceList
|
||||
// ServiceList.
|
||||
type ServiceList struct {
|
||||
Items []Service `json:"items"`
|
||||
}
|
||||
|
||||
// Template is micro deployment template
|
||||
// Template is micro deployment template.
|
||||
type Template struct {
|
||||
Metadata *Metadata `json:"metadata,omitempty"`
|
||||
PodSpec *PodSpec `json:"spec,omitempty"`
|
||||
}
|
||||
|
||||
// Namespace is a Kubernetes Namespace
|
||||
// Namespace is a Kubernetes Namespace.
|
||||
type Namespace struct {
|
||||
Metadata *Metadata `json:"metadata,omitempty"`
|
||||
}
|
||||
|
||||
// NamespaceList
|
||||
// NamespaceList.
|
||||
type NamespaceList struct {
|
||||
Items []Namespace `json:"items"`
|
||||
}
|
||||
|
||||
// ImagePullSecret
|
||||
// ImagePullSecret.
|
||||
type ImagePullSecret struct {
|
||||
Name string `json:"name"`
|
||||
}
|
||||
|
||||
// Secret
|
||||
// Secret.
|
||||
type Secret struct {
|
||||
Type string `json:"type,omitempty"`
|
||||
Data map[string]string `json:"data"`
|
||||
Metadata *Metadata `json:"metadata"`
|
||||
}
|
||||
|
||||
// ServiceAccount
|
||||
// ServiceAccount.
|
||||
type ServiceAccount struct {
|
||||
Metadata *Metadata `json:"metadata,omitempty"`
|
||||
ImagePullSecrets []ImagePullSecret `json:"imagePullSecrets,omitempty"`
|
||||
|
@@ -11,7 +11,7 @@ import (
|
||||
"text/template"
|
||||
)
|
||||
|
||||
// renderTemplateFile renders template for a given resource into writer w
|
||||
// renderTemplateFile renders template for a given resource into writer w.
|
||||
func renderTemplate(resource string, w io.Writer, data interface{}) error {
|
||||
t := template.Must(template.New("kubernetes").Parse(templates[resource]))
|
||||
|
||||
@@ -26,7 +26,7 @@ func renderTemplate(resource string, w io.Writer, data interface{}) error {
|
||||
// https://github.com/kubernetes/kubernetes/blob/7a725418af4661067b56506faabc2d44c6d7703a/pkg/util/crypto/crypto.go
|
||||
|
||||
// CertPoolFromFile returns an x509.CertPool containing the certificates in the given PEM-encoded file.
|
||||
// Returns an error if the file could not be read, a certificate could not be parsed, or if the file does not contain any certificates
|
||||
// Returns an error if the file could not be read, a certificate could not be parsed, or if the file does not contain any certificates.
|
||||
func CertPoolFromFile(filename string) (*x509.CertPool, error) {
|
||||
certs, err := certificatesFromFile(filename)
|
||||
if err != nil {
|
||||
@@ -40,7 +40,7 @@ func CertPoolFromFile(filename string) (*x509.CertPool, error) {
|
||||
}
|
||||
|
||||
// certificatesFromFile returns the x509.Certificates contained in the given PEM-encoded file.
|
||||
// Returns an error if the file could not be read, a certificate could not be parsed, or if the file does not contain any certificates
|
||||
// Returns an error if the file could not be read, a certificate could not be parsed, or if the file does not contain any certificates.
|
||||
func certificatesFromFile(file string) ([]*x509.Certificate, error) {
|
||||
if len(file) == 0 {
|
||||
return nil, errors.New("error reading certificates from an empty filename")
|
||||
@@ -57,7 +57,7 @@ func certificatesFromFile(file string) ([]*x509.Certificate, error) {
|
||||
}
|
||||
|
||||
// CertsFromPEM returns the x509.Certificates contained in the given PEM-encoded byte array
|
||||
// Returns an error if a certificate could not be parsed, or if the data does not contain any certificates
|
||||
// Returns an error if a certificate could not be parsed, or if the data does not contain any certificates.
|
||||
func CertsFromPEM(pemCerts []byte) ([]*x509.Certificate, error) {
|
||||
ok := false
|
||||
certs := []*x509.Certificate{}
|
||||
@@ -87,7 +87,7 @@ func CertsFromPEM(pemCerts []byte) ([]*x509.Certificate, error) {
|
||||
return certs, nil
|
||||
}
|
||||
|
||||
// Format is used to format a string value into a k8s valid name
|
||||
// Format is used to format a string value into a k8s valid name.
|
||||
func Format(v string) string {
|
||||
// to lower case
|
||||
v = strings.ToLower(v)
|
||||
|
@@ -11,14 +11,14 @@ import (
|
||||
)
|
||||
|
||||
const (
|
||||
// EventTypes used
|
||||
// EventTypes used.
|
||||
Added EventType = "ADDED"
|
||||
Modified EventType = "MODIFIED"
|
||||
Deleted EventType = "DELETED"
|
||||
Error EventType = "ERROR"
|
||||
)
|
||||
|
||||
// Watcher is used to watch for events
|
||||
// Watcher is used to watch for events.
|
||||
type Watcher interface {
|
||||
// A channel of events
|
||||
Chan() <-chan Event
|
||||
@@ -35,7 +35,7 @@ type Event struct {
|
||||
Object json.RawMessage `json:"object"`
|
||||
}
|
||||
|
||||
// bodyWatcher scans the body of a request for chunks
|
||||
// bodyWatcher scans the body of a request for chunks.
|
||||
type bodyWatcher struct {
|
||||
results chan Event
|
||||
cancel func()
|
||||
@@ -44,12 +44,12 @@ type bodyWatcher struct {
|
||||
req *api.Request
|
||||
}
|
||||
|
||||
// Changes returns the results channel
|
||||
// Changes returns the results channel.
|
||||
func (wr *bodyWatcher) Chan() <-chan Event {
|
||||
return wr.results
|
||||
}
|
||||
|
||||
// Stop cancels the request
|
||||
// Stop cancels the request.
|
||||
func (wr *bodyWatcher) Stop() {
|
||||
select {
|
||||
case <-wr.stop:
|
||||
@@ -89,7 +89,7 @@ func (wr *bodyWatcher) stream() {
|
||||
}
|
||||
|
||||
// newWatcher creates a k8s body watcher for
|
||||
// a given http request
|
||||
// a given http request.
|
||||
func newWatcher(req *api.Request) (Watcher, error) {
|
||||
// set request context so we can cancel the request
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
|
@@ -1,17 +0,0 @@
|
||||
# Log
|
||||
|
||||
DEPRECATED: use go-micro.dev/v4/logger interface
|
||||
|
||||
This is the global logger for all micro based libraries.
|
||||
|
||||
## Set Logger
|
||||
|
||||
Set the logger for micro libraries
|
||||
|
||||
```go
|
||||
// import go-micro/util/log
|
||||
import "github.com/micro/go-micro/util/log"
|
||||
|
||||
// SetLogger expects github.com/micro/go-micro/debug/log.Log interface
|
||||
log.SetLogger(mylogger)
|
||||
```
|
227
util/log/log.go
227
util/log/log.go
@@ -1,227 +0,0 @@
|
||||
// Package log is a global internal logger
|
||||
// DEPRECATED: this is frozen package, use go-micro.dev/v4/logger
|
||||
package log
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"sync/atomic"
|
||||
|
||||
dlog "go-micro.dev/v4/debug/log"
|
||||
nlog "go-micro.dev/v4/logger"
|
||||
)
|
||||
|
||||
// level is a log level
|
||||
type Level int32
|
||||
|
||||
const (
|
||||
LevelFatal Level = iota
|
||||
LevelError
|
||||
LevelWarn
|
||||
LevelInfo
|
||||
LevelDebug
|
||||
LevelTrace
|
||||
)
|
||||
|
||||
type elog struct {
|
||||
dlog dlog.Log
|
||||
}
|
||||
|
||||
var (
|
||||
// the local logger
|
||||
logger dlog.Log = &elog{}
|
||||
|
||||
// default log level is info
|
||||
level = LevelInfo
|
||||
|
||||
// prefix for all messages
|
||||
prefix string
|
||||
)
|
||||
|
||||
func levelToLevel(l Level) nlog.Level {
|
||||
switch l {
|
||||
case LevelTrace:
|
||||
return nlog.TraceLevel
|
||||
case LevelDebug:
|
||||
return nlog.DebugLevel
|
||||
case LevelWarn:
|
||||
return nlog.WarnLevel
|
||||
case LevelInfo:
|
||||
return nlog.InfoLevel
|
||||
case LevelError:
|
||||
return nlog.ErrorLevel
|
||||
case LevelFatal:
|
||||
return nlog.FatalLevel
|
||||
}
|
||||
return nlog.InfoLevel
|
||||
}
|
||||
|
||||
func init() {
|
||||
switch os.Getenv("MICRO_LOG_LEVEL") {
|
||||
case "trace":
|
||||
level = LevelTrace
|
||||
case "debug":
|
||||
level = LevelDebug
|
||||
case "warn":
|
||||
level = LevelWarn
|
||||
case "info":
|
||||
level = LevelInfo
|
||||
case "error":
|
||||
level = LevelError
|
||||
case "fatal":
|
||||
level = LevelFatal
|
||||
}
|
||||
}
|
||||
|
||||
func (l Level) String() string {
|
||||
switch l {
|
||||
case LevelTrace:
|
||||
return "trace"
|
||||
case LevelDebug:
|
||||
return "debug"
|
||||
case LevelWarn:
|
||||
return "warn"
|
||||
case LevelInfo:
|
||||
return "info"
|
||||
case LevelError:
|
||||
return "error"
|
||||
case LevelFatal:
|
||||
return "fatal"
|
||||
default:
|
||||
return "unknown"
|
||||
}
|
||||
}
|
||||
|
||||
func (el *elog) Read(opt ...dlog.ReadOption) ([]dlog.Record, error) {
|
||||
return el.dlog.Read(opt...)
|
||||
}
|
||||
|
||||
func (el *elog) Write(r dlog.Record) error {
|
||||
return el.dlog.Write(r)
|
||||
}
|
||||
|
||||
func (el *elog) Stream() (dlog.Stream, error) {
|
||||
return el.dlog.Stream()
|
||||
}
|
||||
|
||||
// Log makes use of github.com/micro/debug/log
|
||||
func Log(v ...interface{}) {
|
||||
if len(prefix) > 0 {
|
||||
v = append([]interface{}{prefix, " "}, v...)
|
||||
}
|
||||
nlog.DefaultLogger.Log(levelToLevel(level), v)
|
||||
}
|
||||
|
||||
// Logf makes use of github.com/micro/debug/log
|
||||
func Logf(format string, v ...interface{}) {
|
||||
if len(prefix) > 0 {
|
||||
format = prefix + " " + format
|
||||
}
|
||||
nlog.DefaultLogger.Logf(levelToLevel(level), format, v)
|
||||
}
|
||||
|
||||
// WithLevel logs with the level specified
|
||||
func WithLevel(l Level, v ...interface{}) {
|
||||
if l > level {
|
||||
return
|
||||
}
|
||||
Log(v...)
|
||||
}
|
||||
|
||||
// WithLevel logs with the level specified
|
||||
func WithLevelf(l Level, format string, v ...interface{}) {
|
||||
if l > level {
|
||||
return
|
||||
}
|
||||
Logf(format, v...)
|
||||
}
|
||||
|
||||
// Trace provides trace level logging
|
||||
func Trace(v ...interface{}) {
|
||||
WithLevel(LevelTrace, v...)
|
||||
}
|
||||
|
||||
// Tracef provides trace level logging
|
||||
func Tracef(format string, v ...interface{}) {
|
||||
WithLevelf(LevelTrace, format, v...)
|
||||
}
|
||||
|
||||
// Debug provides debug level logging
|
||||
func Debug(v ...interface{}) {
|
||||
WithLevel(LevelDebug, v...)
|
||||
}
|
||||
|
||||
// Debugf provides debug level logging
|
||||
func Debugf(format string, v ...interface{}) {
|
||||
WithLevelf(LevelDebug, format, v...)
|
||||
}
|
||||
|
||||
// Warn provides warn level logging
|
||||
func Warn(v ...interface{}) {
|
||||
WithLevel(LevelWarn, v...)
|
||||
}
|
||||
|
||||
// Warnf provides warn level logging
|
||||
func Warnf(format string, v ...interface{}) {
|
||||
WithLevelf(LevelWarn, format, v...)
|
||||
}
|
||||
|
||||
// Info provides info level logging
|
||||
func Info(v ...interface{}) {
|
||||
WithLevel(LevelInfo, v...)
|
||||
}
|
||||
|
||||
// Infof provides info level logging
|
||||
func Infof(format string, v ...interface{}) {
|
||||
WithLevelf(LevelInfo, format, v...)
|
||||
}
|
||||
|
||||
// Error provides warn level logging
|
||||
func Error(v ...interface{}) {
|
||||
WithLevel(LevelError, v...)
|
||||
}
|
||||
|
||||
// Errorf provides warn level logging
|
||||
func Errorf(format string, v ...interface{}) {
|
||||
WithLevelf(LevelError, format, v...)
|
||||
}
|
||||
|
||||
// Fatal logs with Log and then exits with os.Exit(1)
|
||||
func Fatal(v ...interface{}) {
|
||||
WithLevel(LevelFatal, v...)
|
||||
}
|
||||
|
||||
// Fatalf logs with Logf and then exits with os.Exit(1)
|
||||
func Fatalf(format string, v ...interface{}) {
|
||||
WithLevelf(LevelFatal, format, v...)
|
||||
}
|
||||
|
||||
// SetLogger sets the local logger
|
||||
func SetLogger(l dlog.Log) {
|
||||
logger = l
|
||||
}
|
||||
|
||||
// GetLogger returns the local logger
|
||||
func GetLogger() dlog.Log {
|
||||
return logger
|
||||
}
|
||||
|
||||
// SetLevel sets the log level
|
||||
func SetLevel(l Level) {
|
||||
atomic.StoreInt32((*int32)(&level), int32(l))
|
||||
}
|
||||
|
||||
// GetLevel returns the current level
|
||||
func GetLevel() Level {
|
||||
return level
|
||||
}
|
||||
|
||||
// Set a prefix for the logger
|
||||
func SetPrefix(p string) {
|
||||
prefix = p
|
||||
}
|
||||
|
||||
// Set service name
|
||||
func Name(name string) {
|
||||
prefix = fmt.Sprintf("[%s]", name)
|
||||
}
|
@@ -15,7 +15,7 @@ import (
|
||||
"go-micro.dev/v4/logger"
|
||||
)
|
||||
|
||||
// ServiceEntry is returned after we query for a service
|
||||
// ServiceEntry is returned after we query for a service.
|
||||
type ServiceEntry struct {
|
||||
Name string
|
||||
Host string
|
||||
@@ -33,13 +33,12 @@ type ServiceEntry struct {
|
||||
sent bool
|
||||
}
|
||||
|
||||
// complete is used to check if we have all the info we need
|
||||
// complete is used to check if we have all the info we need.
|
||||
func (s *ServiceEntry) complete() bool {
|
||||
|
||||
return (len(s.AddrV4) > 0 || len(s.AddrV6) > 0 || len(s.Addr) > 0) && s.Port != 0 && s.hasTXT
|
||||
}
|
||||
|
||||
// QueryParam is used to customize how a Lookup is performed
|
||||
// QueryParam is used to customize how a Lookup is performed.
|
||||
type QueryParam struct {
|
||||
Service string // Service to lookup
|
||||
Domain string // Lookup domain, default "local"
|
||||
@@ -51,7 +50,7 @@ type QueryParam struct {
|
||||
WantUnicastResponse bool // Unicast response desired, as per 5.4 in RFC
|
||||
}
|
||||
|
||||
// DefaultParams is used to return a default set of QueryParam's
|
||||
// DefaultParams is used to return a default set of QueryParam's.
|
||||
func DefaultParams(service string) *QueryParam {
|
||||
return &QueryParam{
|
||||
Service: service,
|
||||
@@ -100,7 +99,7 @@ func Query(params *QueryParam) error {
|
||||
return client.query(params)
|
||||
}
|
||||
|
||||
// Listen listens indefinitely for multicast updates
|
||||
// Listen listens indefinitely for multicast updates.
|
||||
func Listen(entries chan<- *ServiceEntry, exit chan struct{}) error {
|
||||
// Create a new client
|
||||
client, err := newClient()
|
||||
@@ -156,7 +155,7 @@ func Listen(entries chan<- *ServiceEntry, exit chan struct{}) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// Lookup is the same as Query, however it uses all the default parameters
|
||||
// Lookup is the same as Query, however it uses all the default parameters.
|
||||
func Lookup(service string, entries chan<- *ServiceEntry) error {
|
||||
params := DefaultParams(service)
|
||||
params.Entries = entries
|
||||
@@ -164,7 +163,7 @@ func Lookup(service string, entries chan<- *ServiceEntry) error {
|
||||
}
|
||||
|
||||
// Client provides a query interface that can be used to
|
||||
// search for service providers using mDNS
|
||||
// search for service providers using mDNS.
|
||||
type client struct {
|
||||
ipv4UnicastConn *net.UDPConn
|
||||
ipv6UnicastConn *net.UDPConn
|
||||
@@ -178,7 +177,7 @@ type client struct {
|
||||
}
|
||||
|
||||
// NewClient creates a new mdns Client that can be used to query
|
||||
// for records
|
||||
// for records.
|
||||
func newClient() (*client, error) {
|
||||
// TODO(reddaly): At least attempt to bind to the port required in the spec.
|
||||
// Create a IPv4 listener
|
||||
@@ -253,7 +252,7 @@ func newClient() (*client, error) {
|
||||
return c, nil
|
||||
}
|
||||
|
||||
// Close is used to cleanup the client
|
||||
// Close is used to cleanup the client.
|
||||
func (c *client) Close() error {
|
||||
c.closeLock.Lock()
|
||||
defer c.closeLock.Unlock()
|
||||
@@ -281,8 +280,8 @@ func (c *client) Close() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// setInterface is used to set the query interface, uses sytem
|
||||
// default if not provided
|
||||
// setInterface is used to set the query interface, uses system
|
||||
// default if not provided.
|
||||
func (c *client) setInterface(iface *net.Interface, loopback bool) error {
|
||||
p := ipv4.NewPacketConn(c.ipv4UnicastConn)
|
||||
if err := p.JoinGroup(iface, &net.UDPAddr{IP: mdnsGroupIPv4}); err != nil {
|
||||
@@ -309,7 +308,7 @@ func (c *client) setInterface(iface *net.Interface, loopback bool) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// query is used to perform a lookup and stream results
|
||||
// query is used to perform a lookup and stream results.
|
||||
func (c *client) query(params *QueryParam) error {
|
||||
// Create the service name
|
||||
serviceAddr := fmt.Sprintf("%s.%s.", trimDot(params.Service), trimDot(params.Domain))
|
||||
@@ -385,7 +384,7 @@ func (c *client) query(params *QueryParam) error {
|
||||
}
|
||||
}
|
||||
|
||||
// sendQuery is used to multicast a query out
|
||||
// sendQuery is used to multicast a query out.
|
||||
func (c *client) sendQuery(q *dns.Msg) error {
|
||||
buf, err := q.Pack()
|
||||
if err != nil {
|
||||
@@ -400,7 +399,7 @@ func (c *client) sendQuery(q *dns.Msg) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// recv is used to receive until we get a shutdown
|
||||
// recv is used to receive until we get a shutdown.
|
||||
func (c *client) recv(l *net.UDPConn, msgCh chan *dns.Msg) {
|
||||
if l == nil {
|
||||
return
|
||||
@@ -429,7 +428,7 @@ func (c *client) recv(l *net.UDPConn, msgCh chan *dns.Msg) {
|
||||
}
|
||||
}
|
||||
|
||||
// ensureName is used to ensure the named node is in progress
|
||||
// ensureName is used to ensure the named node is in progress.
|
||||
func ensureName(inprogress map[string]*ServiceEntry, name string, typ uint16) *ServiceEntry {
|
||||
if inp, ok := inprogress[name]; ok {
|
||||
return inp
|
||||
@@ -442,7 +441,7 @@ func ensureName(inprogress map[string]*ServiceEntry, name string, typ uint16) *S
|
||||
return inp
|
||||
}
|
||||
|
||||
// alias is used to setup an alias between two entries
|
||||
// alias is used to setup an alias between two entries.
|
||||
func alias(inprogress map[string]*ServiceEntry, src, dst string, typ uint16) {
|
||||
srcEntry := ensureName(inprogress, src, typ)
|
||||
inprogress[dst] = srcEntry
|
||||
|
@@ -46,7 +46,7 @@ func (s *DNSSDService) Records(q dns.Question) []dns.RR {
|
||||
// issued to browse for DNS-SD services, as per section 9. of RFC6763.
|
||||
//
|
||||
// A meta-query has a name of the form "_services._dns-sd._udp.<Domain>" where
|
||||
// Domain is a fully-qualified domain, such as "local."
|
||||
// Domain is a fully-qualified domain, such as "local.".
|
||||
func (s *DNSSDService) dnssdMetaQueryRecords(q dns.Question) []dns.RR {
|
||||
// Intended behavior, as described in the RFC:
|
||||
// ...it may be useful for network administrators to find the list of
|
||||
@@ -80,6 +80,6 @@ func (s *DNSSDService) dnssdMetaQueryRecords(q dns.Question) []dns.RR {
|
||||
// Announcement returns DNS records that should be broadcast during the initial
|
||||
// availability of the service, as described in section 8.3 of RFC 6762.
|
||||
// TODO(reddaly): Add this when Announcement is added to the mdns.Zone interface.
|
||||
//func (s *DNSSDService) Announcement() []dns.RR {
|
||||
// func (s *DNSSDService) Announcement() []dns.RR {
|
||||
// return s.MDNSService.Announcement()
|
||||
//}
|
||||
|
@@ -3,8 +3,9 @@ package mdns
|
||||
import (
|
||||
"reflect"
|
||||
"testing"
|
||||
|
||||
"github.com/miekg/dns"
|
||||
)
|
||||
import "github.com/miekg/dns"
|
||||
|
||||
type mockMDNSService struct{}
|
||||
|
||||
|
@@ -18,7 +18,7 @@ var (
|
||||
mdnsGroupIPv4 = net.ParseIP("224.0.0.251")
|
||||
mdnsGroupIPv6 = net.ParseIP("ff02::fb")
|
||||
|
||||
// mDNS wildcard addresses
|
||||
// mDNS wildcard addresses.
|
||||
mdnsWildcardAddrIPv4 = &net.UDPAddr{
|
||||
IP: net.ParseIP("224.0.0.0"),
|
||||
Port: 5353,
|
||||
@@ -28,7 +28,7 @@ var (
|
||||
Port: 5353,
|
||||
}
|
||||
|
||||
// mDNS endpoint addresses
|
||||
// mDNS endpoint addresses.
|
||||
ipv4Addr = &net.UDPAddr{
|
||||
IP: mdnsGroupIPv4,
|
||||
Port: 5353,
|
||||
@@ -40,10 +40,10 @@ var (
|
||||
)
|
||||
|
||||
// GetMachineIP is a func which returns the outbound IP of this machine.
|
||||
// Used by the server to determine whether to attempt send the response on a local address
|
||||
// Used by the server to determine whether to attempt send the response on a local address.
|
||||
type GetMachineIP func() net.IP
|
||||
|
||||
// Config is used to configure the mDNS server
|
||||
// Config is used to configure the mDNS server.
|
||||
type Config struct {
|
||||
// Zone must be provided to support responding to queries
|
||||
Zone Zone
|
||||
@@ -64,7 +64,7 @@ type Config struct {
|
||||
}
|
||||
|
||||
// Server is an mDNS server used to listen for mDNS queries and respond if we
|
||||
// have a matching local record
|
||||
// have a matching local record.
|
||||
type Server struct {
|
||||
config *Config
|
||||
|
||||
@@ -79,7 +79,7 @@ type Server struct {
|
||||
outboundIP net.IP
|
||||
}
|
||||
|
||||
// NewServer is used to create a new mDNS server from a config
|
||||
// NewServer is used to create a new mDNS server from a config.
|
||||
func NewServer(config *Config) (*Server, error) {
|
||||
setCustomPort(config.Port)
|
||||
|
||||
@@ -152,7 +152,7 @@ func NewServer(config *Config) (*Server, error) {
|
||||
return s, nil
|
||||
}
|
||||
|
||||
// Shutdown is used to shutdown the listener
|
||||
// Shutdown is used to shutdown the listener.
|
||||
func (s *Server) Shutdown() error {
|
||||
s.shutdownLock.Lock()
|
||||
defer s.shutdownLock.Unlock()
|
||||
@@ -176,7 +176,7 @@ func (s *Server) Shutdown() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// recv is a long running routine to receive packets from an interface
|
||||
// recv is a long running routine to receive packets from an interface.
|
||||
func (s *Server) recv(c *net.UDPConn) {
|
||||
if c == nil {
|
||||
return
|
||||
@@ -199,7 +199,7 @@ func (s *Server) recv(c *net.UDPConn) {
|
||||
}
|
||||
}
|
||||
|
||||
// parsePacket is used to parse an incoming packet
|
||||
// parsePacket is used to parse an incoming packet.
|
||||
func (s *Server) parsePacket(packet []byte, from net.Addr) error {
|
||||
var msg dns.Msg
|
||||
if err := msg.Unpack(packet); err != nil {
|
||||
@@ -213,7 +213,7 @@ func (s *Server) parsePacket(packet []byte, from net.Addr) error {
|
||||
return s.handleQuery(&msg, from)
|
||||
}
|
||||
|
||||
// handleQuery is used to handle an incoming query
|
||||
// handleQuery is used to handle an incoming query.
|
||||
func (s *Server) handleQuery(query *dns.Msg, from net.Addr) error {
|
||||
if query.Opcode != dns.OpcodeQuery {
|
||||
// "In both multicast query and multicast response messages, the OPCODE MUST
|
||||
@@ -421,7 +421,7 @@ func (s *Server) probe() {
|
||||
}
|
||||
}
|
||||
|
||||
// SendMulticast us used to send a multicast response packet
|
||||
// SendMulticast us used to send a multicast response packet.
|
||||
func (s *Server) SendMulticast(msg *dns.Msg) error {
|
||||
buf, err := msg.Pack()
|
||||
if err != nil {
|
||||
@@ -436,7 +436,7 @@ func (s *Server) SendMulticast(msg *dns.Msg) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// sendResponse is used to send a response packet
|
||||
// sendResponse is used to send a response packet.
|
||||
func (s *Server) sendResponse(resp *dns.Msg, from net.Addr) error {
|
||||
// TODO(reddaly): Respect the unicast argument, and allow sending responses
|
||||
// over multicast.
|
||||
@@ -463,7 +463,6 @@ func (s *Server) sendResponse(resp *dns.Msg, from net.Addr) error {
|
||||
conn.WriteToUDP(buf, &net.UDPAddr{IP: backupTarget, Port: addr.Port})
|
||||
}
|
||||
return err
|
||||
|
||||
}
|
||||
|
||||
func (s *Server) unregister() error {
|
||||
@@ -502,7 +501,6 @@ func setCustomPort(port int) {
|
||||
}
|
||||
}
|
||||
|
||||
// getOutboundIP returns the IP address of this machine as seen when dialling out
|
||||
func getOutboundIP() net.IP {
|
||||
conn, err := net.Dial("udp", "8.8.8.8:80")
|
||||
if err != nil {
|
||||
|
@@ -16,13 +16,13 @@ const (
|
||||
)
|
||||
|
||||
// Zone is the interface used to integrate with the server and
|
||||
// to serve records dynamically
|
||||
// to serve records dynamically.
|
||||
type Zone interface {
|
||||
// Records returns DNS records in response to a DNS question.
|
||||
Records(q dns.Question) []dns.RR
|
||||
}
|
||||
|
||||
// MDNSService is used to export a named service by implementing a Zone
|
||||
// MDNSService is used to export a named service by implementing a Zone.
|
||||
type MDNSService struct {
|
||||
Instance string // Instance name (e.g. "hostService name")
|
||||
Service string // Service name (e.g. "_http._tcp.")
|
||||
@@ -130,7 +130,7 @@ func NewMDNSService(instance, service, domain, hostName string, port int, ips []
|
||||
}, nil
|
||||
}
|
||||
|
||||
// trimDot is used to trim the dots from the start or end of a string
|
||||
// trimDot is used to trim the dots from the start or end of a string.
|
||||
func trimDot(s string) string {
|
||||
return strings.Trim(s, ".")
|
||||
}
|
||||
@@ -174,7 +174,7 @@ func (m *MDNSService) serviceEnum(q dns.Question) []dns.RR {
|
||||
}
|
||||
}
|
||||
|
||||
// serviceRecords is called when the query matches the service name
|
||||
// serviceRecords is called when the query matches the service name.
|
||||
func (m *MDNSService) serviceRecords(q dns.Question) []dns.RR {
|
||||
switch q.Qtype {
|
||||
case dns.TypeANY:
|
||||
@@ -205,7 +205,7 @@ func (m *MDNSService) serviceRecords(q dns.Question) []dns.RR {
|
||||
}
|
||||
}
|
||||
|
||||
// serviceRecords is called when the query matches the instance name
|
||||
// serviceRecords is called when the query matches the instance name.
|
||||
func (m *MDNSService) instanceRecords(q dns.Question) []dns.RR {
|
||||
switch q.Qtype {
|
||||
case dns.TypeANY:
|
||||
|
@@ -9,7 +9,7 @@ import (
|
||||
"strings"
|
||||
)
|
||||
|
||||
// HostPort format addr and port suitable for dial
|
||||
// HostPort format addr and port suitable for dial.
|
||||
func HostPort(addr string, port interface{}) string {
|
||||
host := addr
|
||||
if strings.Count(addr, ":") > 0 {
|
||||
@@ -26,9 +26,8 @@ func HostPort(addr string, port interface{}) string {
|
||||
}
|
||||
|
||||
// Listen takes addr:portmin-portmax and binds to the first available port
|
||||
// Example: Listen("localhost:5000-6000", fn)
|
||||
// Example: Listen("localhost:5000-6000", fn).
|
||||
func Listen(addr string, fn func(string) (net.Listener, error)) (net.Listener, error) {
|
||||
|
||||
if strings.Count(addr, ":") == 1 && strings.Count(addr, "-") == 0 {
|
||||
return fn(addr)
|
||||
}
|
||||
@@ -79,7 +78,7 @@ func Listen(addr string, fn func(string) (net.Listener, error)) (net.Listener, e
|
||||
return nil, fmt.Errorf("unable to bind to %s", addr)
|
||||
}
|
||||
|
||||
// Proxy returns the proxy and the address if it exits
|
||||
// Proxy returns the proxy and the address if it exits.
|
||||
func Proxy(service string, address []string) (string, []string, bool) {
|
||||
var hasProxy bool
|
||||
|
||||
|
@@ -23,10 +23,9 @@ func TestListen(t *testing.T) {
|
||||
// TODO nats case test
|
||||
// natsAddr := "_INBOX.bID2CMRvlNp0vt4tgNBHWf"
|
||||
// Expect addr DO NOT has extra ":" at the end!
|
||||
|
||||
}
|
||||
|
||||
// TestProxyEnv checks whether we have proxy/network settings in env
|
||||
// TestProxyEnv checks whether we have proxy/network settings in env.
|
||||
func TestProxyEnv(t *testing.T) {
|
||||
service := "foo"
|
||||
address := []string{"bar"}
|
||||
|
@@ -9,7 +9,7 @@ import (
|
||||
"time"
|
||||
)
|
||||
|
||||
// CertOptions are passed to cert options
|
||||
// CertOptions are passed to cert options.
|
||||
type CertOptions struct {
|
||||
IsCA bool
|
||||
Subject pkix.Name
|
||||
@@ -24,38 +24,38 @@ type CertOptions struct {
|
||||
Priv ed25519.PrivateKey
|
||||
}
|
||||
|
||||
// CertOption sets CertOptions
|
||||
// CertOption sets CertOptions.
|
||||
type CertOption func(c *CertOptions)
|
||||
|
||||
// Subject sets the Subject field
|
||||
// Subject sets the Subject field.
|
||||
func Subject(subject pkix.Name) CertOption {
|
||||
return func(c *CertOptions) {
|
||||
c.Subject = subject
|
||||
}
|
||||
}
|
||||
|
||||
// IsCA states the cert is a CA
|
||||
// IsCA states the cert is a CA.
|
||||
func IsCA() CertOption {
|
||||
return func(c *CertOptions) {
|
||||
c.IsCA = true
|
||||
}
|
||||
}
|
||||
|
||||
// DNSNames is a list of hosts to sign in to the certificate
|
||||
// DNSNames is a list of hosts to sign in to the certificate.
|
||||
func DNSNames(names ...string) CertOption {
|
||||
return func(c *CertOptions) {
|
||||
c.DNSNames = names
|
||||
}
|
||||
}
|
||||
|
||||
// IPAddresses is a list of IPs to sign in to the certificate
|
||||
// IPAddresses is a list of IPs to sign in to the certificate.
|
||||
func IPAddresses(ips ...net.IP) CertOption {
|
||||
return func(c *CertOptions) {
|
||||
c.IPAddresses = ips
|
||||
}
|
||||
}
|
||||
|
||||
// KeyPair is the key pair to sign the certificate with
|
||||
// KeyPair is the key pair to sign the certificate with.
|
||||
func KeyPair(pub ed25519.PublicKey, priv ed25519.PrivateKey) CertOption {
|
||||
return func(c *CertOptions) {
|
||||
c.Pub = pub
|
||||
@@ -63,21 +63,21 @@ func KeyPair(pub ed25519.PublicKey, priv ed25519.PrivateKey) CertOption {
|
||||
}
|
||||
}
|
||||
|
||||
// SerialNumber is the Certificate Serial number
|
||||
// SerialNumber is the Certificate Serial number.
|
||||
func SerialNumber(serial *big.Int) CertOption {
|
||||
return func(c *CertOptions) {
|
||||
c.SerialNumber = serial
|
||||
}
|
||||
}
|
||||
|
||||
// NotBefore is the time the certificate is not valid before
|
||||
// NotBefore is the time the certificate is not valid before.
|
||||
func NotBefore(time time.Time) CertOption {
|
||||
return func(c *CertOptions) {
|
||||
c.NotBefore = time
|
||||
}
|
||||
}
|
||||
|
||||
// NotAfter is the time the certificate is not valid after
|
||||
// NotAfter is the time the certificate is not valid after.
|
||||
func NotAfter(time time.Time) CertOption {
|
||||
return func(c *CertOptions) {
|
||||
c.NotAfter = time
|
||||
|
@@ -12,12 +12,12 @@ import (
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
|
||||
// GenerateKey returns an ed25519 key
|
||||
// GenerateKey returns an ed25519 key.
|
||||
func GenerateKey() (ed25519.PublicKey, ed25519.PrivateKey, error) {
|
||||
return ed25519.GenerateKey(rand.Reader)
|
||||
}
|
||||
|
||||
// CA generates a self signed CA and returns cert, key in PEM format
|
||||
// CA generates a self signed CA and returns cert, key in PEM format.
|
||||
func CA(opts ...CertOption) ([]byte, []byte, error) {
|
||||
opts = append(opts, IsCA())
|
||||
options := CertOptions{}
|
||||
@@ -59,7 +59,7 @@ func CA(opts ...CertOption) ([]byte, []byte, error) {
|
||||
return cert.Bytes(), key.Bytes(), nil
|
||||
}
|
||||
|
||||
// CSR generates a certificate request in PEM format
|
||||
// CSR generates a certificate request in PEM format.
|
||||
func CSR(opts ...CertOption) ([]byte, error) {
|
||||
options := CertOptions{}
|
||||
for _, o := range opts {
|
||||
@@ -83,7 +83,7 @@ func CSR(opts ...CertOption) ([]byte, error) {
|
||||
return out.Bytes(), nil
|
||||
}
|
||||
|
||||
// Sign decodes a CSR and signs it with the CA
|
||||
// Sign decodes a CSR and signs it with the CA.
|
||||
func Sign(CACrt, CAKey, CSR []byte, opts ...CertOption) ([]byte, error) {
|
||||
options := CertOptions{}
|
||||
for _, o := range opts {
|
||||
|
@@ -44,7 +44,7 @@ func (p *pool) Close() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// NoOp the Close since we manage it
|
||||
// NoOp the Close since we manage it.
|
||||
func (p *poolConn) Close() error {
|
||||
return nil
|
||||
}
|
||||
|
@@ -7,7 +7,7 @@ import (
|
||||
"go-micro.dev/v4/transport"
|
||||
)
|
||||
|
||||
// Pool is an interface for connection pooling
|
||||
// Pool is an interface for connection pooling.
|
||||
type Pool interface {
|
||||
// Close the pool
|
||||
Close() error
|
||||
|
@@ -138,7 +138,7 @@ func queryToMap(param string) (map[string]interface{}, error) {
|
||||
// buildNewKey will take something like:
|
||||
// origKey = "bar[one][two]"
|
||||
// pieces = [bar one two ]
|
||||
// and return "one[two]"
|
||||
// and return "one[two]".
|
||||
func buildNewKey(origKey string) string {
|
||||
pieces := bracketSplitter.Split(origKey, -1)
|
||||
ret := origKey[len(pieces[0])+1:]
|
||||
|
@@ -52,7 +52,7 @@ func delNodes(old, del []*registry.Node) []*registry.Node {
|
||||
return nodes
|
||||
}
|
||||
|
||||
// CopyService make a copy of service
|
||||
// CopyService make a copy of service.
|
||||
func CopyService(service *registry.Service) *registry.Service {
|
||||
// copy service
|
||||
s := new(registry.Service)
|
||||
@@ -78,7 +78,7 @@ func CopyService(service *registry.Service) *registry.Service {
|
||||
return s
|
||||
}
|
||||
|
||||
// Copy makes a copy of services
|
||||
// Copy makes a copy of services.
|
||||
func Copy(current []*registry.Service) []*registry.Service {
|
||||
services := make([]*registry.Service, len(current))
|
||||
for i, service := range current {
|
||||
@@ -87,7 +87,7 @@ func Copy(current []*registry.Service) []*registry.Service {
|
||||
return services
|
||||
}
|
||||
|
||||
// Merge merges two lists of services and returns a new copy
|
||||
// Merge merges two lists of services and returns a new copy.
|
||||
func Merge(olist []*registry.Service, nlist []*registry.Service) []*registry.Service {
|
||||
var srv []*registry.Service
|
||||
|
||||
@@ -119,7 +119,7 @@ func Merge(olist []*registry.Service, nlist []*registry.Service) []*registry.Ser
|
||||
return srv
|
||||
}
|
||||
|
||||
// Remove removes services and returns a new copy
|
||||
// Remove removes services and returns a new copy.
|
||||
func Remove(old, del []*registry.Service) []*registry.Service {
|
||||
var services []*registry.Service
|
||||
|
||||
|
@@ -8,7 +8,7 @@ import (
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
// Buffer is ring buffer
|
||||
// Buffer is ring buffer.
|
||||
type Buffer struct {
|
||||
size int
|
||||
|
||||
@@ -17,13 +17,13 @@ type Buffer struct {
|
||||
streams map[string]*Stream
|
||||
}
|
||||
|
||||
// Entry is ring buffer data entry
|
||||
// Entry is ring buffer data entry.
|
||||
type Entry struct {
|
||||
Value interface{}
|
||||
Timestamp time.Time
|
||||
}
|
||||
|
||||
// Stream is used to stream the buffer
|
||||
// Stream is used to stream the buffer.
|
||||
type Stream struct {
|
||||
// Id of the stream
|
||||
Id string
|
||||
@@ -33,7 +33,7 @@ type Stream struct {
|
||||
Stop chan bool
|
||||
}
|
||||
|
||||
// Put adds a new value to ring buffer
|
||||
// Put adds a new value to ring buffer.
|
||||
func (b *Buffer) Put(v interface{}) {
|
||||
b.Lock()
|
||||
defer b.Unlock()
|
||||
@@ -61,7 +61,7 @@ func (b *Buffer) Put(v interface{}) {
|
||||
}
|
||||
}
|
||||
|
||||
// Get returns the last n entries
|
||||
// Get returns the last n entries.
|
||||
func (b *Buffer) Get(n int) []*Entry {
|
||||
b.RLock()
|
||||
defer b.RUnlock()
|
||||
@@ -78,7 +78,7 @@ func (b *Buffer) Get(n int) []*Entry {
|
||||
return b.vals[delta:]
|
||||
}
|
||||
|
||||
// Return the entries since a specific time
|
||||
// Return the entries since a specific time.
|
||||
func (b *Buffer) Since(t time.Time) []*Entry {
|
||||
b.RLock()
|
||||
defer b.RUnlock()
|
||||
@@ -107,7 +107,7 @@ func (b *Buffer) Since(t time.Time) []*Entry {
|
||||
}
|
||||
|
||||
// Stream logs from the buffer
|
||||
// Close the channel when you want to stop
|
||||
// Close the channel when you want to stop.
|
||||
func (b *Buffer) Stream() (<-chan *Entry, chan bool) {
|
||||
b.Lock()
|
||||
defer b.Unlock()
|
||||
@@ -125,12 +125,12 @@ func (b *Buffer) Stream() (<-chan *Entry, chan bool) {
|
||||
return entries, stop
|
||||
}
|
||||
|
||||
// Size returns the size of the ring buffer
|
||||
// Size returns the size of the ring buffer.
|
||||
func (b *Buffer) Size() int {
|
||||
return b.size
|
||||
}
|
||||
|
||||
// New returns a new buffer of the given size
|
||||
// New returns a new buffer of the given size.
|
||||
func New(i int) *Buffer {
|
||||
return &Buffer{
|
||||
size: i,
|
||||
|
@@ -5,7 +5,7 @@ import (
|
||||
"syscall"
|
||||
)
|
||||
|
||||
// ShutDownSingals returns all the singals that are being watched for to shut down services.
|
||||
// ShutDownSingals returns all the signals that are being watched for to shut down services.
|
||||
func Shutdown() []os.Signal {
|
||||
return []os.Signal{
|
||||
syscall.SIGTERM, syscall.SIGINT, syscall.SIGQUIT, syscall.SIGKILL,
|
||||
|
@@ -44,7 +44,7 @@ func (p *Pool) Release(s *Socket) {
|
||||
delete(p.pool, s.id)
|
||||
}
|
||||
|
||||
// Close the pool and delete all the sockets
|
||||
// Close the pool and delete all the sockets.
|
||||
func (p *Pool) Close() {
|
||||
p.Lock()
|
||||
defer p.Unlock()
|
||||
@@ -54,7 +54,7 @@ func (p *Pool) Close() {
|
||||
}
|
||||
}
|
||||
|
||||
// NewPool returns a new socket pool
|
||||
// NewPool returns a new socket pool.
|
||||
func NewPool() *Pool {
|
||||
return &Pool{
|
||||
pool: make(map[string]*Socket),
|
||||
|
@@ -7,7 +7,7 @@ import (
|
||||
"go-micro.dev/v4/transport"
|
||||
)
|
||||
|
||||
// Socket is our pseudo socket for transport.Socket
|
||||
// Socket is our pseudo socket for transport.Socket.
|
||||
type Socket struct {
|
||||
id string
|
||||
// closed
|
||||
@@ -30,7 +30,7 @@ func (s *Socket) SetRemote(r string) {
|
||||
s.remote = r
|
||||
}
|
||||
|
||||
// Accept passes a message to the socket which will be processed by the call to Recv
|
||||
// Accept passes a message to the socket which will be processed by the call to Recv.
|
||||
func (s *Socket) Accept(m *transport.Message) error {
|
||||
select {
|
||||
case s.recv <- m:
|
||||
@@ -40,7 +40,7 @@ func (s *Socket) Accept(m *transport.Message) error {
|
||||
}
|
||||
}
|
||||
|
||||
// Process takes the next message off the send queue created by a call to Send
|
||||
// Process takes the next message off the send queue created by a call to Send.
|
||||
func (s *Socket) Process(m *transport.Message) error {
|
||||
select {
|
||||
case msg := <-s.send:
|
||||
@@ -91,7 +91,7 @@ func (s *Socket) Recv(m *transport.Message) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// Close closes the socket
|
||||
// Close closes the socket.
|
||||
func (s *Socket) Close() error {
|
||||
select {
|
||||
case <-s.closed:
|
||||
|
@@ -75,7 +75,7 @@ func (s *stream) Error() error {
|
||||
}
|
||||
|
||||
// New returns a new encapsulated stream
|
||||
// Proto stream within a server.Stream
|
||||
// Proto stream within a server.Stream.
|
||||
func New(service, endpoint string, req interface{}, s Stream) server.Stream {
|
||||
return &stream{
|
||||
Stream: s,
|
||||
|
@@ -15,7 +15,7 @@ type operation struct {
|
||||
maxiumum int
|
||||
}
|
||||
|
||||
// action represents the type of a queued operation
|
||||
// action represents the type of a queued operation.
|
||||
type action int
|
||||
|
||||
const (
|
||||
|
@@ -6,7 +6,7 @@ import (
|
||||
"go-micro.dev/v4/store"
|
||||
)
|
||||
|
||||
// Options represents Sync options
|
||||
// Options represents Sync options.
|
||||
type Options struct {
|
||||
// Stores represents layers in the sync in ascending order. L0, L1, L2, etc
|
||||
Stores []store.Store
|
||||
@@ -16,10 +16,10 @@ type Options struct {
|
||||
SyncMultiplier int64
|
||||
}
|
||||
|
||||
// Option sets Sync Options
|
||||
// Option sets Sync Options.
|
||||
type Option func(o *Options)
|
||||
|
||||
// Stores sets the layers that make up the sync
|
||||
// Stores sets the layers that make up the sync.
|
||||
func Stores(stores ...store.Store) Option {
|
||||
return func(o *Options) {
|
||||
o.Stores = make([]store.Store, len(stores))
|
||||
@@ -29,14 +29,14 @@ func Stores(stores ...store.Store) Option {
|
||||
}
|
||||
}
|
||||
|
||||
// SyncInterval sets the duration between syncs from L0 to L1
|
||||
// SyncInterval sets the duration between syncs from L0 to L1.
|
||||
func SyncInterval(d time.Duration) Option {
|
||||
return func(o *Options) {
|
||||
o.SyncInterval = d
|
||||
}
|
||||
}
|
||||
|
||||
// SyncMultiplier sets the multiplication factor for time to wait each sync layer
|
||||
// SyncMultiplier sets the multiplication factor for time to wait each sync layer.
|
||||
func SyncMultiplier(i int64) Option {
|
||||
return func(o *Options) {
|
||||
o.SyncMultiplier = i
|
||||
|
@@ -11,7 +11,7 @@ import (
|
||||
"go-micro.dev/v4/store"
|
||||
)
|
||||
|
||||
// Sync implements a sync in for stores
|
||||
// Sync implements a sync in for stores.
|
||||
type Sync interface {
|
||||
// Implements the store interface
|
||||
store.Store
|
||||
@@ -27,7 +27,7 @@ type syncStore struct {
|
||||
sync.RWMutex
|
||||
}
|
||||
|
||||
// NewSync returns a new Sync
|
||||
// NewSync returns a new Sync.
|
||||
func NewSync(opts ...Option) Sync {
|
||||
c := &syncStore{}
|
||||
for _, o := range opts {
|
||||
@@ -46,7 +46,6 @@ func (c *syncStore) Close() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// Init initialises the storeOptions
|
||||
func (c *syncStore) Init(opts ...store.Option) error {
|
||||
for _, o := range opts {
|
||||
o(&c.storeOpts)
|
||||
@@ -55,7 +54,7 @@ func (c *syncStore) Init(opts ...store.Option) error {
|
||||
return errors.New("the sync has no stores")
|
||||
}
|
||||
if c.storeOpts.Context == nil {
|
||||
return errors.New("please provide a context to the sync. Cancelling the context signals that the sync is being disposed and syncs the sync")
|
||||
return errors.New("please provide a context to the sync. Canceling the context signals that the sync is being disposed and syncs the sync")
|
||||
}
|
||||
for _, s := range c.syncOpts.Stores {
|
||||
if err := s.Init(); err != nil {
|
||||
@@ -73,12 +72,12 @@ func (c *syncStore) Init(opts ...store.Option) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// Options returns the sync's store options
|
||||
// Options returns the sync's store options.
|
||||
func (c *syncStore) Options() store.Options {
|
||||
return c.storeOpts
|
||||
}
|
||||
|
||||
// String returns a printable string describing the sync
|
||||
// String returns a printable string describing the sync.
|
||||
func (c *syncStore) String() string {
|
||||
backends := make([]string, len(c.syncOpts.Stores))
|
||||
for i, s := range c.syncOpts.Stores {
|
||||
@@ -99,7 +98,7 @@ func (c *syncStore) Write(r *store.Record, opts ...store.WriteOption) error {
|
||||
return c.syncOpts.Stores[0].Write(r, opts...)
|
||||
}
|
||||
|
||||
// Delete removes a key from the sync
|
||||
// Delete removes a key from the sync.
|
||||
func (c *syncStore) Delete(key string, opts ...store.DeleteOption) error {
|
||||
return c.syncOpts.Stores[0].Delete(key, opts...)
|
||||
}
|
||||
|
@@ -5,7 +5,7 @@ import (
|
||||
)
|
||||
|
||||
var (
|
||||
// mock registry data
|
||||
// mock registry data.
|
||||
Data = map[string][]*registry.Service{
|
||||
"foo": {
|
||||
{
|
||||
|
@@ -43,7 +43,7 @@ func (f *fromServiceWrapper) Publish(ctx context.Context, p client.Message, opts
|
||||
return f.Client.Publish(ctx, p, opts...)
|
||||
}
|
||||
|
||||
// FromService wraps a client to inject service and auth metadata
|
||||
// FromService wraps a client to inject service and auth metadata.
|
||||
func FromService(name string, c client.Client) client.Client {
|
||||
return &fromServiceWrapper{
|
||||
c,
|
||||
@@ -53,7 +53,7 @@ func FromService(name string, c client.Client) client.Client {
|
||||
}
|
||||
}
|
||||
|
||||
// HandlerStats wraps a server handler to generate request/error stats
|
||||
// HandlerStats wraps a server handler to generate request/error stats.
|
||||
func HandlerStats(stats stats.Stats) server.HandlerWrapper {
|
||||
// return a handler wrapper
|
||||
return func(h server.HandlerFunc) server.HandlerFunc {
|
||||
@@ -91,7 +91,7 @@ func (c *traceWrapper) Call(ctx context.Context, req client.Request, rsp interfa
|
||||
return err
|
||||
}
|
||||
|
||||
// TraceCall is a call tracing wrapper
|
||||
// TraceCall is a call tracing wrapper.
|
||||
func TraceCall(name string, t trace.Tracer, c client.Client) client.Client {
|
||||
return &traceWrapper{
|
||||
name: name,
|
||||
@@ -100,7 +100,7 @@ func TraceCall(name string, t trace.Tracer, c client.Client) client.Client {
|
||||
}
|
||||
}
|
||||
|
||||
// TraceHandler wraps a server handler to perform tracing
|
||||
// TraceHandler wraps a server handler to perform tracing.
|
||||
func TraceHandler(t trace.Tracer) server.HandlerWrapper {
|
||||
// return a handler wrapper
|
||||
return func(h server.HandlerFunc) server.HandlerFunc {
|
||||
|
Reference in New Issue
Block a user