repository_name
stringlengths
7
107
function_path
stringlengths
4
190
function_identifier
stringlengths
1
236
language
stringclasses
1 value
function
stringlengths
9
647k
docstring
stringlengths
5
488k
function_url
stringlengths
71
285
context
stringlengths
0
2.51M
license
stringclasses
5 values
liyue201/gostl
utils/comparator/comparator.go
UintptrComparator
go
func UintptrComparator(a, b interface{}) int { if a == b { return 0 } if a.(uintptr) < b.(uintptr) { return -1 } return 1 }
UintptrComparator compare a with b -1 , if a < b 0 , if a == b 1 , if a > b
https://github.com/liyue201/gostl/blob/85462939908bc38b2ba8a45855906e6ae4f91a82/utils/comparator/comparator.go#L315-L323
package comparator type Comparator func(a, b interface{}) int func BuiltinTypeComparator(a, b interface{}) int { if a == b { return 0 } switch a.(type) { case int, uint, int8, uint8, int16, uint16, int32, uint32, int64, uint64, uintptr: return cmpInt(a, b) case float32: if a.(float32) < b.(float32) { return -1 } case float64: if a.(float64) < b.(float64) { return -1 } case bool: if a.(bool) == false && b.(bool) == true { return -1 } case string: if a.(string) < b.(string) { return -1 } case complex64: return cmpComplex64(a.(complex64), b.(complex64)) case complex128: return cmpComplex128(a.(complex128), b.(complex128)) } return 1 } func cmpInt(a, b interface{}) int { switch a.(type) { case int: return cmpInt64(int64(a.(int)), int64(b.(int))) case uint: return cmpUint64(uint64(a.(uint)), uint64(b.(uint))) case int8: return cmpInt64(int64(a.(int8)), int64(b.(int8))) case uint8: return cmpUint64(uint64(a.(uint8)), uint64(b.(uint8))) case int16: return cmpInt64(int64(a.(int16)), int64(b.(int16))) case uint16: return cmpUint64(uint64(a.(uint16)), uint64(b.(uint16))) case int32: return cmpInt64(int64(a.(int32)), int64(b.(int32))) case uint32: return cmpUint64(uint64(a.(uint32)), uint64(b.(uint32))) case int64: return cmpInt64(a.(int64), b.(int64)) case uint64: return cmpUint64(a.(uint64), b.(uint64)) case uintptr: return cmpUint64(uint64(a.(uintptr)), uint64(b.(uintptr))) } return 0 } func cmpInt64(a, b int64) int { if a < b { return -1 } return 1 } func cmpUint64(a, b uint64) int { if a < b { return -1 } return 1 } func cmpFloat32(a, b float32) int { if a < b { return -1 } return 1 } func cmpFloat64(a, b float64) int { if a < b { return -1 } return 1 } func cmpComplex64(a, b complex64) int { if real(a) < real(b) { return -1 } if real(a) == real(b) && imag(a) < imag(b) { return -1 } return 1 } func cmpComplex128(a, b complex128) int { if real(a) < real(b) { return -1 } if real(a) == real(b) && imag(a) < imag(b) { return -1 } return 1 } func Reverse(cmp Comparator) Comparator { return func(a, b interface{}) int { return -cmp(a, b) } } func IntComparator(a, b interface{}) int { if a == b { return 0 } if a.(int) < b.(int) { return -1 } return 1 } func UintComparator(a, b interface{}) int { if a == b { return 0 } if a.(uint) < b.(uint) { return -1 } return 1 } func Int8Comparator(a, b interface{}) int { if a == b { return 0 } if a.(int8) < b.(int8) { return -1 } return 1 } func Uint8Comparator(a, b interface{}) int { if a == b { return 0 } if a.(uint8) < b.(uint8) { return -1 } return 1 } func Int16Comparator(a, b interface{}) int { if a == b { return 0 } if a.(int16) < b.(int16) { return -1 } return 1 } func Uint16Comparator(a, b interface{}) int { if a == b { return 0 } if a.(uint16) < b.(uint16) { return -1 } return 1 } func Int32Comparator(a, b interface{}) int { if a == b { return 0 } if a.(int32) < b.(int32) { return -1 } return 1 } func Uint32Comparator(a, b interface{}) int { if a == b { return 0 } if a.(uint32) < b.(uint32) { return -1 } return 1 } func Int64Comparator(a, b interface{}) int { if a == b { return 0 } if a.(int64) < b.(int64) { return -1 } return 1 } func Uint64Comparator(a, b interface{}) int { if a == b { return 0 } if a.(uint64) < b.(uint64) { return -1 } return 1 } func Float32Comparator(a, b interface{}) int { if a == b { return 0 } if a.(float32) < b.(float32) { return -1 } return 1 } func Float64Comparator(a, b interface{}) int { if a == b { return 0 } if a.(float64) < b.(float64) { return -1 } return 1 } func StringComparator(a, b interface{}) int { if a == b { return 0 } if a.(string) < b.(string) { return -1 } return 1 }
MIT License
abice/go-enum
example/user_template_enum.go
ParseOceanColor
go
func ParseOceanColor(name string) (OceanColor, error) { if x, ok := _OceanColorValue[name]; ok { return x, nil } return OceanColor(0), fmt.Errorf("%s is not a valid OceanColor", name) }
ParseOceanColor attempts to convert a string to a OceanColor
https://github.com/abice/go-enum/blob/6e988a2d0ac87c0fb4971d020a904527bb4960ee/example/user_template_enum.go#L45-L50
package example import ( "fmt" ) const ( OceanColorCerulean OceanColor = iota OceanColorBlue OceanColorGreen ) const _OceanColorName = "CeruleanBlueGreen" var _OceanColorMap = map[OceanColor]string{ 0: _OceanColorName[0:8], 1: _OceanColorName[8:12], 2: _OceanColorName[12:17], } func (x OceanColor) String() string { if str, ok := _OceanColorMap[x]; ok { return str } return fmt.Sprintf("OceanColor(%d)", x) } var _OceanColorValue = map[string]OceanColor{ _OceanColorName[0:8]: 0, _OceanColorName[8:12]: 1, _OceanColorName[12:17]: 2, }
MIT License
plaid/plaid-go
plaid/model_product_status.go
SetStatus
go
func (o *ProductStatus) SetStatus(v string) { o.Status = v }
SetStatus sets field value
https://github.com/plaid/plaid-go/blob/c2a20f380d37eecba36138b04e14f540b59cc22a/plaid/model_product_status.go#L70-L72
package plaid import ( "encoding/json" "time" ) type ProductStatus struct { Status string `json:"status"` LastStatusChange time.Time `json:"last_status_change"` Breakdown ProductStatusBreakdown `json:"breakdown"` AdditionalProperties map[string]interface{} } type _ProductStatus ProductStatus func NewProductStatus(status string, lastStatusChange time.Time, breakdown ProductStatusBreakdown) *ProductStatus { this := ProductStatus{} this.Status = status this.LastStatusChange = lastStatusChange this.Breakdown = breakdown return &this } func NewProductStatusWithDefaults() *ProductStatus { this := ProductStatus{} return &this } func (o *ProductStatus) GetStatus() string { if o == nil { var ret string return ret } return o.Status } func (o *ProductStatus) GetStatusOk() (*string, bool) { if o == nil { return nil, false } return &o.Status, true }
MIT License
automationbroker/apb
vendor/github.com/automationbroker/broker-client-go/client/clientset/versioned/typed/automationbroker/v1alpha1/bundlebinding.go
Create
go
func (c *bundleBindings) Create(bundleBinding *v1alpha1.BundleBinding) (result *v1alpha1.BundleBinding, err error) { result = &v1alpha1.BundleBinding{} err = c.client.Post(). Namespace(c.ns). Resource("bundlebindings"). Body(bundleBinding). Do(). Into(result) return }
Create takes the representation of a bundleBinding and creates it. Returns the server's representation of the bundleBinding, and an error, if there is any.
https://github.com/automationbroker/apb/blob/77a4cd4036d7713c137ab931537933d226547cdf/vendor/github.com/automationbroker/broker-client-go/client/clientset/versioned/typed/automationbroker/v1alpha1/bundlebinding.go#L96-L105
package v1alpha1 import ( scheme "github.com/automationbroker/broker-client-go/client/clientset/versioned/scheme" v1alpha1 "github.com/automationbroker/broker-client-go/pkg/apis/automationbroker/v1alpha1" v1 "k8s.io/apimachinery/pkg/apis/meta/v1" types "k8s.io/apimachinery/pkg/types" watch "k8s.io/apimachinery/pkg/watch" rest "k8s.io/client-go/rest" ) type BundleBindingsGetter interface { BundleBindings(namespace string) BundleBindingInterface } type BundleBindingInterface interface { Create(*v1alpha1.BundleBinding) (*v1alpha1.BundleBinding, error) Update(*v1alpha1.BundleBinding) (*v1alpha1.BundleBinding, error) Delete(name string, options *v1.DeleteOptions) error DeleteCollection(options *v1.DeleteOptions, listOptions v1.ListOptions) error Get(name string, options v1.GetOptions) (*v1alpha1.BundleBinding, error) List(opts v1.ListOptions) (*v1alpha1.BundleBindingList, error) Watch(opts v1.ListOptions) (watch.Interface, error) Patch(name string, pt types.PatchType, data []byte, subresources ...string) (result *v1alpha1.BundleBinding, err error) BundleBindingExpansion } type bundleBindings struct { client rest.Interface ns string } func newBundleBindings(c *AutomationbrokerV1alpha1Client, namespace string) *bundleBindings { return &bundleBindings{ client: c.RESTClient(), ns: namespace, } } func (c *bundleBindings) Get(name string, options v1.GetOptions) (result *v1alpha1.BundleBinding, err error) { result = &v1alpha1.BundleBinding{} err = c.client.Get(). Namespace(c.ns). Resource("bundlebindings"). Name(name). VersionedParams(&options, scheme.ParameterCodec). Do(). Into(result) return } func (c *bundleBindings) List(opts v1.ListOptions) (result *v1alpha1.BundleBindingList, err error) { result = &v1alpha1.BundleBindingList{} err = c.client.Get(). Namespace(c.ns). Resource("bundlebindings"). VersionedParams(&opts, scheme.ParameterCodec). Do(). Into(result) return } func (c *bundleBindings) Watch(opts v1.ListOptions) (watch.Interface, error) { opts.Watch = true return c.client.Get(). Namespace(c.ns). Resource("bundlebindings"). VersionedParams(&opts, scheme.ParameterCodec). Watch() }
Apache License 2.0
go-acme/lego
providers/dns/acmedns/acmedns.go
register
go
func (d *DNSProvider) register(domain, fqdn string) error { newAcct, err := d.client.RegisterAccount(nil) if err != nil { return err } err = d.storage.Put(domain, newAcct) if err != nil { return err } err = d.storage.Save() if err != nil { return err } return ErrCNAMERequired{ Domain: domain, FQDN: fqdn, Target: newAcct.FullDomain, } }
register creates a new ACME-DNS account for the given domain. If account creation works as expected a ErrCNAMERequired error is returned describing the one-time manual CNAME setup required to complete setup of the ACME-DNS hook for the domain. If any other error occurs it is returned as-is.
https://github.com/go-acme/lego/blob/60ae6e6dc935977d0e9d7b7d965e14384c973c18/providers/dns/acmedns/acmedns.go#L137-L162
package acmedns import ( "errors" "fmt" "github.com/cpu/goacmedns" "github.com/go-acme/lego/v4/challenge/dns01" "github.com/go-acme/lego/v4/platform/config/env" ) const ( envNamespace = "ACME_DNS_" EnvAPIBase = envNamespace + "API_BASE" EnvStoragePath = envNamespace + "STORAGE_PATH" ) type acmeDNSClient interface { UpdateTXTRecord(goacmedns.Account, string) error RegisterAccount([]string) (goacmedns.Account, error) } type DNSProvider struct { client acmeDNSClient storage goacmedns.Storage } func NewDNSProvider() (*DNSProvider, error) { values, err := env.Get(EnvAPIBase, EnvStoragePath) if err != nil { return nil, fmt.Errorf("acme-dns: %w", err) } client := goacmedns.NewClient(values[EnvAPIBase]) storage := goacmedns.NewFileStorage(values[EnvStoragePath], 0o600) return NewDNSProviderClient(client, storage) } func NewDNSProviderClient(client acmeDNSClient, storage goacmedns.Storage) (*DNSProvider, error) { if client == nil { return nil, errors.New("ACME-DNS Client must be not nil") } if storage == nil { return nil, errors.New("ACME-DNS Storage must be not nil") } return &DNSProvider{ client: client, storage: storage, }, nil } type ErrCNAMERequired struct { Domain string FQDN string Target string } func (e ErrCNAMERequired) Error() string { return fmt.Sprintf("acme-dns: new account created for %q. "+ "To complete setup for %q you must provision the following "+ "CNAME in your DNS zone and re-run this provider when it is "+ "in place:\n"+ "%s CNAME %s.", e.Domain, e.Domain, e.FQDN, e.Target) } func (d *DNSProvider) Present(domain, _, keyAuth string) error { fqdn, value := dns01.GetRecord(domain, keyAuth) account, err := d.storage.Fetch(domain) if err != nil && !errors.Is(err, goacmedns.ErrDomainNotFound) { return err } if errors.Is(err, goacmedns.ErrDomainNotFound) { return d.register(domain, fqdn) } return d.client.UpdateTXTRecord(account, value) } func (d *DNSProvider) CleanUp(_, _, _ string) error { return nil }
MIT License
uber/makisu
lib/utils/httputil/httputil.go
IsConflict
go
func IsConflict(err error) bool { return IsStatus(err, http.StatusConflict) }
IsConflict returns true if err is a "status conflict" StatusError.
https://github.com/uber/makisu/blob/5fdc8f4b92160be8c2bb69827779439eedaed81e/lib/utils/httputil/httputil.go#L92-L94
package httputil import ( "context" "crypto/tls" "errors" "fmt" "io" "io/ioutil" "net/http" "net/url" "time" "github.com/cenkalti/backoff" "github.com/uber/makisu/lib/log" ) var retryableCodes = map[int]struct{}{ http.StatusTooManyRequests: {}, http.StatusBadGateway: {}, http.StatusServiceUnavailable: {}, http.StatusGatewayTimeout: {}, } type StatusError struct { Method string URL string Status int Header http.Header ResponseDump string } func NewStatusError(resp *http.Response) StatusError { defer resp.Body.Close() respBytes, err := ioutil.ReadAll(resp.Body) respDump := string(respBytes) if err != nil { respDump = fmt.Sprintf("failed to dump response: %s", err) } return StatusError{ Method: resp.Request.Method, URL: resp.Request.URL.String(), Status: resp.StatusCode, Header: resp.Header, ResponseDump: respDump, } } func (e StatusError) Error() string { if e.ResponseDump == "" { return fmt.Sprintf("%s %s %d", e.Method, e.URL, e.Status) } return fmt.Sprintf("%s %s %d: %s", e.Method, e.URL, e.Status, e.ResponseDump) } func IsStatus(err error, status int) bool { var e StatusError if errors.As(err, &e) { return e.Status == status } return false } func IsCreated(err error) bool { return IsStatus(err, http.StatusCreated) } func IsNotFound(err error) bool { return IsStatus(err, http.StatusNotFound) }
Apache License 2.0
acomagu/bufpipe
bufpipe.go
Write
go
func (w *PipeWriter) Write(data []byte) (int, error) { w.cond.L.Lock() defer w.cond.L.Unlock() if w.werr != nil { return 0, w.werr } n, err := w.buf.Write(data) w.cond.Signal() return n, err }
Write implements the standard Write interface: it writes data to the internal buffer. If the read end is closed with an error, that err is returned as err; otherwise err is ErrClosedPipe.
https://github.com/acomagu/bufpipe/blob/cd7a5f79d3c413d14c0c60fd31dae7b397fc955a/bufpipe.go#L98-L109
package bufpipe import ( "bytes" "errors" "io" "sync" ) var ErrClosedPipe = errors.New("bufpipe: read/write on closed pipe") type pipe struct { cond *sync.Cond buf *bytes.Buffer rerr, werr error } type PipeReader struct { *pipe } type PipeWriter struct { *pipe } func New(buf []byte) (*PipeReader, *PipeWriter) { p := &pipe{ buf: bytes.NewBuffer(buf), cond: sync.NewCond(new(sync.Mutex)), } return &PipeReader{ pipe: p, }, &PipeWriter{ pipe: p, } } func (r *PipeReader) Read(data []byte) (int, error) { r.cond.L.Lock() defer r.cond.L.Unlock() RETRY: n, err := r.buf.Read(data) if err == io.EOF && r.rerr == nil && n == 0 { r.cond.Wait() goto RETRY } if err == io.EOF { return n, r.rerr } return n, err } func (r *PipeReader) Close() error { return r.CloseWithError(nil) } func (r *PipeReader) CloseWithError(err error) error { r.cond.L.Lock() defer r.cond.L.Unlock() if err == nil { err = ErrClosedPipe } r.werr = err return nil }
MIT License
jmhodges/howsmyssl
vendor/golang.org/x/crypto/chacha20poly1305/chacha20poly1305.go
sliceForAppend
go
func sliceForAppend(in []byte, n int) (head, tail []byte) { if total := len(in) + n; cap(in) >= total { head = in[:total] } else { head = make([]byte, total) copy(head, in) } tail = head[len(in):] return }
sliceForAppend takes a slice and a requested number of bytes. It returns a slice with the contents of the given slice followed by that many bytes and a second slice that aliases into it and contains only the extra bytes. If the original slice has sufficient capacity then no allocation is performed.
https://github.com/jmhodges/howsmyssl/blob/b72af40d21cbb12b85932ef1bc18e50459f39263/vendor/golang.org/x/crypto/chacha20poly1305/chacha20poly1305.go#L85-L94
package chacha20poly1305 import ( "crypto/cipher" "errors" ) const ( KeySize = 32 NonceSize = 12 NonceSizeX = 24 ) type chacha20poly1305 struct { key [KeySize]byte } func New(key []byte) (cipher.AEAD, error) { if len(key) != KeySize { return nil, errors.New("chacha20poly1305: bad key length") } ret := new(chacha20poly1305) copy(ret.key[:], key) return ret, nil } func (c *chacha20poly1305) NonceSize() int { return NonceSize } func (c *chacha20poly1305) Overhead() int { return 16 } func (c *chacha20poly1305) Seal(dst, nonce, plaintext, additionalData []byte) []byte { if len(nonce) != NonceSize { panic("chacha20poly1305: bad nonce length passed to Seal") } if uint64(len(plaintext)) > (1<<38)-64 { panic("chacha20poly1305: plaintext too large") } return c.seal(dst, nonce, plaintext, additionalData) } var errOpen = errors.New("chacha20poly1305: message authentication failed") func (c *chacha20poly1305) Open(dst, nonce, ciphertext, additionalData []byte) ([]byte, error) { if len(nonce) != NonceSize { panic("chacha20poly1305: bad nonce length passed to Open") } if len(ciphertext) < 16 { return nil, errOpen } if uint64(len(ciphertext)) > (1<<38)-48 { panic("chacha20poly1305: ciphertext too large") } return c.open(dst, nonce, ciphertext, additionalData) }
MIT License
konveyor/move2kube
environment/local.go
GetSource
go
func (e *Local) GetSource() string { return e.WorkspaceSource }
GetSource returns the source of Local
https://github.com/konveyor/move2kube/blob/70982af31410f4c2e729e2083ccfbcd03329600c/environment/local.go#L175-L177
package environment import ( "bytes" "errors" "fmt" "io/ioutil" "net" "os" "os/exec" "path/filepath" "github.com/konveyor/move2kube/filesystem" "github.com/konveyor/move2kube/types" environmenttypes "github.com/konveyor/move2kube/types/environment" "github.com/sirupsen/logrus" ) type Local struct { EnvInfo WorkspaceSource string WorkspaceContext string GRPCQAReceiver net.Addr } func NewLocal(envInfo EnvInfo, grpcQAReceiver net.Addr) (ei EnvironmentInstance, err error) { local := &Local{ EnvInfo: envInfo, GRPCQAReceiver: grpcQAReceiver, } local.WorkspaceContext, err = ioutil.TempDir(local.TempPath, types.AppNameShort) if err != nil { logrus.Errorf("Unable to create temp dir : %s", err) return local, err } local.WorkspaceSource, err = ioutil.TempDir(local.TempPath, workspaceDir) if err != nil { logrus.Errorf("Unable to create temp dir : %s", err) } local.Reset() return local, nil } func (e *Local) Reset() error { if err := filesystem.Replicate(e.Context, e.WorkspaceContext); err != nil { logrus.Errorf("Unable to copy contents to directory %s, %s : %s", e.Context, e.WorkspaceContext, err) return err } if err := filesystem.Replicate(e.Source, e.WorkspaceSource); err != nil { logrus.Errorf("Unable to copy contents to directory %s, %s : %s", e.Source, e.WorkspaceSource, err) return err } return nil } func (e *Local) Exec(cmd environmenttypes.Command) (stdout string, stderr string, exitcode int, err error) { var outb, errb bytes.Buffer var execcmd *exec.Cmd if len(cmd) > 0 { execcmd = exec.Command(cmd[0], cmd[1:]...) } else { err := fmt.Errorf("no command found to execute") logrus.Errorf("%s", err) return "", "", 0, err } execcmd.Dir = e.WorkspaceContext execcmd.Stdout = &outb execcmd.Stderr = &errb execcmd.Env = e.getEnv() err = execcmd.Run() if err != nil { var ee *exec.ExitError var pe *os.PathError if errors.As(err, &ee) { exitcode = ee.ExitCode() err = nil } else if errors.As(err, &pe) { logrus.Errorf("PathError during execution of command: %v", pe) err = pe } else { logrus.Errorf("Generic error during execution of command: %v", err) } } return outb.String(), errb.String(), exitcode, err } func (e *Local) Destroy() error { err := os.RemoveAll(e.WorkspaceSource) if err != nil { logrus.Errorf("Unable to remove directory %s : %s", e.WorkspaceSource, err) } err = os.RemoveAll(e.WorkspaceContext) if err != nil { logrus.Errorf("Unable to remove directory %s : %s", e.WorkspaceContext, err) } return nil } func (e *Local) Download(path string) (string, error) { output, err := ioutil.TempDir(e.TempPath, "*") if err != nil { logrus.Errorf("Unable to create temp dir : %s", err) return path, err } ps, err := os.Stat(path) if err != nil { logrus.Errorf("Unable to stat source : %s", path) return "", err } if ps.Mode().IsRegular() { output = filepath.Join(output, filepath.Base(path)) } err = filesystem.Replicate(path, output) if err != nil { logrus.Errorf("Unable to replicate in syncoutput : %s", err) return path, err } return output, nil } func (e *Local) Upload(outpath string) (envpath string, err error) { envpath, err = ioutil.TempDir(e.TempPath, "*") if err != nil { logrus.Errorf("Unable to create temp dir : %s", err) return outpath, err } ps, err := os.Stat(outpath) if err != nil { logrus.Errorf("Unable to stat source : %s", outpath) return "", err } if ps.Mode().IsRegular() { envpath = filepath.Join(envpath, filepath.Base(outpath)) } err = filesystem.Replicate(outpath, envpath) if err != nil { logrus.Errorf("Unable to replicate in syncoutput : %s", err) return outpath, err } return envpath, nil } func (e *Local) GetContext() string { return e.WorkspaceContext }
Apache License 2.0
kubernetes-csi/csi-lib-utils
vendor/google.golang.org/protobuf/types/known/wrapperspb/wrappers.pb.go
Descriptor
go
func (*Int64Value) Descriptor() ([]byte, []int) { return file_google_protobuf_wrappers_proto_rawDescGZIP(), []int{2} }
Deprecated: Use Int64Value.ProtoReflect.Descriptor instead.
https://github.com/kubernetes-csi/csi-lib-utils/blob/a2ccb594bb74b61a0655d3431c6365a6a567c7af/vendor/google.golang.org/protobuf/types/known/wrapperspb/wrappers.pb.go#L210-L212
package wrapperspb import ( protoreflect "google.golang.org/protobuf/reflect/protoreflect" protoimpl "google.golang.org/protobuf/runtime/protoimpl" reflect "reflect" sync "sync" ) type DoubleValue struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields Value float64 `protobuf:"fixed64,1,opt,name=value,proto3" json:"value,omitempty"` } func Double(v float64) *DoubleValue { return &DoubleValue{Value: v} } func (x *DoubleValue) Reset() { *x = DoubleValue{} if protoimpl.UnsafeEnabled { mi := &file_google_protobuf_wrappers_proto_msgTypes[0] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *DoubleValue) String() string { return protoimpl.X.MessageStringOf(x) } func (*DoubleValue) ProtoMessage() {} func (x *DoubleValue) ProtoReflect() protoreflect.Message { mi := &file_google_protobuf_wrappers_proto_msgTypes[0] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } func (*DoubleValue) Descriptor() ([]byte, []int) { return file_google_protobuf_wrappers_proto_rawDescGZIP(), []int{0} } func (x *DoubleValue) GetValue() float64 { if x != nil { return x.Value } return 0 } type FloatValue struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields Value float32 `protobuf:"fixed32,1,opt,name=value,proto3" json:"value,omitempty"` } func Float(v float32) *FloatValue { return &FloatValue{Value: v} } func (x *FloatValue) Reset() { *x = FloatValue{} if protoimpl.UnsafeEnabled { mi := &file_google_protobuf_wrappers_proto_msgTypes[1] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *FloatValue) String() string { return protoimpl.X.MessageStringOf(x) } func (*FloatValue) ProtoMessage() {} func (x *FloatValue) ProtoReflect() protoreflect.Message { mi := &file_google_protobuf_wrappers_proto_msgTypes[1] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } func (*FloatValue) Descriptor() ([]byte, []int) { return file_google_protobuf_wrappers_proto_rawDescGZIP(), []int{1} } func (x *FloatValue) GetValue() float32 { if x != nil { return x.Value } return 0 } type Int64Value struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields Value int64 `protobuf:"varint,1,opt,name=value,proto3" json:"value,omitempty"` } func Int64(v int64) *Int64Value { return &Int64Value{Value: v} } func (x *Int64Value) Reset() { *x = Int64Value{} if protoimpl.UnsafeEnabled { mi := &file_google_protobuf_wrappers_proto_msgTypes[2] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *Int64Value) String() string { return protoimpl.X.MessageStringOf(x) } func (*Int64Value) ProtoMessage() {} func (x *Int64Value) ProtoReflect() protoreflect.Message { mi := &file_google_protobuf_wrappers_proto_msgTypes[2] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) }
Apache License 2.0
csweichel/werft
pkg/werft/service.go
GetJob
go
func (srv *Service) GetJob(ctx context.Context, req *v1.GetJobRequest) (resp *v1.GetJobResponse, err error) { job, err := srv.Jobs.Get(ctx, req.Name) if err != nil { return nil, status.Error(codes.Internal, err.Error()) } if job == nil { return nil, status.Error(codes.NotFound, "not found") } return &v1.GetJobResponse{ Result: job, }, nil }
GetJob returns the information about a particular job
https://github.com/csweichel/werft/blob/ae1062a47b6bde2b5b98d29e76dcef696eeab5b2/pkg/werft/service.go#L472-L484
package werft import ( "bytes" "context" "fmt" "io" "io/ioutil" "os" "path/filepath" "strings" "sync" "time" termtohtml "github.com/buildkite/terminal-to-html" "github.com/csweichel/werft/pkg/api/repoconfig" v1 "github.com/csweichel/werft/pkg/api/v1" "github.com/csweichel/werft/pkg/filterexpr" "github.com/csweichel/werft/pkg/logcutter" "github.com/csweichel/werft/pkg/store" "github.com/gogo/protobuf/proto" "github.com/golang/protobuf/ptypes" log "github.com/sirupsen/logrus" "github.com/technosophos/moniker" "golang.org/x/xerrors" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" "gopkg.in/yaml.v3" ) func (srv *Service) StartLocalJob(inc v1.WerftService_StartLocalJobServer) error { req, err := inc.Recv() if err != nil { return err } if req.GetMetadata() == nil { return status.Error(codes.InvalidArgument, "first request must contain metadata") } md := *req.GetMetadata() log.WithField("name", md).Debug("StartLocalJob - received metadata") dfs, err := ioutil.TempFile(os.TempDir(), "werft-lcp") if err != nil { return err } defer dfs.Close() defer os.Remove(dfs.Name()) var ( configYAML []byte jobYAML []byte phase int ) const ( phaseConfigYaml = 0 phaseJobYaml = 1 phaseWorkspaceTar = 2 ) for { req, err = inc.Recv() if err != nil { return err } if req.GetConfigYaml() != nil { if phase != phaseConfigYaml { return status.Error(codes.InvalidArgument, "expected config yaml") } configYAML = append(configYAML, req.GetConfigYaml()...) continue } if req.GetJobYaml() != nil { if phase == phaseConfigYaml { phase = phaseJobYaml } if phase != phaseJobYaml { return status.Error(codes.InvalidArgument, "expected job yaml") } jobYAML = append(jobYAML, req.GetJobYaml()...) continue } if req.GetWorkspaceTar() != nil { if phase == phaseJobYaml { phase = phaseWorkspaceTar } if phase != phaseWorkspaceTar { return status.Error(codes.InvalidArgument, "expected workspace tar") } data := req.GetWorkspaceTar() n, err := dfs.Write(data) if err != nil { return status.Error(codes.Internal, err.Error()) } if n != len(data) { return status.Error(codes.Internal, io.ErrShortWrite.Error()) } } if req.GetWorkspaceTarDone() { if phase != phaseWorkspaceTar { return status.Error(codes.InvalidArgument, "expected prior workspace tar") } break } } _, err = dfs.Seek(0, 0) if len(configYAML) == 0 && len(jobYAML) == 0 { return status.Error(codes.InvalidArgument, "either config or job YAML must not be empty") } cp := &LocalContentProvider{ TarStream: dfs, Namespace: srv.Executor.Config.Namespace, Kubeconfig: srv.Executor.KubeConfig, Clientset: srv.Executor.Client, } flatOwner := strings.ReplaceAll(strings.ToLower(md.Owner), " ", "") name := cleanupPodName(fmt.Sprintf("local-%s-%s", flatOwner, moniker.New().NameSep("-"))) jobStatus, err := srv.RunJob(inc.Context(), name, md, cp, jobYAML, false, time.Time{}) if err != nil { return status.Error(codes.Internal, err.Error()) } log.WithField("status", jobStatus).Info(("started new local job")) return inc.SendAndClose(&v1.StartJobResponse{ Status: jobStatus, }) } func (srv *Service) StartGitHubJob(ctx context.Context, req *v1.StartGitHubJobRequest) (resp *v1.StartJobResponse, err error) { if req.GithubToken != "" { return nil, status.Errorf(codes.InvalidArgument, "Per-job GitHub tokens are no longer supported") } if req.Metadata.Repository.Host == "" { req.Metadata.Repository.Host = "github.com" } return srv.StartJob(ctx, &v1.StartJobRequest{ JobPath: req.JobPath, JobYaml: req.JobYaml, Metadata: req.Metadata, Sideload: req.Sideload, WaitUntil: req.WaitUntil, NameSuffix: req.NameSuffix, }) } func (srv *Service) StartJob(ctx context.Context, req *v1.StartJobRequest) (resp *v1.StartJobResponse, err error) { log.WithField("req", proto.MarshalTextString(req)).Info("StartJob request") md := req.Metadata err = srv.RepositoryProvider.Resolve(ctx, md.Repository) if err != nil { return nil, status.Errorf(codes.Internal, "cannot resolve request: %q", err) } atns, err := srv.RepositoryProvider.RemoteAnnotations(ctx, md.Repository) if err != nil { return nil, err } for k, v := range atns { md.Annotations = append(md.Annotations, &v1.Annotation{ Key: k, Value: v, }) } var cp ContentProvider cp, err = srv.RepositoryProvider.ContentProvider(ctx, md.Repository) if err != nil { return nil, status.Errorf(codes.Internal, "cannot produce content provider: %q", err) } if len(req.Sideload) > 0 { cp = &SideloadingContentProvider{ Delegate: cp, TarStream: bytes.NewReader(req.Sideload), Namespace: srv.Executor.Config.Namespace, Kubeconfig: srv.Executor.KubeConfig, Clientset: srv.Executor.Client, } } var fp FileProvider fp, err = srv.RepositoryProvider.FileProvider(ctx, md.Repository) if err != nil { return nil, status.Errorf(codes.Internal, "cannot produce file provider: %q", err) } var ( jobYAML = req.JobYaml tplpath = req.JobPath jobSpecName = "custom" ) if jobYAML == nil { if tplpath == "" { repoCfg, err := getRepoCfg(ctx, fp) if err != nil { return nil, status.Error(codes.Internal, err.Error()) } tplpath = repoCfg.TemplatePath(req.Metadata) } if tplpath == "" { return nil, status.Errorf(codes.NotFound, "no jobspec found in repo config") } in, err := fp.Download(ctx, tplpath) if err != nil { return nil, status.Errorf(codes.Internal, "cannot download jobspec from %s: %s", tplpath, err.Error()) } jobYAML, err = ioutil.ReadAll(in) in.Close() if err != nil { return nil, status.Errorf(codes.Internal, "cannot download jobspec from %s: %s", tplpath, err.Error()) } } if tplpath != "" { jobSpecName = strings.TrimSpace(strings.TrimSuffix(filepath.Base(tplpath), filepath.Ext(tplpath))) } md.JobSpecName = jobSpecName refname := md.Repository.Ref refname = strings.TrimPrefix(refname, "refs/heads/") refname = strings.TrimPrefix(refname, "refs/tags/") refname = strings.ReplaceAll(refname, "/", "-") refname = strings.ReplaceAll(refname, "_", "-") refname = strings.ReplaceAll(refname, "@", "-") refname = strings.ToLower(refname) if refname == "" { refname = moniker.New().NameSep("-") } name := cleanupPodName(fmt.Sprintf("%s-%s-%s", md.Repository.Repo, jobSpecName, refname)) if req.NameSuffix != "" { if len(req.NameSuffix) > 20 { return nil, status.Error(codes.InvalidArgument, "name suffix must be less than 20 characters") } name += "-" + req.NameSuffix } if refname != "" { t, err := srv.Groups.Next(name) if err != nil { return nil, status.Error(codes.Internal, err.Error()) } name = fmt.Sprintf("%s.%d", name, t) } canReplay := len(req.Sideload) == 0 var waitUntil time.Time if req.WaitUntil != nil { waitUntil, err = ptypes.Timestamp(req.WaitUntil) if err != nil { return nil, status.Errorf(codes.InvalidArgument, "waitUntil is invalid: %v", err) } if !canReplay { return nil, status.Error(codes.InvalidArgument, "cannot delay the execution of non-replayable jobs (i.e. jobs with custom GitHub token or sideload)") } } jobStatus, err := srv.RunJob(ctx, name, *md, cp, jobYAML, canReplay, waitUntil) if err != nil { return nil, status.Error(codes.Internal, err.Error()) } log.WithField("status", jobStatus).Info(("started new GitHub job")) return &v1.StartJobResponse{ Status: jobStatus, }, nil } func getRepoCfg(ctx context.Context, fp FileProvider) (*repoconfig.C, error) { werftYAML, err := fp.Download(ctx, PathWerftConfig) if err != nil { return nil, xerrors.Errorf("cannot get repo config: %w", err) } var repoCfg repoconfig.C err = yaml.NewDecoder(werftYAML).Decode(&repoCfg) if err != nil { return nil, xerrors.Errorf("cannot unmarshal repo config: %w", err) } return &repoCfg, nil } func cleanupPodName(name string) string { name = strings.TrimSpace(name) if len(name) == 0 { name = "unknown" } if len(name) > 58 { name = name[:58] } segs := strings.Split(name, ".") for i, n := range segs { s := strings.ToLower(n)[0] if !(('a' <= s && s <= 'z') || ('0' <= s && s <= '9')) { n = "a" + n[1:] } e := strings.ToLower(n)[len(n)-1] if !(('a' <= e && e <= 'z') || ('0' <= e && e <= '9')) { n = n[:len(n)-1] + "a" } segs[i] = n } name = strings.Join(segs, ".") return name } func (srv *Service) StartFromPreviousJob(ctx context.Context, req *v1.StartFromPreviousJobRequest) (*v1.StartJobResponse, error) { oldJobStatus, err := srv.Jobs.Get(ctx, req.PreviousJob) if err == store.ErrNotFound { return nil, status.Error(codes.NotFound, "job spec not found") } if err != nil { return nil, status.Error(codes.Internal, err.Error()) } jobYAML, err := srv.Jobs.GetJobSpec(req.PreviousJob) if err == store.ErrNotFound { return nil, status.Error(codes.NotFound, "job spec not found") } if err != nil { return nil, status.Error(codes.Internal, err.Error()) } name := req.PreviousJob if strings.Contains(name, ".") { segs := strings.Split(name, ".") name = strings.Join(segs[0:len(segs)-1], ".") } nr, err := srv.Groups.Next(name) if err != nil { return nil, status.Error(codes.Internal, err.Error()) } name = fmt.Sprintf("%s.%d", name, nr) md := oldJobStatus.Metadata md.Finished = nil cp, err := srv.RepositoryProvider.ContentProvider(ctx, md.Repository) if err != nil { return nil, status.Error(codes.Internal, err.Error()) } canReplay := true var waitUntil time.Time if req.WaitUntil != nil { waitUntil, err = ptypes.Timestamp(req.WaitUntil) if err != nil { return nil, status.Errorf(codes.InvalidArgument, "waitUntil is invalid: %v", err) } } jobStatus, err := srv.RunJob(ctx, name, *oldJobStatus.Metadata, cp, jobYAML, canReplay, waitUntil) if err != nil { return nil, status.Error(codes.Internal, err.Error()) } log.WithField("name", req.PreviousJob).WithField("old-name", name).Info(("started new job from an old one")) return &v1.StartJobResponse{ Status: jobStatus, }, nil } func newTarStreamAdapter(inc v1.WerftService_StartLocalJobServer, initial []byte) io.Reader { return &tarStreamAdapter{ inc: inc, remainder: initial, } } type tarStreamAdapter struct { inc v1.WerftService_StartLocalJobServer remainder []byte } func (tsa *tarStreamAdapter) Read(p []byte) (n int, err error) { if len(tsa.remainder) == 0 { var msg *v1.StartLocalJobRequest msg, err = tsa.inc.Recv() if err != nil { return 0, err } data := msg.GetWorkspaceTar() if data == nil { log.Debug("tar upload done") return 0, io.EOF } n = copy(p, data) tsa.remainder = data[n:] return } n = copy(p, tsa.remainder) tsa.remainder = tsa.remainder[n:] return n, nil } func (srv *Service) ListJobs(ctx context.Context, req *v1.ListJobsRequest) (resp *v1.ListJobsResponse, err error) { result, total, err := srv.Jobs.Find(ctx, req.Filter, req.Order, int(req.Start), int(req.Limit)) if err != nil { return nil, status.Error(codes.Internal, err.Error()) } res := make([]*v1.JobStatus, len(result)) for i := range result { res[i] = &result[i] } return &v1.ListJobsResponse{ Total: int32(total), Result: res, }, nil } func (srv *Service) Subscribe(req *v1.SubscribeRequest, resp v1.WerftService_SubscribeServer) (err error) { evts := srv.events.On("job") for evt := range evts { job := evt.Args[0].(*v1.JobStatus) if !filterexpr.MatchesFilter(job, req.Filter) { continue } resp.Send(&v1.SubscribeResponse{ Result: job, }) } return nil }
MIT License
rackerlabs/cs-reboot-info
Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/orchestration/v1/stackresources/results.go
IsEmpty
go
func (r ResourcePage) IsEmpty() (bool, error) { resources, err := ExtractResources(r) if err != nil { return true, err } return len(resources) == 0, nil }
IsEmpty returns true if a page contains no Server results.
https://github.com/rackerlabs/cs-reboot-info/blob/acd1293844a39bf54f2e1049756499ef1b5bdf02/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/orchestration/v1/stackresources/results.go#L68-L74
package stackresources import ( "time" "github.com/mitchellh/mapstructure" "github.com/rackspace/gophercloud" "github.com/rackspace/gophercloud/pagination" ) type Resource struct { Links []gophercloud.Link `mapstructure:"links"` LogicalID string `mapstructure:"logical_resource_id"` Name string `mapstructure:"resource_name"` PhysicalID string `mapstructure:"physical_resource_id"` RequiredBy []interface{} `mapstructure:"required_by"` Status string `mapstructure:"resource_status"` StatusReason string `mapstructure:"resource_status_reason"` Type string `mapstructure:"resource_type"` UpdatedTime time.Time `mapstructure:"-"` } type FindResult struct { gophercloud.Result } func (r FindResult) Extract() ([]Resource, error) { if r.Err != nil { return nil, r.Err } var res struct { Res []Resource `mapstructure:"resources"` } if err := mapstructure.Decode(r.Body, &res); err != nil { return nil, err } resources := r.Body.(map[string]interface{})["resources"].([]interface{}) for i, resourceRaw := range resources { resource := resourceRaw.(map[string]interface{}) if date, ok := resource["updated_time"]; ok && date != nil { t, err := time.Parse(time.RFC3339, date.(string)) if err != nil { return nil, err } res.Res[i].UpdatedTime = t } } return res.Res, nil } type ResourcePage struct { pagination.MarkerPageBase }
Apache License 2.0
emer/etable
etensor/bits.go
MetaData
go
func (tsr *Bits) MetaData(key string) (string, bool) { if tsr.Meta == nil { return "", false } val, ok := tsr.Meta[key] return val, ok }
MetaData retrieves value of given key, bool = false if not set
https://github.com/emer/etable/blob/871eae24be96073632cf9cf922317d657c3787a4/etensor/bits.go#L354-L360
package etensor import ( "errors" "fmt" "log" "strings" "github.com/apache/arrow/go/arrow" "github.com/emer/etable/bitslice" "github.com/goki/ki/ints" "github.com/goki/ki/kit" "gonum.org/v1/gonum/mat" ) type BoolType struct{} func (t *BoolType) ID() arrow.Type { return arrow.BOOL } func (t *BoolType) Name() string { return "bool" } func (t *BoolType) BitWidth() int { return 1 } type Bits struct { Shape Values bitslice.Slice Meta map[string]string } func NewBits(shape, strides []int, names []string) *Bits { bt := &Bits{} bt.SetShape(shape, strides, names) ln := bt.Len() bt.Values = bitslice.Make(ln, 0) return bt } func NewBitsShape(shape *Shape) *Bits { bt := &Bits{} bt.CopyShape(shape) ln := bt.Len() bt.Values = bitslice.Make(ln, 0) return bt } func (tsr *Bits) ShapeObj() *Shape { return &tsr.Shape } func (tsr *Bits) DataType() Type { return BOOL } func (tsr *Bits) Value(i []int) bool { j := int(tsr.Offset(i)); return tsr.Values.Index(j) } func (tsr *Bits) Value1D(i int) bool { return tsr.Values.Index(i) } func (tsr *Bits) Set(i []int, val bool) { j := int(tsr.Offset(i)); tsr.Values.Set(j, val) } func (tsr *Bits) Set1D(i int, val bool) { tsr.Values.Set(i, val) } func (tsr *Bits) IsNull(i []int) bool { return false } func (tsr *Bits) IsNull1D(i int) bool { return false } func (tsr *Bits) SetNull(i []int, nul bool) {} func (tsr *Bits) SetNull1D(i int, nul bool) {} func Float64ToBool(val float64) bool { bv := true if val == 0 { bv = false } return bv } func BoolToFloat64(bv bool) float64 { if bv { return 1 } else { return 0 } } func (tsr *Bits) FloatVal(i []int) float64 { j := tsr.Offset(i) return BoolToFloat64(tsr.Values.Index(j)) } func (tsr *Bits) SetFloat(i []int, val float64) { j := tsr.Offset(i) tsr.Values.Set(j, Float64ToBool(val)) } func (tsr *Bits) StringVal(i []int) string { j := tsr.Offset(i) return kit.ToString(tsr.Values.Index(j)) } func (tsr *Bits) SetString(i []int, val string) { if bv, ok := kit.ToBool(val); ok { j := tsr.Offset(i) tsr.Values.Set(j, bv) } } func (tsr *Bits) FloatVal1D(off int) float64 { return BoolToFloat64(tsr.Values.Index(off)) } func (tsr *Bits) SetFloat1D(off int, val float64) { tsr.Values.Set(off, Float64ToBool(val)) } func (tsr *Bits) FloatValRowCell(row, cell int) float64 { _, sz := tsr.RowCellSize() return BoolToFloat64(tsr.Values.Index(row*sz + cell)) } func (tsr *Bits) SetFloatRowCell(row, cell int, val float64) { _, sz := tsr.RowCellSize() tsr.Values.Set(row*sz+cell, Float64ToBool(val)) } func (tsr *Bits) Floats(flt *[]float64) { sz := tsr.Len() SetFloat64SliceLen(flt, sz) for j := 0; j < sz; j++ { (*flt)[j] = BoolToFloat64(tsr.Values.Index(j)) } } func (tsr *Bits) SetFloats(vals []float64) { sz := ints.MinInt(tsr.Len(), len(vals)) for j := 0; j < sz; j++ { tsr.Values.Set(j, Float64ToBool(vals[j])) } } func (tsr *Bits) StringVal1D(off int) string { return kit.ToString(tsr.Values.Index(off)) } func (tsr *Bits) SetString1D(off int, val string) { if bv, ok := kit.ToBool(val); ok { tsr.Values.Set(off, bv) } } func (tsr *Bits) StringValRowCell(row, cell int) string { _, sz := tsr.RowCellSize() return kit.ToString(tsr.Values.Index(row*sz + cell)) } func (tsr *Bits) SetStringRowCell(row, cell int, val string) { if bv, ok := kit.ToBool(val); ok { _, sz := tsr.RowCellSize() tsr.Values.Set(row*sz+cell, bv) } } func (tsr *Bits) SubSpace(offs []int) Tensor { return nil } func (tsr *Bits) SubSpaceTry(offs []int) (Tensor, error) { return nil, errors.New("etensor.Bits does not support SubSpace") } func (tsr *Bits) Range() (min, max float64, minIdx, maxIdx int) { minIdx = -1 maxIdx = -1 return } func (tsr *Bits) Agg(ini float64, fun AggFunc) float64 { ln := tsr.Len() ag := ini for j := 0; j < ln; j++ { ag = fun(j, BoolToFloat64(tsr.Values.Index(j)), ag) } return ag } func (tsr *Bits) Eval(res *[]float64, fun EvalFunc) { ln := tsr.Len() if len(*res) != ln { *res = make([]float64, ln) } for j := 0; j < ln; j++ { (*res)[j] = fun(j, BoolToFloat64(tsr.Values.Index(j))) } } func (tsr *Bits) SetFunc(fun EvalFunc) { ln := tsr.Len() for j := 0; j < ln; j++ { tsr.Values.Set(j, Float64ToBool(fun(j, BoolToFloat64(tsr.Values.Index(j))))) } } func (tsr *Bits) SetZeros() { ln := tsr.Len() for j := 0; j < ln; j++ { tsr.Values.Set(j, false) } } func (tsr *Bits) Clone() Tensor { csr := NewBitsShape(&tsr.Shape) csr.Values = tsr.Values.Clone() return csr } func (tsr *Bits) CopyFrom(frm Tensor) { if fsm, ok := frm.(*Bits); ok { copy(tsr.Values, fsm.Values) return } sz := ints.MinInt(len(tsr.Values), frm.Len()) for i := 0; i < sz; i++ { tsr.Values.Set(i, Float64ToBool(frm.FloatVal1D(i))) } } func (tsr *Bits) CopyShapeFrom(frm Tensor) { tsr.SetShape(frm.Shapes(), frm.Strides(), frm.DimNames()) } func (tsr *Bits) CopyCellsFrom(frm Tensor, to, start, n int) { if fsm, ok := frm.(*Bits); ok { for i := 0; i < n; i++ { tsr.Values.Set(to+i, fsm.Values.Index(start+i)) } return } for i := 0; i < n; i++ { tsr.Values.Set(to+i, Float64ToBool(frm.FloatVal1D(start+i))) } } func (tsr *Bits) SetShape(shape, strides []int, names []string) { tsr.Shape.SetShape(shape, strides, names) nln := tsr.Len() tsr.Values.SetLen(nln) } func (tsr *Bits) SetNumRows(rows int) { if !tsr.IsRowMajor() { return } rows = ints.MaxInt(1, rows) cln := tsr.Len() crows := tsr.Dim(0) inln := cln / crows nln := rows * inln tsr.Shape.Shp[0] = rows tsr.Values.SetLen(nln) } func (tsr *Bits) Dims() (r, c int) { log.Println("etensor Dims gonum Matrix call made on Bits Tensor -- not supported") return 0, 0 } func (tsr *Bits) At(i, j int) float64 { log.Println("etensor At gonum Matrix call made on Bits Tensor -- not supported") return 0 } func (tsr *Bits) T() mat.Matrix { log.Println("etensor T gonum Matrix call made on Bits Tensor -- not supported") return mat.Transpose{tsr} } func (tsr *Bits) Label() string { return fmt.Sprintf("Bits: %s", tsr.Shape.String()) } func (tsr *Bits) String() string { str := tsr.Label() sz := tsr.Len() if sz > 1000 { return str } var b strings.Builder b.WriteString(str) b.WriteString("\n") oddRow := true rows, cols, _, _ := Prjn2DShape(&tsr.Shape, oddRow) for r := 0; r < rows; r++ { rc, _ := Prjn2DCoords(&tsr.Shape, oddRow, r, 0) b.WriteString(fmt.Sprintf("%v: ", rc)) for c := 0; c < cols; c++ { vl := Prjn2DVal(tsr, oddRow, r, c) b.WriteString(fmt.Sprintf("%g ", vl)) } b.WriteString("\n") } return b.String() } func (tsr *Bits) SetMetaData(key, val string) { if tsr.Meta == nil { tsr.Meta = make(map[string]string) } tsr.Meta[key] = val }
BSD 3-Clause New or Revised License
terra-project/mantle-sdk
lcd/models/param_change.go
MarshalBinary
go
func (m *ParamChange) MarshalBinary() ([]byte, error) { if m == nil { return nil, nil } return swag.WriteJSON(m) }
MarshalBinary interface implementation
https://github.com/terra-project/mantle-sdk/blob/99e0b656c1de904ea98ce778fa339f8b9dcbaece/lcd/models/param_change.go#L37-L42
package models import ( "github.com/go-openapi/strfmt" "github.com/go-openapi/swag" ) type ParamChange struct { Key string `json:"key,omitempty"` Subkey string `json:"subkey,omitempty"` Subspace string `json:"subspace,omitempty"` Value interface{} `json:"value,omitempty"` } func (m *ParamChange) Validate(formats strfmt.Registry) error { return nil }
Apache License 2.0
cloudfoundry-incubator/bosh-alicloud-cpi-release
src/bosh-alicloud-cpi/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/ecs/revoke_security_group_egress.go
RevokeSecurityGroupEgressWithCallback
go
func (client *Client) RevokeSecurityGroupEgressWithCallback(request *RevokeSecurityGroupEgressRequest, callback func(response *RevokeSecurityGroupEgressResponse, err error)) <-chan int { result := make(chan int, 1) err := client.AddAsyncTask(func() { var response *RevokeSecurityGroupEgressResponse var err error defer close(result) response, err = client.RevokeSecurityGroupEgress(request) callback(response, err) result <- 1 }) if err != nil { defer close(result) callback(nil, err) result <- 0 } return result }
RevokeSecurityGroupEgressWithCallback invokes the ecs.RevokeSecurityGroupEgress API asynchronously api document: https://help.aliyun.com/api/ecs/revokesecuritygroupegress.html asynchronous document: https://help.aliyun.com/document_detail/66220.html
https://github.com/cloudfoundry-incubator/bosh-alicloud-cpi-release/blob/9776d3ef967051fdce16294580fd37cd8ed9814a/src/bosh-alicloud-cpi/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/ecs/revoke_security_group_egress.go#L58-L74
package ecs import ( "github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests" "github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses" ) func (client *Client) RevokeSecurityGroupEgress(request *RevokeSecurityGroupEgressRequest) (response *RevokeSecurityGroupEgressResponse, err error) { response = CreateRevokeSecurityGroupEgressResponse() err = client.DoAction(request, response) return } func (client *Client) RevokeSecurityGroupEgressWithChan(request *RevokeSecurityGroupEgressRequest) (<-chan *RevokeSecurityGroupEgressResponse, <-chan error) { responseChan := make(chan *RevokeSecurityGroupEgressResponse, 1) errChan := make(chan error, 1) err := client.AddAsyncTask(func() { defer close(responseChan) defer close(errChan) response, err := client.RevokeSecurityGroupEgress(request) if err != nil { errChan <- err } else { responseChan <- response } }) if err != nil { errChan <- err close(responseChan) close(errChan) } return responseChan, errChan }
Apache License 2.0
mehrdadrad/mylg
nms/snmp.go
BulkWalk
go
func (c *SNMPClient) BulkWalk(oid ...string) ([]*snmpgo.VarBind, error) { var r []*snmpgo.VarBind snmp, err := snmpgo.NewSNMP(c.Args) if err != nil { return r, err } oids, err := snmpgo.NewOids(oid) if err != nil { return r, err } if err = snmp.Open(); err != nil { return r, err } defer snmp.Close() pdu, err := snmp.GetBulkWalk(oids, 0, 5) if err != nil { return r, err } r = pdu.VarBinds() return r, nil }
BulkWalk retrieves a subtree of management values
https://github.com/mehrdadrad/mylg/blob/faba8672ef9f2693ca9093d2a3a671114401e55a/nms/snmp.go#L113-L136
package nms import ( "fmt" "net" "strings" "time" "github.com/k-sone/snmpgo" "github.com/mehrdadrad/mylg/cli" ) var ( OID = map[string]string{ "sysDescr": "1.3.6.1.2.1.1.1.0", "ifDescr": "1.3.6.1.2.1.2.2.1.2", "ifAlias": "1.3.6.1.2.1.31.1.1.1.18", "ifOperStatus": "1.3.6.1.2.1.2.2.1.8", "ifHCInOctets": "1.3.6.1.2.1.31.1.1.1.6", "ifHCInUcastPkts": "1.3.6.1.2.1.31.1.1.1.7", "ifHCOutOctets": "1.3.6.1.2.1.31.1.1.1.10", "ifHCOutUcastPkts": "1.3.6.1.2.1.31.1.1.1.11", "ifHCInMulticastPkts": "1.3.6.1.2.1.31.1.1.1.8", "ifHCOutMulticastPkts": "1.3.6.1.2.1.31.1.1.1.12", "ifHCInBroadcastPkts": "1.3.6.1.2.1.31.1.1.1.9", "ifHCOutBroadcastPkts": "1.3.6.1.2.1.31.1.1.1.13", "ifInDiscards": "1.3.6.1.2.1.2.2.1.13", "ifInErrors": "1.3.6.1.2.1.2.2.1.14", "ifOutDiscards": "1.3.6.1.2.1.2.2.1.19", "ifOutErrors": "1.3.6.1.2.1.2.2.1.20", } ) type SNMPClient struct { Args snmpgo.SNMPArguments Host string SysDescr string } func NewSNMP(a string, cfg cli.Config) (*SNMPClient, error) { var ( host, flag = cli.Flag(a) community = cli.SetFlag(flag, "c", cfg.Snmp.Community).(string) timeout = cli.SetFlag(flag, "t", cfg.Snmp.Timeout).(string) version = cli.SetFlag(flag, "v", cfg.Snmp.Version).(string) retries = cli.SetFlag(flag, "r", cfg.Snmp.Retries).(int) port = cli.SetFlag(flag, "p", cfg.Snmp.Port).(int) securityLevel = cli.SetFlag(flag, "l", cfg.Snmp.Securitylevel).(string) privacyProto = cli.SetFlag(flag, "x", cfg.Snmp.Privacyproto).(string) privacyPass = cli.SetFlag(flag, "X", cfg.Snmp.Privacypass).(string) authProto = cli.SetFlag(flag, "a", cfg.Snmp.Authproto).(string) authPass = cli.SetFlag(flag, "A", cfg.Snmp.Authpass).(string) ) tDuration, err := time.ParseDuration(timeout) if err != nil { return &SNMPClient{}, err } args := snmpgo.SNMPArguments{ Timeout: tDuration, Address: net.JoinHostPort(host, fmt.Sprintf("%d", port)), Retries: uint(retries), Community: community, } switch version { case "1": args.Version = snmpgo.V1 case "2", "2c": args.Version = snmpgo.V2c case "3": authProto = strings.ToUpper(authProto) privacyProto = strings.ToUpper(privacyProto) args.Version = snmpgo.V3 args.AuthProtocol = snmpgo.AuthProtocol(authProto) args.AuthPassword = authPass args.PrivProtocol = snmpgo.PrivProtocol(privacyProto) args.PrivPassword = privacyPass default: return &SNMPClient{}, fmt.Errorf("wrong version") } switch strings.ToLower(securityLevel) { case "noauthnopriv": args.SecurityLevel = snmpgo.NoAuthNoPriv case "authnopriv": args.SecurityLevel = snmpgo.AuthNoPriv case "authpriv": args.SecurityLevel = snmpgo.AuthPriv } if err = argsValidate(&args); err != nil { return &SNMPClient{}, err } return &SNMPClient{ Args: args, Host: host, SysDescr: "", }, nil }
MIT License
tidb-incubator/tinysql
domain/domain.go
NewDomain
go
func NewDomain(store kv.Storage, ddlLease time.Duration, statsLease time.Duration, factory pools.Factory) *Domain { capacity := 200 return &Domain{ store: store, SchemaValidator: NewSchemaValidator(ddlLease), exit: make(chan struct{}), sysSessionPool: newSessionPool(capacity, factory), statsLease: statsLease, infoHandle: infoschema.NewHandle(store), } }
NewDomain creates a new domain. Should not create multiple domains for the same store.
https://github.com/tidb-incubator/tinysql/blob/1f08ceeae7f525dee0a0c8931ac594ef06d21cc5/domain/domain.go#L461-L471
package domain import ( "context" "os" "sync" "sync/atomic" "time" "unsafe" "github.com/ngaut/pools" "github.com/pingcap/errors" "github.com/pingcap/failpoint" "github.com/pingcap/tidb/ddl" "github.com/pingcap/tidb/infoschema" "github.com/pingcap/tidb/kv" "github.com/pingcap/tidb/meta" "github.com/pingcap/tidb/parser/model" "github.com/pingcap/tidb/parser/mysql" "github.com/pingcap/tidb/parser/terror" "github.com/pingcap/tidb/sessionctx" "github.com/pingcap/tidb/sessionctx/variable" "github.com/pingcap/tidb/statistics" "github.com/pingcap/tidb/store/tikv" "github.com/pingcap/tidb/util" "github.com/pingcap/tidb/util/logutil" "go.etcd.io/etcd/clientv3" "go.uber.org/zap" "google.golang.org/grpc" "google.golang.org/grpc/keepalive" ) type Domain struct { store kv.Storage infoHandle *infoschema.Handle statsHandle unsafe.Pointer statsLease time.Duration ddl ddl.DDL m sync.Mutex SchemaValidator SchemaValidator sysSessionPool *sessionPool exit chan struct{} etcdClient *clientv3.Client gvc GlobalVariableCache wg sync.WaitGroup } func (do *Domain) loadInfoSchema(handle *infoschema.Handle, usedSchemaVersion int64, startTS uint64) (int64, []int64, bool, error) { var fullLoad bool snapshot, err := do.store.GetSnapshot(kv.NewVersion(startTS)) if err != nil { return 0, nil, fullLoad, err } m := meta.NewSnapshotMeta(snapshot) neededSchemaVersion, err := m.GetSchemaVersion() if err != nil { return 0, nil, fullLoad, err } if usedSchemaVersion != 0 && usedSchemaVersion == neededSchemaVersion { return neededSchemaVersion, nil, fullLoad, nil } defer func() { if err != nil || neededSchemaVersion < do.InfoSchema().SchemaMetaVersion() { logutil.BgLogger().Info("do not update self schema version to etcd", zap.Int64("usedSchemaVersion", usedSchemaVersion), zap.Int64("neededSchemaVersion", neededSchemaVersion), zap.Error(err)) return } err = do.ddl.SchemaSyncer().UpdateSelfVersion(context.Background(), neededSchemaVersion) if err != nil { logutil.BgLogger().Info("update self version failed", zap.Int64("usedSchemaVersion", usedSchemaVersion), zap.Int64("neededSchemaVersion", neededSchemaVersion), zap.Error(err)) } }() startTime := time.Now() ok, tblIDs, err := do.tryLoadSchemaDiffs(m, usedSchemaVersion, neededSchemaVersion) if err != nil { logutil.BgLogger().Error("failed to load schema diff", zap.Error(err)) } if ok { logutil.BgLogger().Info("diff load InfoSchema success", zap.Int64("usedSchemaVersion", usedSchemaVersion), zap.Int64("neededSchemaVersion", neededSchemaVersion), zap.Duration("start time", time.Since(startTime)), zap.Int64s("tblIDs", tblIDs)) return neededSchemaVersion, tblIDs, fullLoad, nil } fullLoad = true schemas, err := do.fetchAllSchemasWithTables(m) if err != nil { return 0, nil, fullLoad, err } newISBuilder, err := infoschema.NewBuilder(handle).InitWithDBInfos(schemas, neededSchemaVersion) if err != nil { return 0, nil, fullLoad, err } logutil.BgLogger().Info("full load InfoSchema success", zap.Int64("usedSchemaVersion", usedSchemaVersion), zap.Int64("neededSchemaVersion", neededSchemaVersion), zap.Duration("start time", time.Since(startTime))) newISBuilder.Build() return neededSchemaVersion, nil, fullLoad, nil } func (do *Domain) fetchAllSchemasWithTables(m *meta.Meta) ([]*model.DBInfo, error) { allSchemas, err := m.ListDatabases() if err != nil { return nil, err } splittedSchemas := do.splitForConcurrentFetch(allSchemas) doneCh := make(chan error, len(splittedSchemas)) for _, schemas := range splittedSchemas { go do.fetchSchemasWithTables(schemas, m, doneCh) } for range splittedSchemas { err = <-doneCh if err != nil { return nil, err } } return allSchemas, nil } const fetchSchemaConcurrency = 8 func (do *Domain) splitForConcurrentFetch(schemas []*model.DBInfo) [][]*model.DBInfo { groupSize := (len(schemas) + fetchSchemaConcurrency - 1) / fetchSchemaConcurrency splitted := make([][]*model.DBInfo, 0, fetchSchemaConcurrency) schemaCnt := len(schemas) for i := 0; i < schemaCnt; i += groupSize { end := i + groupSize if end > schemaCnt { end = schemaCnt } splitted = append(splitted, schemas[i:end]) } return splitted } func (do *Domain) fetchSchemasWithTables(schemas []*model.DBInfo, m *meta.Meta, done chan error) { for _, di := range schemas { if di.State != model.StatePublic { continue } tables, err := m.ListTables(di.ID) if err != nil { done <- err return } di.Tables = make([]*model.TableInfo, 0, len(tables)) for _, tbl := range tables { if tbl.State != model.StatePublic { continue } infoschema.ConvertCharsetCollateToLowerCaseIfNeed(tbl) di.Tables = append(di.Tables, tbl) } } done <- nil } const ( initialVersion = 0 maxNumberOfDiffsToLoad = 100 ) func isTooOldSchema(usedVersion, newVersion int64) bool { if usedVersion == initialVersion || newVersion-usedVersion > maxNumberOfDiffsToLoad { return true } return false } func (do *Domain) tryLoadSchemaDiffs(m *meta.Meta, usedVersion, newVersion int64) (bool, []int64, error) { if isTooOldSchema(usedVersion, newVersion) { return false, nil, nil } var diffs []*model.SchemaDiff for usedVersion < newVersion { usedVersion++ diff, err := m.GetSchemaDiff(usedVersion) if err != nil { return false, nil, err } if diff == nil { return false, nil, nil } diffs = append(diffs, diff) } builder := infoschema.NewBuilder(do.infoHandle).InitWithOldInfoSchema() tblIDs := make([]int64, 0, len(diffs)) for _, diff := range diffs { ids, err := builder.ApplyDiff(m, diff) if err != nil { return false, nil, err } tblIDs = append(tblIDs, ids...) } builder.Build() return true, tblIDs, nil } func (do *Domain) InfoSchema() infoschema.InfoSchema { return do.infoHandle.Get() } func (do *Domain) DDL() ddl.DDL { return do.ddl } func (do *Domain) Store() kv.Storage { return do.store } func (do *Domain) GetScope(status string) variable.ScopeFlag { return variable.DefaultStatusVarScopeFlag } func (do *Domain) Reload() error { failpoint.Inject("ErrorMockReloadFailed", func(val failpoint.Value) { if val.(bool) { failpoint.Return(errors.New("mock reload failed")) } }) do.m.Lock() defer do.m.Unlock() startTime := time.Now() var err error var neededSchemaVersion int64 ver, err := do.store.CurrentVersion() if err != nil { return err } schemaVersion := int64(0) oldInfoSchema := do.infoHandle.Get() if oldInfoSchema != nil { schemaVersion = oldInfoSchema.SchemaMetaVersion() } var ( fullLoad bool changedTableIDs []int64 ) neededSchemaVersion, changedTableIDs, fullLoad, err = do.loadInfoSchema(do.infoHandle, schemaVersion, ver.Ver) if err != nil { return err } if fullLoad { logutil.BgLogger().Info("full load and reset schema validator") do.SchemaValidator.Reset() } do.SchemaValidator.Update(ver.Ver, schemaVersion, neededSchemaVersion, changedTableIDs) lease := do.DDL().GetLease() sub := time.Since(startTime) if sub > (lease/2) && lease > 0 { logutil.BgLogger().Warn("loading schema takes a long time", zap.Duration("take time", sub)) } return nil } func (do *Domain) loadSchemaInLoop(lease time.Duration) { defer do.wg.Done() ticker := time.NewTicker(lease / 2) defer ticker.Stop() defer recoverInDomain("loadSchemaInLoop", true) syncer := do.ddl.SchemaSyncer() for { select { case <-ticker.C: err := do.Reload() if err != nil { logutil.BgLogger().Error("reload schema in loop failed", zap.Error(err)) } case _, ok := <-syncer.GlobalVersionCh(): err := do.Reload() if err != nil { logutil.BgLogger().Error("reload schema in loop failed", zap.Error(err)) } if !ok { logutil.BgLogger().Warn("reload schema in loop, schema syncer need rewatch") syncer.WatchGlobalSchemaVer(context.Background()) } case <-syncer.Done(): logutil.BgLogger().Info("reload schema in loop, schema syncer need restart") do.SchemaValidator.Stop() err := do.mustRestartSyncer() if err != nil { logutil.BgLogger().Error("reload schema in loop, schema syncer restart failed", zap.Error(err)) break } exitLoop := do.mustReload() if exitLoop { logutil.BgLogger().Error("domain is closed, exit loadSchemaInLoop") return } do.SchemaValidator.Restart() logutil.BgLogger().Info("schema syncer restarted") case <-do.exit: return } } } func (do *Domain) mustRestartSyncer() error { ctx := context.Background() syncer := do.ddl.SchemaSyncer() for { err := syncer.Restart(ctx) if err == nil { return nil } if do.isClose() { return err } time.Sleep(time.Second) logutil.BgLogger().Info("restart the schema syncer failed", zap.Error(err)) } } func (do *Domain) mustReload() (exitLoop bool) { for { err := do.Reload() if err == nil { logutil.BgLogger().Info("mustReload succeed") return false } logutil.BgLogger().Info("reload the schema failed", zap.Error(err)) if do.isClose() { return true } time.Sleep(200 * time.Millisecond) } } func (do *Domain) isClose() bool { select { case <-do.exit: logutil.BgLogger().Info("domain is closed") return true default: } return false } func (do *Domain) Close() { startTime := time.Now() if do.ddl != nil { terror.Log(do.ddl.Stop()) } close(do.exit) if do.etcdClient != nil { terror.Log(errors.Trace(do.etcdClient.Close())) } do.sysSessionPool.Close() do.wg.Wait() logutil.BgLogger().Info("domain closed", zap.Duration("take time", time.Since(startTime))) } type ddlCallback struct { ddl.BaseCallback do *Domain } func (c *ddlCallback) OnChanged(err error) error { if err != nil { return err } logutil.BgLogger().Info("performing DDL change, must reload") err = c.do.Reload() if err != nil { logutil.BgLogger().Error("performing DDL change failed", zap.Error(err)) } return nil } const resourceIdleTimeout = 3 * time.Minute
Apache License 2.0
kubernetes-csi/csi-lib-utils
vendor/k8s.io/client-go/applyconfigurations/admissionregistration/v1/rule.go
WithAPIGroups
go
func (b *RuleApplyConfiguration) WithAPIGroups(values ...string) *RuleApplyConfiguration { for i := range values { b.APIGroups = append(b.APIGroups, values[i]) } return b }
WithAPIGroups adds the given value to the APIGroups field in the declarative configuration and returns the receiver, so that objects can be build by chaining "With" function invocations. If called multiple times, values provided by each call will be appended to the APIGroups field.
https://github.com/kubernetes-csi/csi-lib-utils/blob/a2ccb594bb74b61a0655d3431c6365a6a567c7af/vendor/k8s.io/client-go/applyconfigurations/admissionregistration/v1/rule.go#L43-L48
package v1 import ( v1 "k8s.io/api/admissionregistration/v1" ) type RuleApplyConfiguration struct { APIGroups []string `json:"apiGroups,omitempty"` APIVersions []string `json:"apiVersions,omitempty"` Resources []string `json:"resources,omitempty"` Scope *v1.ScopeType `json:"scope,omitempty"` } func Rule() *RuleApplyConfiguration { return &RuleApplyConfiguration{} }
Apache License 2.0
uber-archive/cherami-server
common/service.go
GetHostPort
go
func (h *Service) GetHostPort() string { h.startWg.Wait() return h.hostPort }
GetHostPort returns the host port for this service
https://github.com/uber-archive/cherami-server/blob/da747b7be487feeaba1a5d7cb01e71343e6f8452/common/service.go#L138-L141
package common import ( "fmt" "math/rand" "net/http" "os" "strings" "time" log "github.com/sirupsen/logrus" "github.com/uber-common/bark" "github.com/uber/cherami-server/common/configure" dconfig "github.com/uber/cherami-server/common/dconfigclient" "github.com/uber/cherami-server/common/metrics" "github.com/uber/cherami-thrift/.generated/go/controller" "github.com/uber/tchannel-go" "github.com/uber/tchannel-go/thrift" ) const roleKey = "serviceName" func NewService(serviceName string, uuid string, cfg configure.CommonServiceConfig, resolver UUIDResolver, hostHWInfoReader HostHardwareInfoReader, reporter metrics.Reporter, dClient dconfig.Client, authManager AuthManager) *Service { sVice := &Service{ sName: serviceName, cfg: cfg, resolver: resolver, hostHWInfoReader: hostHWInfoReader, hostUUID: uuid, bLimitsEnabled: true, mReporter: reporter, runtimeMetricsReporter: metrics.NewRuntimeMetricsReporter(reporter, time.Minute, cfg.GetLogger()), dClient: dClient, authManager: authManager, } if hostName, e := os.Hostname(); e != nil { log.Fatal("Error getting hostname") } else { sVice.hostName = hostName } sVice.startWg.Add(1) return sVice } func (h *Service) UpdateAdvertisedName(deploymentName string) { if h.sName == FrontendServiceName { if IsDevelopmentEnvironment(deploymentName) { h.sName = FrontendServiceName } else { parts := strings.Split(deploymentName, "_") if len(parts) != 2 { log.Fatal("Unexpected deployment name") } tenancy := strings.ToLower(parts[0]) if tenancy == TenancyProd { h.sName = FrontendServiceName } else { h.sName = fmt.Sprintf("%v_%v", FrontendServiceName, tenancy) } } } } func (h *Service) GetTChannel() *tchannel.Channel { h.startWg.Wait() return h.ch } func (h *Service) GetConfig() configure.CommonServiceConfig { return h.cfg } func (h *Service) GetRingpopMonitor() RingpopMonitor { h.startWg.Wait() return h.rpm } func (h *Service) GetClientFactory() ClientFactory { h.startWg.Wait() return h.cFactory } func (h *Service) SetClientFactory(cf ClientFactory) { h.cFactory = cf } func (h *Service) GetWSConnector() WSConnector { h.startWg.Wait() return h.wsConnector } func (h *Service) GetLoadReporterDaemonFactory() LoadReporterDaemonFactory { h.startWg.Wait() return h.rFactory }
MIT License
clivern/beetle
core/model/namespace.go
ConvertToJSON
go
func (d *Namespaces) ConvertToJSON() (string, error) { data, err := json.Marshal(&d) if err != nil { return "", err } return string(data), nil }
ConvertToJSON convert object to json
https://github.com/clivern/beetle/blob/fb778dd7a2ccdf563efd6bdb843679474e347ef0/core/model/namespace.go#L51-L57
package model import ( "encoding/json" ) type Namespace struct { Name string `json:"name"` UID string `json:"uid"` Status string `json:"status"` } type Namespaces struct { Namespaces []Namespace `json:"namespaces"` } func (d *Namespace) LoadFromJSON(data []byte) (bool, error) { err := json.Unmarshal(data, &d) if err != nil { return false, err } return true, nil } func (d *Namespace) ConvertToJSON() (string, error) { data, err := json.Marshal(&d) if err != nil { return "", err } return string(data), nil } func (d *Namespaces) LoadFromJSON(data []byte) (bool, error) { err := json.Unmarshal(data, &d) if err != nil { return false, err } return true, nil }
MIT License
fernandrone/drone-ignore-config
vendor/github.com/google/go-github/github/repos.go
List
go
func (s *RepositoriesService) List(ctx context.Context, user string, opt *RepositoryListOptions) ([]*Repository, *Response, error) { var u string if user != "" { u = fmt.Sprintf("users/%v/repos", user) } else { u = "user/repos" } u, err := addOptions(u, opt) if err != nil { return nil, nil, err } req, err := s.client.NewRequest("GET", u, nil) if err != nil { return nil, nil, err } acceptHeaders := []string{mediaTypeCodesOfConductPreview, mediaTypeTopicsPreview} req.Header.Set("Accept", strings.Join(acceptHeaders, ", ")) var repos []*Repository resp, err := s.client.Do(ctx, req, &repos) if err != nil { return nil, resp, err } return repos, resp, nil }
List the repositories for a user. Passing the empty string will list repositories for the authenticated user. GitHub API docs: https://developer.github.com/v3/repos/#list-user-repositories
https://github.com/fernandrone/drone-ignore-config/blob/48513862a5d4c63a31ea8af555a0944857581277/vendor/github.com/google/go-github/github/repos.go#L164-L192
package github import ( "context" "fmt" "strings" ) type RepositoriesService service type Repository struct { ID *int64 `json:"id,omitempty"` NodeID *string `json:"node_id,omitempty"` Owner *User `json:"owner,omitempty"` Name *string `json:"name,omitempty"` FullName *string `json:"full_name,omitempty"` Description *string `json:"description,omitempty"` Homepage *string `json:"homepage,omitempty"` CodeOfConduct *CodeOfConduct `json:"code_of_conduct,omitempty"` DefaultBranch *string `json:"default_branch,omitempty"` MasterBranch *string `json:"master_branch,omitempty"` CreatedAt *Timestamp `json:"created_at,omitempty"` PushedAt *Timestamp `json:"pushed_at,omitempty"` UpdatedAt *Timestamp `json:"updated_at,omitempty"` HTMLURL *string `json:"html_url,omitempty"` CloneURL *string `json:"clone_url,omitempty"` GitURL *string `json:"git_url,omitempty"` MirrorURL *string `json:"mirror_url,omitempty"` SSHURL *string `json:"ssh_url,omitempty"` SVNURL *string `json:"svn_url,omitempty"` Language *string `json:"language,omitempty"` Fork *bool `json:"fork,omitempty"` ForksCount *int `json:"forks_count,omitempty"` NetworkCount *int `json:"network_count,omitempty"` OpenIssuesCount *int `json:"open_issues_count,omitempty"` StargazersCount *int `json:"stargazers_count,omitempty"` SubscribersCount *int `json:"subscribers_count,omitempty"` WatchersCount *int `json:"watchers_count,omitempty"` Size *int `json:"size,omitempty"` AutoInit *bool `json:"auto_init,omitempty"` Parent *Repository `json:"parent,omitempty"` Source *Repository `json:"source,omitempty"` Organization *Organization `json:"organization,omitempty"` Permissions *map[string]bool `json:"permissions,omitempty"` AllowRebaseMerge *bool `json:"allow_rebase_merge,omitempty"` AllowSquashMerge *bool `json:"allow_squash_merge,omitempty"` AllowMergeCommit *bool `json:"allow_merge_commit,omitempty"` Topics []string `json:"topics,omitempty"` Archived *bool `json:"archived,omitempty"` License *License `json:"license,omitempty"` Private *bool `json:"private,omitempty"` HasIssues *bool `json:"has_issues,omitempty"` HasWiki *bool `json:"has_wiki,omitempty"` HasPages *bool `json:"has_pages,omitempty"` HasProjects *bool `json:"has_projects,omitempty"` HasDownloads *bool `json:"has_downloads,omitempty"` LicenseTemplate *string `json:"license_template,omitempty"` GitignoreTemplate *string `json:"gitignore_template,omitempty"` TeamID *int64 `json:"team_id,omitempty"` URL *string `json:"url,omitempty"` ArchiveURL *string `json:"archive_url,omitempty"` AssigneesURL *string `json:"assignees_url,omitempty"` BlobsURL *string `json:"blobs_url,omitempty"` BranchesURL *string `json:"branches_url,omitempty"` CollaboratorsURL *string `json:"collaborators_url,omitempty"` CommentsURL *string `json:"comments_url,omitempty"` CommitsURL *string `json:"commits_url,omitempty"` CompareURL *string `json:"compare_url,omitempty"` ContentsURL *string `json:"contents_url,omitempty"` ContributorsURL *string `json:"contributors_url,omitempty"` DeploymentsURL *string `json:"deployments_url,omitempty"` DownloadsURL *string `json:"downloads_url,omitempty"` EventsURL *string `json:"events_url,omitempty"` ForksURL *string `json:"forks_url,omitempty"` GitCommitsURL *string `json:"git_commits_url,omitempty"` GitRefsURL *string `json:"git_refs_url,omitempty"` GitTagsURL *string `json:"git_tags_url,omitempty"` HooksURL *string `json:"hooks_url,omitempty"` IssueCommentURL *string `json:"issue_comment_url,omitempty"` IssueEventsURL *string `json:"issue_events_url,omitempty"` IssuesURL *string `json:"issues_url,omitempty"` KeysURL *string `json:"keys_url,omitempty"` LabelsURL *string `json:"labels_url,omitempty"` LanguagesURL *string `json:"languages_url,omitempty"` MergesURL *string `json:"merges_url,omitempty"` MilestonesURL *string `json:"milestones_url,omitempty"` NotificationsURL *string `json:"notifications_url,omitempty"` PullsURL *string `json:"pulls_url,omitempty"` ReleasesURL *string `json:"releases_url,omitempty"` StargazersURL *string `json:"stargazers_url,omitempty"` StatusesURL *string `json:"statuses_url,omitempty"` SubscribersURL *string `json:"subscribers_url,omitempty"` SubscriptionURL *string `json:"subscription_url,omitempty"` TagsURL *string `json:"tags_url,omitempty"` TreesURL *string `json:"trees_url,omitempty"` TeamsURL *string `json:"teams_url,omitempty"` TextMatches []TextMatch `json:"text_matches,omitempty"` } func (r Repository) String() string { return Stringify(r) } type RepositoryListOptions struct { Visibility string `url:"visibility,omitempty"` Affiliation string `url:"affiliation,omitempty"` Type string `url:"type,omitempty"` Sort string `url:"sort,omitempty"` Direction string `url:"direction,omitempty"` ListOptions }
MIT License
cloudflare/cbpfc
cbpfc_test.go
TestNoIndirectGuard
go
func TestNoIndirectGuard(t *testing.T) { insns := toInstructions([]bpf.Instruction{ bpf.LoadConstant{Dst: bpf.RegA, Val: 23}, bpf.RetA{}, }) blocks := mustSplitBlocks(t, 1, insns) addIndirectPacketGuards(blocks) matchBlock(t, blocks[0], insns, nil) }
Check we don't add a guard if there are no packet loads
https://github.com/cloudflare/cbpfc/blob/6dacae9d44bc4c2874c5b72275b58a05da669903/cbpfc_test.go#L974-L985
package cbpfc import ( "reflect" "strings" "testing" "golang.org/x/net/bpf" ) func requireError(tb testing.TB, err error, contains string) { tb.Helper() if err == nil { tb.Fatalf("expected error %s", contains) } if !strings.Contains(err.Error(), contains) { tb.Fatalf("error %v does not contain %s", err, contains) } } func TestZero(t *testing.T) { _, err := compile([]bpf.Instruction{}) requireError(t, err, "can't compile 0 instructions") } func TestRaw(t *testing.T) { _, err := compile([]bpf.Instruction{ bpf.RawInstruction{}, }) requireError(t, err, "unsupported instruction 0:") } func TestExtension(t *testing.T) { for i := 0; i < 256; i++ { ext := bpf.Extension(i) _, err := compile([]bpf.Instruction{ bpf.LoadExtension{Num: ext}, bpf.RetA{}, }) switch ext { case bpf.ExtLen: if err != nil { t.Fatal("ExtLen not accepted", err) } default: requireError(t, err, "unsupported BPF extension 0:") } } } func TestJumpOut(t *testing.T) { _, err := compile([]bpf.Instruction{ bpf.LoadConstant{Dst: bpf.RegX, Val: 0}, bpf.Jump{Skip: 0}, }) requireError(t, err, "instruction 1: ja 0 flows past last instruction") } func TestJumpIfOut(t *testing.T) { _, err := compile([]bpf.Instruction{ bpf.LoadConstant{Dst: bpf.RegA, Val: 0}, bpf.JumpIf{Cond: bpf.JumpEqual, Val: 2, SkipTrue: 0, SkipFalse: 1}, }) requireError(t, err, "instruction 1: jneq #2,1 flows past last instruction") } func TestJumpIfXOut(t *testing.T) { _, err := compile([]bpf.Instruction{ bpf.LoadConstant{Dst: bpf.RegA, Val: 0}, bpf.LoadConstant{Dst: bpf.RegX, Val: 3}, bpf.JumpIfX{Cond: bpf.JumpEqual, SkipTrue: 1, SkipFalse: 0}, }) requireError(t, err, "instruction 2: jeq x,1 flows past last instruction") } func TestFallthroughOut(t *testing.T) { _, err := compile([]bpf.Instruction{ bpf.LoadConstant{Dst: bpf.RegA, Val: 0}, }) requireError(t, err, "instruction 0: ld #0 flows past last instruction") } func TestNormalizeJumps(t *testing.T) { insns := func(skipTrue, skipFalse uint8) []instruction { return toInstructions([]bpf.Instruction{ bpf.JumpIf{Cond: bpf.JumpEqual, SkipTrue: skipTrue, SkipFalse: skipFalse}, bpf.JumpIfX{Cond: bpf.JumpEqual, SkipTrue: skipTrue, SkipFalse: skipFalse}, bpf.JumpIf{Cond: bpf.JumpNotEqual, SkipTrue: skipTrue, SkipFalse: skipFalse}, bpf.JumpIfX{Cond: bpf.JumpNotEqual, SkipTrue: skipTrue, SkipFalse: skipFalse}, bpf.JumpIf{Cond: bpf.JumpGreaterThan, SkipTrue: skipTrue, SkipFalse: skipFalse}, bpf.JumpIfX{Cond: bpf.JumpGreaterThan, SkipTrue: skipTrue, SkipFalse: skipFalse}, bpf.JumpIf{Cond: bpf.JumpLessThan, SkipTrue: skipTrue, SkipFalse: skipFalse}, bpf.JumpIfX{Cond: bpf.JumpLessThan, SkipTrue: skipTrue, SkipFalse: skipFalse}, bpf.JumpIf{Cond: bpf.JumpGreaterOrEqual, SkipTrue: skipTrue, SkipFalse: skipFalse}, bpf.JumpIfX{Cond: bpf.JumpGreaterOrEqual, SkipTrue: skipTrue, SkipFalse: skipFalse}, bpf.JumpIf{Cond: bpf.JumpLessOrEqual, SkipTrue: skipTrue, SkipFalse: skipFalse}, bpf.JumpIfX{Cond: bpf.JumpLessOrEqual, SkipTrue: skipTrue, SkipFalse: skipFalse}, bpf.JumpIf{Cond: bpf.JumpBitsSet, SkipTrue: skipTrue, SkipFalse: skipFalse}, bpf.JumpIfX{Cond: bpf.JumpBitsSet, SkipTrue: skipTrue, SkipFalse: skipFalse}, bpf.JumpIf{Cond: bpf.JumpBitsNotSet, SkipTrue: skipTrue, SkipFalse: skipFalse}, bpf.JumpIfX{Cond: bpf.JumpBitsNotSet, SkipTrue: skipTrue, SkipFalse: skipFalse}, }) } invertedInsns := func(skipTrue, skipFalse uint8) []instruction { return toInstructions([]bpf.Instruction{ bpf.JumpIf{Cond: bpf.JumpNotEqual, SkipTrue: skipTrue, SkipFalse: skipFalse}, bpf.JumpIfX{Cond: bpf.JumpNotEqual, SkipTrue: skipTrue, SkipFalse: skipFalse}, bpf.JumpIf{Cond: bpf.JumpEqual, SkipTrue: skipTrue, SkipFalse: skipFalse}, bpf.JumpIfX{Cond: bpf.JumpEqual, SkipTrue: skipTrue, SkipFalse: skipFalse}, bpf.JumpIf{Cond: bpf.JumpLessOrEqual, SkipTrue: skipTrue, SkipFalse: skipFalse}, bpf.JumpIfX{Cond: bpf.JumpLessOrEqual, SkipTrue: skipTrue, SkipFalse: skipFalse}, bpf.JumpIf{Cond: bpf.JumpGreaterOrEqual, SkipTrue: skipTrue, SkipFalse: skipFalse}, bpf.JumpIfX{Cond: bpf.JumpGreaterOrEqual, SkipTrue: skipTrue, SkipFalse: skipFalse}, bpf.JumpIf{Cond: bpf.JumpLessThan, SkipTrue: skipTrue, SkipFalse: skipFalse}, bpf.JumpIfX{Cond: bpf.JumpLessThan, SkipTrue: skipTrue, SkipFalse: skipFalse}, bpf.JumpIf{Cond: bpf.JumpGreaterThan, SkipTrue: skipTrue, SkipFalse: skipFalse}, bpf.JumpIfX{Cond: bpf.JumpGreaterThan, SkipTrue: skipTrue, SkipFalse: skipFalse}, bpf.JumpIf{Cond: bpf.JumpBitsNotSet, SkipTrue: skipTrue, SkipFalse: skipFalse}, bpf.JumpIfX{Cond: bpf.JumpBitsNotSet, SkipTrue: skipTrue, SkipFalse: skipFalse}, bpf.JumpIf{Cond: bpf.JumpBitsSet, SkipTrue: skipTrue, SkipFalse: skipFalse}, bpf.JumpIfX{Cond: bpf.JumpBitsSet, SkipTrue: skipTrue, SkipFalse: skipFalse}, }) } check := func(t *testing.T, input []instruction, expected []instruction) { normalizeJumps(input) if !reflect.DeepEqual(input, expected) { t.Fatalf("\nGot:\n%v\n\nExpected:\n%v", input, expected) } } check(t, insns(1, 0), insns(1, 0)) check(t, insns(1, 3), insns(1, 3)) check(t, insns(0, 3), invertedInsns(3, 0)) } func TestInstructionReadsRegA(t *testing.T) { checkMemoryStatus(t, map[bpf.Instruction]bool{ bpf.ALUOpConstant{}: true, bpf.ALUOpX{}: true, bpf.Jump{}: false, bpf.JumpIf{}: true, bpf.JumpIfX{}: true, bpf.LoadAbsolute{}: false, bpf.LoadConstant{Dst: bpf.RegA}: false, bpf.LoadConstant{Dst: bpf.RegX}: false, bpf.LoadExtension{}: false, bpf.LoadIndirect{}: false, bpf.LoadMemShift{}: false, bpf.LoadScratch{Dst: bpf.RegA}: false, bpf.LoadScratch{Dst: bpf.RegX}: false, bpf.NegateA{}: true, bpf.RetA{}: true, bpf.RetConstant{}: false, bpf.StoreScratch{Src: bpf.RegA}: true, bpf.StoreScratch{Src: bpf.RegX}: false, bpf.TAX{}: true, bpf.TXA{}: false, }, func(insn bpf.Instruction) bool { return memReads(insn).regs[bpf.RegA] }) } func TestInstructionWritesRegA(t *testing.T) { checkMemoryStatus(t, map[bpf.Instruction]bool{ bpf.ALUOpConstant{}: true, bpf.ALUOpX{}: true, bpf.Jump{}: false, bpf.JumpIf{}: false, bpf.JumpIfX{}: false, bpf.LoadAbsolute{}: true, bpf.LoadConstant{Dst: bpf.RegA}: true, bpf.LoadConstant{Dst: bpf.RegX}: false, bpf.LoadExtension{}: true, bpf.LoadIndirect{}: true, bpf.LoadMemShift{}: false, bpf.LoadScratch{Dst: bpf.RegA}: true, bpf.LoadScratch{Dst: bpf.RegX}: false, bpf.NegateA{}: true, bpf.RetA{}: false, bpf.RetConstant{}: false, bpf.StoreScratch{Src: bpf.RegA}: false, bpf.StoreScratch{Src: bpf.RegX}: false, bpf.TAX{}: false, bpf.TXA{}: true, }, func(insn bpf.Instruction) bool { return memWrites(insn).regs[bpf.RegA] }) } func TestInstructionReadsRegX(t *testing.T) { checkMemoryStatus(t, map[bpf.Instruction]bool{ bpf.ALUOpConstant{}: false, bpf.ALUOpX{}: true, bpf.Jump{}: false, bpf.JumpIf{}: false, bpf.JumpIfX{}: true, bpf.LoadAbsolute{}: false, bpf.LoadConstant{Dst: bpf.RegA}: false, bpf.LoadConstant{Dst: bpf.RegX}: false, bpf.LoadExtension{}: false, bpf.LoadIndirect{}: true, bpf.LoadMemShift{}: false, bpf.LoadScratch{Dst: bpf.RegA}: false, bpf.LoadScratch{Dst: bpf.RegX}: false, bpf.NegateA{}: false, bpf.RetA{}: false, bpf.RetConstant{}: false, bpf.StoreScratch{Src: bpf.RegA}: false, bpf.StoreScratch{Src: bpf.RegX}: true, bpf.TAX{}: false, bpf.TXA{}: true, }, func(insn bpf.Instruction) bool { return memReads(insn).regs[bpf.RegX] }) } func TestInstructionWritesRegX(t *testing.T) { checkMemoryStatus(t, map[bpf.Instruction]bool{ bpf.ALUOpConstant{}: false, bpf.ALUOpX{}: false, bpf.Jump{}: false, bpf.JumpIf{}: false, bpf.JumpIfX{}: false, bpf.LoadAbsolute{}: false, bpf.LoadConstant{Dst: bpf.RegA}: false, bpf.LoadConstant{Dst: bpf.RegX}: true, bpf.LoadExtension{}: false, bpf.LoadIndirect{}: false, bpf.LoadMemShift{}: true, bpf.LoadScratch{Dst: bpf.RegA}: false, bpf.LoadScratch{Dst: bpf.RegX}: true, bpf.NegateA{}: false, bpf.RetA{}: false, bpf.RetConstant{}: false, bpf.StoreScratch{Src: bpf.RegA}: false, bpf.StoreScratch{Src: bpf.RegX}: false, bpf.TAX{}: true, bpf.TXA{}: false, }, func(insn bpf.Instruction) bool { return memWrites(insn).regs[bpf.RegX] }) } func TestInstructionReadsScratch(t *testing.T) { checkMemoryStatus(t, map[bpf.Instruction]bool{ bpf.ALUOpConstant{}: false, bpf.ALUOpX{}: false, bpf.Jump{}: false, bpf.JumpIf{}: false, bpf.JumpIfX{}: false, bpf.LoadAbsolute{}: false, bpf.LoadConstant{Dst: bpf.RegA}: false, bpf.LoadConstant{Dst: bpf.RegX}: false, bpf.LoadExtension{}: false, bpf.LoadIndirect{}: false, bpf.LoadMemShift{}: false, bpf.LoadScratch{Dst: bpf.RegA, N: 3}: true, bpf.LoadScratch{Dst: bpf.RegX, N: 3}: true, bpf.NegateA{}: false, bpf.RetA{}: false, bpf.RetConstant{}: false, bpf.StoreScratch{Src: bpf.RegA, N: 3}: false, bpf.StoreScratch{Src: bpf.RegX, N: 3}: false, bpf.TAX{}: false, bpf.TXA{}: false, }, func(insn bpf.Instruction) bool { return memReads(insn).scratch[3] }) } func TestInstructionWritesScratch(t *testing.T) { checkMemoryStatus(t, map[bpf.Instruction]bool{ bpf.ALUOpConstant{}: false, bpf.ALUOpX{}: false, bpf.Jump{}: false, bpf.JumpIf{}: false, bpf.JumpIfX{}: false, bpf.LoadAbsolute{}: false, bpf.LoadConstant{Dst: bpf.RegA}: false, bpf.LoadConstant{Dst: bpf.RegX}: false, bpf.LoadExtension{}: false, bpf.LoadIndirect{}: false, bpf.LoadMemShift{}: false, bpf.LoadScratch{Dst: bpf.RegA, N: 3}: false, bpf.LoadScratch{Dst: bpf.RegX, N: 3}: false, bpf.NegateA{}: false, bpf.RetA{}: false, bpf.RetConstant{}: false, bpf.StoreScratch{Src: bpf.RegA, N: 3}: true, bpf.StoreScratch{Src: bpf.RegX, N: 3}: true, bpf.TAX{}: false, bpf.TXA{}: false, }, func(insn bpf.Instruction) bool { return memWrites(insn).scratch[3] }) } func checkMemoryStatus(t *testing.T, expected map[bpf.Instruction]bool, test func(bpf.Instruction) bool) { t.Helper() for insn, value := range expected { if test(insn) != value { t.Fatalf("Instruction %v expected %v got %v", insn, value, test(insn)) } } } func TestUninitializedReg(t *testing.T) { insns := toInstructions([]bpf.Instruction{ bpf.RetA{}, }) blocks := mustSplitBlocks(t, 1, insns) err := initializeMemory(blocks) if err != nil { t.Fatal(err) } matchBlock(t, blocks[0], join( []instruction{{Instruction: bpf.LoadConstant{Dst: bpf.RegA, Val: 0}}}, insns, ), nil) } func TestPartiallyUninitializedReg(t *testing.T) { insns := toInstructions([]bpf.Instruction{ bpf.LoadConstant{Dst: bpf.RegA, Val: 3}, bpf.JumpIf{Cond: bpf.JumpEqual, Val: 3, SkipTrue: 0, SkipFalse: 1}, bpf.TAX{}, bpf.TXA{}, bpf.RetA{}, }) blocks := mustSplitBlocks(t, 3, insns) err := initializeMemory(blocks) if err != nil { t.Fatal(err) } matchBlock(t, blocks[0], join( []instruction{{Instruction: bpf.LoadConstant{Dst: bpf.RegX, Val: 0}}}, insns[:2], ), nil) matchBlock(t, blocks[1], insns[2:3], nil) matchBlock(t, blocks[2], insns[3:], nil) } func TestUninitializedScratch(t *testing.T) { insns := toInstructions([]bpf.Instruction{ bpf.LoadScratch{Dst: bpf.RegA, N: 2}, bpf.RetA{}, }) blocks := mustSplitBlocks(t, 1, insns) requireError(t, initializeMemory(blocks), "instruction 0: ld M[2] reads potentially uninitialized scratch register M[2]") } func TestPartiallyUninitializedScratch(t *testing.T) { insns := toInstructions([]bpf.Instruction{ bpf.LoadConstant{Dst: bpf.RegA, Val: 3}, bpf.JumpIf{Cond: bpf.JumpEqual, Val: 3, SkipTrue: 0, SkipFalse: 1}, bpf.StoreScratch{Src: bpf.RegA, N: 5}, bpf.LoadScratch{Dst: bpf.RegA, N: 5}, bpf.RetA{}, }) blocks := mustSplitBlocks(t, 3, insns) requireError(t, initializeMemory(blocks), "instruction 3: ld M[5] reads potentially uninitialized scratch register M[5]") } func TestBlocksJump(t *testing.T) { insns := toInstructions([]bpf.Instruction{ bpf.LoadConstant{Dst: bpf.RegX, Val: 3}, bpf.Jump{Skip: 1}, bpf.RetConstant{Val: 0}, bpf.RetConstant{Val: 1}, }) blocks := mustSplitBlocks(t, 2, insns) matchBlock(t, blocks[0], insns[:2], map[pos]*block{3: blocks[1]}) matchBlock(t, blocks[1], insns[3:], map[pos]*block{}) } func TestBlocksJumpIf(t *testing.T) { insns := toInstructions([]bpf.Instruction{ bpf.LoadConstant{Dst: bpf.RegA, Val: 0}, bpf.JumpIf{Cond: bpf.JumpEqual, Val: 3, SkipTrue: 1, SkipFalse: 0}, bpf.RetConstant{Val: 0}, bpf.RetConstant{Val: 1}, }) blocks := mustSplitBlocks(t, 3, insns) matchBlock(t, blocks[0], insns[0:2], map[pos]*block{2: blocks[1], 3: blocks[2]}) matchBlock(t, blocks[1], insns[2:3], map[pos]*block{}) matchBlock(t, blocks[2], insns[3:4], map[pos]*block{}) } func TestBlocksJumpIfX(t *testing.T) { insns := toInstructions([]bpf.Instruction{ bpf.LoadConstant{Dst: bpf.RegA, Val: 0}, bpf.LoadConstant{Dst: bpf.RegX, Val: 3}, bpf.JumpIfX{Cond: bpf.JumpEqual, SkipTrue: 1, SkipFalse: 0}, bpf.RetConstant{Val: 0}, bpf.RetConstant{Val: 1}, }) blocks := mustSplitBlocks(t, 3, insns) matchBlock(t, blocks[0], insns[0:3], map[pos]*block{3: blocks[1], 4: blocks[2]}) matchBlock(t, blocks[1], insns[3:4], map[pos]*block{}) matchBlock(t, blocks[2], insns[4:5], map[pos]*block{}) } func TestDivisionByZeroImm(t *testing.T) { test := func(t *testing.T, op bpf.ALUOp) { t.Helper() blocks := mustSplitBlocks(t, 1, toInstructions([]bpf.Instruction{ bpf.ALUOpConstant{Op: op, Val: 0}, bpf.RetConstant{}, })) requireError(t, addDivideByZeroGuards(blocks), "divides by 0") } test(t, bpf.ALUOpDiv) test(t, bpf.ALUOpMod) } func TestDivisionByZeroX(t *testing.T) { test := func(t *testing.T, op bpf.ALUOp) { t.Helper() insns := toInstructions([]bpf.Instruction{ bpf.LoadAbsolute{Size: 1, Off: 0}, bpf.TXA{}, bpf.ALUOpX{Op: op}, bpf.RetConstant{}, }) blocks := mustSplitBlocks(t, 1, insns) err := addDivideByZeroGuards(blocks) if err != nil { t.Fatal(err) } matchBlock(t, blocks[0], join( insns[:2], []instruction{{Instruction: checkXNotZero{}}}, insns[2:], ), nil) } test(t, bpf.ALUOpDiv) test(t, bpf.ALUOpMod) } func TestDivisionByZeroXTwice(t *testing.T) { test := func(t *testing.T, op bpf.ALUOp) { t.Helper() insns := toInstructions([]bpf.Instruction{ bpf.LoadAbsolute{Size: 1, Off: 0}, bpf.TXA{}, bpf.ALUOpX{Op: op}, bpf.ALUOpX{Op: op}, bpf.RetConstant{}, }) blocks := mustSplitBlocks(t, 1, insns) err := addDivideByZeroGuards(blocks) if err != nil { t.Fatal(err) } matchBlock(t, blocks[0], join( insns[:2], []instruction{{Instruction: checkXNotZero{}}}, insns[2:], ), nil) } test(t, bpf.ALUOpDiv) test(t, bpf.ALUOpMod) } func TestDivisionByZeroXConstant(t *testing.T) { test := func(t *testing.T, op bpf.ALUOp) { t.Helper() insns := toInstructions([]bpf.Instruction{ bpf.LoadAbsolute{Size: 1, Off: 0}, bpf.TXA{}, bpf.ALUOpX{Op: op}, bpf.LoadConstant{Dst: bpf.RegX}, bpf.ALUOpX{Op: op}, bpf.RetConstant{}, }) blocks := mustSplitBlocks(t, 1, insns) err := addDivideByZeroGuards(blocks) if err != nil { t.Fatal(err) } matchBlock(t, blocks[0], join( insns[:2], []instruction{{Instruction: checkXNotZero{}}}, insns[2:4], []instruction{{Instruction: checkXNotZero{}}}, insns[4:], ), nil) } test(t, bpf.ALUOpDiv) test(t, bpf.ALUOpMod) } func TestDivisionByZeroXMemShift(t *testing.T) { test := func(t *testing.T, op bpf.ALUOp) { t.Helper() insns := toInstructions([]bpf.Instruction{ bpf.LoadAbsolute{Size: 1, Off: 0}, bpf.TXA{}, bpf.ALUOpX{Op: op}, bpf.LoadMemShift{Off: 2}, bpf.ALUOpX{Op: op}, bpf.RetConstant{}, }) blocks := mustSplitBlocks(t, 1, insns) err := addDivideByZeroGuards(blocks) if err != nil { t.Fatal(err) } matchBlock(t, blocks[0], join( insns[:2], []instruction{{Instruction: checkXNotZero{}}}, insns[2:4], []instruction{{Instruction: checkXNotZero{}}}, insns[4:], ), nil) } test(t, bpf.ALUOpDiv) test(t, bpf.ALUOpMod) } func TestDivisionByZeroXTXA(t *testing.T) { test := func(t *testing.T, op bpf.ALUOp) { t.Helper() insns := toInstructions([]bpf.Instruction{ bpf.LoadAbsolute{Size: 1, Off: 0}, bpf.TXA{}, bpf.ALUOpX{Op: op}, bpf.TAX{}, bpf.ALUOpX{Op: op}, bpf.RetConstant{}, }) blocks := mustSplitBlocks(t, 1, insns) err := addDivideByZeroGuards(blocks) if err != nil { t.Fatal(err) } matchBlock(t, blocks[0], join( insns[:2], []instruction{{Instruction: checkXNotZero{}}}, insns[2:4], []instruction{{Instruction: checkXNotZero{}}}, insns[4:], ), nil) } test(t, bpf.ALUOpDiv) test(t, bpf.ALUOpMod) } func TestDivisionByZeroParentsOK(t *testing.T) { test := func(t *testing.T, op bpf.ALUOp) { t.Helper() insns := toInstructions([]bpf.Instruction{ bpf.LoadAbsolute{Size: 1, Off: 0}, bpf.TXA{}, bpf.ALUOpX{Op: op}, bpf.JumpIf{Cond: bpf.JumpEqual, Val: 3, SkipTrue: 0, SkipFalse: 2}, bpf.LoadAbsolute{Size: 1, Off: 1}, bpf.Jump{Skip: 1}, bpf.LoadAbsolute{Size: 1, Off: 2}, bpf.ALUOpX{Op: op}, bpf.RetConstant{}, }) blocks := mustSplitBlocks(t, 4, insns) err := addDivideByZeroGuards(blocks) if err != nil { t.Fatal(err) } matchBlock(t, blocks[0], join( insns[:2], []instruction{{Instruction: checkXNotZero{}}}, insns[2:4], ), nil) matchBlock(t, blocks[1], insns[4:6], nil) matchBlock(t, blocks[2], insns[6:7], nil) matchBlock(t, blocks[3], insns[7:], nil) } test(t, bpf.ALUOpDiv) test(t, bpf.ALUOpMod) } func TestDivisionByZeroParentsNOK(t *testing.T) { test := func(t *testing.T, op bpf.ALUOp) { t.Helper() insns := toInstructions([]bpf.Instruction{ bpf.LoadAbsolute{Size: 1, Off: 0}, bpf.TXA{}, bpf.ALUOpX{Op: op}, bpf.JumpIf{Cond: bpf.JumpEqual, Val: 3, SkipTrue: 0, SkipFalse: 2}, bpf.LoadMemShift{Off: 1}, bpf.Jump{Skip: 1}, bpf.LoadAbsolute{Size: 1, Off: 2}, bpf.ALUOpX{Op: op}, bpf.RetConstant{}, }) blocks := mustSplitBlocks(t, 4, insns) err := addDivideByZeroGuards(blocks) if err != nil { t.Fatal(err) } matchBlock(t, blocks[0], join( insns[:2], []instruction{{Instruction: checkXNotZero{}}}, insns[2:4], ), nil) matchBlock(t, blocks[1], insns[4:6], nil) matchBlock(t, blocks[2], insns[6:7], nil) matchBlock(t, blocks[3], join( []instruction{{Instruction: checkXNotZero{}}}, insns[7:], ), nil) } test(t, bpf.ALUOpDiv) test(t, bpf.ALUOpMod) } func TestAbsoluteGuardSize(t *testing.T) { insns := toInstructions([]bpf.Instruction{ bpf.LoadAbsolute{Size: 4, Off: 10}, bpf.LoadAbsolute{Size: 1, Off: 10}, bpf.RetConstant{}, }) blocks := mustSplitBlocks(t, 1, insns) addAbsolutePacketGuards(blocks) matchBlock(t, blocks[0], join( []instruction{{Instruction: packetGuardAbsolute{guard: 14}}}, insns, ), nil) } func TestNoAbsoluteGuard(t *testing.T) { insns := toInstructions([]bpf.Instruction{ bpf.LoadConstant{Dst: bpf.RegA, Val: 23}, bpf.RetA{}, }) blocks := mustSplitBlocks(t, 1, insns) addAbsolutePacketGuards(blocks) matchBlock(t, blocks[0], insns, nil) } func TestAbsoluteGuardParentsOK(t *testing.T) { insns := toInstructions([]bpf.Instruction{ bpf.LoadAbsolute{Size: 4, Off: 10}, bpf.JumpIf{Cond: bpf.JumpEqual, Val: 3, SkipTrue: 0, SkipFalse: 2}, bpf.LoadAbsolute{Size: 4, Off: 10}, bpf.Jump{Skip: 1}, bpf.LoadAbsolute{Size: 2, Off: 8}, bpf.LoadAbsolute{Size: 1, Off: 9}, bpf.RetA{}, }) blocks := mustSplitBlocks(t, 4, insns) addAbsolutePacketGuards(blocks) matchBlock(t, blocks[0], join( []instruction{{Instruction: packetGuardAbsolute{guard: 14}}}, insns[:2], ), nil) matchBlock(t, blocks[1], insns[2:4], nil) matchBlock(t, blocks[2], insns[4:5], nil) matchBlock(t, blocks[3], insns[5:], nil) } func TestAbsoluteGuardParentNoMatch(t *testing.T) { insns := toInstructions([]bpf.Instruction{ bpf.LoadAbsolute{Size: 4, Off: 10}, bpf.JumpIf{Cond: bpf.JumpEqual, Val: 3, SkipTrue: 0, SkipFalse: 3}, bpf.LoadAbsolute{Size: 4, Off: 12}, bpf.JumpIf{Cond: bpf.JumpEqual, Val: 3, SkipTrue: 0, SkipFalse: 1}, bpf.RetA{}, bpf.RetConstant{}, }) blocks := mustSplitBlocks(t, 4, insns) addAbsolutePacketGuards(blocks) matchBlock(t, blocks[0], join( []instruction{{Instruction: packetGuardAbsolute{guard: 16}}}, insns[:2], ), nil) matchBlock(t, blocks[1], insns[2:4], nil) matchBlock(t, blocks[2], insns[4:5], nil) matchBlock(t, blocks[3], insns[5:], nil) } func TestAbsoluteGuardParentDeepNoMatch(t *testing.T) { insns := toInstructions([]bpf.Instruction{ bpf.LoadAbsolute{Size: 4, Off: 10}, bpf.JumpIf{Cond: bpf.JumpEqual, Val: 3, SkipTrue: 0, SkipFalse: 5}, bpf.LoadAbsolute{Size: 4, Off: 12}, bpf.JumpIf{Cond: bpf.JumpEqual, Val: 3, SkipTrue: 0, SkipFalse: 3}, bpf.LoadAbsolute{Size: 4, Off: 14}, bpf.JumpIf{Cond: bpf.JumpEqual, Val: 3, SkipTrue: 0, SkipFalse: 1}, bpf.RetA{}, bpf.RetConstant{}, }) blocks := mustSplitBlocks(t, 5, insns) addAbsolutePacketGuards(blocks) matchBlock(t, blocks[0], join( []instruction{{Instruction: packetGuardAbsolute{guard: 18}}}, insns[:2], ), nil) matchBlock(t, blocks[1], insns[2:4], nil) matchBlock(t, blocks[2], insns[4:6], nil) matchBlock(t, blocks[3], insns[6:7], nil) matchBlock(t, blocks[4], insns[7:], nil) } func TestAbsoluteGuardParentMatch(t *testing.T) { insns := toInstructions([]bpf.Instruction{ bpf.LoadAbsolute{Size: 4, Off: 10}, bpf.JumpIf{Cond: bpf.JumpEqual, Val: 3, SkipTrue: 0, SkipFalse: 2}, bpf.LoadAbsolute{Size: 4, Off: 11}, bpf.RetA{}, bpf.LoadAbsolute{Size: 1, Off: 15}, bpf.RetConstant{}, }) blocks := mustSplitBlocks(t, 3, insns) addAbsolutePacketGuards(blocks) matchBlock(t, blocks[0], join( []instruction{{Instruction: packetGuardAbsolute{guard: 15}}}, insns[:2], ), nil) matchBlock(t, blocks[1], insns[2:4], nil) matchBlock(t, blocks[2], join( []instruction{{Instruction: packetGuardAbsolute{guard: 16}}}, insns[4:], ), nil) } func TestIndirectGuardSize(t *testing.T) { insns := toInstructions([]bpf.Instruction{ bpf.LoadIndirect{Size: 4, Off: 10}, bpf.LoadIndirect{Size: 1, Off: 10}, bpf.RetConstant{}, }) blocks := mustSplitBlocks(t, 1, insns) addIndirectPacketGuards(blocks) matchBlock(t, blocks[0], join( []instruction{{Instruction: packetGuardIndirect{guard: 14}}}, insns, ), nil) }
BSD 3-Clause New or Revised License
linki/mate
vendor/google.golang.org/api/dns/v1/dns-gen.go
Do
go
func (c *ChangesCreateCall) Do(opts ...googleapi.CallOption) (*Change, error) { gensupport.SetOptions(c.urlParams_, opts...) res, err := c.doRequest("json") if res != nil && res.StatusCode == http.StatusNotModified { if res.Body != nil { res.Body.Close() } return nil, &googleapi.Error{ Code: res.StatusCode, Header: res.Header, } } if err != nil { return nil, err } defer googleapi.CloseBody(res) if err := googleapi.CheckResponse(res); err != nil { return nil, err } ret := &Change{ ServerResponse: googleapi.ServerResponse{ Header: res.Header, HTTPStatusCode: res.StatusCode, }, } target := &ret if err := json.NewDecoder(res.Body).Decode(target); err != nil { return nil, err } return ret, nil }
Do executes the "dns.changes.create" call. Exactly one of *Change or error will be non-nil. Any non-2xx status code is an error. Response headers are in either *Change.ServerResponse.Header or (if a response was returned at all) in error.(*googleapi.Error).Header. Use googleapi.IsNotModified to check whether the returned error was because http.StatusNotModified was returned.
https://github.com/linki/mate/blob/848c39ec72b8cfe26b38cc62a6b1286c8b868f51/vendor/google.golang.org/api/dns/v1/dns-gen.go#L616-L681
package dns import ( "bytes" "encoding/json" "errors" "fmt" context "golang.org/x/net/context" ctxhttp "golang.org/x/net/context/ctxhttp" gensupport "google.golang.org/api/gensupport" googleapi "google.golang.org/api/googleapi" "io" "net/http" "net/url" "strconv" "strings" ) var _ = bytes.NewBuffer var _ = strconv.Itoa var _ = fmt.Sprintf var _ = json.NewDecoder var _ = io.Copy var _ = url.Parse var _ = gensupport.MarshalJSON var _ = googleapi.Version var _ = errors.New var _ = strings.Replace var _ = context.Canceled var _ = ctxhttp.Do const apiId = "dns:v1" const apiName = "dns" const apiVersion = "v1" const basePath = "https://www.googleapis.com/dns/v1/projects/" const ( CloudPlatformScope = "https://www.googleapis.com/auth/cloud-platform" CloudPlatformReadOnlyScope = "https://www.googleapis.com/auth/cloud-platform.read-only" NdevClouddnsReadonlyScope = "https://www.googleapis.com/auth/ndev.clouddns.readonly" NdevClouddnsReadwriteScope = "https://www.googleapis.com/auth/ndev.clouddns.readwrite" ) func New(client *http.Client) (*Service, error) { if client == nil { return nil, errors.New("client is nil") } s := &Service{client: client, BasePath: basePath} s.Changes = NewChangesService(s) s.ManagedZones = NewManagedZonesService(s) s.Projects = NewProjectsService(s) s.ResourceRecordSets = NewResourceRecordSetsService(s) return s, nil } type Service struct { client *http.Client BasePath string UserAgent string Changes *ChangesService ManagedZones *ManagedZonesService Projects *ProjectsService ResourceRecordSets *ResourceRecordSetsService } func (s *Service) userAgent() string { if s.UserAgent == "" { return googleapi.UserAgent } return googleapi.UserAgent + " " + s.UserAgent } func NewChangesService(s *Service) *ChangesService { rs := &ChangesService{s: s} return rs } type ChangesService struct { s *Service } func NewManagedZonesService(s *Service) *ManagedZonesService { rs := &ManagedZonesService{s: s} return rs } type ManagedZonesService struct { s *Service } func NewProjectsService(s *Service) *ProjectsService { rs := &ProjectsService{s: s} return rs } type ProjectsService struct { s *Service } func NewResourceRecordSetsService(s *Service) *ResourceRecordSetsService { rs := &ResourceRecordSetsService{s: s} return rs } type ResourceRecordSetsService struct { s *Service } type Change struct { Additions []*ResourceRecordSet `json:"additions,omitempty"` Deletions []*ResourceRecordSet `json:"deletions,omitempty"` Id string `json:"id,omitempty"` Kind string `json:"kind,omitempty"` StartTime string `json:"startTime,omitempty"` Status string `json:"status,omitempty"` googleapi.ServerResponse `json:"-"` ForceSendFields []string `json:"-"` NullFields []string `json:"-"` } func (s *Change) MarshalJSON() ([]byte, error) { type noMethod Change raw := noMethod(*s) return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) } type ChangesListResponse struct { Changes []*Change `json:"changes,omitempty"` Kind string `json:"kind,omitempty"` NextPageToken string `json:"nextPageToken,omitempty"` googleapi.ServerResponse `json:"-"` ForceSendFields []string `json:"-"` NullFields []string `json:"-"` } func (s *ChangesListResponse) MarshalJSON() ([]byte, error) { type noMethod ChangesListResponse raw := noMethod(*s) return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) } type ManagedZone struct { CreationTime string `json:"creationTime,omitempty"` Description string `json:"description,omitempty"` DnsName string `json:"dnsName,omitempty"` Id uint64 `json:"id,omitempty,string"` Kind string `json:"kind,omitempty"` Name string `json:"name,omitempty"` NameServerSet string `json:"nameServerSet,omitempty"` NameServers []string `json:"nameServers,omitempty"` googleapi.ServerResponse `json:"-"` ForceSendFields []string `json:"-"` NullFields []string `json:"-"` } func (s *ManagedZone) MarshalJSON() ([]byte, error) { type noMethod ManagedZone raw := noMethod(*s) return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) } type ManagedZonesListResponse struct { Kind string `json:"kind,omitempty"` ManagedZones []*ManagedZone `json:"managedZones,omitempty"` NextPageToken string `json:"nextPageToken,omitempty"` googleapi.ServerResponse `json:"-"` ForceSendFields []string `json:"-"` NullFields []string `json:"-"` } func (s *ManagedZonesListResponse) MarshalJSON() ([]byte, error) { type noMethod ManagedZonesListResponse raw := noMethod(*s) return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) } type Project struct { Id string `json:"id,omitempty"` Kind string `json:"kind,omitempty"` Number uint64 `json:"number,omitempty,string"` Quota *Quota `json:"quota,omitempty"` googleapi.ServerResponse `json:"-"` ForceSendFields []string `json:"-"` NullFields []string `json:"-"` } func (s *Project) MarshalJSON() ([]byte, error) { type noMethod Project raw := noMethod(*s) return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) } type Quota struct { Kind string `json:"kind,omitempty"` ManagedZones int64 `json:"managedZones,omitempty"` ResourceRecordsPerRrset int64 `json:"resourceRecordsPerRrset,omitempty"` RrsetAdditionsPerChange int64 `json:"rrsetAdditionsPerChange,omitempty"` RrsetDeletionsPerChange int64 `json:"rrsetDeletionsPerChange,omitempty"` RrsetsPerManagedZone int64 `json:"rrsetsPerManagedZone,omitempty"` TotalRrdataSizePerChange int64 `json:"totalRrdataSizePerChange,omitempty"` ForceSendFields []string `json:"-"` NullFields []string `json:"-"` } func (s *Quota) MarshalJSON() ([]byte, error) { type noMethod Quota raw := noMethod(*s) return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) } type ResourceRecordSet struct { Kind string `json:"kind,omitempty"` Name string `json:"name,omitempty"` Rrdatas []string `json:"rrdatas,omitempty"` Ttl int64 `json:"ttl,omitempty"` Type string `json:"type,omitempty"` ForceSendFields []string `json:"-"` NullFields []string `json:"-"` } func (s *ResourceRecordSet) MarshalJSON() ([]byte, error) { type noMethod ResourceRecordSet raw := noMethod(*s) return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) } type ResourceRecordSetsListResponse struct { Kind string `json:"kind,omitempty"` NextPageToken string `json:"nextPageToken,omitempty"` Rrsets []*ResourceRecordSet `json:"rrsets,omitempty"` googleapi.ServerResponse `json:"-"` ForceSendFields []string `json:"-"` NullFields []string `json:"-"` } func (s *ResourceRecordSetsListResponse) MarshalJSON() ([]byte, error) { type noMethod ResourceRecordSetsListResponse raw := noMethod(*s) return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) } type ChangesCreateCall struct { s *Service project string managedZone string change *Change urlParams_ gensupport.URLParams ctx_ context.Context header_ http.Header } func (r *ChangesService) Create(project string, managedZone string, change *Change) *ChangesCreateCall { c := &ChangesCreateCall{s: r.s, urlParams_: make(gensupport.URLParams)} c.project = project c.managedZone = managedZone c.change = change return c } func (c *ChangesCreateCall) Fields(s ...googleapi.Field) *ChangesCreateCall { c.urlParams_.Set("fields", googleapi.CombineFields(s)) return c } func (c *ChangesCreateCall) Context(ctx context.Context) *ChangesCreateCall { c.ctx_ = ctx return c } func (c *ChangesCreateCall) Header() http.Header { if c.header_ == nil { c.header_ = make(http.Header) } return c.header_ } func (c *ChangesCreateCall) doRequest(alt string) (*http.Response, error) { reqHeaders := make(http.Header) for k, v := range c.header_ { reqHeaders[k] = v } reqHeaders.Set("User-Agent", c.s.userAgent()) var body io.Reader = nil body, err := googleapi.WithoutDataWrapper.JSONReader(c.change) if err != nil { return nil, err } reqHeaders.Set("Content-Type", "application/json") c.urlParams_.Set("alt", alt) urls := googleapi.ResolveRelative(c.s.BasePath, "{project}/managedZones/{managedZone}/changes") urls += "?" + c.urlParams_.Encode() req, _ := http.NewRequest("POST", urls, body) req.Header = reqHeaders googleapi.Expand(req.URL, map[string]string{ "project": c.project, "managedZone": c.managedZone, }) return gensupport.SendRequest(c.ctx_, c.s.client, req) }
MIT License
monaco-io/request
request/request.go
PATCH
go
func (r *Request) PATCH(url string) *Request { return r. use(Method{Data: "PATCH"}). use(URL{Data: url}) }
PATCH use PATCH method and http url
https://github.com/monaco-io/request/blob/724b00dafdac538d5fa8d4773503173a67518ade/request/request.go#L92-L96
package request import ( originContext "context" "crypto/tls" "net/http" "github.com/monaco-io/request/context" "github.com/monaco-io/request/response" ) type Request struct { ctx *context.Context } func (r *Request) use(p Plugin) *Request { p.Apply(r.Ctx()) return r } func New() *Request { return &Request{ctx: context.New()} } func NewWithContext(ctx originContext.Context) *Request { return &Request{ctx: context.NewWithContext(ctx)} } func (r *Request) Error() error { return r.ctx.Error() } func (r *Request) Ctx() *context.Context { return r.ctx } func (r *Request) POST(url string) *Request { return r. use(Method{Data: "POST"}). use(URL{Data: url}) } func (r *Request) GET(url string) *Request { return r. use(Method{Data: "GET"}). use(URL{Data: url}) } func (r *Request) PUT(url string) *Request { return r. use(Method{Data: "PUT"}). use(URL{Data: url}) } func (r *Request) DELETE(url string) *Request { return r. use(Method{Data: "DELETE"}). use(URL{Data: url}) } func (r *Request) OPTIONS(url string) *Request { return r. use(Method{Data: "OPTIONS"}). use(URL{Data: url}) } func (r *Request) HEAD(url string) *Request { return r. use(Method{Data: "HEAD"}). use(URL{Data: url}) } func (r *Request) TRACE(url string) *Request { return r. use(Method{Data: "TRACE"}). use(URL{Data: url}) }
MIT License
goadesign/goa-cellar
app/controllers.go
MountPublicController
go
func MountPublicController(service *goa.Service, ctrl PublicController) { initService(service) var h goa.Handler service.Mux.Handle("OPTIONS", "/ui", ctrl.MuxHandler("preflight", handlePublicOrigin(cors.HandlePreflight()), nil)) h = ctrl.FileHandler("/ui", "public/html/index.html") h = handlePublicOrigin(h) service.Mux.Handle("GET", "/ui", ctrl.MuxHandler("serve", h, nil)) service.LogInfo("mount", "ctrl", "Public", "files", "public/html/index.html", "route", "GET /ui") }
MountPublicController "mounts" a Public resource controller on the given service.
https://github.com/goadesign/goa-cellar/blob/88979d5a1ca553aae0e62797eef31108d9302bfa/app/controllers.go#L545-L554
package app import ( "context" "github.com/goadesign/goa" "github.com/goadesign/goa/cors" "net/http" ) func initService(service *goa.Service) { service.Encoder.Register(goa.NewJSONEncoder, "application/json") service.Encoder.Register(goa.NewGobEncoder, "application/gob", "application/x-gob") service.Encoder.Register(goa.NewXMLEncoder, "application/xml") service.Decoder.Register(goa.NewJSONDecoder, "application/json") service.Decoder.Register(goa.NewGobDecoder, "application/gob", "application/x-gob") service.Decoder.Register(goa.NewXMLDecoder, "application/xml") service.Encoder.Register(goa.NewJSONEncoder, "*/*") service.Decoder.Register(goa.NewJSONDecoder, "*/*") } type AccountController interface { goa.Muxer Create(*CreateAccountContext) error Delete(*DeleteAccountContext) error List(*ListAccountContext) error Show(*ShowAccountContext) error Update(*UpdateAccountContext) error } func MountAccountController(service *goa.Service, ctrl AccountController) { initService(service) var h goa.Handler service.Mux.Handle("OPTIONS", "/cellar/accounts", ctrl.MuxHandler("preflight", handleAccountOrigin(cors.HandlePreflight()), nil)) service.Mux.Handle("OPTIONS", "/cellar/accounts/:accountID", ctrl.MuxHandler("preflight", handleAccountOrigin(cors.HandlePreflight()), nil)) h = func(ctx context.Context, rw http.ResponseWriter, req *http.Request) error { if err := goa.ContextError(ctx); err != nil { return err } rctx, err := NewCreateAccountContext(ctx, req, service) if err != nil { return err } if rawPayload := goa.ContextRequest(ctx).Payload; rawPayload != nil { rctx.Payload = rawPayload.(*CreateAccountPayload) } else { return goa.MissingPayloadError() } return ctrl.Create(rctx) } h = handleAccountOrigin(h) service.Mux.Handle("POST", "/cellar/accounts", ctrl.MuxHandler("create", h, unmarshalCreateAccountPayload)) service.LogInfo("mount", "ctrl", "Account", "action", "Create", "route", "POST /cellar/accounts") h = func(ctx context.Context, rw http.ResponseWriter, req *http.Request) error { if err := goa.ContextError(ctx); err != nil { return err } rctx, err := NewDeleteAccountContext(ctx, req, service) if err != nil { return err } return ctrl.Delete(rctx) } h = handleAccountOrigin(h) service.Mux.Handle("DELETE", "/cellar/accounts/:accountID", ctrl.MuxHandler("delete", h, nil)) service.LogInfo("mount", "ctrl", "Account", "action", "Delete", "route", "DELETE /cellar/accounts/:accountID") h = func(ctx context.Context, rw http.ResponseWriter, req *http.Request) error { if err := goa.ContextError(ctx); err != nil { return err } rctx, err := NewListAccountContext(ctx, req, service) if err != nil { return err } return ctrl.List(rctx) } h = handleAccountOrigin(h) service.Mux.Handle("GET", "/cellar/accounts", ctrl.MuxHandler("list", h, nil)) service.LogInfo("mount", "ctrl", "Account", "action", "List", "route", "GET /cellar/accounts") h = func(ctx context.Context, rw http.ResponseWriter, req *http.Request) error { if err := goa.ContextError(ctx); err != nil { return err } rctx, err := NewShowAccountContext(ctx, req, service) if err != nil { return err } return ctrl.Show(rctx) } h = handleAccountOrigin(h) service.Mux.Handle("GET", "/cellar/accounts/:accountID", ctrl.MuxHandler("show", h, nil)) service.LogInfo("mount", "ctrl", "Account", "action", "Show", "route", "GET /cellar/accounts/:accountID") h = func(ctx context.Context, rw http.ResponseWriter, req *http.Request) error { if err := goa.ContextError(ctx); err != nil { return err } rctx, err := NewUpdateAccountContext(ctx, req, service) if err != nil { return err } if rawPayload := goa.ContextRequest(ctx).Payload; rawPayload != nil { rctx.Payload = rawPayload.(*UpdateAccountPayload) } else { return goa.MissingPayloadError() } return ctrl.Update(rctx) } h = handleAccountOrigin(h) service.Mux.Handle("PUT", "/cellar/accounts/:accountID", ctrl.MuxHandler("update", h, unmarshalUpdateAccountPayload)) service.LogInfo("mount", "ctrl", "Account", "action", "Update", "route", "PUT /cellar/accounts/:accountID") } func handleAccountOrigin(h goa.Handler) goa.Handler { return func(ctx context.Context, rw http.ResponseWriter, req *http.Request) error { origin := req.Header.Get("Origin") if origin == "" { return h(ctx, rw, req) } if cors.MatchOrigin(origin, "http://swagger.goa.design") { ctx = goa.WithLogContext(ctx, "origin", origin) rw.Header().Set("Access-Control-Allow-Origin", origin) rw.Header().Set("Vary", "Origin") rw.Header().Set("Access-Control-Max-Age", "600") rw.Header().Set("Access-Control-Allow-Credentials", "true") if acrm := req.Header.Get("Access-Control-Request-Method"); acrm != "" { rw.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, PATCH, DELETE") } return h(ctx, rw, req) } return h(ctx, rw, req) } } func unmarshalCreateAccountPayload(ctx context.Context, service *goa.Service, req *http.Request) error { payload := &createAccountPayload{} if err := service.DecodeRequest(req, payload); err != nil { return err } if err := payload.Validate(); err != nil { goa.ContextRequest(ctx).Payload = payload return err } goa.ContextRequest(ctx).Payload = payload.Publicize() return nil } func unmarshalUpdateAccountPayload(ctx context.Context, service *goa.Service, req *http.Request) error { payload := &updateAccountPayload{} if err := service.DecodeRequest(req, payload); err != nil { return err } if err := payload.Validate(); err != nil { goa.ContextRequest(ctx).Payload = payload return err } goa.ContextRequest(ctx).Payload = payload.Publicize() return nil } type BottleController interface { goa.Muxer Create(*CreateBottleContext) error Delete(*DeleteBottleContext) error List(*ListBottleContext) error Rate(*RateBottleContext) error Show(*ShowBottleContext) error Update(*UpdateBottleContext) error Watch(*WatchBottleContext) error } func MountBottleController(service *goa.Service, ctrl BottleController) { initService(service) var h goa.Handler service.Mux.Handle("OPTIONS", "/cellar/accounts/:accountID/bottles", ctrl.MuxHandler("preflight", handleBottleOrigin(cors.HandlePreflight()), nil)) service.Mux.Handle("OPTIONS", "/cellar/accounts/:accountID/bottles/:bottleID", ctrl.MuxHandler("preflight", handleBottleOrigin(cors.HandlePreflight()), nil)) service.Mux.Handle("OPTIONS", "/cellar/accounts/:accountID/bottles/:bottleID/actions/rate", ctrl.MuxHandler("preflight", handleBottleOrigin(cors.HandlePreflight()), nil)) service.Mux.Handle("OPTIONS", "/cellar/accounts/:accountID/bottles/:bottleID/watch", ctrl.MuxHandler("preflight", handleBottleOrigin(cors.HandlePreflight()), nil)) h = func(ctx context.Context, rw http.ResponseWriter, req *http.Request) error { if err := goa.ContextError(ctx); err != nil { return err } rctx, err := NewCreateBottleContext(ctx, req, service) if err != nil { return err } if rawPayload := goa.ContextRequest(ctx).Payload; rawPayload != nil { rctx.Payload = rawPayload.(*CreateBottlePayload) } else { return goa.MissingPayloadError() } return ctrl.Create(rctx) } h = handleBottleOrigin(h) service.Mux.Handle("POST", "/cellar/accounts/:accountID/bottles", ctrl.MuxHandler("create", h, unmarshalCreateBottlePayload)) service.LogInfo("mount", "ctrl", "Bottle", "action", "Create", "route", "POST /cellar/accounts/:accountID/bottles") h = func(ctx context.Context, rw http.ResponseWriter, req *http.Request) error { if err := goa.ContextError(ctx); err != nil { return err } rctx, err := NewDeleteBottleContext(ctx, req, service) if err != nil { return err } return ctrl.Delete(rctx) } h = handleBottleOrigin(h) service.Mux.Handle("DELETE", "/cellar/accounts/:accountID/bottles/:bottleID", ctrl.MuxHandler("delete", h, nil)) service.LogInfo("mount", "ctrl", "Bottle", "action", "Delete", "route", "DELETE /cellar/accounts/:accountID/bottles/:bottleID") h = func(ctx context.Context, rw http.ResponseWriter, req *http.Request) error { if err := goa.ContextError(ctx); err != nil { return err } rctx, err := NewListBottleContext(ctx, req, service) if err != nil { return err } return ctrl.List(rctx) } h = handleBottleOrigin(h) service.Mux.Handle("GET", "/cellar/accounts/:accountID/bottles", ctrl.MuxHandler("list", h, nil)) service.LogInfo("mount", "ctrl", "Bottle", "action", "List", "route", "GET /cellar/accounts/:accountID/bottles") h = func(ctx context.Context, rw http.ResponseWriter, req *http.Request) error { if err := goa.ContextError(ctx); err != nil { return err } rctx, err := NewRateBottleContext(ctx, req, service) if err != nil { return err } if rawPayload := goa.ContextRequest(ctx).Payload; rawPayload != nil { rctx.Payload = rawPayload.(*RateBottlePayload) } else { return goa.MissingPayloadError() } return ctrl.Rate(rctx) } h = handleBottleOrigin(h) service.Mux.Handle("PUT", "/cellar/accounts/:accountID/bottles/:bottleID/actions/rate", ctrl.MuxHandler("rate", h, unmarshalRateBottlePayload)) service.LogInfo("mount", "ctrl", "Bottle", "action", "Rate", "route", "PUT /cellar/accounts/:accountID/bottles/:bottleID/actions/rate") h = func(ctx context.Context, rw http.ResponseWriter, req *http.Request) error { if err := goa.ContextError(ctx); err != nil { return err } rctx, err := NewShowBottleContext(ctx, req, service) if err != nil { return err } return ctrl.Show(rctx) } h = handleBottleOrigin(h) service.Mux.Handle("GET", "/cellar/accounts/:accountID/bottles/:bottleID", ctrl.MuxHandler("show", h, nil)) service.LogInfo("mount", "ctrl", "Bottle", "action", "Show", "route", "GET /cellar/accounts/:accountID/bottles/:bottleID") h = func(ctx context.Context, rw http.ResponseWriter, req *http.Request) error { if err := goa.ContextError(ctx); err != nil { return err } rctx, err := NewUpdateBottleContext(ctx, req, service) if err != nil { return err } if rawPayload := goa.ContextRequest(ctx).Payload; rawPayload != nil { rctx.Payload = rawPayload.(*BottlePayload) } else { return goa.MissingPayloadError() } return ctrl.Update(rctx) } h = handleBottleOrigin(h) service.Mux.Handle("PATCH", "/cellar/accounts/:accountID/bottles/:bottleID", ctrl.MuxHandler("update", h, unmarshalUpdateBottlePayload)) service.LogInfo("mount", "ctrl", "Bottle", "action", "Update", "route", "PATCH /cellar/accounts/:accountID/bottles/:bottleID") h = func(ctx context.Context, rw http.ResponseWriter, req *http.Request) error { if err := goa.ContextError(ctx); err != nil { return err } rctx, err := NewWatchBottleContext(ctx, req, service) if err != nil { return err } return ctrl.Watch(rctx) } h = handleBottleOrigin(h) service.Mux.Handle("GET", "/cellar/accounts/:accountID/bottles/:bottleID/watch", ctrl.MuxHandler("watch", h, nil)) service.LogInfo("mount", "ctrl", "Bottle", "action", "Watch", "route", "GET /cellar/accounts/:accountID/bottles/:bottleID/watch") } func handleBottleOrigin(h goa.Handler) goa.Handler { return func(ctx context.Context, rw http.ResponseWriter, req *http.Request) error { origin := req.Header.Get("Origin") if origin == "" { return h(ctx, rw, req) } if cors.MatchOrigin(origin, "http://swagger.goa.design") { ctx = goa.WithLogContext(ctx, "origin", origin) rw.Header().Set("Access-Control-Allow-Origin", origin) rw.Header().Set("Vary", "Origin") rw.Header().Set("Access-Control-Max-Age", "600") rw.Header().Set("Access-Control-Allow-Credentials", "true") if acrm := req.Header.Get("Access-Control-Request-Method"); acrm != "" { rw.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, PATCH, DELETE") } return h(ctx, rw, req) } return h(ctx, rw, req) } } func unmarshalCreateBottlePayload(ctx context.Context, service *goa.Service, req *http.Request) error { payload := &createBottlePayload{} if err := service.DecodeRequest(req, payload); err != nil { return err } if err := payload.Validate(); err != nil { goa.ContextRequest(ctx).Payload = payload return err } goa.ContextRequest(ctx).Payload = payload.Publicize() return nil } func unmarshalRateBottlePayload(ctx context.Context, service *goa.Service, req *http.Request) error { payload := &rateBottlePayload{} if err := service.DecodeRequest(req, payload); err != nil { return err } if err := payload.Validate(); err != nil { goa.ContextRequest(ctx).Payload = payload return err } goa.ContextRequest(ctx).Payload = payload.Publicize() return nil } func unmarshalUpdateBottlePayload(ctx context.Context, service *goa.Service, req *http.Request) error { payload := &bottlePayload{} if err := service.DecodeRequest(req, payload); err != nil { return err } if err := payload.Validate(); err != nil { goa.ContextRequest(ctx).Payload = payload return err } goa.ContextRequest(ctx).Payload = payload.Publicize() return nil } type HealthController interface { goa.Muxer Health(*HealthHealthContext) error } func MountHealthController(service *goa.Service, ctrl HealthController) { initService(service) var h goa.Handler service.Mux.Handle("OPTIONS", "/cellar/_ah/health", ctrl.MuxHandler("preflight", handleHealthOrigin(cors.HandlePreflight()), nil)) h = func(ctx context.Context, rw http.ResponseWriter, req *http.Request) error { if err := goa.ContextError(ctx); err != nil { return err } rctx, err := NewHealthHealthContext(ctx, req, service) if err != nil { return err } return ctrl.Health(rctx) } h = handleHealthOrigin(h) service.Mux.Handle("GET", "/cellar/_ah/health", ctrl.MuxHandler("health", h, nil)) service.LogInfo("mount", "ctrl", "Health", "action", "Health", "route", "GET /cellar/_ah/health") } func handleHealthOrigin(h goa.Handler) goa.Handler { return func(ctx context.Context, rw http.ResponseWriter, req *http.Request) error { origin := req.Header.Get("Origin") if origin == "" { return h(ctx, rw, req) } if cors.MatchOrigin(origin, "http://swagger.goa.design") { ctx = goa.WithLogContext(ctx, "origin", origin) rw.Header().Set("Access-Control-Allow-Origin", origin) rw.Header().Set("Vary", "Origin") rw.Header().Set("Access-Control-Max-Age", "600") rw.Header().Set("Access-Control-Allow-Credentials", "true") if acrm := req.Header.Get("Access-Control-Request-Method"); acrm != "" { rw.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, PATCH, DELETE") } return h(ctx, rw, req) } return h(ctx, rw, req) } } type JsController interface { goa.Muxer goa.FileServer } func MountJsController(service *goa.Service, ctrl JsController) { initService(service) var h goa.Handler service.Mux.Handle("OPTIONS", "/js/*filepath", ctrl.MuxHandler("preflight", handleJsOrigin(cors.HandlePreflight()), nil)) h = ctrl.FileHandler("/js/*filepath", "public/js") h = handleJsOrigin(h) service.Mux.Handle("GET", "/js/*filepath", ctrl.MuxHandler("serve", h, nil)) service.LogInfo("mount", "ctrl", "Js", "files", "public/js", "route", "GET /js/*filepath") h = ctrl.FileHandler("/js/", "public/js/index.html") h = handleJsOrigin(h) service.Mux.Handle("GET", "/js/", ctrl.MuxHandler("serve", h, nil)) service.LogInfo("mount", "ctrl", "Js", "files", "public/js/index.html", "route", "GET /js/") } func handleJsOrigin(h goa.Handler) goa.Handler { return func(ctx context.Context, rw http.ResponseWriter, req *http.Request) error { origin := req.Header.Get("Origin") if origin == "" { return h(ctx, rw, req) } if cors.MatchOrigin(origin, "*") { ctx = goa.WithLogContext(ctx, "origin", origin) rw.Header().Set("Access-Control-Allow-Origin", origin) rw.Header().Set("Access-Control-Allow-Credentials", "false") if acrm := req.Header.Get("Access-Control-Request-Method"); acrm != "" { rw.Header().Set("Access-Control-Allow-Methods", "GET, OPTIONS") } return h(ctx, rw, req) } if cors.MatchOrigin(origin, "http://swagger.goa.design") { ctx = goa.WithLogContext(ctx, "origin", origin) rw.Header().Set("Access-Control-Allow-Origin", origin) rw.Header().Set("Vary", "Origin") rw.Header().Set("Access-Control-Max-Age", "600") rw.Header().Set("Access-Control-Allow-Credentials", "true") if acrm := req.Header.Get("Access-Control-Request-Method"); acrm != "" { rw.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, PATCH, DELETE") } return h(ctx, rw, req) } return h(ctx, rw, req) } } type PublicController interface { goa.Muxer goa.FileServer }
MIT License
horahoradev/horahora
video_service/protocol/mocks/mock_server.go
SendAndClose
go
func (m *MockVideoService_UploadVideoServer) SendAndClose(arg0 *proto.UploadResponse) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "SendAndClose", arg0) ret0, _ := ret[0].(error) return ret0 }
SendAndClose mocks base method
https://github.com/horahoradev/horahora/blob/15cc3be1b08a370574e90fbc0bd75b1cd037f49d/video_service/protocol/mocks/mock_server.go#L82-L87
package mocks import ( context "context" gomock "github.com/golang/mock/gomock" proto "github.com/horahoradev/horahora/video_service/protocol" metadata "google.golang.org/grpc/metadata" reflect "reflect" ) type MockVideoService_UploadVideoServer struct { ctrl *gomock.Controller recorder *MockVideoService_UploadVideoServerMockRecorder } type MockVideoService_UploadVideoServerMockRecorder struct { mock *MockVideoService_UploadVideoServer } func NewMockVideoService_UploadVideoServer(ctrl *gomock.Controller) *MockVideoService_UploadVideoServer { mock := &MockVideoService_UploadVideoServer{ctrl: ctrl} mock.recorder = &MockVideoService_UploadVideoServerMockRecorder{mock} return mock } func (m *MockVideoService_UploadVideoServer) EXPECT() *MockVideoService_UploadVideoServerMockRecorder { return m.recorder } func (m *MockVideoService_UploadVideoServer) Context() context.Context { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Context") ret0, _ := ret[0].(context.Context) return ret0 } func (mr *MockVideoService_UploadVideoServerMockRecorder) Context() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Context", reflect.TypeOf((*MockVideoService_UploadVideoServer)(nil).Context)) } func (m *MockVideoService_UploadVideoServer) Recv() (*proto.InputVideoChunk, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Recv") ret0, _ := ret[0].(*proto.InputVideoChunk) ret1, _ := ret[1].(error) return ret0, ret1 } func (mr *MockVideoService_UploadVideoServerMockRecorder) Recv() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Recv", reflect.TypeOf((*MockVideoService_UploadVideoServer)(nil).Recv)) } func (m *MockVideoService_UploadVideoServer) RecvMsg(arg0 interface{}) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "RecvMsg", arg0) ret0, _ := ret[0].(error) return ret0 } func (mr *MockVideoService_UploadVideoServerMockRecorder) RecvMsg(arg0 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "RecvMsg", reflect.TypeOf((*MockVideoService_UploadVideoServer)(nil).RecvMsg), arg0) }
MIT License
root4loot/rescope
vendor/github.com/akamensky/argparse/argparse.go
IntList
go
func (o *Command) IntList(short string, long string, opts *Options) *[]int { result := make([]int, 0) a := &arg{ result: &result, sname: short, lname: long, size: 2, opts: opts, unique: false, } if err := o.addArg(a); err != nil { panic(fmt.Errorf("unable to add IntList: %s", err.Error())) } return &result }
IntList creates new integer list argument. This is the argument that is allowed to be present multiple times on CLI. All appearances of this argument on CLI will be collected into the list of integers. If no argument provided, then the list is empty. Takes same parameters as Int Returns a pointer the list of integers.
https://github.com/root4loot/rescope/blob/3423ba047ed5ac5d89822dbd88dc6e90f076e964/vendor/github.com/akamensky/argparse/argparse.go#L367-L384
package argparse import ( "errors" "fmt" "os" "strings" ) const DisableDescription = "DISABLEDDESCRIPTIONWILLNOTSHOWUP" var disableHelp = false type Command struct { name string description string args []*arg commands []*Command parsed bool happened bool parent *Command HelpFunc func(c *Command, msg interface{}) string exitOnHelp bool } func (o Command) GetName() string { return o.name } func (o Command) GetDescription() string { return o.description } func (o Command) GetArgs() (args []Arg) { for _, arg := range o.args { args = append(args, arg) } return } func (o Command) GetCommands() []*Command { return o.commands } func (o Command) GetParent() *Command { return o.parent } func (o *Command) Help(msg interface{}) string { tempC := o for tempC.HelpFunc == nil { if tempC.parent == nil { return "" } tempC = tempC.parent } return tempC.HelpFunc(o, msg) } type Parser struct { Command } type Options struct { Required bool Validate func(args []string) error Help string Default interface{} } func NewParser(name string, description string) *Parser { p := &Parser{} p.name = name p.description = description p.args = make([]*arg, 0) p.commands = make([]*Command, 0) p.help("h", "help") p.exitOnHelp = true p.HelpFunc = (*Command).Usage return p } func (o *Command) NewCommand(name string, description string) *Command { c := new(Command) c.name = name c.description = description c.parsed = false c.parent = o if !disableHelp { c.help("h", "help") c.exitOnHelp = true c.HelpFunc = (*Command).Usage } if o.commands == nil { o.commands = make([]*Command, 0) } o.commands = append(o.commands, c) return c } func (o *Parser) DisableHelp() { disableHelp = true for i, arg := range o.args { if _, ok := arg.result.(*help); ok { o.args = append(o.args[:i], o.args[i+1:]...) } } for _, com := range o.commands { for i, comArg := range com.args { if _, ok := comArg.result.(*help); ok { com.args = append(com.args[:i], com.args[i+1:]...) } } } } func (o *Command) ExitOnHelp(b bool) { o.exitOnHelp = b for _, c := range o.commands { c.ExitOnHelp(b) } } func (o *Parser) SetHelp(sname, lname string) { o.DisableHelp() o.help(sname, lname) } func (o *Command) Flag(short string, long string, opts *Options) *bool { var result bool a := &arg{ result: &result, sname: short, lname: long, size: 1, opts: opts, unique: true, } if err := o.addArg(a); err != nil { panic(fmt.Errorf("unable to add Flag: %s", err.Error())) } return &result } func (o *Command) FlagCounter(short string, long string, opts *Options) *int { var result int a := &arg{ result: &result, sname: short, lname: long, size: 1, opts: opts, unique: false, } if err := o.addArg(a); err != nil { panic(fmt.Errorf("unable to add FlagCounter: %s", err.Error())) } return &result } func (o *Command) String(short string, long string, opts *Options) *string { var result string a := &arg{ result: &result, sname: short, lname: long, size: 2, opts: opts, unique: true, } if err := o.addArg(a); err != nil { panic(fmt.Errorf("unable to add String: %s", err.Error())) } return &result } func (o *Command) Int(short string, long string, opts *Options) *int { var result int a := &arg{ result: &result, sname: short, lname: long, size: 2, opts: opts, unique: true, } if err := o.addArg(a); err != nil { panic(fmt.Errorf("unable to add Int: %s", err.Error())) } return &result } func (o *Command) Float(short string, long string, opts *Options) *float64 { var result float64 a := &arg{ result: &result, sname: short, lname: long, size: 2, opts: opts, unique: true, } if err := o.addArg(a); err != nil { panic(fmt.Errorf("unable to add Float: %s", err.Error())) } return &result } func (o *Command) File(short string, long string, flag int, perm os.FileMode, opts *Options) *os.File { var result os.File a := &arg{ result: &result, sname: short, lname: long, size: 2, opts: opts, unique: true, fileFlag: flag, filePerm: perm, } if err := o.addArg(a); err != nil { panic(fmt.Errorf("unable to add File: %s", err.Error())) } return &result } func (o *Command) List(short string, long string, opts *Options) *[]string { return o.StringList(short, long, opts) } func (o *Command) StringList(short string, long string, opts *Options) *[]string { result := make([]string, 0) a := &arg{ result: &result, sname: short, lname: long, size: 2, opts: opts, unique: false, } if err := o.addArg(a); err != nil { panic(fmt.Errorf("unable to add StringList: %s", err.Error())) } return &result }
MIT License
go-playground/locales
en_MT/en_MT.go
FmtDateShort
go
func (en *en_MT) FmtDateShort(t time.Time) string { b := make([]byte, 0, 32) if t.Day() < 10 { b = append(b, '0') } b = strconv.AppendInt(b, int64(t.Day()), 10) b = append(b, []byte{0x2f}...) if t.Month() < 10 { b = append(b, '0') } b = strconv.AppendInt(b, int64(t.Month()), 10) b = append(b, []byte{0x2f}...) if t.Year() > 0 { b = strconv.AppendInt(b, int64(t.Year()), 10) } else { b = strconv.AppendInt(b, int64(-t.Year()), 10) } return string(b) }
FmtDateShort returns the short date representation of 't' for 'en_MT'
https://github.com/go-playground/locales/blob/52f01e016def96714dc09cf5cdd58f5660eeca02/en_MT/en_MT.go#L419-L445
package en_MT import ( "math" "strconv" "time" "github.com/go-playground/locales" "github.com/go-playground/locales/currency" ) type en_MT struct { locale string pluralsCardinal []locales.PluralRule pluralsOrdinal []locales.PluralRule pluralsRange []locales.PluralRule decimal string group string minus string percent string perMille string timeSeparator string inifinity string currencies []string currencyNegativePrefix string currencyNegativeSuffix string monthsAbbreviated []string monthsNarrow []string monthsWide []string daysAbbreviated []string daysNarrow []string daysShort []string daysWide []string periodsAbbreviated []string periodsNarrow []string periodsShort []string periodsWide []string erasAbbreviated []string erasNarrow []string erasWide []string timezones map[string]string } func New() locales.Translator { return &en_MT{ locale: "en_MT", pluralsCardinal: []locales.PluralRule{2, 6}, pluralsOrdinal: []locales.PluralRule{2, 3, 4, 6}, pluralsRange: []locales.PluralRule{6}, decimal: ".", group: ",", minus: "-", percent: "%", perMille: "‰", timeSeparator: ":", inifinity: "∞", currencies: []string{"ADP", "AED", "AFA", "AFN", "ALK", "ALL", "AMD", "ANG", "AOA", "AOK", "AON", "AOR", "ARA", "ARL", "ARM", "ARP", "ARS", "ATS", "AUD", "AWG", "AZM", "AZN", "BAD", "BAM", "BAN", "BBD", "BDT", "BEC", "BEF", "BEL", "BGL", "BGM", "BGN", "BGO", "BHD", "BIF", "BMD", "BND", "BOB", "BOL", "BOP", "BOV", "BRB", "BRC", "BRE", "BRL", "BRN", "BRR", "BRZ", "BSD", "BTN", "BUK", "BWP", "BYB", "BYN", "BYR", "BZD", "CAD", "CDF", "CHE", "CHF", "CHW", "CLE", "CLF", "CLP", "CNH", "CNX", "CNY", "COP", "COU", "CRC", "CSD", "CSK", "CUC", "CUP", "CVE", "CYP", "CZK", "DDM", "DEM", "DJF", "DKK", "DOP", "DZD", "ECS", "ECV", "EEK", "EGP", "ERN", "ESA", "ESB", "ESP", "ETB", "EUR", "FIM", "FJD", "FKP", "FRF", "GB£", "GEK", "GEL", "GHC", "GHS", "GIP", "GMD", "GNF", "GNS", "GQE", "GRD", "GTQ", "GWE", "GWP", "GYD", "HKD", "HNL", "HRD", "HRK", "HTG", "HUF", "IDR", "IEP", "ILP", "ILR", "ILS", "INR", "IQD", "IRR", "ISJ", "ISK", "ITL", "JMD", "JOD", "JPY", "KES", "KGS", "KHR", "KMF", "KPW", "KRH", "KRO", "KRW", "KWD", "KYD", "KZT", "LAK", "LBP", "LKR", "LRD", "LSL", "LTL", "LTT", "LUC", "LUF", "LUL", "LVL", "LVR", "LYD", "MAD", "MAF", "MCF", "MDC", "MDL", "MGA", "MGF", "MKD", "MKN", "MLF", "MMK", "MNT", "MOP", "MRO", "MRU", "MTL", "MTP", "MUR", "MVP", "MVR", "MWK", "MXN", "MXP", "MXV", "MYR", "MZE", "MZM", "MZN", "NAD", "NGN", "NIC", "NIO", "NLG", "NOK", "NPR", "NZD", "OMR", "PAB", "PEI", "PEN", "PES", "PGK", "PHP", "PKR", "PLN", "PLZ", "PTE", "PYG", "QAR", "RHD", "ROL", "RON", "RSD", "RUB", "RUR", "RWF", "SAR", "SBD", "SCR", "SDD", "SDG", "SDP", "SEK", "SGD", "SHP", "SIT", "SKK", "SLL", "SOS", "SRD", "SRG", "SSP", "STD", "STN", "SUR", "SVC", "SYP", "SZL", "THB", "TJR", "TJS", "TMM", "TMT", "TND", "TOP", "TPE", "TRL", "TRY", "TTD", "TWD", "TZS", "UAH", "UAK", "UGS", "UGX", "USD", "USN", "USS", "UYI", "UYP", "UYU", "UYW", "UZS", "VEB", "VEF", "VES", "VND", "VNN", "VUV", "WST", "XAF", "XAG", "XAU", "XBA", "XBB", "XBC", "XBD", "XCD", "XDR", "XEU", "XFO", "XFU", "XOF", "XPD", "XPF", "XPT", "XRE", "XSU", "XTS", "XUA", "XXX", "YDD", "YER", "YUD", "YUM", "YUN", "YUR", "ZAL", "ZAR", "ZMK", "ZMW", "ZRN", "ZRZ", "ZWD", "ZWL", "ZWR"}, currencyNegativePrefix: "(", currencyNegativeSuffix: ")", monthsAbbreviated: []string{"", "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"}, monthsNarrow: []string{"", "J", "F", "M", "A", "M", "J", "J", "A", "S", "O", "N", "D"}, monthsWide: []string{"", "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"}, daysAbbreviated: []string{"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"}, daysNarrow: []string{"S", "M", "T", "W", "T", "F", "S"}, daysShort: []string{"Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"}, daysWide: []string{"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}, periodsAbbreviated: []string{"am", "pm"}, periodsNarrow: []string{"", "pm"}, periodsWide: []string{"am", "pm"}, erasAbbreviated: []string{"BC", "AD"}, erasNarrow: []string{"B", "A"}, erasWide: []string{"Before Christ", "Anno Domini"}, timezones: map[string]string{"ACDT": "Australian Central Daylight Time", "ACST": "Australian Central Standard Time", "ACWDT": "Australian Central Western Daylight Time", "ACWST": "Australian Central Western Standard Time", "ADT": "Atlantic Daylight Time", "AEDT": "Australian Eastern Daylight Time", "AEST": "Australian Eastern Standard Time", "AKDT": "Alaska Daylight Time", "AKST": "Alaska Standard Time", "ARST": "Argentina Summer Time", "ART": "Argentina Standard Time", "AST": "Atlantic Standard Time", "AWDT": "Australian Western Daylight Time", "AWST": "Australian Western Standard Time", "BOT": "Bolivia Time", "BT": "Bhutan Time", "CAT": "Central Africa Time", "CDT": "Central Daylight Time", "CHADT": "Chatham Daylight Time", "CHAST": "Chatham Standard Time", "CLST": "Chile Summer Time", "CLT": "Chile Standard Time", "COST": "Colombia Summer Time", "COT": "Colombia Standard Time", "CST": "Central Standard Time", "ChST": "Chamorro Standard Time", "EAT": "East Africa Time", "ECT": "Ecuador Time", "EDT": "Eastern Daylight Time", "EST": "Eastern Standard Time", "GFT": "French Guiana Time", "GMT": "Greenwich Mean Time", "GST": "Gulf Standard Time", "GYT": "Guyana Time", "HADT": "Hawaii-Aleutian Daylight Time", "HAST": "Hawaii-Aleutian Standard Time", "HAT": "Newfoundland Daylight Time", "HECU": "Cuba Daylight Time", "HEEG": "East Greenland Summer Time", "HENOMX": "Northwest Mexico Daylight Time", "HEOG": "West Greenland Summer Time", "HEPM": "St Pierre & Miquelon Daylight Time", "HEPMX": "Mexican Pacific Daylight Time", "HKST": "Hong Kong Summer Time", "HKT": "Hong Kong Standard Time", "HNCU": "Cuba Standard Time", "HNEG": "East Greenland Standard Time", "HNNOMX": "Northwest Mexico Standard Time", "HNOG": "West Greenland Standard Time", "HNPM": "St Pierre & Miquelon Standard Time", "HNPMX": "Mexican Pacific Standard Time", "HNT": "Newfoundland Standard Time", "IST": "India Standard Time", "JDT": "Japan Daylight Time", "JST": "Japan Standard Time", "LHDT": "Lord Howe Daylight Time", "LHST": "Lord Howe Standard Time", "MDT": "Mountain Daylight Time", "MESZ": "Central European Summer Time", "MEZ": "Central European Standard Time", "MST": "Mountain Standard Time", "MYT": "Malaysia Time", "NZDT": "New Zealand Daylight Time", "NZST": "New Zealand Standard Time", "OESZ": "Eastern European Summer Time", "OEZ": "Eastern European Standard Time", "PDT": "Pacific Daylight Time", "PST": "Pacific Standard Time", "SAST": "South Africa Standard Time", "SGT": "Singapore Standard Time", "SRT": "Suriname Time", "TMST": "Turkmenistan Summer Time", "TMT": "Turkmenistan Standard Time", "UYST": "Uruguay Summer Time", "UYT": "Uruguay Standard Time", "VET": "Venezuela Time", "WARST": "Western Argentina Summer Time", "WART": "Western Argentina Standard Time", "WAST": "West Africa Summer Time", "WAT": "West Africa Standard Time", "WESZ": "Western European Summer Time", "WEZ": "Western European Standard Time", "WIB": "Western Indonesia Time", "WIT": "Eastern Indonesia Time", "WITA": "Central Indonesia Time", "∅∅∅": "Brasilia Summer Time"}, } } func (en *en_MT) Locale() string { return en.locale } func (en *en_MT) PluralsCardinal() []locales.PluralRule { return en.pluralsCardinal } func (en *en_MT) PluralsOrdinal() []locales.PluralRule { return en.pluralsOrdinal } func (en *en_MT) PluralsRange() []locales.PluralRule { return en.pluralsRange } func (en *en_MT) CardinalPluralRule(num float64, v uint64) locales.PluralRule { n := math.Abs(num) i := int64(n) if i == 1 && v == 0 { return locales.PluralRuleOne } return locales.PluralRuleOther } func (en *en_MT) OrdinalPluralRule(num float64, v uint64) locales.PluralRule { n := math.Abs(num) nMod10 := math.Mod(n, 10) nMod100 := math.Mod(n, 100) if nMod10 == 1 && nMod100 != 11 { return locales.PluralRuleOne } else if nMod10 == 2 && nMod100 != 12 { return locales.PluralRuleTwo } else if nMod10 == 3 && nMod100 != 13 { return locales.PluralRuleFew } return locales.PluralRuleOther } func (en *en_MT) RangePluralRule(num1 float64, v1 uint64, num2 float64, v2 uint64) locales.PluralRule { return locales.PluralRuleOther } func (en *en_MT) MonthAbbreviated(month time.Month) string { return en.monthsAbbreviated[month] } func (en *en_MT) MonthsAbbreviated() []string { return en.monthsAbbreviated[1:] } func (en *en_MT) MonthNarrow(month time.Month) string { return en.monthsNarrow[month] } func (en *en_MT) MonthsNarrow() []string { return en.monthsNarrow[1:] } func (en *en_MT) MonthWide(month time.Month) string { return en.monthsWide[month] } func (en *en_MT) MonthsWide() []string { return en.monthsWide[1:] } func (en *en_MT) WeekdayAbbreviated(weekday time.Weekday) string { return en.daysAbbreviated[weekday] } func (en *en_MT) WeekdaysAbbreviated() []string { return en.daysAbbreviated } func (en *en_MT) WeekdayNarrow(weekday time.Weekday) string { return en.daysNarrow[weekday] } func (en *en_MT) WeekdaysNarrow() []string { return en.daysNarrow } func (en *en_MT) WeekdayShort(weekday time.Weekday) string { return en.daysShort[weekday] } func (en *en_MT) WeekdaysShort() []string { return en.daysShort } func (en *en_MT) WeekdayWide(weekday time.Weekday) string { return en.daysWide[weekday] } func (en *en_MT) WeekdaysWide() []string { return en.daysWide } func (en *en_MT) Decimal() string { return en.decimal } func (en *en_MT) Group() string { return en.group } func (en *en_MT) Minus() string { return en.minus } func (en *en_MT) FmtNumber(num float64, v uint64) string { s := strconv.FormatFloat(math.Abs(num), 'f', int(v), 64) l := len(s) + 2 + 1*len(s[:len(s)-int(v)-1])/3 count := 0 inWhole := v == 0 b := make([]byte, 0, l) for i := len(s) - 1; i >= 0; i-- { if s[i] == '.' { b = append(b, en.decimal[0]) inWhole = true continue } if inWhole { if count == 3 { b = append(b, en.group[0]) count = 1 } else { count++ } } b = append(b, s[i]) } if num < 0 { b = append(b, en.minus[0]) } for i, j := 0, len(b)-1; i < j; i, j = i+1, j-1 { b[i], b[j] = b[j], b[i] } return string(b) } func (en *en_MT) FmtPercent(num float64, v uint64) string { s := strconv.FormatFloat(math.Abs(num), 'f', int(v), 64) l := len(s) + 3 b := make([]byte, 0, l) for i := len(s) - 1; i >= 0; i-- { if s[i] == '.' { b = append(b, en.decimal[0]) continue } b = append(b, s[i]) } if num < 0 { b = append(b, en.minus[0]) } for i, j := 0, len(b)-1; i < j; i, j = i+1, j-1 { b[i], b[j] = b[j], b[i] } b = append(b, en.percent...) return string(b) } func (en *en_MT) FmtCurrency(num float64, v uint64, currency currency.Type) string { s := strconv.FormatFloat(math.Abs(num), 'f', int(v), 64) symbol := en.currencies[currency] l := len(s) + len(symbol) + 2 + 1*len(s[:len(s)-int(v)-1])/3 count := 0 inWhole := v == 0 b := make([]byte, 0, l) for i := len(s) - 1; i >= 0; i-- { if s[i] == '.' { b = append(b, en.decimal[0]) inWhole = true continue } if inWhole { if count == 3 { b = append(b, en.group[0]) count = 1 } else { count++ } } b = append(b, s[i]) } for j := len(symbol) - 1; j >= 0; j-- { b = append(b, symbol[j]) } if num < 0 { b = append(b, en.minus[0]) } for i, j := 0, len(b)-1; i < j; i, j = i+1, j-1 { b[i], b[j] = b[j], b[i] } if int(v) < 2 { if v == 0 { b = append(b, en.decimal...) } for i := 0; i < 2-int(v); i++ { b = append(b, '0') } } return string(b) } func (en *en_MT) FmtAccounting(num float64, v uint64, currency currency.Type) string { s := strconv.FormatFloat(math.Abs(num), 'f', int(v), 64) symbol := en.currencies[currency] l := len(s) + len(symbol) + 4 + 1*len(s[:len(s)-int(v)-1])/3 count := 0 inWhole := v == 0 b := make([]byte, 0, l) for i := len(s) - 1; i >= 0; i-- { if s[i] == '.' { b = append(b, en.decimal[0]) inWhole = true continue } if inWhole { if count == 3 { b = append(b, en.group[0]) count = 1 } else { count++ } } b = append(b, s[i]) } if num < 0 { for j := len(symbol) - 1; j >= 0; j-- { b = append(b, symbol[j]) } b = append(b, en.currencyNegativePrefix[0]) } else { for j := len(symbol) - 1; j >= 0; j-- { b = append(b, symbol[j]) } } for i, j := 0, len(b)-1; i < j; i, j = i+1, j-1 { b[i], b[j] = b[j], b[i] } if int(v) < 2 { if v == 0 { b = append(b, en.decimal...) } for i := 0; i < 2-int(v); i++ { b = append(b, '0') } } if num < 0 { b = append(b, en.currencyNegativeSuffix...) } return string(b) }
MIT License
go-kratos/beer-shop
app/user/service/internal/data/ent/address/where.go
PostCode
go
func PostCode(v string) predicate.Address { return predicate.Address(func(s *sql.Selector) { s.Where(sql.EQ(s.C(FieldPostCode), v)) }) }
PostCode applies equality check predicate on the "post_code" field. It's identical to PostCodeEQ.
https://github.com/go-kratos/beer-shop/blob/2234d936fdcaad2ef6779ed79a6432f9a1721572/app/user/service/internal/data/ent/address/where.go#L118-L122
package address import ( "time" "entgo.io/ent/dialect/sql" "entgo.io/ent/dialect/sql/sqlgraph" "github.com/go-kratos/beer-shop/app/user/service/internal/data/ent/predicate" ) func ID(id int64) predicate.Address { return predicate.Address(func(s *sql.Selector) { s.Where(sql.EQ(s.C(FieldID), id)) }) } func IDEQ(id int64) predicate.Address { return predicate.Address(func(s *sql.Selector) { s.Where(sql.EQ(s.C(FieldID), id)) }) } func IDNEQ(id int64) predicate.Address { return predicate.Address(func(s *sql.Selector) { s.Where(sql.NEQ(s.C(FieldID), id)) }) } func IDIn(ids ...int64) predicate.Address { return predicate.Address(func(s *sql.Selector) { if len(ids) == 0 { s.Where(sql.False()) return } v := make([]interface{}, len(ids)) for i := range v { v[i] = ids[i] } s.Where(sql.In(s.C(FieldID), v...)) }) } func IDNotIn(ids ...int64) predicate.Address { return predicate.Address(func(s *sql.Selector) { if len(ids) == 0 { s.Where(sql.False()) return } v := make([]interface{}, len(ids)) for i := range v { v[i] = ids[i] } s.Where(sql.NotIn(s.C(FieldID), v...)) }) } func IDGT(id int64) predicate.Address { return predicate.Address(func(s *sql.Selector) { s.Where(sql.GT(s.C(FieldID), id)) }) } func IDGTE(id int64) predicate.Address { return predicate.Address(func(s *sql.Selector) { s.Where(sql.GTE(s.C(FieldID), id)) }) } func IDLT(id int64) predicate.Address { return predicate.Address(func(s *sql.Selector) { s.Where(sql.LT(s.C(FieldID), id)) }) } func IDLTE(id int64) predicate.Address { return predicate.Address(func(s *sql.Selector) { s.Where(sql.LTE(s.C(FieldID), id)) }) } func Name(v string) predicate.Address { return predicate.Address(func(s *sql.Selector) { s.Where(sql.EQ(s.C(FieldName), v)) }) } func Mobile(v string) predicate.Address { return predicate.Address(func(s *sql.Selector) { s.Where(sql.EQ(s.C(FieldMobile), v)) }) } func Address(v string) predicate.Address { return predicate.Address(func(s *sql.Selector) { s.Where(sql.EQ(s.C(FieldAddress), v)) }) }
MIT License
ucloud/redis-cluster-operator
pkg/redisutil/errors.go
IsInconsistentError
go
func IsInconsistentError(err error) bool { e, ok := err.(ClusterInfosError) return ok && e.Inconsistent() }
IsInconsistentError eturns true if the error is due to cluster inconsistencies
https://github.com/ucloud/redis-cluster-operator/blob/6eecca84605265a866e257d11ae2d2e2b3dcab0d/pkg/redisutil/errors.go#L67-L70
package redisutil import "fmt" type Error string func (e Error) Error() string { return string(e) } const nodeNotFoundedError = Error("node not founded") func IsNodeNotFoundedError(err error) bool { return err == nodeNotFoundedError } type ClusterInfosError struct { errs map[string]error partial bool inconsistent bool } func NewClusterInfosError() ClusterInfosError { return ClusterInfosError{ errs: make(map[string]error), partial: false, inconsistent: false, } } func (e ClusterInfosError) Error() string { s := "" if e.partial { s += "Cluster infos partial: " for addr, err := range e.errs { s += fmt.Sprintf("%s: '%s'", addr, err) } return s } if e.inconsistent { s += "Cluster view is inconsistent" } return s } func (e ClusterInfosError) Partial() bool { return e.partial } func (e ClusterInfosError) Inconsistent() bool { return e.inconsistent } func IsPartialError(err error) bool { e, ok := err.(ClusterInfosError) return ok && e.Partial() }
Apache License 2.0
aws-controllers-k8s/elasticache-controller
pkg/resource/user/sdk.go
terminalAWSError
go
func (rm *resourceManager) terminalAWSError(err error) bool { if err == nil { return false } awsErr, ok := ackerr.AWSError(err) if !ok { return false } switch awsErr.Code() { case "UserAlreadyExists", "UserQuotaExceeded", "DuplicateUserName", "InvalidParameterValue", "InvalidParameterCombination", "InvalidUserState", "UserNotFound", "DefaultUserAssociatedToUserGroup": return true default: return false } }
terminalAWSError returns awserr, true; if the supplied error is an aws Error type and if the exception indicates that it is a Terminal exception 'Terminal' exception are specified in generator configuration
https://github.com/aws-controllers-k8s/elasticache-controller/blob/ebb3ad07d8805942a91951b82dc6fa7a8a927eb9/pkg/resource/user/sdk.go#L564-L585
package user import ( "context" "strings" ackv1alpha1 "github.com/aws-controllers-k8s/runtime/apis/core/v1alpha1" ackcompare "github.com/aws-controllers-k8s/runtime/pkg/compare" ackcondition "github.com/aws-controllers-k8s/runtime/pkg/condition" ackerr "github.com/aws-controllers-k8s/runtime/pkg/errors" ackrtlog "github.com/aws-controllers-k8s/runtime/pkg/runtime/log" "github.com/aws/aws-sdk-go/aws" svcsdk "github.com/aws/aws-sdk-go/service/elasticache" corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" svcapitypes "github.com/aws-controllers-k8s/elasticache-controller/apis/v1alpha1" ) var ( _ = &metav1.Time{} _ = strings.ToLower("") _ = &aws.JSONValue{} _ = &svcsdk.ElastiCache{} _ = &svcapitypes.User{} _ = ackv1alpha1.AWSAccountID("") _ = &ackerr.NotFound _ = &ackcondition.NotManagedMessage ) func (rm *resourceManager) sdkFind( ctx context.Context, r *resource, ) (latest *resource, err error) { rlog := ackrtlog.FromContext(ctx) exit := rlog.Trace("rm.sdkFind") defer exit(err) if rm.requiredFieldsMissingFromReadManyInput(r) { return nil, ackerr.NotFound } input, err := rm.newListRequestPayload(r) if err != nil { return nil, err } var resp *svcsdk.DescribeUsersOutput resp, err = rm.sdkapi.DescribeUsersWithContext(ctx, input) rm.metrics.RecordAPICall("READ_MANY", "DescribeUsers", err) if err != nil { if awsErr, ok := ackerr.AWSError(err); ok && awsErr.Code() == "UserNotFound" { return nil, ackerr.NotFound } return nil, err } ko := r.ko.DeepCopy() found := false for _, elem := range resp.Users { if elem.ARN != nil { if ko.Status.ACKResourceMetadata == nil { ko.Status.ACKResourceMetadata = &ackv1alpha1.ResourceMetadata{} } tmpARN := ackv1alpha1.AWSResourceName(*elem.ARN) ko.Status.ACKResourceMetadata.ARN = &tmpARN } if elem.AccessString != nil { ko.Spec.AccessString = elem.AccessString } else { ko.Spec.AccessString = nil } if elem.Authentication != nil { f2 := &svcapitypes.Authentication{} if elem.Authentication.PasswordCount != nil { f2.PasswordCount = elem.Authentication.PasswordCount } if elem.Authentication.Type != nil { f2.Type = elem.Authentication.Type } ko.Status.Authentication = f2 } else { ko.Status.Authentication = nil } if elem.Engine != nil { ko.Spec.Engine = elem.Engine } else { ko.Spec.Engine = nil } if elem.Status != nil { ko.Status.Status = elem.Status } else { ko.Status.Status = nil } if elem.UserGroupIds != nil { f5 := []*string{} for _, f5iter := range elem.UserGroupIds { var f5elem string f5elem = *f5iter f5 = append(f5, &f5elem) } ko.Status.UserGroupIDs = f5 } else { ko.Status.UserGroupIDs = nil } if elem.UserId != nil { ko.Spec.UserID = elem.UserId } else { ko.Spec.UserID = nil } if elem.UserName != nil { ko.Spec.UserName = elem.UserName } else { ko.Spec.UserName = nil } found = true break } if !found { return nil, ackerr.NotFound } rm.setStatusDefaults(ko) rm.setSyncedCondition(resp.Users[0].Status, &resource{ko}) return &resource{ko}, nil } func (rm *resourceManager) requiredFieldsMissingFromReadManyInput( r *resource, ) bool { return r.ko.Spec.UserID == nil } func (rm *resourceManager) newListRequestPayload( r *resource, ) (*svcsdk.DescribeUsersInput, error) { res := &svcsdk.DescribeUsersInput{} if r.ko.Spec.UserID != nil { res.SetUserId(*r.ko.Spec.UserID) } return res, nil } func (rm *resourceManager) sdkCreate( ctx context.Context, desired *resource, ) (created *resource, err error) { rlog := ackrtlog.FromContext(ctx) exit := rlog.Trace("rm.sdkCreate") defer exit(err) input, err := rm.newCreateRequestPayload(ctx, desired) if err != nil { return nil, err } var resp *svcsdk.CreateUserOutput _ = resp resp, err = rm.sdkapi.CreateUserWithContext(ctx, input) rm.metrics.RecordAPICall("CREATE", "CreateUser", err) if err != nil { return nil, err } ko := desired.ko.DeepCopy() if ko.Status.ACKResourceMetadata == nil { ko.Status.ACKResourceMetadata = &ackv1alpha1.ResourceMetadata{} } if resp.ARN != nil { arn := ackv1alpha1.AWSResourceName(*resp.ARN) ko.Status.ACKResourceMetadata.ARN = &arn } if resp.AccessString != nil { ko.Spec.AccessString = resp.AccessString } else { ko.Spec.AccessString = nil } if resp.Authentication != nil { f2 := &svcapitypes.Authentication{} if resp.Authentication.PasswordCount != nil { f2.PasswordCount = resp.Authentication.PasswordCount } if resp.Authentication.Type != nil { f2.Type = resp.Authentication.Type } ko.Status.Authentication = f2 } else { ko.Status.Authentication = nil } if resp.Engine != nil { ko.Spec.Engine = resp.Engine } else { ko.Spec.Engine = nil } if resp.Status != nil { ko.Status.Status = resp.Status } else { ko.Status.Status = nil } if resp.UserGroupIds != nil { f5 := []*string{} for _, f5iter := range resp.UserGroupIds { var f5elem string f5elem = *f5iter f5 = append(f5, &f5elem) } ko.Status.UserGroupIDs = f5 } else { ko.Status.UserGroupIDs = nil } if resp.UserId != nil { ko.Spec.UserID = resp.UserId } else { ko.Spec.UserID = nil } if resp.UserName != nil { ko.Spec.UserName = resp.UserName } else { ko.Spec.UserName = nil } rm.setStatusDefaults(ko) ko, err = rm.CustomCreateUserSetOutput(ctx, desired, resp, ko) if err != nil { return nil, err } rm.setSyncedCondition(resp.Status, &resource{ko}) return &resource{ko}, nil } func (rm *resourceManager) newCreateRequestPayload( ctx context.Context, r *resource, ) (*svcsdk.CreateUserInput, error) { res := &svcsdk.CreateUserInput{} if r.ko.Spec.AccessString != nil { res.SetAccessString(*r.ko.Spec.AccessString) } if r.ko.Spec.Engine != nil { res.SetEngine(*r.ko.Spec.Engine) } if r.ko.Spec.NoPasswordRequired != nil { res.SetNoPasswordRequired(*r.ko.Spec.NoPasswordRequired) } if r.ko.Spec.Passwords != nil { f3 := []*string{} for _, f3iter := range r.ko.Spec.Passwords { var f3elem string if f3iter != nil { tmpSecret, err := rm.rr.SecretValueFromReference(ctx, f3iter) if err != nil { return nil, err } if tmpSecret != "" { f3elem = tmpSecret } } f3 = append(f3, &f3elem) } res.SetPasswords(f3) } if r.ko.Spec.Tags != nil { f4 := []*svcsdk.Tag{} for _, f4iter := range r.ko.Spec.Tags { f4elem := &svcsdk.Tag{} if f4iter.Key != nil { f4elem.SetKey(*f4iter.Key) } if f4iter.Value != nil { f4elem.SetValue(*f4iter.Value) } f4 = append(f4, f4elem) } res.SetTags(f4) } if r.ko.Spec.UserID != nil { res.SetUserId(*r.ko.Spec.UserID) } if r.ko.Spec.UserName != nil { res.SetUserName(*r.ko.Spec.UserName) } return res, nil } func (rm *resourceManager) sdkUpdate( ctx context.Context, desired *resource, latest *resource, delta *ackcompare.Delta, ) (updated *resource, err error) { rlog := ackrtlog.FromContext(ctx) exit := rlog.Trace("rm.sdkUpdate") defer exit(err) updated, err = rm.CustomModifyUser(ctx, desired, latest, delta) if updated != nil || err != nil { return updated, err } input, err := rm.newUpdateRequestPayload(ctx, desired) if err != nil { return nil, err } rm.populateUpdatePayload(input, desired, delta) var resp *svcsdk.ModifyUserOutput _ = resp resp, err = rm.sdkapi.ModifyUserWithContext(ctx, input) rm.metrics.RecordAPICall("UPDATE", "ModifyUser", err) if err != nil { return nil, err } ko := desired.ko.DeepCopy() if ko.Status.ACKResourceMetadata == nil { ko.Status.ACKResourceMetadata = &ackv1alpha1.ResourceMetadata{} } if resp.ARN != nil { arn := ackv1alpha1.AWSResourceName(*resp.ARN) ko.Status.ACKResourceMetadata.ARN = &arn } if resp.AccessString != nil { ko.Spec.AccessString = resp.AccessString } else { ko.Spec.AccessString = nil } if resp.Authentication != nil { f2 := &svcapitypes.Authentication{} if resp.Authentication.PasswordCount != nil { f2.PasswordCount = resp.Authentication.PasswordCount } if resp.Authentication.Type != nil { f2.Type = resp.Authentication.Type } ko.Status.Authentication = f2 } else { ko.Status.Authentication = nil } if resp.Engine != nil { ko.Spec.Engine = resp.Engine } else { ko.Spec.Engine = nil } if resp.Status != nil { ko.Status.Status = resp.Status } else { ko.Status.Status = nil } if resp.UserGroupIds != nil { f5 := []*string{} for _, f5iter := range resp.UserGroupIds { var f5elem string f5elem = *f5iter f5 = append(f5, &f5elem) } ko.Status.UserGroupIDs = f5 } else { ko.Status.UserGroupIDs = nil } if resp.UserId != nil { ko.Spec.UserID = resp.UserId } else { ko.Spec.UserID = nil } if resp.UserName != nil { ko.Spec.UserName = resp.UserName } else { ko.Spec.UserName = nil } rm.setStatusDefaults(ko) ko, err = rm.CustomModifyUserSetOutput(ctx, desired, resp, ko) if err != nil { return nil, err } rm.setSyncedCondition(resp.Status, &resource{ko}) return &resource{ko}, nil } func (rm *resourceManager) newUpdateRequestPayload( ctx context.Context, r *resource, ) (*svcsdk.ModifyUserInput, error) { res := &svcsdk.ModifyUserInput{} if r.ko.Spec.UserID != nil { res.SetUserId(*r.ko.Spec.UserID) } return res, nil } func (rm *resourceManager) sdkDelete( ctx context.Context, r *resource, ) (latest *resource, err error) { rlog := ackrtlog.FromContext(ctx) exit := rlog.Trace("rm.sdkDelete") defer exit(err) input, err := rm.newDeleteRequestPayload(r) if err != nil { return nil, err } var resp *svcsdk.DeleteUserOutput _ = resp resp, err = rm.sdkapi.DeleteUserWithContext(ctx, input) rm.metrics.RecordAPICall("DELETE", "DeleteUser", err) return nil, err } func (rm *resourceManager) newDeleteRequestPayload( r *resource, ) (*svcsdk.DeleteUserInput, error) { res := &svcsdk.DeleteUserInput{} if r.ko.Spec.UserID != nil { res.SetUserId(*r.ko.Spec.UserID) } return res, nil } func (rm *resourceManager) setStatusDefaults( ko *svcapitypes.User, ) { if ko.Status.ACKResourceMetadata == nil { ko.Status.ACKResourceMetadata = &ackv1alpha1.ResourceMetadata{} } if ko.Status.ACKResourceMetadata.OwnerAccountID == nil { ko.Status.ACKResourceMetadata.OwnerAccountID = &rm.awsAccountID } if ko.Status.Conditions == nil { ko.Status.Conditions = []*ackv1alpha1.Condition{} } } func (rm *resourceManager) updateConditions( r *resource, onSuccess bool, err error, ) (*resource, bool) { ko := r.ko.DeepCopy() rm.setStatusDefaults(ko) var terminalCondition *ackv1alpha1.Condition = nil var recoverableCondition *ackv1alpha1.Condition = nil var syncCondition *ackv1alpha1.Condition = nil for _, condition := range ko.Status.Conditions { if condition.Type == ackv1alpha1.ConditionTypeTerminal { terminalCondition = condition } if condition.Type == ackv1alpha1.ConditionTypeRecoverable { recoverableCondition = condition } if condition.Type == ackv1alpha1.ConditionTypeResourceSynced { syncCondition = condition } } if rm.terminalAWSError(err) || err == ackerr.SecretTypeNotSupported || err == ackerr.SecretNotFound { if terminalCondition == nil { terminalCondition = &ackv1alpha1.Condition{ Type: ackv1alpha1.ConditionTypeTerminal, } ko.Status.Conditions = append(ko.Status.Conditions, terminalCondition) } var errorMessage = "" if err == ackerr.SecretTypeNotSupported || err == ackerr.SecretNotFound { errorMessage = err.Error() } else { awsErr, _ := ackerr.AWSError(err) errorMessage = awsErr.Error() } terminalCondition.Status = corev1.ConditionTrue terminalCondition.Message = &errorMessage } else { if terminalCondition != nil { terminalCondition.Status = corev1.ConditionFalse terminalCondition.Message = nil } if err != nil { if recoverableCondition == nil { recoverableCondition = &ackv1alpha1.Condition{ Type: ackv1alpha1.ConditionTypeRecoverable, } ko.Status.Conditions = append(ko.Status.Conditions, recoverableCondition) } recoverableCondition.Status = corev1.ConditionTrue awsErr, _ := ackerr.AWSError(err) errorMessage := err.Error() if awsErr != nil { errorMessage = awsErr.Error() } recoverableCondition.Message = &errorMessage } else if recoverableCondition != nil { recoverableCondition.Status = corev1.ConditionFalse recoverableCondition.Message = nil } } _ = syncCondition if terminalCondition != nil || recoverableCondition != nil || syncCondition != nil { return &resource{ko}, true } return nil, false }
Apache License 2.0
hyperledger/aries-framework-go
pkg/framework/context/context.go
WithProtocolServices
go
func WithProtocolServices(services ...dispatcher.ProtocolService) ProviderOption { return func(opts *Provider) error { opts.services = services return nil } }
WithProtocolServices injects a protocol services into the context.
https://github.com/hyperledger/aries-framework-go/blob/5ab9da9e29ab15dd980cd455cc44f788e031356c/pkg/framework/context/context.go#L453-L458
package context import ( "encoding/json" "errors" "fmt" "strings" "time" "github.com/btcsuite/btcutil/base58" "github.com/cenkalti/backoff/v4" jsonld "github.com/piprate/json-gold/ld" "github.com/hyperledger/aries-framework-go/pkg/common/log" "github.com/hyperledger/aries-framework-go/pkg/crypto" "github.com/hyperledger/aries-framework-go/pkg/didcomm/common/service" "github.com/hyperledger/aries-framework-go/pkg/didcomm/dispatcher" "github.com/hyperledger/aries-framework-go/pkg/didcomm/packer" "github.com/hyperledger/aries-framework-go/pkg/didcomm/protocol/didexchange" "github.com/hyperledger/aries-framework-go/pkg/didcomm/transport" "github.com/hyperledger/aries-framework-go/pkg/framework/aries/api" vdrapi "github.com/hyperledger/aries-framework-go/pkg/framework/aries/api/vdr" "github.com/hyperledger/aries-framework-go/pkg/kms" "github.com/hyperledger/aries-framework-go/pkg/secretlock" "github.com/hyperledger/aries-framework-go/pkg/store/did" "github.com/hyperledger/aries-framework-go/pkg/store/ld" "github.com/hyperledger/aries-framework-go/pkg/store/verifiable" "github.com/hyperledger/aries-framework-go/pkg/vdr/fingerprint" "github.com/hyperledger/aries-framework-go/spi/storage" ) const ( defaultGetDIDsMaxRetries = 3 kaIdentifier = "#" ) var logger = log.New("aries-framework/pkg/framework/context") type Provider struct { services []dispatcher.ProtocolService msgSvcProvider api.MessageServiceProvider storeProvider storage.Provider protocolStateStoreProvider storage.Provider kms kms.KeyManager secretLock secretlock.Service crypto crypto.Crypto packager transport.Packager primaryPacker packer.Packer packers []packer.Packer serviceEndpoint string routerEndpoint string outboundDispatcher dispatcher.Outbound messenger service.MessengerHandler outboundTransports []transport.OutboundTransport vdr vdrapi.Registry verifiableStore verifiable.Store didConnectionStore did.ConnectionStore contextStore ld.ContextStore remoteProviderStore ld.RemoteProviderStore documentLoader jsonld.DocumentLoader transportReturnRoute string frameworkID string keyType kms.KeyType keyAgreementType kms.KeyType mediaTypeProfiles []string getDIDsMaxRetries uint64 getDIDsBackOffDuration time.Duration } type inboundHandler struct { handlers []dispatcher.ProtocolService } func (in *inboundHandler) HandleInbound(msg service.DIDCommMsg, ctx service.DIDCommContext) (string, error) { for i := range in.handlers { if in.handlers[i].Accept(msg.Type()) { return in.handlers[i].HandleInbound(msg, ctx) } } return "", fmt.Errorf("no inbound handlers for msg type: %s", msg.Type()) } func New(opts ...ProviderOption) (*Provider, error) { ctxProvider := Provider{ getDIDsMaxRetries: defaultGetDIDsMaxRetries, getDIDsBackOffDuration: time.Second, } for _, opt := range opts { err := opt(&ctxProvider) if err != nil { return nil, fmt.Errorf("option failed: %w", err) } } return &ctxProvider, nil } func (p *Provider) OutboundDispatcher() dispatcher.Outbound { return p.outboundDispatcher } func (p *Provider) OutboundTransports() []transport.OutboundTransport { return p.outboundTransports } func (p *Provider) Service(id string) (interface{}, error) { for _, v := range p.services { if v.Name() == id { return v, nil } } return nil, api.ErrSvcNotFound } func (p *Provider) KMS() kms.KeyManager { return p.kms } func (p *Provider) SecretLock() secretlock.Service { return p.secretLock } func (p *Provider) Crypto() crypto.Crypto { return p.crypto } func (p *Provider) Packager() transport.Packager { return p.packager } func (p *Provider) Messenger() service.Messenger { return p.messenger } func (p *Provider) Packers() []packer.Packer { return p.packers } func (p *Provider) PrimaryPacker() packer.Packer { return p.primaryPacker } func (p *Provider) ServiceEndpoint() string { return p.serviceEndpoint } func (p *Provider) RouterEndpoint() string { return p.routerEndpoint } func (p *Provider) tryToHandle( svc service.InboundHandler, msg service.DIDCommMsgMap, ctx service.DIDCommContext) error { if err := p.messenger.HandleInbound(msg, ctx); err != nil { return fmt.Errorf("messenger HandleInbound: %w", err) } _, err := svc.HandleInbound(msg, ctx) return err } func (p *Provider) InboundMessageHandler() transport.InboundMessageHandler { return func(envelope *transport.Envelope) error { msg, err := service.ParseDIDCommMsgMap(envelope.Message) if err != nil { return err } for _, svc := range p.services { if svc.Accept(msg.Type()) { var myDID, theirDID string switch svc.Name() { case didexchange.DIDExchange: default: myDID, theirDID, err = p.getDIDs(envelope) if err != nil { return fmt.Errorf("inbound message handler: %w", err) } } _, err = svc.HandleInbound(msg, service.NewDIDCommContext(myDID, theirDID, nil)) return err } } for _, svc := range p.msgSvcProvider.Services() { h := struct { Purpose []string `json:"~purpose"` }{} err = msg.Decode(&h) if err != nil { return err } if svc.Accept(msg.Type(), h.Purpose) { myDID, theirDID, err := p.getDIDs(envelope) if err != nil { return fmt.Errorf("inbound message handler: %w", err) } return p.tryToHandle(svc, msg, service.NewDIDCommContext(myDID, theirDID, nil)) } } return fmt.Errorf("no message handlers found for the message type: %s", msg.Type()) } } func (p *Provider) getDIDs(envelope *transport.Envelope) (string, string, error) { var ( myDID string theirDID string err error ) return myDID, theirDID, backoff.Retry(func() error { var notFound bool if id := strings.Index(string(envelope.ToKey), kaIdentifier); id > 0 && strings.Index(string(envelope.ToKey), "\"kid\":\"did:") > 0 { myDID, err = pubKeyToDID(envelope.ToKey) if err != nil { return fmt.Errorf("getMyDID: envelope.ToKey as myDID: %w", err) } logger.Debugf("envelope.ToKey as myDID: %v", myDID) } else { myDID, err = p.didConnectionStore.GetDID(base58.Encode(envelope.ToKey)) if errors.Is(err, did.ErrNotFound) { notFound = true didKey, _ := fingerprint.CreateDIDKey(envelope.ToKey) myDID, err = p.didConnectionStore.GetDID(didKey) if err != nil && !errors.Is(err, did.ErrNotFound) { return fmt.Errorf("failed to get my did from didKey: %w", err) } } else if err != nil { return fmt.Errorf("failed to get my did: %w", err) } } if id := strings.Index(string(envelope.FromKey), kaIdentifier); id > 0 && strings.Index(string(envelope.FromKey), "\"kid\":\"did:") > 0 { theirDID, err = pubKeyToDID(envelope.FromKey) if err != nil { return fmt.Errorf("getDIDs: envelope.FromKey as theirDID: %w", err) } logger.Debugf("envelope.FromKey as theirDID: %v", theirDID) } else { if envelope.FromKey != nil { theirDID, err = p.didConnectionStore.GetDID(base58.Encode(envelope.FromKey)) if notFound && errors.Is(err, did.ErrNotFound) { didKey, _ := fingerprint.CreateDIDKey(envelope.FromKey) theirDID, err = p.didConnectionStore.GetDID(didKey) if err != nil && !errors.Is(err, did.ErrNotFound) { return fmt.Errorf("failed to get their did from didKey: %w", err) } } else if err != nil { return fmt.Errorf("failed to get their did: %w", err) } } } return nil }, backoff.WithMaxRetries(backoff.NewConstantBackOff(p.getDIDsBackOffDuration), p.getDIDsMaxRetries)) } func pubKeyToDID(key []byte) (string, error) { toKey := &crypto.PublicKey{} err := json.Unmarshal(key, toKey) if err != nil { return "", fmt.Errorf("pubKeyToDID: unmarshal key: %w", err) } return toKey.KID[:strings.Index(toKey.KID, kaIdentifier)], nil } func (p *Provider) InboundDIDCommMessageHandler() func() service.InboundHandler { return func() service.InboundHandler { tmp := make([]dispatcher.ProtocolService, len(p.services)) copy(tmp, p.services) return &inboundHandler{handlers: tmp} } } func (p *Provider) StorageProvider() storage.Provider { return p.storeProvider } func (p *Provider) ProtocolStateStorageProvider() storage.Provider { return p.protocolStateStoreProvider } func (p *Provider) VDRegistry() vdrapi.Registry { return p.vdr } func (p *Provider) TransportReturnRoute() string { return p.transportReturnRoute } func (p *Provider) AriesFrameworkID() string { return p.frameworkID } func (p *Provider) VerifiableStore() verifiable.Store { return p.verifiableStore } func (p *Provider) DIDConnectionStore() did.ConnectionStore { return p.didConnectionStore } func (p *Provider) JSONLDContextStore() ld.ContextStore { return p.contextStore } func (p *Provider) JSONLDRemoteProviderStore() ld.RemoteProviderStore { return p.remoteProviderStore } func (p *Provider) JSONLDDocumentLoader() jsonld.DocumentLoader { return p.documentLoader } func (p *Provider) KeyType() kms.KeyType { return p.keyType } func (p *Provider) KeyAgreementType() kms.KeyType { return p.keyAgreementType } func (p *Provider) MediaTypeProfiles() []string { return p.mediaTypeProfiles } type ProviderOption func(opts *Provider) error func WithOutboundTransports(transports ...transport.OutboundTransport) ProviderOption { return func(opts *Provider) error { opts.outboundTransports = transports return nil } } func WithGetDIDsMaxRetries(retries uint64) ProviderOption { return func(opts *Provider) error { opts.getDIDsMaxRetries = retries return nil } } func WithGetDIDsBackOffDuration(duration time.Duration) ProviderOption { return func(opts *Provider) error { opts.getDIDsBackOffDuration = duration return nil } } func WithOutboundDispatcher(outboundDispatcher dispatcher.Outbound) ProviderOption { return func(opts *Provider) error { opts.outboundDispatcher = outboundDispatcher return nil } } func WithMessengerHandler(mh service.MessengerHandler) ProviderOption { return func(opts *Provider) error { opts.messenger = mh return nil } } func WithTransportReturnRoute(transportReturnRoute string) ProviderOption { return func(opts *Provider) error { opts.transportReturnRoute = transportReturnRoute return nil } }
Apache License 2.0
cppforlife/knctl
vendor/github.com/gregjones/httpcache/httpcache.go
RoundTrip
go
func (t *Transport) RoundTrip(req *http.Request) (resp *http.Response, err error) { cacheKey := cacheKey(req) cacheable := (req.Method == "GET" || req.Method == "HEAD") && req.Header.Get("range") == "" var cachedResp *http.Response if cacheable { cachedResp, err = CachedResponse(t.Cache, req) } else { t.Cache.Delete(cacheKey) } transport := t.Transport if transport == nil { transport = http.DefaultTransport } if cacheable && cachedResp != nil && err == nil { if t.MarkCachedResponses { cachedResp.Header.Set(XFromCache, "1") } if varyMatches(cachedResp, req) { freshness := getFreshness(cachedResp.Header, req.Header) if freshness == fresh { return cachedResp, nil } if freshness == stale { var req2 *http.Request etag := cachedResp.Header.Get("etag") if etag != "" && req.Header.Get("etag") == "" { req2 = cloneRequest(req) req2.Header.Set("if-none-match", etag) } lastModified := cachedResp.Header.Get("last-modified") if lastModified != "" && req.Header.Get("last-modified") == "" { if req2 == nil { req2 = cloneRequest(req) } req2.Header.Set("if-modified-since", lastModified) } if req2 != nil { req = req2 } } } resp, err = transport.RoundTrip(req) if err == nil && req.Method == "GET" && resp.StatusCode == http.StatusNotModified { endToEndHeaders := getEndToEndHeaders(resp.Header) for _, header := range endToEndHeaders { cachedResp.Header[header] = resp.Header[header] } resp = cachedResp } else if (err != nil || (cachedResp != nil && resp.StatusCode >= 500)) && req.Method == "GET" && canStaleOnError(cachedResp.Header, req.Header) { return cachedResp, nil } else { if err != nil || resp.StatusCode != http.StatusOK { t.Cache.Delete(cacheKey) } if err != nil { return nil, err } } } else { reqCacheControl := parseCacheControl(req.Header) if _, ok := reqCacheControl["only-if-cached"]; ok { resp = newGatewayTimeoutResponse(req) } else { resp, err = transport.RoundTrip(req) if err != nil { return nil, err } } } if cacheable && canStore(parseCacheControl(req.Header), parseCacheControl(resp.Header)) { for _, varyKey := range headerAllCommaSepValues(resp.Header, "vary") { varyKey = http.CanonicalHeaderKey(varyKey) fakeHeader := "X-Varied-" + varyKey reqValue := req.Header.Get(varyKey) if reqValue != "" { resp.Header.Set(fakeHeader, reqValue) } } switch req.Method { case "GET": resp.Body = &cachingReadCloser{ R: resp.Body, OnEOF: func(r io.Reader) { resp := *resp resp.Body = ioutil.NopCloser(r) respBytes, err := httputil.DumpResponse(&resp, true) if err == nil { t.Cache.Set(cacheKey, respBytes) } }, } default: respBytes, err := httputil.DumpResponse(resp, true) if err == nil { t.Cache.Set(cacheKey, respBytes) } } } else { t.Cache.Delete(cacheKey) } return resp, nil }
RoundTrip takes a Request and returns a Response If there is a fresh Response already in cache, then it will be returned without connecting to the server. If there is a stale Response, then any validators it contains will be set on the new request to give the server a chance to respond with NotModified. If this happens, then the cached Response will be returned.
https://github.com/cppforlife/knctl/blob/47e523d82b9d655d8648fe36d371a084b4613945/vendor/github.com/gregjones/httpcache/httpcache.go#L139-L254
package httpcache import ( "bufio" "bytes" "errors" "io" "io/ioutil" "net/http" "net/http/httputil" "strings" "sync" "time" ) const ( stale = iota fresh transparent XFromCache = "X-From-Cache" ) type Cache interface { Get(key string) (responseBytes []byte, ok bool) Set(key string, responseBytes []byte) Delete(key string) } func cacheKey(req *http.Request) string { if req.Method == http.MethodGet { return req.URL.String() } else { return req.Method + " " + req.URL.String() } } func CachedResponse(c Cache, req *http.Request) (resp *http.Response, err error) { cachedVal, ok := c.Get(cacheKey(req)) if !ok { return } b := bytes.NewBuffer(cachedVal) return http.ReadResponse(bufio.NewReader(b), req) } type MemoryCache struct { mu sync.RWMutex items map[string][]byte } func (c *MemoryCache) Get(key string) (resp []byte, ok bool) { c.mu.RLock() resp, ok = c.items[key] c.mu.RUnlock() return resp, ok } func (c *MemoryCache) Set(key string, resp []byte) { c.mu.Lock() c.items[key] = resp c.mu.Unlock() } func (c *MemoryCache) Delete(key string) { c.mu.Lock() delete(c.items, key) c.mu.Unlock() } func NewMemoryCache() *MemoryCache { c := &MemoryCache{items: map[string][]byte{}} return c } type Transport struct { Transport http.RoundTripper Cache Cache MarkCachedResponses bool } func NewTransport(c Cache) *Transport { return &Transport{Cache: c, MarkCachedResponses: true} } func (t *Transport) Client() *http.Client { return &http.Client{Transport: t} } func varyMatches(cachedResp *http.Response, req *http.Request) bool { for _, header := range headerAllCommaSepValues(cachedResp.Header, "vary") { header = http.CanonicalHeaderKey(header) if header != "" && req.Header.Get(header) != cachedResp.Header.Get("X-Varied-"+header) { return false } } return true }
Apache License 2.0
wi2l/fizz
markdown/builder.go
H3
go
func (b *Builder) H3(text string) *Builder { return b.writeln(header(text, 3)).nl() }
H3 adds a level 3 header to the markdown.
https://github.com/wi2l/fizz/blob/d0b235e1c18db64d5fcb3206fb912d490a6af1a5/markdown/builder.go#L63-L65
package markdown import ( "fmt" "math" "regexp" "strings" "golang.org/x/text/unicode/norm" ) type TableAlignment uint8 const ( AlignLeft TableAlignment = iota AlignCenter AlignRight ) var reCRLN = regexp.MustCompile(`\r?\n`) type Builder struct { markdown string } func (b *Builder) String() string { return strings.TrimSpace(b.nl().markdown) } func (b *Builder) Block() *Builder { return new(Builder) } func (b *Builder) Line(text string) *Builder { return b.write(text) } func (b *Builder) P(text string) *Builder { return b.writeln(text).nl() } func (b *Builder) H1(text string) *Builder { return b.writeln(header(text, 1)).nl() } func (b *Builder) H2(text string) *Builder { return b.writeln(header(text, 2)).nl() }
MIT License
haproxytech/dataplaneapi
operations/stick_table/get_stick_table_entries_responses.go
WithConfigurationVersion
go
func (o *GetStickTableEntriesDefault) WithConfigurationVersion(configurationVersion string) *GetStickTableEntriesDefault { o.ConfigurationVersion = configurationVersion return o }
WithConfigurationVersion adds the configurationVersion to the get stick table entries default response
https://github.com/haproxytech/dataplaneapi/blob/b362aae0b04d0e330bd9dcfbf9f315b670de013b/operations/stick_table/get_stick_table_entries_responses.go#L118-L121
package stick_table import ( "net/http" "github.com/go-openapi/runtime" "github.com/haproxytech/client-native/v2/models" ) const GetStickTableEntriesOKCode int = 200 type GetStickTableEntriesOK struct { Payload models.StickTableEntries `json:"body,omitempty"` } func NewGetStickTableEntriesOK() *GetStickTableEntriesOK { return &GetStickTableEntriesOK{} } func (o *GetStickTableEntriesOK) WithPayload(payload models.StickTableEntries) *GetStickTableEntriesOK { o.Payload = payload return o } func (o *GetStickTableEntriesOK) SetPayload(payload models.StickTableEntries) { o.Payload = payload } func (o *GetStickTableEntriesOK) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { rw.WriteHeader(200) payload := o.Payload if payload == nil { payload = models.StickTableEntries{} } if err := producer.Produce(rw, payload); err != nil { panic(err) } } type GetStickTableEntriesDefault struct { _statusCode int ConfigurationVersion string `json:"Configuration-Version"` Payload *models.Error `json:"body,omitempty"` } func NewGetStickTableEntriesDefault(code int) *GetStickTableEntriesDefault { if code <= 0 { code = 500 } return &GetStickTableEntriesDefault{ _statusCode: code, } } func (o *GetStickTableEntriesDefault) WithStatusCode(code int) *GetStickTableEntriesDefault { o._statusCode = code return o } func (o *GetStickTableEntriesDefault) SetStatusCode(code int) { o._statusCode = code }
Apache License 2.0
spoke-d/thermionic
cmd/therm/cmd_discover_shutdown.go
NewDiscoverShutdownCmd
go
func NewDiscoverShutdownCmd(ui clui.UI) clui.Command { c := &discoverShutdownCmd{ ui: ui, flagset: flagset.NewFlagSet("discover", flag.ExitOnError), } c.init() return c }
NewDiscoverShutdownCmd creates a Command with sane defaults
https://github.com/spoke-d/thermionic/blob/d2438c51b10f8abb051b1d008e4a0067fd0537c6/cmd/therm/cmd_discover_shutdown.go#L27-L34
package main import ( "flag" "github.com/go-kit/kit/log" "github.com/go-kit/kit/log/level" "github.com/pborman/uuid" "github.com/pkg/errors" "github.com/spoke-d/clui" "github.com/spoke-d/clui/flagset" "github.com/spoke-d/thermionic/internal/exec" ) type discoverShutdownCmd struct { ui clui.UI flagset *flagset.FlagSet debug bool address string serverCert string clientCert string clientKey string }
Apache License 2.0
anuvu/zot
pkg/api/authz.go
can
go
func (ac *AccessController) can(username, action, repository string) bool { can := false pg, ok := ac.Config.Repositories[repository] if ok { can = isPermitted(username, action, pg) } if !can { if ac.isAdmin(username) && contains(ac.Config.AdminPolicy.Actions, action) { can = true } } return can }
can verifies if a user can do action on repository.
https://github.com/anuvu/zot/blob/8f3d7d371909729758f5a23f826c81fc4ad1e7c5/pkg/api/authz.go#L64-L80
package api import ( "context" "encoding/base64" "net/http" "strings" "time" "github.com/anuvu/zot/pkg/api/config" "github.com/anuvu/zot/pkg/log" "github.com/gorilla/mux" ) type contextKey int const ( CREATE = "create" READ = "read" UPDATE = "update" DELETE = "delete" authzCtxKey contextKey = 0 ) type AccessController struct { Config *config.AccessControlConfig Log log.Logger } type AccessControlContext struct { userAllowedRepos []string isAdmin bool } func NewAccessController(config *config.Config) *AccessController { return &AccessController{ Config: config.AccessControl, Log: log.NewLogger(config.Log.Level, config.Log.Output), } } func (ac *AccessController) getReadRepos(username string) []string { var repos []string for r, pg := range ac.Config.Repositories { for _, p := range pg.Policies { if (contains(p.Users, username) && contains(p.Actions, READ)) || contains(pg.DefaultPolicy, READ) { repos = append(repos, r) } } } return repos }
Apache License 2.0
thethingsnetwork/lorawan-stack
pkg/util/test/application_services.go
GetCollaborator
go
func (m MockApplicationAccessServer) GetCollaborator(ctx context.Context, req *ttnpb.GetApplicationCollaboratorRequest) (*ttnpb.GetCollaboratorResponse, error) { if m.GetCollaboratorFunc == nil { panic("GetCollaborator called, but not set") } return m.GetCollaboratorFunc(ctx, req) }
GetCollaborator calls GetCollaboratorFunc if set and panics otherwise.
https://github.com/thethingsnetwork/lorawan-stack/blob/228c615c0d55ce2eb21c750d644d9e9dd73d9f77/pkg/util/test/application_services.go#L77-L82
package test import ( "context" pbtypes "github.com/gogo/protobuf/types" "go.thethings.network/lorawan-stack/v3/pkg/ttnpb" ) type MockApplicationAccessServer struct { CreateAPIKeyFunc func(context.Context, *ttnpb.CreateApplicationAPIKeyRequest) (*ttnpb.APIKey, error) GetAPIKeyFunc func(context.Context, *ttnpb.GetApplicationAPIKeyRequest) (*ttnpb.APIKey, error) ListAPIKeysFunc func(context.Context, *ttnpb.ListApplicationAPIKeysRequest) (*ttnpb.APIKeys, error) ListCollaboratorsFunc func(context.Context, *ttnpb.ListApplicationCollaboratorsRequest) (*ttnpb.Collaborators, error) ListRightsFunc func(context.Context, *ttnpb.ApplicationIdentifiers) (*ttnpb.Rights, error) GetCollaboratorFunc func(context.Context, *ttnpb.GetApplicationCollaboratorRequest) (*ttnpb.GetCollaboratorResponse, error) SetCollaboratorFunc func(context.Context, *ttnpb.SetApplicationCollaboratorRequest) (*pbtypes.Empty, error) UpdateAPIKeyFunc func(context.Context, *ttnpb.UpdateApplicationAPIKeyRequest) (*ttnpb.APIKey, error) } func (m MockApplicationAccessServer) ListRights(ctx context.Context, req *ttnpb.ApplicationIdentifiers) (*ttnpb.Rights, error) { if m.ListRightsFunc == nil { panic("ListRights called, but not set") } return m.ListRightsFunc(ctx, req) } func (m MockApplicationAccessServer) CreateAPIKey(ctx context.Context, req *ttnpb.CreateApplicationAPIKeyRequest) (*ttnpb.APIKey, error) { if m.CreateAPIKeyFunc == nil { panic("CreateAPIKey called, but not set") } return m.CreateAPIKeyFunc(ctx, req) } func (m MockApplicationAccessServer) ListAPIKeys(ctx context.Context, req *ttnpb.ListApplicationAPIKeysRequest) (*ttnpb.APIKeys, error) { if m.ListAPIKeysFunc == nil { panic("ListAPIKeys called, but not set") } return m.ListAPIKeysFunc(ctx, req) } func (m MockApplicationAccessServer) GetAPIKey(ctx context.Context, req *ttnpb.GetApplicationAPIKeyRequest) (*ttnpb.APIKey, error) { if m.GetAPIKeyFunc == nil { panic("GetAPIKey called, but not set") } return m.GetAPIKeyFunc(ctx, req) } func (m MockApplicationAccessServer) UpdateAPIKey(ctx context.Context, req *ttnpb.UpdateApplicationAPIKeyRequest) (*ttnpb.APIKey, error) { if m.UpdateAPIKeyFunc == nil { panic("UpdateAPIKey called, but not set") } return m.UpdateAPIKeyFunc(ctx, req) }
Apache License 2.0
teambition/gear
logging/logger.go
SetJSONLog
go
func (l *Logger) SetJSONLog() *Logger { l.mu.Lock() defer l.mu.Unlock() l.json = true return l }
SetJSONLog set the logger writing JSON string log. It will become default in Gear@v2.
https://github.com/teambition/gear/blob/2a69ff4b7ee92d8e9bbc0e8b44ee7484af2fd117/logging/logger.go#L504-L509
package logging import ( "bytes" "encoding/json" "fmt" "io" "os" "strconv" "strings" "sync" "time" "github.com/teambition/gear" ) var crlfEscaper = strings.NewReplacer("\r", "\\r", "\n", "\\n") type Messager interface { fmt.Stringer Format() (string, error) } type Log map[string]interface{} func (l Log) Format() (string, error) { res, err := json.Marshal(l) if err == nil { return string(res), nil } return "", err } func (l Log) GoString() string { count := len(l) buf := bytes.NewBufferString("Log{") for key, value := range l { if count--; count == 0 { fmt.Fprintf(buf, "%s:%#v}", key, value) } else { fmt.Fprintf(buf, "%s:%#v, ", key, value) } } return buf.String() } func (l Log) String() string { return l.GoString() } func (l Log) KV(key string, value interface{}) Log { l[key] = value return l } func (l Log) From(log Log) Log { for key, val := range log { l[key] = val } return l } func (l Log) Into(log Log) Log { for key, val := range l { log[key] = val } return log } func (l Log) With(log map[string]interface{}) Log { cp := l.Into(Log{}) for key, val := range log { cp[key] = val } return cp } func (l Log) Reset() { for key := range l { delete(l, key) } } type Level uint8 const ( EmergLevel Level = iota AlertLevel CritLevel ErrLevel WarningLevel NoticeLevel InfoLevel DebugLevel ) const CritiLevel = CritLevel func (l Level) String() string { switch l { case EmergLevel: return "emerg" case AlertLevel: return "alert" case CritLevel: return "crit" case ErrLevel: return "err" case WarningLevel: return "warning" case NoticeLevel: return "notice" case InfoLevel: return "info" case DebugLevel: return "debug" default: return "log" } } func ParseLevel(lvl string) (Level, error) { switch strings.ToLower(lvl) { case "emergency", "emerg": return EmergLevel, nil case "alert": return AlertLevel, nil case "critical", "crit", "criti": return CritLevel, nil case "error", "err": return ErrLevel, nil case "warning", "warn": return WarningLevel, nil case "notice": return NoticeLevel, nil case "info": return InfoLevel, nil case "debug": return DebugLevel, nil } var l Level return l, fmt.Errorf("not a valid gear logging Level: %q", lvl) } func SetLoggerLevel(logger *Logger, lvl string) error { level, err := ParseLevel(lvl) if err == nil { logger.SetLevel(level) } return err } var std = New(os.Stderr) func Default(devMode ...bool) *Logger { if len(devMode) > 0 && devMode[0] { std.SetLogConsume(developmentConsume) } return std } func developmentConsume(log Log, ctx *gear.Context) { std.mu.Lock() defer std.mu.Unlock() end := time.Now().UTC() FprintWithColor(std.Out, fmt.Sprintf("%s", log["ip"]), ColorGreen) fmt.Fprintf(std.Out, ` - - [%s] "%s %s %s" `, end.Format(std.tf), log["method"], log["uri"], log["proto"]) status := log["status"].(int) FprintWithColor(std.Out, strconv.Itoa(status), colorStatus(status)) resTime := float64(end.Sub(ctx.StartAt)) / 1e6 fmt.Fprintln(std.Out, fmt.Sprintf(" %d %.3fms", log["length"], resTime)) } func New(w io.Writer) *Logger { logger := &Logger{Out: w} logger.SetLevel(DebugLevel) logger.SetTimeFormat("2006-01-02T15:04:05.000Z") logger.SetLogFormat("[%s] %s %s") logger.init = func(log Log, ctx *gear.Context) { log["start"] = ctx.StartAt.Format(logger.tf) log["ip"] = ctx.IP().String() log["scheme"] = ctx.Scheme() log["proto"] = ctx.Req.Proto log["method"] = ctx.Method log["uri"] = ctx.Req.RequestURI if s := ctx.GetHeader(gear.HeaderOrigin); s != "" { log["origin"] = s } if s := ctx.GetHeader(gear.HeaderReferer); s != "" { log["referer"] = s } if s := ctx.GetHeader(gear.HeaderXCanary); s != "" { log["xCanary"] = s } log["userAgent"] = ctx.GetHeader(gear.HeaderUserAgent) } logger.consume = func(log Log, ctx *gear.Context) { end := time.Now().UTC() log["duration"] = end.Sub(ctx.StartAt) / 1e6 if s := ctx.GetHeader(gear.HeaderXRequestID); s != "" { log["xRequestId"] = s } else if s := ctx.Res.Get(gear.HeaderXRequestID); s != "" { log["xRequestId"] = s } if router := gear.GetRouterPatternFromCtx(ctx); router != "" { log["router"] = fmt.Sprintf("%s %s", ctx.Method, router) } if err := logger.output(end, InfoLevel, log); err != nil { logger.output(end, ErrLevel, err) } } return logger } type Logger struct { Out io.Writer json bool l Level tf, lf string mu sync.Mutex init func(Log, *gear.Context) consume func(Log, *gear.Context) } func (l *Logger) checkLogLevel(level Level) bool { return level <= l.l } func (l *Logger) Emerg(v interface{}) { l.output(time.Now().UTC(), EmergLevel, v) } func (l *Logger) Alert(v interface{}) { if l.checkLogLevel(AlertLevel) { l.output(time.Now().UTC(), AlertLevel, v) } } func (l *Logger) Crit(v interface{}) { if l.checkLogLevel(CritLevel) { l.output(time.Now().UTC(), CritLevel, v) } } func (l *Logger) Err(v interface{}) { if l.checkLogLevel(ErrLevel) { l.output(time.Now().UTC(), ErrLevel, v) } } func (l *Logger) Warning(v interface{}) { if l.checkLogLevel(WarningLevel) { l.output(time.Now().UTC(), WarningLevel, v) } } func (l *Logger) Notice(v interface{}) { if l.checkLogLevel(NoticeLevel) { l.output(time.Now().UTC(), NoticeLevel, v) } } func (l *Logger) Info(v interface{}) { if l.checkLogLevel(InfoLevel) { l.output(time.Now().UTC(), InfoLevel, v) } } func (l *Logger) Debug(v interface{}) { if l.checkLogLevel(DebugLevel) { l.output(time.Now().UTC(), DebugLevel, v) } } func (l *Logger) Debugf(format string, args ...interface{}) { if l.checkLogLevel(DebugLevel) { l.output(time.Now().UTC(), DebugLevel, fmt.Sprintf(format, args...)) } } func (l *Logger) Panic(v interface{}) { s := format(v) l.Emerg(s) panic(s) } var exit = func() { os.Exit(1) } func (l *Logger) Fatal(v interface{}) { l.Emerg(v) exit() } func (l *Logger) Print(args ...interface{}) { l.mu.Lock() defer l.mu.Unlock() fmt.Fprint(l.Out, args...) } func (l *Logger) Printf(format string, args ...interface{}) { l.mu.Lock() defer l.mu.Unlock() fmt.Fprintf(l.Out, format, args...) } func (l *Logger) Println(args ...interface{}) { l.mu.Lock() defer l.mu.Unlock() fmt.Fprintln(l.Out, args...) } func (l *Logger) output(t time.Time, level Level, v interface{}) (err error) { if l.json { var log Log if level > ErrLevel { log = format2Log(v) } else { log = formatError2Log(v) } log["time"] = t.Format(l.tf) log["level"] = level.String() return l.OutputJSON(log) } var s string if level > ErrLevel { s = format(v) } else { s = formatError(v) } return l.Output(t, level, s) } func (l *Logger) Output(t time.Time, level Level, s string) (err error) { l.mu.Lock() defer l.mu.Unlock() if l := len(s); l > 0 && s[l-1] == '\n' { s = s[0 : l-1] } _, err = fmt.Fprintf(l.Out, l.lf, t.UTC().Format(l.tf), level.String(), crlfEscaper.Replace(s)) if err == nil { l.Out.Write([]byte{'\n'}) } return } func (l *Logger) OutputJSON(log Log) (err error) { l.mu.Lock() defer l.mu.Unlock() var str string if str, err = log.Format(); err == nil { _, err = fmt.Fprint(l.Out, crlfEscaper.Replace(str)) if err == nil { l.Out.Write([]byte{'\n'}) } } return } func (l *Logger) GetLevel() Level { l.mu.Lock() defer l.mu.Unlock() return l.l } func (l *Logger) SetLevel(level Level) *Logger { l.mu.Lock() defer l.mu.Unlock() if level > DebugLevel { panic(gear.Err.WithMsg("invalid logger level")) } l.l = level return l }
MIT License
skanehira/docui
docker/network.go
Networks
go
func (d *Docker) Networks(opt types.NetworkListOptions) ([]types.NetworkResource, error) { return d.NetworkList(context.TODO(), opt) }
Networks get networks
https://github.com/skanehira/docui/blob/e0a6691d4af44ecf6ad5bb63585597029cd5e48f/docker/network.go#L10-L12
package docker import ( "context" "github.com/docker/docker/api/types" )
MIT License
beego/mux
tree.go
GetName
go
func (n *Node) GetName(name string) *Node { if n.getRootNode().namedRoutes != nil { return n.getRootNode().namedRoutes[name] } return nil }
GetName returns the name for the route, if any.
https://github.com/beego/mux/blob/6660b4b5accbb383fac89498e57d3250d5e907ac/tree.go#L318-L323
package mux import ( "fmt" "net/url" "regexp" "strings" ) const Version = "0.0.1" var ( allowSuffixExt = []string{".json", ".xml", ".html"} extWildRegexp = regexp.MustCompile(`([^.]+).(.+)`) wildRegexp = regexp.MustCompile(`(.+)`) wordRegexp = regexp.MustCompile(`^\w+$`) paramRegexp = regexp.MustCompile(`^:\w+$`) optionalParamRegexp = regexp.MustCompile(`^\?:\w+$`) defaultOptions = Options{ CaseSensitive: true, PathClean: true, StrictSlash: true, UseEncodedPath: true, } ) type Options struct { CaseSensitive bool PathClean bool StrictSlash bool UseEncodedPath bool } func NewTrie(args ...Options) *Trie { opts := defaultOptions if len(args) > 0 { opts = args[0] } return &Trie{ caseSensitive: opts.CaseSensitive, pathClean: opts.PathClean, strictSlash: opts.StrictSlash, useEncodedPath: opts.UseEncodedPath, root: &Node{ parent: nil, children: make(map[string]*Node), handlers: make(map[string]interface{}), }, } } type Trie struct { caseSensitive bool pathClean bool strictSlash bool useEncodedPath bool root *Node } func (t *Trie) Parse(pattern string) *Node { if strings.Contains(pattern, "//") { panic(fmt.Errorf(`multi-slash exist: "%s"`, pattern)) } _pattern := strings.TrimPrefix(pattern, "/") if !t.caseSensitive { _pattern = strings.ToLower(_pattern) } node := parsePattern(t.root, strings.Split(_pattern, "/")) if node.pattern == "" { node.pattern = pattern } return node } func (t *Trie) Match(path string) (*Matched, error) { if path == "" || path[0] != '/' { return nil, fmt.Errorf(`path is not start with "/": "%s"`, path) } if t.pathClean { path = pathClean(path) } if !t.caseSensitive { path = strings.ToLower(path) } start := 1 end := len(path) matched := new(Matched) parent := t.root for i := 1; i <= end; i++ { if i < end && path[i] != '/' { continue } segment := path[start:i] node := matchNode(parent, segment, path[i:]) if node == nil { if parent.endpoint && i == end && segment == "" { matched.Path = path[:end-1] } if i == end { for _, ext := range allowSuffixExt { if strings.HasSuffix(segment, ext) { node = matchNode(parent, strings.TrimSuffix(segment, ext), path[i:]) if node != nil { if matched.Params == nil { matched.Params = make(map[string]string) } matched.Params[":ext"] = ext[1:] goto ParentNode } } } } return matched, nil } ParentNode: parent = node if len(parent.name) > 0 { if matched.Params == nil { matched.Params = make(map[string]string) } if parent.wildcard { if len(parent.name) == 1 { segs := strings.Split(path[start:end], "/") starValue := []string{} for { if len(segs) > 0 { starValue = append(starValue, segs[0]) } if len(segs) == 1 { break } else { segs = segs[1:] } n := matchNode(parent, segs[0], strings.Join(segs, "/")) if n != nil { matched.Params[parent.name[0]] = strings.Join(starValue, "/") parent = n i = i + 1 + len(segs[0]) start = start + len(strings.Join(starValue, "/")) goto END } else { i = i + 1 + len(segs[0]) } } matched.Params[parent.name[0]] = strings.Join(starValue, "/") } else { values := parent.regex.FindStringSubmatch(path[start:end]) if len(values) != len(parent.name)+1 { return nil, fmt.Errorf("%s: Find wrong match %v, need names %v", path, values, parent.name) } for i, name := range parent.name { matched.Params[name] = values[i+1] } } break } else if parent.regex == nil { matched.Params[parent.name[0]] = segment } else { values := parent.regex.FindStringSubmatch(segment) for i, name := range parent.name { matched.Params[name] = values[i+1] } } } start = i + 1 END: } switch { case parent.endpoint: matched.Node = parent case parent.getChild("") != nil: matched.Path = path + "/" case len(parent.optionChildren) > 0: for _, child := range parent.optionChildren { matched.Node = child break } } return matched, nil } type Matched struct { Node *Node Params map[string]string Path string } type Node struct { name, allow []string pattern, segment string endpoint, wildcard, optional bool parent *Node segChildren []*Node optionChildren []*Node varyChildren []*Node children map[string]*Node handlers map[string]interface{} regex *regexp.Regexp namedRoutes map[string]*Node } func (n *Node) getSegments() string { segments := n.segment if n.parent != nil { segments = n.parent.getSegments() + "/" + segments } return segments } func (n *Node) getChild(key string) *Node { if strings.Contains(key, "::") { key = strings.Replace(key, "::", ":", -1) } if v, ok := n.children[key]; ok { return v } for _, c := range n.segChildren { if c.segment == key { return c } } for _, c := range n.optionChildren { if c.segment == key { return c } } for _, c := range n.varyChildren { if c.segment == key { return c } } return nil } func (n *Node) Name(name string) *Node { if n.getRootNode().namedRoutes == nil { n.getRootNode().namedRoutes = map[string]*Node{name: n} } else { if _, ok := n.getRootNode().namedRoutes[name]; ok { panic(fmt.Errorf("mux: route already has name %q, can't set", name)) } n.getRootNode().namedRoutes[name] = n } return n }
Apache License 2.0
centurylinklabs/panamax-kubernetes-adapter-go
Godeps/_workspace/src/github.com/GoogleCloudPlatform/kubernetes/pkg/client/helper.go
DefaultKubernetesUserAgent
go
func DefaultKubernetesUserAgent() string { commit := version.Get().GitCommit if len(commit) > 7 { commit = commit[:7] } if len(commit) == 0 { commit = "unknown" } version := version.Get().GitVersion seg := strings.SplitN(version, "-", 2) version = seg[0] return fmt.Sprintf("%s/%s (%s/%s) kubernetes/%s", path.Base(os.Args[0]), version, gruntime.GOOS, gruntime.GOARCH, commit) }
DefaultKubernetesUserAgent returns the default user agent that clients can use.
https://github.com/centurylinklabs/panamax-kubernetes-adapter-go/blob/788d52c95fa598ab0cf65e5b26526301a16d11aa/Godeps/_workspace/src/github.com/GoogleCloudPlatform/kubernetes/pkg/client/helper.go#L365-L377
package client import ( "fmt" "net" "net/http" "net/url" "os" "path" "reflect" gruntime "runtime" "strings" "time" "github.com/GoogleCloudPlatform/kubernetes/pkg/api/latest" "github.com/GoogleCloudPlatform/kubernetes/pkg/runtime" "github.com/GoogleCloudPlatform/kubernetes/pkg/version" ) type Config struct { Host string Prefix string Version string LegacyBehavior bool Codec runtime.Codec Username string Password string BearerToken string TLSClientConfig Insecure bool UserAgent string Transport http.RoundTripper } type KubeletConfig struct { Port uint EnableHttps bool TLSClientConfig } type TLSClientConfig struct { CertFile string KeyFile string CAFile string CertData []byte KeyData []byte CAData []byte } func New(c *Config) (*Client, error) { config := *c if err := SetKubernetesDefaults(&config); err != nil { return nil, err } client, err := RESTClientFor(&config) if err != nil { return nil, err } return &Client{client}, nil } func MatchesServerVersion(c *Config) error { client, err := New(c) if err != nil { return err } clientVersion := version.Get() serverVersion, err := client.ServerVersion() if err != nil { return fmt.Errorf("couldn't read version from server: %v\n", err) } if s := *serverVersion; !reflect.DeepEqual(clientVersion, s) { return fmt.Errorf("server version (%#v) differs from client version (%#v)!\n", s, clientVersion) } return nil } func NewOrDie(c *Config) *Client { client, err := New(c) if err != nil { panic(err) } return client } func SetKubernetesDefaults(config *Config) error { if config.Prefix == "" { config.Prefix = "/api" } if len(config.UserAgent) == 0 { config.UserAgent = DefaultKubernetesUserAgent() } if len(config.Version) == 0 { config.Version = defaultVersionFor(config) } version := config.Version versionInterfaces, err := latest.InterfacesFor(version) if err != nil { return fmt.Errorf("API version '%s' is not recognized (valid values: %s)", version, strings.Join(latest.Versions, ", ")) } if config.Codec == nil { config.Codec = versionInterfaces.Codec } config.LegacyBehavior = (version == "v1beta1" || version == "v1beta2") return nil } func RESTClientFor(config *Config) (*RESTClient, error) { if len(config.Version) == 0 { return nil, fmt.Errorf("version is required when initializing a RESTClient") } if config.Codec == nil { return nil, fmt.Errorf("Codec is required when initializing a RESTClient") } baseURL, err := defaultServerUrlFor(config) if err != nil { return nil, err } client := NewRESTClient(baseURL, config.Version, config.Codec, config.LegacyBehavior) transport, err := TransportFor(config) if err != nil { return nil, err } if transport != http.DefaultTransport { client.Client = &http.Client{Transport: transport} } return client, nil } func TransportFor(config *Config) (http.RoundTripper, error) { hasCA := len(config.CAFile) > 0 || len(config.CAData) > 0 hasCert := len(config.CertFile) > 0 || len(config.CertData) > 0 if config.Transport != nil && (hasCA || hasCert || config.Insecure) { return nil, fmt.Errorf("using a custom transport with TLS certificate options or the insecure flag is not allowed") } tlsConfig, err := TLSConfigFor(config) if err != nil { return nil, err } var transport http.RoundTripper if config.Transport != nil { transport = config.Transport } else { if tlsConfig != nil { transport = &http.Transport{ TLSClientConfig: tlsConfig, Proxy: http.ProxyFromEnvironment, Dial: (&net.Dialer{ Timeout: 30 * time.Second, KeepAlive: 30 * time.Second, }).Dial, TLSHandshakeTimeout: 10 * time.Second, } } else { transport = http.DefaultTransport } } transport, err = HTTPWrappersForConfig(config, transport) if err != nil { return nil, err } return transport, nil } func HTTPWrappersForConfig(config *Config, rt http.RoundTripper) (http.RoundTripper, error) { hasBasicAuth := config.Username != "" || config.Password != "" if hasBasicAuth && config.BearerToken != "" { return nil, fmt.Errorf("username/password or bearer token may be set, but not both") } switch { case config.BearerToken != "": rt = NewBearerAuthRoundTripper(config.BearerToken, rt) case hasBasicAuth: rt = NewBasicAuthRoundTripper(config.Username, config.Password, rt) } if len(config.UserAgent) > 0 { rt = NewUserAgentRoundTripper(config.UserAgent, rt) } return rt, nil } func DefaultServerURL(host, prefix, version string, defaultTLS bool) (*url.URL, error) { if host == "" { return nil, fmt.Errorf("host must be a URL or a host:port pair") } if version == "" { return nil, fmt.Errorf("version must be set") } base := host hostURL, err := url.Parse(base) if err != nil { return nil, err } if hostURL.Scheme == "" { scheme := "http://" if defaultTLS { scheme = "https://" } hostURL, err = url.Parse(scheme + base) if err != nil { return nil, err } if hostURL.Path != "" && hostURL.Path != "/" { return nil, fmt.Errorf("host must be a URL or a host:port pair: %s", base) } } if hostURL.Path == "" { if prefix == "" { prefix = "/" } hostURL.Path = prefix } hostURL.Path = path.Join(hostURL.Path, version) return hostURL, nil } func IsConfigTransportTLS(config Config) bool { config.Version = defaultVersionFor(&config) baseURL, err := defaultServerUrlFor(&config) if err != nil { return false } return baseURL.Scheme == "https" } func defaultServerUrlFor(config *Config) (*url.URL, error) { hasCA := len(config.CAFile) != 0 || len(config.CAData) != 0 hasCert := len(config.CertFile) != 0 || len(config.CertData) != 0 defaultTLS := hasCA || hasCert || config.Insecure host := config.Host if host == "" { host = "localhost" } return DefaultServerURL(host, config.Prefix, config.Version, defaultTLS) } func defaultVersionFor(config *Config) string { version := config.Version if version == "" { version = latest.Version } return version }
Apache License 2.0
shopify/themekit
src/env/conf.go
Set
go
func (c *Conf) Set(name string, initial Env, overrides ...Env) (*Env, error) { if name == "" { return nil, ErrInvalidEnvironmentName } var err error c.Envs[name], err = newEnv(name, initial, append([]Env{c.osEnv}, overrides...)...) return c.Envs[name], err }
Set will set the environment value and then mixin any overrides passed in. The os overrides and defaults will also be mixed into the new environment
https://github.com/shopify/themekit/blob/67657c9b0b3c269462b1bb33797c78cc6caa8ccc/src/env/conf.go#L103-L110
package env import ( "errors" "fmt" "io" "io/ioutil" "os" "path/filepath" "encoding/json" "github.com/caarlos0/env" "github.com/joho/godotenv" "github.com/shibukawa/configdir" "gopkg.in/yaml.v1" ) const ( vendor = "Shopify" appname = "Themekit" filename = "variables" ) var ( cdir = configdir.New(vendor, appname) supportedExts = []string{"yml", "yaml", "json"} ErrEnvDoesNotExist = errors.New("environment does not exist in this environments list") ErrEnvNotDefined = errors.New("environment was found but not defined") ErrNoEnvironmentsDefined = errors.New("no environments defined, nothing to write") ErrInvalidEnvironmentName = errors.New("environment name cannot be blank") ) type Conf struct { Envs map[string]*Env osEnv Env path string } func init() { cdir.LocalPath, _ = os.Getwd() } func SourceVariables(flagpath string) error { if flagpath != "" { return godotenv.Load(flagpath) } if fldr := cdir.QueryFolderContainsFile(filename); fldr != nil { return godotenv.Load(filepath.Join(fldr.Path, filename)) } return nil } func New(configPath string) Conf { conf := Conf{ Envs: make(map[string]*Env), osEnv: Env{}, path: configPath, } env.Parse(&conf.osEnv) return conf } func Load(configPath string) (Conf, error) { conf := New(configPath) path, ext, err := searchConfigPath(configPath) if err != nil { return conf, err } contents, err := ioutil.ReadFile(path) if err != nil { return conf, err } contents = []byte(os.ExpandEnv(string(contents))) switch ext { case "yml", "yaml": if err = yaml.Unmarshal(contents, &conf.Envs); err != nil { return conf, fmt.Errorf("Invalid yaml found while loading the config file: %v", err) } case "json": if err = json.Unmarshal(contents, &conf.Envs); err != nil { return conf, fmt.Errorf("Invalid json found while loading the config file: %v", err) } } return conf, nil }
MIT License
simagix/keyhole
sim/runner.go
SetTPS
go
func (rn *Runner) SetTPS(tps int) { rn.tps = tps }
SetTPS set transaction per second
https://github.com/simagix/keyhole/blob/7174018f9e99228b339dc2b286e336aee09f487c/sim/runner.go#L100-L102
package sim import ( "bufio" "context" "encoding/json" "fmt" "log" "os" "os/signal" "runtime" "strings" "sync" "syscall" "time" "github.com/simagix/gox" anly "github.com/simagix/keyhole/analytics" "github.com/simagix/keyhole/mdb" "go.mongodb.org/mongo-driver/bson" "go.mongodb.org/mongo-driver/mongo" "go.mongodb.org/mongo-driver/mongo/options" "go.mongodb.org/mongo-driver/x/mongo/driver/connstring" ) const ( outdir = "./out" ) type Runner struct { Logger *gox.Logger `bson:"keyhole"` Metrics map[string][]bson.M `bson:"metrics"` Results []string `bson:"results"` auto bool channel chan string client *mongo.Client clusterType string collectionName string conns int connString connstring.ConnString dbName string drop bool duration int filename string mutex sync.RWMutex peek bool simOnly bool tps int txFilename string uri string uriList []string verbose bool } func NewRunner(connString connstring.ConnString) (*Runner, error) { var err error runner := Runner{Logger: gox.GetLogger("keyhole"), connString: connString, conns: runtime.NumCPU(), channel: make(chan string), collectionName: mdb.ExamplesCollection, Metrics: map[string][]bson.M{}, mutex: sync.RWMutex{}} runner.dbName = connString.Database if runner.dbName == "" { runner.dbName = mdb.KeyholeDB } if runner.client, err = mdb.NewMongoClient(connString.String()); err != nil { return &runner, err } stats := mdb.NewClusterStats("") stats.GetClusterStatsSummary(runner.client) runner.clusterType = stats.Cluster if runner.clusterType == "" { runner.Logger.Warn("unable to retrieve cluster type") } runner.uriList = []string{connString.String()} if runner.clusterType == mdb.Sharded { if shards, err := mdb.GetShards(runner.client); err != nil { return &runner, err } else if runner.uriList, err = mdb.GetAllShardURIs(shards, connString); err != nil { return &runner, err } } runner.uri = runner.uriList[len(runner.uriList)-1] return &runner, nil } func (rn *Runner) SetCollection(collectionName string) { if collectionName != "" { rn.collectionName = collectionName } else { rn.collectionName = mdb.ExamplesCollection } }
Apache License 2.0
vbaksa/promoter
vendor/github.com/docker/distribution/registry/storage/driver/filesystem/driver.go
FromParameters
go
func FromParameters(parameters map[string]interface{}) (*Driver, error) { params, err := fromParametersImpl(parameters) if err != nil || params == nil { return nil, err } return New(*params), nil }
FromParameters constructs a new Driver with a given parameters map Optional Parameters: - rootdirectory - maxthreads
https://github.com/vbaksa/promoter/blob/01f99cbc59570e17b88e49dcc02c67386426da90/vendor/github.com/docker/distribution/registry/storage/driver/filesystem/driver.go#L68-L74
package filesystem import ( "bufio" "bytes" "fmt" "io" "io/ioutil" "os" "path" "reflect" "strconv" "time" "github.com/docker/distribution/context" storagedriver "github.com/docker/distribution/registry/storage/driver" "github.com/docker/distribution/registry/storage/driver/base" "github.com/docker/distribution/registry/storage/driver/factory" ) const ( driverName = "filesystem" defaultRootDirectory = "/var/lib/registry" defaultMaxThreads = uint64(100) minThreads = uint64(25) ) type DriverParameters struct { RootDirectory string MaxThreads uint64 } func init() { factory.Register(driverName, &filesystemDriverFactory{}) } type filesystemDriverFactory struct{} func (factory *filesystemDriverFactory) Create(parameters map[string]interface{}) (storagedriver.StorageDriver, error) { return FromParameters(parameters) } type driver struct { rootDirectory string } type baseEmbed struct { base.Base } type Driver struct { baseEmbed }
Apache License 2.0
jkomoros/boardgame
boardgame-util/lib/golden/comparer.go
ApplyNextSpecialAdminMove
go
func (c *comparer) ApplyNextSpecialAdminMove() (bool, error) { nextMoveRec, err := c.golden.Move(c.lastVerifiedVersion + 1) if err != nil { return false, nil } if nextMoveRec.Proposer >= 0 { return false, nil } move := c.game.MoveByName(nextMoveRec.Name) if move == nil { return false, errors.New("Couldn't fetch move named: " + nextMoveRec.Name) } if isSeatPlayer, ok := move.(interfaces.SeatPlayerMover); ok && isSeatPlayer.IsSeatPlayerMove() { index, err := move.Reader().PlayerIndexProp("TargetPlayerIndex") if err != nil { return false, errors.New("Couldn't get expected TargetPlayerIndex from next SeatPlayer: " + err.Error()) } c.storage.injectPlayerToSeat(index) if err := <-c.manager.Internals().ForceFixUp(c.game); err != nil { return false, errors.New("Couldn't force inject a SeatPlayer move: " + err.Error()) } return true, nil } if c.manager.Internals().ForceNextTimer() { return true, nil } return false, errors.New("At version " + strconv.Itoa(c.lastVerifiedVersion) + " the next player move to apply was not applied by a player. This implies that the fixUp move named " + nextMoveRec.Name + " is erroneously returning an error from its Legal method.") }
ApplyNextSpecialAdminMove will return the next special admin move, returning true if one was applied. Typically Admin (FixUp) moves are applied automatically by the engine after a PlayerMove is applied. But two special kinds of moves have to be handeled specially: 1) timers that are queued up but have not fired yet, and 2) SeatPlayer moves.
https://github.com/jkomoros/boardgame/blob/8898c2fef62886c854799846a86c0de1d546f78a/boardgame-util/lib/golden/comparer.go#L241-L290
package golden import ( "bytes" "encoding/json" "errors" "fmt" "reflect" "strconv" "time" "github.com/jkomoros/boardgame" "github.com/jkomoros/boardgame/moves/interfaces" "github.com/jkomoros/boardgame/storage/filesystem/record" ) type comparer struct { manager *boardgame.GameManager golden *record.Record storage *storageManager game *boardgame.Game buf *bytes.Buffer lastBuf *bytes.Buffer lastVerifiedVersion int } func newComparer(manager *boardgame.GameManager, rec *record.Record, storage *storageManager) (*comparer, error) { if existingGameRec, _ := storage.Game(rec.Game().ID); existingGameRec != nil { return nil, errors.New("The storage layer already has a game with that ID. Use a fresh storage manager") } storage.gameRecords[rec.Game().ID] = rec game, err := manager.Internals().RecreateGame(rec.Game()) if err != nil { return nil, errors.New("Couldn't create game: " + err.Error()) } result := &comparer{ manager, rec, storage, game, nil, nil, 0, } return result, nil } func (c *comparer) PrintDebug() { if c.lastBuf == nil { return } if c.lastBuf.Len() == 0 { return } fmt.Println(c.lastBuf) fmt.Println("Last state: ") state := c.game.State(c.lastVerifiedVersion) jsonBuf, _ := json.MarshalIndent(state, "", "\t") fmt.Println(string(jsonBuf)) } func (c *comparer) ResetDebugLog() { c.lastBuf = c.buf logger, buf := newLogger() c.manager.SetLogger(logger) c.buf = buf } func (c *comparer) GoldenHasRemainingMoves() bool { return c.golden.Game().Version > c.lastVerifiedVersion } func (c *comparer) LastVerifiedVersion() int { return c.lastVerifiedVersion } func (c *comparer) AdvanceToNextInitiatorMove() { if c.game.Version() > 0 { c.lastVerifiedVersion++ } for c.lastVerifiedVersion <= len(c.golden.RawMoves())+2 { nextMoveRec, err := c.golden.Move(c.lastVerifiedVersion + 1) if err != nil { return } if nextMoveRec.Initiator == nextMoveRec.Version { return } c.lastVerifiedVersion++ } } func (c *comparer) VerifyUnverifiedMoves() error { verifiedAtLeastOne := false for c.lastVerifiedVersion < c.game.Version() { stateToCompare, err := c.golden.State(c.lastVerifiedVersion) if err != nil { return errors.New("Couldn't get " + strconv.Itoa(c.lastVerifiedVersion) + " state: " + err.Error()) } storageRec, err := c.manager.Storage().State(c.game.ID(), c.lastVerifiedVersion) if err != nil { return errors.New("Couldn't get state storage rec from game: " + err.Error()) } if c.lastVerifiedVersion > 0 { recMove, err := c.golden.Move(c.lastVerifiedVersion) if err != nil { return errors.New("Couldn't get move " + strconv.Itoa(c.lastVerifiedVersion) + " from record") } moves := c.game.MoveRecords(c.lastVerifiedVersion) if len(moves) < 1 { return errors.New("Didn't fetch historical move records for " + strconv.Itoa(c.lastVerifiedVersion)) } if err := compareMoveStorageRecords(*moves[len(moves)-1], *recMove, false); err != nil { return errors.New("Move " + strconv.Itoa(c.lastVerifiedVersion) + " compared differently: " + err.Error()) } } if err := compareJSONBlobs(storageRec, stateToCompare); err != nil { return errors.New("State " + strconv.Itoa(c.lastVerifiedVersion) + " compared differently: " + err.Error()) } c.lastVerifiedVersion++ verifiedAtLeastOne = true } if !verifiedAtLeastOne && c.game.Version() > 0 { return errors.New("VerifyUnverifiedMoves didn't verify any new moves; this implies that ApplyNextMove isn't actually applying the next move") } return nil } func (c *comparer) ApplyNextMove() (bool, error) { applied, err := c.ApplyNextSpecialAdminMove() if err != nil { return false, errors.New("Couldn't apply next special admin move: " + err.Error()) } if applied { return true, nil } applied, err = c.ApplyNextPlayerMove() if err != nil { return false, errors.New("Couldn't apply next player move: " + err.Error()) } return applied, nil } func (c *comparer) ApplyNextPlayerMove() (bool, error) { nextMoveRec, err := c.golden.Move(c.lastVerifiedVersion + 1) if err != nil { return false, nil } if nextMoveRec.Proposer < 0 { return false, nil } nextMove, err := c.manager.Internals().InflateMoveStorageRecord(nextMoveRec, c.game) if err != nil { return false, errors.New("Couldn't inflate move: " + err.Error()) } if err := <-c.game.ProposeMove(nextMove, nextMoveRec.Proposer); err != nil { return false, errors.New("Couldn't propose next move in chain: " + strconv.Itoa(nextMoveRec.Version) + ": " + err.Error()) } return true, nil }
Apache License 2.0
coinrust/crex
backtest/backtest.go
Plot
go
func (b *Backtest) Plot() { var plotData PlotData strategyTester := b.strategyTesters[0] for _, v := range strategyTester.logs { plotData.NameItems = append(plotData.NameItems, v.Time.Format(SimpleDateTimeFormat)) plotData.Prices = append(plotData.Prices, v.Prices[0]) plotData.Equities = append(plotData.Equities, v.TotalEquity()) } p := charts.NewPage() p.Add(b.priceLine(&plotData), b.equityLine(&plotData)) filename := filepath.Join(b.outputDir, "result.html") f, err := os.Create(filename) if err != nil { log.Error(err) } replaceJSAssets(&p.JSAssets) replaceCssAssets(&p.CSSAssets) p.Render(f) }
Plot Output backtest results
https://github.com/coinrust/crex/blob/bd91078db7fe1ca076c1ed417af3f6871f5fede8/backtest/backtest.go#L414-L438
package backtest import ( . "github.com/coinrust/crex" _ "github.com/coinrust/crex/backtest/statik" "github.com/coinrust/crex/dataloader" "github.com/coinrust/crex/log" "github.com/coinrust/crex/utils" "github.com/go-echarts/go-echarts/charts" "github.com/go-echarts/go-echarts/datatypes" "github.com/json-iterator/go" "github.com/rakyll/statik/fs" "io/ioutil" slog "log" "os" "path/filepath" "time" ) const ( OriginEChartsJs = "https://go-echarts.github.io/go-echarts-assets/assets/echarts.min.js" MyEChartsJs = "https://cdnjs.cloudflare.com/ajax/libs/echarts/4.7.0/echarts.min.js" OriginEChartsBulmaCss = "https://go-echarts.github.io/go-echarts-assets/assets/bulma.min.css" MyEChartsBulmaCss = "https://cdnjs.cloudflare.com/ajax/libs/bulma/0.8.2/css/bulma.min.css" SimpleDateTimeFormat = "2006-01-02 15:04:05.000" ) var ( reportHistoryTemplate string ) var json = jsoniter.ConfigCompatibleWithStandardLibrary func init() { statikFS, err := fs.New() if err != nil { slog.Fatal(err) } f, err := statikFS.Open("/ReportHistoryTemplate.html") if err != nil { slog.Fatal(err) } d, err := ioutil.ReadAll(f) if err != nil { slog.Fatal(err) } reportHistoryTemplate = string(d) } type PlotData struct { NameItems []string Prices []float64 Equities []float64 } type DataState struct { PrevTime int64 Time int64 Index int } type Backtest struct { datas []*dataloader.Data symbol string strategyTesters []*StrategyTester baseOutputDir string outputDir string start time.Time end time.Time currentTimeNS int64 timeNsDatas []int64 startedAt time.Time endedAt time.Time } func NewBacktestFromParams(datas []*dataloader.Data, symbol string, start time.Time, end time.Time, strategyParamsList []*StrategyTesterParams, outputDir string) *Backtest { var strategyTesters []*StrategyTester for _, strategyParams := range strategyParamsList { strategyTester := &StrategyTester{ StrategyTesterParams: strategyParams, } if err := strategyTester.Setup(); err != nil { panic(err) } strategyTesters = append(strategyTesters, strategyTester) } b := &Backtest{ datas: datas, symbol: symbol, start: start, end: end, strategyTesters: strategyTesters, baseOutputDir: outputDir, } for _, v := range strategyTesters { v.backtest = b } return b } func NewBacktest(datas []*dataloader.Data, symbol string, start time.Time, end time.Time, strategy Strategy, exchanges []ExchangeSim, outputDir string) *Backtest { b := &Backtest{ datas: datas, symbol: symbol, start: start, end: end, baseOutputDir: outputDir, } strategyTester := &StrategyTester{ StrategyTesterParams: &StrategyTesterParams{ strategy: strategy, exchanges: exchanges, }, backtest: b, } if err := strategyTester.Setup(); err != nil { panic(err) } b.strategyTesters = []*StrategyTester{strategyTester} return b } func (b *Backtest) SetDatas(datas []*dataloader.Data) { b.datas = datas } func (b *Backtest) GetTime() time.Time { return time.Unix(0, b.currentTimeNS) } func (b *Backtest) initLogs() { if b.baseOutputDir == "" { log.SetLogger(&EmptyLogger{}) return } if err := os.MkdirAll(b.baseOutputDir, os.ModePerm); err != nil { panic(err) } b.outputDir = filepath.Join(b.baseOutputDir, time.Now().Format("20060102150405")) if err := os.MkdirAll(b.outputDir, os.ModePerm); err != nil { panic(err) } logger := NewBtLogger(b, filepath.Join(b.outputDir, "result.log"), log.DebugLevel, false, true) log.SetLogger(logger) } func (b *Backtest) Run() { SetIdGenerate(utils.NewIdGenerate(b.start)) b.initLogs() b.startedAt = time.Now() for _, data := range b.datas { data.Reset(b.start, b.end) } if !b.next() { log.Error("error") return } for _, strategyTester := range b.strategyTesters { strategyTester.Init() strategyTester.addInitItemStats() strategyTester.OnInit() } for { for _, strategyTester := range b.strategyTesters { strategyTester.OnTick() } for _, strategyTester := range b.strategyTesters { strategyTester.RunEventLoopOnce() } var stopped bool for _, strategyTester := range b.strategyTesters { strategyTester.addItemStats() if strategyTester.strategy.IsStopped() { stopped = true } } if stopped { break } if !b.next() { break } } for _, strategyTester := range b.strategyTesters { strategyTester.OnExit() strategyTester.Sync() } log.Sync() b.endedAt = time.Now() } func (b *Backtest) next() bool { if len(b.datas) == 1 { return b.nextOne() } if b.currentTimeNS == 0 { for _, data := range b.datas { if !data.Next() { return false } } b.resetSortedDatas() b.currentTimeNS = b.timeNsDatas[len(b.timeNsDatas)-1] n := len(b.datas) for i := 0; i < n; i++ { data := b.datas[i] for { if data.GetOrderBook().Time.UnixNano() >= b.currentTimeNS { break } if !data.Next() { return false } } } return true } for { for _, timeNs := range b.timeNsDatas { if b.currentTimeNS < timeNs { b.currentTimeNS = timeNs if !b.ensureMoveNext(b.currentTimeNS) { return false } return true } } for _, data := range b.datas { if !data.Next() { return false } } b.resetSortedDatas() } } func (b *Backtest) ensureMoveNext(ns int64) bool { n := len(b.datas) count := 0 for i := 0; i < n; i++ { data := b.datas[i] for { if data.GetOrderBook().Time.UnixNano() >= ns { break } if !data.Next() { return false } count++ } } if count > 0 { b.resetSortedDatas() } return true } func (b *Backtest) resetSortedDatas() { nDatas := len(b.datas) if len(b.timeNsDatas) != nDatas*2 { b.timeNsDatas = make([]int64, nDatas*2) } for i := 0; i < nDatas; i++ { index := i * 2 b.timeNsDatas[index] = b.datas[i].GetOrderBookRaw(1).Time.UnixNano() b.timeNsDatas[index+1] = b.datas[i].GetOrderBook().Time.UnixNano() } utils.SortInt64(b.timeNsDatas) } func (b *Backtest) nextOne() bool { ret := b.datas[0].Next() if ret { b.currentTimeNS = b.datas[0].GetOrderBook().Time.UnixNano() } return ret } func (b *Backtest) GetPrices() (result []float64) { n := len(b.datas) result = make([]float64, n) for i := 0; i < n; i++ { result[i] = b.datas[i].GetOrderBook().Price() } return } func (b *Backtest) GetLogs(index int) LogItems { return b.strategyTesters[index].GetLogs() } func (b *Backtest) ComputeStats() (result *Stats) { return b.ComputeStatsByIndex(0) } func (b *Backtest) ComputeStatsByIndex(index int) (result *Stats) { if index >= len(b.strategyTesters) { return nil } return b.strategyTesters[index].ComputeStats() } func (b *Backtest) HtmlReport() { b.strategyTesters[0].HtmlReport() } func (b *Backtest) priceLine(plotData *PlotData) *charts.Line { line := charts.NewLine() line.SetGlobalOptions( charts.InitOpts{PageTitle: "价格", Width: "1270px", Height: "500px"}, charts.ToolboxOpts{Show: true}, charts.TooltipOpts{Show: true, Trigger: "axis", TriggerOn: "mousemove|click"}, charts.DataZoomOpts{Type: "slider", Start: 0, End: 100}, charts.YAxisOpts{SplitLine: charts.SplitLineOpts{Show: true}, Scale: true}, ) line.AddXAxis(plotData.NameItems) line.AddYAxis("price", plotData.Prices, charts.MPNameTypeItem{Name: "最大值", Type: "max"}, charts.MPNameTypeItem{Name: "最小值", Type: "min"}, charts.MPStyleOpts{Label: charts.LabelTextOpts{Show: true}}, ) return line } func (b *Backtest) equityLine(plotData *PlotData) *charts.Line { line := charts.NewLine() line.SetGlobalOptions( charts.InitOpts{PageTitle: "净值", Width: "1270px", Height: "400px"}, charts.ToolboxOpts{Show: true}, charts.TooltipOpts{Show: true, Trigger: "axis", TriggerOn: "mousemove|click"}, charts.DataZoomOpts{Type: "slider", Start: 0, End: 100}, charts.YAxisOpts{SplitLine: charts.SplitLineOpts{Show: true}, Scale: true}, ) line.AddXAxis(plotData.NameItems) line.AddYAxis("equity", plotData.Equities, charts.MPNameTypeItem{Name: "最大值", Type: "max"}, charts.MPNameTypeItem{Name: "最小值", Type: "min"}, charts.MPStyleOpts{Label: charts.LabelTextOpts{Show: true}}, ) return line }
MIT License
plaid/plaid-go
plaid/model_transfer_user_address_in_response.go
GetCountryOk
go
func (o *TransferUserAddressInResponse) GetCountryOk() (*string, bool) { if o == nil { return nil, false } return o.Country.Get(), o.Country.IsSet() }
GetCountryOk returns a tuple with the Country field value and a boolean to check if the value has been set. NOTE: If the value is an explicit nil, `nil, true` will be returned
https://github.com/plaid/plaid-go/blob/c2a20f380d37eecba36138b04e14f540b59cc22a/plaid/model_transfer_user_address_in_response.go#L174-L179
package plaid import ( "encoding/json" ) type TransferUserAddressInResponse struct { Street NullableString `json:"street"` City NullableString `json:"city"` Region NullableString `json:"region"` PostalCode NullableString `json:"postal_code"` Country NullableString `json:"country"` AdditionalProperties map[string]interface{} } type _TransferUserAddressInResponse TransferUserAddressInResponse func NewTransferUserAddressInResponse(street NullableString, city NullableString, region NullableString, postalCode NullableString, country NullableString) *TransferUserAddressInResponse { this := TransferUserAddressInResponse{} this.Street = street this.City = city this.Region = region this.PostalCode = postalCode this.Country = country return &this } func NewTransferUserAddressInResponseWithDefaults() *TransferUserAddressInResponse { this := TransferUserAddressInResponse{} return &this } func (o *TransferUserAddressInResponse) GetStreet() string { if o == nil || o.Street.Get() == nil { var ret string return ret } return *o.Street.Get() } func (o *TransferUserAddressInResponse) GetStreetOk() (*string, bool) { if o == nil { return nil, false } return o.Street.Get(), o.Street.IsSet() } func (o *TransferUserAddressInResponse) SetStreet(v string) { o.Street.Set(&v) } func (o *TransferUserAddressInResponse) GetCity() string { if o == nil || o.City.Get() == nil { var ret string return ret } return *o.City.Get() } func (o *TransferUserAddressInResponse) GetCityOk() (*string, bool) { if o == nil { return nil, false } return o.City.Get(), o.City.IsSet() } func (o *TransferUserAddressInResponse) SetCity(v string) { o.City.Set(&v) } func (o *TransferUserAddressInResponse) GetRegion() string { if o == nil || o.Region.Get() == nil { var ret string return ret } return *o.Region.Get() } func (o *TransferUserAddressInResponse) GetRegionOk() (*string, bool) { if o == nil { return nil, false } return o.Region.Get(), o.Region.IsSet() } func (o *TransferUserAddressInResponse) SetRegion(v string) { o.Region.Set(&v) } func (o *TransferUserAddressInResponse) GetPostalCode() string { if o == nil || o.PostalCode.Get() == nil { var ret string return ret } return *o.PostalCode.Get() } func (o *TransferUserAddressInResponse) GetPostalCodeOk() (*string, bool) { if o == nil { return nil, false } return o.PostalCode.Get(), o.PostalCode.IsSet() } func (o *TransferUserAddressInResponse) SetPostalCode(v string) { o.PostalCode.Set(&v) } func (o *TransferUserAddressInResponse) GetCountry() string { if o == nil || o.Country.Get() == nil { var ret string return ret } return *o.Country.Get() }
MIT License
spkaeros/rscgo
pkg/game/world/location.go
Near
go
func (l Location) Near(other entity.Location, radius int) bool { return l.LongestDeltaCoords(other.X(), other.Y()) <= radius }
EntityWithin Returns true if the other location is within radius tiles of the receiver location, otherwise false.
https://github.com/spkaeros/rscgo/blob/b6f29c32bdb16216c804e164b1935269beca129d/pkg/game/world/location.go#L335-L337
package world import ( "fmt" "math" "go.uber.org/atomic" "github.com/spkaeros/rscgo/pkg/game/entity" "github.com/spkaeros/rscgo/pkg/rand" ) type ( Direction = int Plane = int ) var OrderedDirections = [...]Direction{West, East, North, South, SouthWest, SouthEast, NorthWest, NorthEast} const ( North Direction = iota NorthWest West SouthWest South SouthEast East NorthEast LeftFighting RightFighting ) const ( PlaneGround Plane = iota PlaneSecond PlaneThird PlaneBasement ) type Location struct { x, y *atomic.Uint32 } func (l Location) Clone() entity.Location { return NewLocation(l.X(), l.Y()) } func (l Location) X() int { if l.x == nil { return -1 } return int(l.x.Load()) } func (l Location) Y() int { if l.y == nil { return -1 } return int(l.y.Load()) } func (l Location) SetX(x int) { l.x.Store(uint32(x)) } func (l Location) SetY(y int) { l.y.Store(uint32(y)) } func (l Location) Wilderness() int { if l.X() > 344 { return 0 } return (2203-(l.Y()+1776))/6 + 1 } var ( DeathPoint = NewLocation(0, 0) SpawnPoint = Lumbridge.Clone() Lumbridge = NewLocation(122, 647) Varrock = NewLocation(122, 647) Edgeville = NewLocation(220, 445) ) func NewLocation(x, y int) Location { return Location{x: atomic.NewUint32(uint32(x)), y: atomic.NewUint32(uint32(y))} } func (l Location) Point() entity.Location { return l.Clone() } func (l Location) DirectionTo(destX, destY int) int { sprites := [3][3]int{{SouthWest, West, NorthWest}, {South, -1, North}, {SouthEast, East, NorthEast}} xIndex, yIndex := l.X()-destX+1, l.Y()-destY+1 if xIndex >= 3 || yIndex >= 3 || yIndex < 0 || xIndex < 0 { xIndex, yIndex = 1, 2 } return sprites[xIndex][yIndex] } func NewRandomLocation(bounds [2]Location) Location { return NewLocation(rand.Rng.Intn(bounds[1].X()-bounds[0].X())+bounds[0].X(), rand.Rng.Intn(bounds[1].Y()-bounds[0].Y())+bounds[0].Y()) } func (l Location) String() string { return fmt.Sprintf("[%d,%d]", l.X(), l.Y()) } func (l Location) Within(minX, maxX, minY, maxY int) bool { return l.WithinArea([2]entity.Location { NewLocation(minX, minY), NewLocation(maxX, maxY) }) } func (l Location) IsValid() bool { return l.WithinArea([2]entity.Location { NewLocation(0, 0), NewLocation(MaxX, MaxY)}) } func (l Location) NextStep(d entity.Location) entity.Location { next := l.Step(l.DirectionToward(d)) if l.Collides(next) { if l.X() < d.X() { if next = l.Step(West); l.Collides(next) { return next } } if l.X() > d.X() { if next = l.Step(East); l.Collides(next) { return next } } if l.Y() < d.Y() { if next = l.Step(South); l.Collides(next) { return next } next = l.Step(South) } if l.Y() > d.Y() { if next = l.Step(North); l.Collides(next) { return next } next = l.Step(North) } } return next } func (l Location) PivotTo(loc entity.Location) (deltas [2][]int) { step := 0.0 deltaX := float64(loc.X() - l.X()) deltaY := float64(loc.Y() - l.Y()) if math.Abs(deltaX) >= math.Abs(deltaY) { step = math.Abs(deltaX) } else { step = math.Abs(deltaY) } deltaX /= step deltaY /= step x, y := float64(l.X()), float64(l.Y()) for i := 1.0; i <= step; i++ { if l.Collides(NewLocation(int(math.Floor(x)),int(math.Floor(y)))) { return [2][]int { {}, {} } } else { deltas[0] = append(deltas[0], int(x+deltaX)) deltas[1] = append(deltas[1], int(y+deltaY)) } x += deltaX y += deltaY } return } func (l Location) Collides(dst entity.Location) bool { return !l.ReachableCoords(dst.X(), dst.Y()) } func (l Location) ReachableCoords(x, y int) bool { dst := entity.Location(NewLocation(x, y)) if l.LongestDelta(dst) > 1 { dst = l.NextTileToward(dst) } if IsTileBlocking(l.X(), l.Y(), byte(ClipBit(l.DirectionToward(dst))), true) || IsTileBlocking(dst.X(), dst.Y(), byte(ClipBit(dst.DirectionToward(l))), false) { return false } if dst.X() != l.X() && dst.Y() != l.Y() { var vmask, hmask byte if dst.X() > l.X() { vmask |= ClipSouth } else { vmask |= ClipNorth } if dst.Y() > l.Y() { hmask |= ClipEast } else { hmask |= ClipWest } return !IsTileBlocking(l.X(), dst.Y(), vmask, false) || !IsTileBlocking(dst.X(), l.Y(), hmask, false) } return true } func (l Location) Step(dir int) entity.Location { loc := l.Clone() if dir == 2 || dir == 1 || dir == 3 { loc.SetX(loc.X()+1) } else if dir == 5 || dir == 6 || dir == 7 { loc.SetX(loc.X()-1) } if dir == 7 || dir == 0 || dir == 1 { loc.SetY(loc.Y()-1) } else if dir == 4 || dir == 5 || dir == 6 { loc.SetY(loc.Y()+1) } return loc } func (l Location) Equals(o interface{}) bool { switch o.(type) { case Location: return l.LongestDelta(o.(Location)) == 0 case *Location: return l.LongestDelta(*o.(*Location)) == 0 case *Player: return l.LongestDelta(o.(*Player).Point()) == 0 case Player: return l.LongestDelta(o.(Player).Point()) == 0 case *NPC: return l.LongestDelta(o.(*NPC).Point()) == 0 case NPC: return l.LongestDelta(o.(NPC).Point()) == 0 case *Object: return l.LongestDelta(o.(*Object).Entity.Location) == 0 case Object: return l.LongestDelta(o.(Object).Entity.Location) == 0 case *GroundItem: return l.LongestDelta(o.(*GroundItem).Entity.Location) == 0 case GroundItem: return l.LongestDelta(o.(GroundItem).Entity.Location) == 0 case *Mob: return l.LongestDelta(o.(*Mob).Point()) == 0 case Mob: return l.LongestDelta(o.(Mob).Point()) == 0 } return false } func (l Location) Delta(other entity.Location) (delta int) { return l.LongestDelta(other) } func (l Location) DeltaX(other entity.Location) (deltaX int) { deltaX = int(math.Abs(float64(other.X()) - float64(l.X()))) return } func (l Location) DeltaY(other entity.Location) (deltaY int) { deltaY = int(math.Abs(float64(other.Y()) - float64(l.Y()))) return } func (l Location) TheirDeltaY(other entity.Location) (deltaY int) { return other.Y() - l.Y() } func (l Location) TheirDeltaX(other entity.Location) (deltaY int) { return other.X() - l.X() } func (l Location) LongestDelta(other entity.Location) int { if x, y := l.DeltaX(other), l.DeltaY(other); x > y { return x } else { return y } } func (l Location) LongestDeltaCoords(x, y int) int { return l.LongestDelta(NewLocation(x, y)) } func (l Location) EuclideanDistance(other entity.Location) float64 { return math.Sqrt(math.Pow(float64(l.DeltaX(other)), 2) + math.Pow(float64(l.DeltaY(other)), 2)) } func (l Location) WithinRange(other entity.Location, radius int) bool { return l.Near(other, radius) }
ISC License
zhongantech/annchain.og
client/httplib/httplib.go
Delete
go
func Delete(url string) *BeegoHTTPRequest { return NewBeegoRequest(url, "DELETE") }
Delete returns *BeegoHttpRequest DELETE method.
https://github.com/zhongantech/annchain.og/blob/1e7f230aeb77106ebfc482aa76b4df2e72cd1b84/client/httplib/httplib.go#L123-L125
package httplib import ( "bytes" "compress/gzip" "crypto/tls" "encoding/json" "encoding/xml" "fmt" "gopkg.in/yaml.v2" "io" "io/ioutil" "log" "mime/multipart" "net" "net/http" "net/http/cookiejar" "net/http/httputil" "net/url" "os" "strings" "sync" "time" ) var defaultSetting = BeegoHTTPSettings{ UserAgent: "beegoServer", ConnectTimeout: 60 * time.Second, ReadWriteTimeout: 60 * time.Second, Gzip: true, DumpBody: true, } var defaultCookieJar http.CookieJar var settingMutex sync.Mutex func createDefaultCookie() { settingMutex.Lock() defer settingMutex.Unlock() defaultCookieJar, _ = cookiejar.New(nil) } func SetDefaultSetting(setting BeegoHTTPSettings) { settingMutex.Lock() defer settingMutex.Unlock() defaultSetting = setting } func NewBeegoRequest(rawurl, method string) *BeegoHTTPRequest { var resp http.Response u, err := url.Parse(rawurl) if err != nil { log.Println("Httplib:", err) } req := http.Request{ URL: u, Method: strings.ToUpper(method), Header: make(http.Header), Proto: "HTTP/1.1", ProtoMajor: 1, ProtoMinor: 1, } return &BeegoHTTPRequest{ url: rawurl, req: &req, params: map[string][]string{}, files: map[string]string{}, setting: defaultSetting, resp: &resp, } } func Get(url string) *BeegoHTTPRequest { return NewBeegoRequest(url, "GET") } func Post(url string) *BeegoHTTPRequest { return NewBeegoRequest(url, "POST") } func Put(url string) *BeegoHTTPRequest { return NewBeegoRequest(url, "PUT") }
Apache License 2.0
go-playground/locales
bn_IN/bn_IN.go
FmtNumber
go
func (bn *bn_IN) FmtNumber(num float64, v uint64) string { s := strconv.FormatFloat(math.Abs(num), 'f', int(v), 64) l := len(s) + 2 + 1*len(s[:len(s)-int(v)-1])/3 count := 0 inWhole := v == 0 inSecondary := false groupThreshold := 3 b := make([]byte, 0, l) for i := len(s) - 1; i >= 0; i-- { if s[i] == '.' { b = append(b, bn.decimal[0]) inWhole = true continue } if inWhole { if count == groupThreshold { b = append(b, bn.group[0]) count = 1 if !inSecondary { inSecondary = true groupThreshold = 2 } } else { count++ } } b = append(b, s[i]) } if num < 0 { b = append(b, bn.minus[0]) } for i, j := 0, len(b)-1; i < j; i, j = i+1, j-1 { b[i], b[j] = b[j], b[i] } return string(b) }
FmtNumber returns 'num' with digits/precision of 'v' for 'bn_IN' and handles both Whole and Real numbers based on 'v'
https://github.com/go-playground/locales/blob/52f01e016def96714dc09cf5cdd58f5660eeca02/bn_IN/bn_IN.go#L227-L274
package bn_IN import ( "math" "strconv" "time" "github.com/go-playground/locales" "github.com/go-playground/locales/currency" ) type bn_IN struct { locale string pluralsCardinal []locales.PluralRule pluralsOrdinal []locales.PluralRule pluralsRange []locales.PluralRule decimal string group string minus string percent string perMille string timeSeparator string inifinity string currencies []string monthsAbbreviated []string monthsNarrow []string monthsWide []string daysAbbreviated []string daysNarrow []string daysShort []string daysWide []string periodsAbbreviated []string periodsNarrow []string periodsShort []string periodsWide []string erasAbbreviated []string erasNarrow []string erasWide []string timezones map[string]string } func New() locales.Translator { return &bn_IN{ locale: "bn_IN", pluralsCardinal: []locales.PluralRule{2, 6}, pluralsOrdinal: []locales.PluralRule{2, 3, 4, 5, 6}, pluralsRange: []locales.PluralRule{2, 6}, decimal: ".", group: ",", minus: "-", percent: "%", perMille: "‰", timeSeparator: ":", inifinity: "∞", currencies: []string{"ADP", "AED", "AFA", "AFN", "ALK", "ALL", "AMD", "ANG", "AOA", "AOK", "AON", "AOR", "ARA", "ARL", "ARM", "ARP", "ARS", "ATS", "AUD", "AWG", "AZM", "AZN", "BAD", "BAM", "BAN", "BBD", "BDT", "BEC", "BEF", "BEL", "BGL", "BGM", "BGN", "BGO", "BHD", "BIF", "BMD", "BND", "BOB", "BOL", "BOP", "BOV", "BRB", "BRC", "BRE", "BRL", "BRN", "BRR", "BRZ", "BSD", "BTN", "BUK", "BWP", "BYB", "BYN", "BYR", "BZD", "CAD", "CDF", "CHE", "CHF", "CHW", "CLE", "CLF", "CLP", "CNH", "CNX", "CNY", "COP", "COU", "CRC", "CSD", "CSK", "CUC", "CUP", "CVE", "CYP", "CZK", "DDM", "DEM", "DJF", "DKK", "DOP", "DZD", "ECS", "ECV", "EEK", "EGP", "ERN", "ESA", "ESB", "ESP", "ETB", "EUR", "FIM", "FJD", "FKP", "FRF", "GBP", "GEK", "GEL", "GHC", "GHS", "GIP", "GMD", "GNF", "GNS", "GQE", "GRD", "GTQ", "GWE", "GWP", "GYD", "HKD", "HNL", "HRD", "HRK", "HTG", "HUF", "IDR", "IEP", "ILP", "ILR", "ILS", "INR", "IQD", "IRR", "ISJ", "ISK", "ITL", "JMD", "JOD", "JPY", "KES", "KGS", "KHR", "KMF", "KPW", "KRH", "KRO", "KRW", "KWD", "KYD", "KZT", "LAK", "LBP", "LKR", "LRD", "LSL", "LTL", "LTT", "LUC", "LUF", "LUL", "LVL", "LVR", "LYD", "MAD", "MAF", "MCF", "MDC", "MDL", "MGA", "MGF", "MKD", "MKN", "MLF", "MMK", "MNT", "MOP", "MRO", "MRU", "MTL", "MTP", "MUR", "MVP", "MVR", "MWK", "MXN", "MXP", "MXV", "MYR", "MZE", "MZM", "MZN", "NAD", "NGN", "NIC", "NIO", "NLG", "NOK", "NPR", "NZD", "OMR", "PAB", "PEI", "PEN", "PES", "PGK", "PHP", "PKR", "PLN", "PLZ", "PTE", "PYG", "QAR", "RHD", "ROL", "RON", "RSD", "RUB", "RUR", "RWF", "SAR", "SBD", "SCR", "SDD", "SDG", "SDP", "SEK", "SGD", "SHP", "SIT", "SKK", "SLL", "SOS", "SRD", "SRG", "SSP", "STD", "STN", "SUR", "SVC", "SYP", "SZL", "THB", "TJR", "TJS", "TMM", "TMT", "TND", "TOP", "TPE", "TRL", "TRY", "TTD", "TWD", "TZS", "UAH", "UAK", "UGS", "UGX", "USD", "USN", "USS", "UYI", "UYP", "UYU", "UYW", "UZS", "VEB", "VEF", "VES", "VND", "VNN", "VUV", "WST", "XAF", "XAG", "XAU", "XBA", "XBB", "XBC", "XBD", "XCD", "XDR", "XEU", "XFO", "XFU", "XOF", "XPD", "XPF", "XPT", "XRE", "XSU", "XTS", "XUA", "XXX", "YDD", "YER", "YUD", "YUM", "YUN", "YUR", "ZAL", "ZAR", "ZMK", "ZMW", "ZRN", "ZRZ", "ZWD", "ZWL", "ZWR"}, monthsAbbreviated: []string{"", "জানু", "ফেব", "মার্চ", "এপ্রিল", "মে", "জুন", "জুলাই", "আগস্ট", "সেপ্টেম্বর", "অক্টোবর", "নভেম্বর", "ডিসেম্বর"}, monthsNarrow: []string{"", "জা", "ফে", "মা", "এ", "মে", "জুন", "জু", "আ", "সে", "অ", "ন", "ডি"}, monthsWide: []string{"", "জানুয়ারী", "ফেব্রুয়ারী", "মার্চ", "এপ্রিল", "মে", "জুন", "জুলাই", "আগস্ট", "সেপ্টেম্বর", "অক্টোবর", "নভেম্বর", "ডিসেম্বর"}, daysAbbreviated: []string{"রবি", "সোম", "মঙ্গল", "বুধ", "বৃহস্পতি", "শুক্র", "শনি"}, daysNarrow: []string{"র", "সো", "ম", "বু", "বৃ", "শু", "শ"}, daysShort: []string{"রঃ", "সোঃ", "মঃ", "বুঃ", "বৃঃ", "শুঃ", "শনি"}, daysWide: []string{"রবিবার", "সোমবার", "মঙ্গলবার", "বুধবার", "বৃহস্পতিবার", "শুক্রবার", "শনিবার"}, periodsAbbreviated: []string{"AM", "PM"}, periodsNarrow: []string{"AM", "PM"}, periodsWide: []string{"AM", "PM"}, erasAbbreviated: []string{"খ্রিস্টপূর্ব", "খৃষ্টাব্দ"}, erasNarrow: []string{"", ""}, erasWide: []string{"খ্রিস্টপূর্ব", "খ্রীষ্টাব্দ"}, timezones: map[string]string{"ACDT": "অস্ট্রেলীয় কেন্দ্রীয় দিবালোক সময়", "ACST": "অস্ট্রেলীয় কেন্দ্রীয় মানক সময়", "ACWDT": "অস্ট্রেলীয় কেন্দ্রীয় পশ্চিমি দিবালোক সময়", "ACWST": "অস্ট্রেলীয় কেন্দ্রীয় পশ্চিমি মানক সময়", "ADT": "অতলান্তিক দিবালোক সময়", "AEDT": "অস্ট্রেলীয় পূর্ব দিবালোক সময়", "AEST": "অস্ট্রেলীয় পূর্ব মানক সময়", "AKDT": "আলাস্কা দিবালোক সময়", "AKST": "আলাস্কা মানক সময়", "ARST": "আর্জেন্টিনা গ্রীষ্মকালীন সময়", "ART": "আর্জেন্টিনা মানক সময়", "AST": "অতলান্তিক মানক সময়", "AWDT": "অস্ট্রেলীয় পশ্চিমি দিবালোক সময়", "AWST": "অস্ট্রেলীয় পশ্চিমি মানক সময়", "BOT": "বোলিভিয়া সময়", "BT": "ভুটান সময়", "CAT": "মধ্য আফ্রিকা সময়", "CDT": "কেন্দ্রীয় দিবালোক সময়", "CHADT": "চ্যাথাম দিবালোক সময়", "CHAST": "চ্যাথাম মানক সময়", "CLST": "চিলি গ্রীষ্মকালীন সময়", "CLT": "চিলি মানক সময়", "COST": "কোলোম্বিয়া গ্রীষ্মকালীন সময়", "COT": "কোলোম্বিয়া মানক সময়", "CST": "কেন্দ্রীয় মানক সময়", "ChST": "চামেরো মানক সময়", "EAT": "পূর্ব আফ্রিকা সময়", "ECT": "ইকুয়েডর সময়", "EDT": "পূর্বাঞ্চলের দিবালোক সময়", "EST": "পূর্বাঞ্চলের প্রমাণ সময়", "GFT": "ফরাসি গায়ানা সময়", "GMT": "গ্রীনিচ মিন টাইম", "GST": "উপসাগরীয় মানক সময়", "GYT": "গুয়ানা সময়", "HADT": "হাওয়াই-আলেউত দিবালোক সময়", "HAST": "হাওয়াই-আলেউত মানক সময়", "HAT": "নিউফাউন্ডল্যান্ড দিবালোক সময়", "HECU": "কিউবা দিবালোক সময়", "HEEG": "পূর্ব গ্রীনল্যান্ড গ্রীষ্মকালীন সময়", "HENOMX": "উত্তরপশ্চিম মেক্সিকোর দিনের সময়", "HEOG": "পশ্চিম গ্রীনল্যান্ড গ্রীষ্মকালীন সময়", "HEPM": "সেন্ট পিয়ের ও মিকেলন দিবালোক সময়", "HEPMX": "মেক্সিকান প্রশান্ত মহাসাগরীয় দিবালোক সময়", "HKST": "হং কং গ্রীষ্মকালীন সময়", "HKT": "হং কং মানক সময়", "HNCU": "কিউবা মানক সময়", "HNEG": "পূর্ব গ্রীনল্যান্ড মানক সময়", "HNNOMX": "উত্তরপশ্চিম মেক্সিকোর মানক সময়", "HNOG": "পশ্চিম গ্রীনল্যান্ড মানক সময়", "HNPM": "সেন্ট পিয়ের ও মিকেলন মানক সময়", "HNPMX": "মেক্সিকান প্রশান্ত মহসাগরীয় মানক সময়", "HNT": "নিউফাউন্ডল্যান্ড মানক সময়", "IST": "ভারতীয় মানক সময়", "JDT": "জাপান দিবালোক সময়", "JST": "জাপান মানক সময়", "LHDT": "লর্ড হাওয়ে দিবালোক মসয়", "LHST": "লর্ড হাওয়ে মানক মসয়", "MDT": "পার্বত্য অঞ্চলের দিনের সময়", "MESZ": "মধ্য ইউরোপীয় গ্রীষ্মকালীন সময়", "MEZ": "মধ্য ইউরোপীয় মানক সময়", "MST": "পার্বত্য অঞ্চলের প্রমাণ সময়", "MYT": "মালয়েশিয়া সময়", "NZDT": "নিউজিল্যান্ড দিবালোক সময়", "NZST": "নিউজিল্যান্ড মানক সময়", "OESZ": "পূর্ব ইউরোপীয় গ্রীষ্মকালীন সময়", "OEZ": "পূর্ব ইউরোপীয় মানক সময়", "PDT": "প্রশান্ত মহাসাগরীয় অঞ্চলের দিনের সময়", "PST": "প্রশান্ত মহাসাগরীয় অঞ্চলের মানক সময়", "SAST": "দক্ষিণ আফ্রিকা মানক সময়", "SGT": "সিঙ্গাপুর মানক সময়", "SRT": "সুরিনাম সময়", "TMST": "তুর্কমেনিস্তান গ্রীষ্মকালীন সময়", "TMT": "তুর্কমেনিস্তান মানক সময়", "UYST": "উরুগুয়ে গ্রীষ্মকালীন সময়", "UYT": "উরুগুয়ে মানক সময়", "VET": "ভেনেজুয়েলা সময়", "WARST": "পশ্চিমি আর্জেনটিনা গ্রীষ্মকালীন সময়", "WART": "পশ্চিমি আর্জেনটিনার প্রমাণ সময়", "WAST": "পশ্চিম আফ্রিকা গ্রীষ্মকালীন সময়", "WAT": "পশ্চিম আফ্রিকা মানক সময়", "WESZ": "পশ্চিম ইউরোপীয় গ্রীষ্মকালীন সময়", "WEZ": "পশ্চিম ইউরোপীয় মানক সময়", "WIB": "পশ্চিমী ইন্দোনেশিয়া সময়", "WIT": "পূর্ব ইন্দোনেশিয়া সময়", "WITA": "কেন্দ্রীয় ইন্দোনেশিয়া সময়", "∅∅∅": "অ্যামাজন গ্রীষ্মকালীন সময়"}, } } func (bn *bn_IN) Locale() string { return bn.locale } func (bn *bn_IN) PluralsCardinal() []locales.PluralRule { return bn.pluralsCardinal } func (bn *bn_IN) PluralsOrdinal() []locales.PluralRule { return bn.pluralsOrdinal } func (bn *bn_IN) PluralsRange() []locales.PluralRule { return bn.pluralsRange } func (bn *bn_IN) CardinalPluralRule(num float64, v uint64) locales.PluralRule { n := math.Abs(num) i := int64(n) if (i == 0) || (n == 1) { return locales.PluralRuleOne } return locales.PluralRuleOther } func (bn *bn_IN) OrdinalPluralRule(num float64, v uint64) locales.PluralRule { n := math.Abs(num) if n == 1 || n == 5 || n == 7 || n == 8 || n == 9 || n == 10 { return locales.PluralRuleOne } else if n == 2 || n == 3 { return locales.PluralRuleTwo } else if n == 4 { return locales.PluralRuleFew } else if n == 6 { return locales.PluralRuleMany } return locales.PluralRuleOther } func (bn *bn_IN) RangePluralRule(num1 float64, v1 uint64, num2 float64, v2 uint64) locales.PluralRule { start := bn.CardinalPluralRule(num1, v1) end := bn.CardinalPluralRule(num2, v2) if start == locales.PluralRuleOne && end == locales.PluralRuleOne { return locales.PluralRuleOne } else if start == locales.PluralRuleOne && end == locales.PluralRuleOther { return locales.PluralRuleOther } return locales.PluralRuleOther } func (bn *bn_IN) MonthAbbreviated(month time.Month) string { return bn.monthsAbbreviated[month] } func (bn *bn_IN) MonthsAbbreviated() []string { return bn.monthsAbbreviated[1:] } func (bn *bn_IN) MonthNarrow(month time.Month) string { return bn.monthsNarrow[month] } func (bn *bn_IN) MonthsNarrow() []string { return bn.monthsNarrow[1:] } func (bn *bn_IN) MonthWide(month time.Month) string { return bn.monthsWide[month] } func (bn *bn_IN) MonthsWide() []string { return bn.monthsWide[1:] } func (bn *bn_IN) WeekdayAbbreviated(weekday time.Weekday) string { return bn.daysAbbreviated[weekday] } func (bn *bn_IN) WeekdaysAbbreviated() []string { return bn.daysAbbreviated } func (bn *bn_IN) WeekdayNarrow(weekday time.Weekday) string { return bn.daysNarrow[weekday] } func (bn *bn_IN) WeekdaysNarrow() []string { return bn.daysNarrow } func (bn *bn_IN) WeekdayShort(weekday time.Weekday) string { return bn.daysShort[weekday] } func (bn *bn_IN) WeekdaysShort() []string { return bn.daysShort } func (bn *bn_IN) WeekdayWide(weekday time.Weekday) string { return bn.daysWide[weekday] } func (bn *bn_IN) WeekdaysWide() []string { return bn.daysWide } func (bn *bn_IN) Decimal() string { return bn.decimal } func (bn *bn_IN) Group() string { return bn.group } func (bn *bn_IN) Minus() string { return bn.minus }
MIT License
kubernetes-csi/csi-lib-utils
vendor/k8s.io/client-go/kubernetes/typed/events/v1beta1/event.go
Create
go
func (c *events) Create(ctx context.Context, event *v1beta1.Event, opts v1.CreateOptions) (result *v1beta1.Event, err error) { result = &v1beta1.Event{} err = c.client.Post(). Namespace(c.ns). Resource("events"). VersionedParams(&opts, scheme.ParameterCodec). Body(event). Do(ctx). Into(result) return }
Create takes the representation of a event and creates it. Returns the server's representation of the event, and an error, if there is any.
https://github.com/kubernetes-csi/csi-lib-utils/blob/a2ccb594bb74b61a0655d3431c6365a6a567c7af/vendor/k8s.io/client-go/kubernetes/typed/events/v1beta1/event.go#L116-L126
package v1beta1 import ( "context" json "encoding/json" "fmt" "time" v1beta1 "k8s.io/api/events/v1beta1" v1 "k8s.io/apimachinery/pkg/apis/meta/v1" types "k8s.io/apimachinery/pkg/types" watch "k8s.io/apimachinery/pkg/watch" eventsv1beta1 "k8s.io/client-go/applyconfigurations/events/v1beta1" scheme "k8s.io/client-go/kubernetes/scheme" rest "k8s.io/client-go/rest" ) type EventsGetter interface { Events(namespace string) EventInterface } type EventInterface interface { Create(ctx context.Context, event *v1beta1.Event, opts v1.CreateOptions) (*v1beta1.Event, error) Update(ctx context.Context, event *v1beta1.Event, opts v1.UpdateOptions) (*v1beta1.Event, error) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error Get(ctx context.Context, name string, opts v1.GetOptions) (*v1beta1.Event, error) List(ctx context.Context, opts v1.ListOptions) (*v1beta1.EventList, error) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1beta1.Event, err error) Apply(ctx context.Context, event *eventsv1beta1.EventApplyConfiguration, opts v1.ApplyOptions) (result *v1beta1.Event, err error) EventExpansion } type events struct { client rest.Interface ns string } func newEvents(c *EventsV1beta1Client, namespace string) *events { return &events{ client: c.RESTClient(), ns: namespace, } } func (c *events) Get(ctx context.Context, name string, options v1.GetOptions) (result *v1beta1.Event, err error) { result = &v1beta1.Event{} err = c.client.Get(). Namespace(c.ns). Resource("events"). Name(name). VersionedParams(&options, scheme.ParameterCodec). Do(ctx). Into(result) return } func (c *events) List(ctx context.Context, opts v1.ListOptions) (result *v1beta1.EventList, err error) { var timeout time.Duration if opts.TimeoutSeconds != nil { timeout = time.Duration(*opts.TimeoutSeconds) * time.Second } result = &v1beta1.EventList{} err = c.client.Get(). Namespace(c.ns). Resource("events"). VersionedParams(&opts, scheme.ParameterCodec). Timeout(timeout). Do(ctx). Into(result) return } func (c *events) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) { var timeout time.Duration if opts.TimeoutSeconds != nil { timeout = time.Duration(*opts.TimeoutSeconds) * time.Second } opts.Watch = true return c.client.Get(). Namespace(c.ns). Resource("events"). VersionedParams(&opts, scheme.ParameterCodec). Timeout(timeout). Watch(ctx) }
Apache License 2.0
gxlog/gxlog
writer/async.go
Close
go
func (async *Async) Close() { close(async.chanClose) close(async.chanData) for data := range async.chanData { async.writer.Write(data.Bytes, data.Record) } }
Close closes the internal channel and waits until all logs in the channel have been output. It does NOT close the underlying writer.
https://github.com/gxlog/gxlog/blob/722997cdd93cc0382f8af912f91e5421ddc648af/writer/async.go#L46-L52
package writer import ( "github.com/gxlog/gxlog/iface" ) type logData struct { Bytes []byte Record *iface.Record } type Async struct { writer iface.Writer chanData chan logData chanClose chan struct{} } func NewAsync(writer iface.Writer, cap int) *Async { async := &Async{ writer: writer, chanData: make(chan logData, cap), chanClose: make(chan struct{}), } go async.serve() return async } func (async *Async) Write(bs []byte, record *iface.Record) { async.chanData <- logData{Bytes: bs, Record: record} }
MIT License
jasonwinn/geocoder
geocoder.go
GeocodingReverse
go
func GeocodingReverse(location Location) ([]Address, error) { var addresses []Address url := getURLGeocodingReverse(location, "") results, err := httpRequest(url) if err != nil { log.Println(err) return addresses, err } addresses = convertResultsToAddress(results) return addresses, nil }
GeocodingReverse function is used to convert a Location structure to an Address structure
https://github.com/jasonwinn/geocoder/blob/0a8a678400b8abdf29dd60b9dac3fd5268fad101/geocoder.go#L234-L251
package geocoder import ( "encoding/json" "errors" "log" "net/http" "strconv" "strings" "github.com/kelvins/geocoder/structs" ) var ApiKey string const ( geocodeApiUrl = "https://maps.googleapis.com/maps/api/geocode/json?" ) type Address struct { Street string Number int Neighborhood string District string City string County string State string Country string PostalCode string FormattedAddress string Types string } type Location struct { Latitude float64 Longitude float64 } func (address *Address) FormatAddress() string { var content []string if address.Number > 0 { content = append(content, strconv.Itoa(address.Number)) } content = append(content, address.Street) content = append(content, address.Neighborhood) content = append(content, address.District) content = append(content, address.PostalCode) content = append(content, address.City) content = append(content, address.County) content = append(content, address.State) content = append(content, address.Country) var formattedAddress string for _, value := range content { if value != "" { if formattedAddress != "" { formattedAddress += ", " } formattedAddress += value } } return formattedAddress } func httpRequest(url string) (structs.Results, error) { var results structs.Results req, err := http.NewRequest("GET", url, nil) if err != nil { return results, err } client := &http.Client{} resp, err := client.Do(req) if err != nil { return results, err } defer resp.Body.Close() err = json.NewDecoder(resp.Body).Decode(&results) if err != nil { return results, err } if strings.ToUpper(results.Status) != "OK" { switch strings.ToUpper(results.Status) { case "ZERO_RESULTS": err = errors.New("No results found.") break case "OVER_QUERY_LIMIT": err = errors.New("You are over your quota.") break case "REQUEST_DENIED": err = errors.New("Your request was denied.") break case "INVALID_REQUEST": err = errors.New("Probably the query is missing.") break case "UNKNOWN_ERROR": err = errors.New("Server error. Please, try again.") break default: break } } return results, err } func Geocoding(address Address) (Location, error) { var location Location formattedAddress := address.FormatAddress() formattedAddress = strings.Replace(formattedAddress, " ", "+", -1) url := geocodeApiUrl + "address=" + formattedAddress if ApiKey != "" { url += "&key=" + ApiKey } results, err := httpRequest(url) if err != nil { log.Println(err) return location, err } location.Latitude = results.Results[0].Geometry.Location.Lat location.Longitude = results.Results[0].Geometry.Location.Lng return location, nil } func convertResultsToAddress(results structs.Results) (addresses []Address) { for index := 0; index < len(results.Results); index++ { var address Address for _, component := range results.Results[index].AddressComponents { for _, types := range component.Types { switch types { case "route": address.Street = component.LongName break case "street_number": address.Number, _ = strconv.Atoi(component.LongName) break case "neighborhood": address.Neighborhood = component.LongName break case "sublocality": address.District = component.LongName break case "sublocality_level_1": address.District = component.LongName break case "locality": address.City = component.LongName break case "administrative_area_level_3": address.City = component.LongName break case "administrative_area_level_2": address.County = component.LongName break case "administrative_area_level_1": address.State = component.LongName break case "country": address.Country = component.LongName break case "postal_code": address.PostalCode = component.LongName break default: break } } } address.FormattedAddress = results.Results[index].FormattedAddress address.Types = results.Results[index].Types[0] addresses = append(addresses, address) } return }
MIT License
small-ek/antgo
crypto/uuid/uuid.go
NewDCEGroup
go
func NewDCEGroup() UUID { var result, err = uuid.NewDCESecurity(DomainGroup, uint32(os.Getgid())) if err != nil { logs.Error(err.Error()) } return result }
NewDCEGroup returns a DCE Security (Version 2) UUID in the group domain with the id returned by os.Getgid. NewDCESecurity(Group, uint32(os.Getgid()))
https://github.com/small-ek/antgo/blob/c7524282bd7994fa75516e14be6cf38f980043d2/crypto/uuid/uuid.go#L46-L52
package uuid import ( "github.com/google/uuid" "github.com/small-ek/antgo/os/logs" "os" ) type UUID = uuid.UUID const ( DomainPerson = uuid.Domain(0) DomainGroup = uuid.Domain(1) DomainOrg = uuid.Domain(2) ) func New() UUID { return uuid.New() } func Create() UUID { var result, err = uuid.NewUUID() if err != nil { logs.Error(err.Error()) } return result }
Apache License 2.0
open-horizon/edge-sync-service
core/storage/cache.go
RetrieveAllObjectsAndUpdateDestinationListForDestination
go
func (store *Cache) RetrieveAllObjectsAndUpdateDestinationListForDestination(orgID string, destType string, destID string) ([]common.MetaData, common.SyncServiceError) { return store.Store.RetrieveAllObjectsAndUpdateDestinationListForDestination(orgID, destType, destID) }
RetrieveAllObjectsAndUpdateDestinationListForDestination retrieves objects that are in use on a given node and returns the list of metadata
https://github.com/open-horizon/edge-sync-service/blob/41883c0b8f1ab78e82ce5e49bc99dc4e54be34fc/core/storage/cache.go#L407-L409
package storage import ( "fmt" "io" "sync" "time" "github.com/open-horizon/edge-sync-service/common" ) type Cache struct { destinations map[string]map[string]common.Destination Store Storage lock sync.RWMutex } func (store *Cache) Init() common.SyncServiceError { if err := store.Store.Init(); err != nil { return err } return store.cacheDestinations() } func (store *Cache) cacheDestinations() common.SyncServiceError { destinations, err := store.Store.RetrieveDestinations("", "") if err != nil { return &Error{"Failed to initialize the cache. Error: " + err.Error()} } store.lock.Lock() defer store.lock.Unlock() store.destinations = make(map[string]map[string]common.Destination, 0) for _, dest := range destinations { if store.destinations[dest.DestOrgID] == nil { store.destinations[dest.DestOrgID] = make(map[string]common.Destination, 0) } id := dest.DestType + ":" + dest.DestID store.destinations[dest.DestOrgID][id] = dest } return nil } func (store *Cache) Stop() { store.Store.Stop() } func (store *Cache) PerformMaintenance() { store.Store.PerformMaintenance() } func (store *Cache) Cleanup(isTest bool) common.SyncServiceError { return store.Store.Cleanup(isTest) } func (store *Cache) StoreObject(metaData common.MetaData, data []byte, status string) ([]common.StoreDestinationStatus, common.SyncServiceError) { return store.Store.StoreObject(metaData, data, status) } func (store *Cache) StoreObjectData(orgID string, objectType string, objectID string, dataReader io.Reader) (bool, common.SyncServiceError) { return store.Store.StoreObjectData(orgID, objectType, objectID, dataReader) } func (store *Cache) StoreObjectTempData(orgID string, objectType string, objectID string, dataReader io.Reader) (bool, common.SyncServiceError) { return store.Store.StoreObjectTempData(orgID, objectType, objectID, dataReader) } func (store *Cache) RemoveObjectTempData(orgID string, objectType string, objectID string) common.SyncServiceError { return store.Store.RemoveObjectTempData(orgID, objectType, objectID) } func (store *Cache) RetrieveTempObjectData(orgID string, objectType string, objectID string) (io.Reader, common.SyncServiceError) { return store.Store.RetrieveTempObjectData(orgID, objectType, objectID) } func (store *Cache) AppendObjectData(orgID string, objectType string, objectID string, dataReader io.Reader, dataLength uint32, offset int64, total int64, isFirstChunk bool, isLastChunk bool) common.SyncServiceError { return store.Store.AppendObjectData(orgID, objectType, objectID, dataReader, dataLength, offset, total, isFirstChunk, isLastChunk) } func (store *Cache) UpdateObjectStatus(orgID string, objectType string, objectID string, status string) common.SyncServiceError { return store.Store.UpdateObjectStatus(orgID, objectType, objectID, status) } func (store *Cache) UpdateObjectSourceDataURI(orgID string, objectType string, objectID string, sourceDataURI string) common.SyncServiceError { return store.Store.UpdateObjectSourceDataURI(orgID, objectType, objectID, sourceDataURI) } func (store *Cache) RetrieveObjectStatus(orgID string, objectType string, objectID string) (string, common.SyncServiceError) { return store.Store.RetrieveObjectStatus(orgID, objectType, objectID) } func (store *Cache) RetrieveObjectRemainingConsumers(orgID string, objectType string, objectID string) (int, common.SyncServiceError) { return store.Store.RetrieveObjectRemainingConsumers(orgID, objectType, objectID) } func (store *Cache) DecrementAndReturnRemainingConsumers(orgID string, objectType string, objectID string) (int, common.SyncServiceError) { return store.Store.DecrementAndReturnRemainingConsumers(orgID, objectType, objectID) } func (store *Cache) DecrementAndReturnRemainingReceivers(orgID string, objectType string, objectID string) (int, common.SyncServiceError) { return store.Store.DecrementAndReturnRemainingReceivers(orgID, objectType, objectID) } func (store *Cache) ResetObjectRemainingConsumers(orgID string, objectType string, objectID string) common.SyncServiceError { return store.Store.ResetObjectRemainingConsumers(orgID, objectType, objectID) } func (store *Cache) RetrieveUpdatedObjects(orgID string, objectType string, received bool) ([]common.MetaData, common.SyncServiceError) { return store.Store.RetrieveUpdatedObjects(orgID, objectType, received) } func (store *Cache) RetrieveObjectsWithDestinationPolicy(orgID string, received bool) ([]common.ObjectDestinationPolicy, common.SyncServiceError) { return store.Store.RetrieveObjectsWithDestinationPolicy(orgID, received) } func (store *Cache) RetrieveObjectsWithDestinationPolicyByService(orgID, serviceOrgID, serviceName string) ([]common.ObjectDestinationPolicy, common.SyncServiceError) { return store.Store.RetrieveObjectsWithDestinationPolicyByService(orgID, serviceOrgID, serviceName) } func (store *Cache) RetrieveObjectsWithDestinationPolicyUpdatedSince(orgID string, since int64) ([]common.ObjectDestinationPolicy, common.SyncServiceError) { return store.Store.RetrieveObjectsWithDestinationPolicyUpdatedSince(orgID, since) } func (store *Cache) RetrieveObjectsWithFilters(orgID string, destinationPolicy *bool, dpServiceOrgID string, dpServiceName string, dpPropertyName string, since int64, objectType string, objectID string, destinationType string, destinationID string, noData *bool, expirationTimeBefore string, deleted *bool) ([]common.MetaData, common.SyncServiceError) { return store.Store.RetrieveObjectsWithFilters(orgID, destinationPolicy, dpServiceOrgID, dpServiceName, dpPropertyName, since, objectType, objectID, destinationType, destinationID, noData, expirationTimeBefore, deleted) } func (store *Cache) RetrieveAllObjects(orgID string, objectType string) ([]common.ObjectDestinationPolicy, common.SyncServiceError) { return store.Store.RetrieveAllObjects(orgID, objectType) } func (store *Cache) RetrieveObjects(orgID string, destType string, destID string, resend int) ([]common.MetaData, common.SyncServiceError) { return store.Store.RetrieveObjects(orgID, destType, destID, resend) } func (store *Cache) RetrieveConsumedObjects() ([]common.ConsumedObject, common.SyncServiceError) { return store.Store.RetrieveConsumedObjects() } func (store *Cache) RetrieveObject(orgID string, objectType string, objectID string) (*common.MetaData, common.SyncServiceError) { return store.Store.RetrieveObject(orgID, objectType, objectID) } func (store *Cache) RetrieveObjectAndStatus(orgID string, objectType string, objectID string) (*common.MetaData, string, common.SyncServiceError) { return store.Store.RetrieveObjectAndStatus(orgID, objectType, objectID) } func (store *Cache) RetrieveObjectData(orgID string, objectType string, objectID string) (io.Reader, common.SyncServiceError) { return store.Store.RetrieveObjectData(orgID, objectType, objectID) } func (store *Cache) ReadObjectData(orgID string, objectType string, objectID string, size int, offset int64) ([]byte, bool, int, common.SyncServiceError) { return store.Store.ReadObjectData(orgID, objectType, objectID, size, offset) } func (store *Cache) CloseDataReader(dataReader io.Reader) common.SyncServiceError { return store.Store.CloseDataReader(dataReader) } func (store *Cache) MarkObjectDeleted(orgID string, objectType string, objectID string) common.SyncServiceError { return store.Store.MarkObjectDeleted(orgID, objectType, objectID) } func (store *Cache) MarkDestinationPolicyReceived(orgID string, objectType string, objectID string) common.SyncServiceError { return store.Store.MarkDestinationPolicyReceived(orgID, objectType, objectID) } func (store *Cache) ActivateObject(orgID string, objectType string, objectID string) common.SyncServiceError { return store.Store.ActivateObject(orgID, objectType, objectID) } func (store *Cache) GetObjectsToActivate() ([]common.MetaData, common.SyncServiceError) { return store.Store.GetObjectsToActivate() } func (store *Cache) DeleteStoredObject(orgID string, objectType string, objectID string) common.SyncServiceError { return store.Store.DeleteStoredObject(orgID, objectType, objectID) } func (store *Cache) DeleteStoredData(orgID string, objectType string, objectID string) common.SyncServiceError { return store.Store.DeleteStoredData(orgID, objectType, objectID) } func (store *Cache) CleanObjects() common.SyncServiceError { return store.Store.CleanObjects() } func (store *Cache) GetObjectDestinations(metaData common.MetaData) ([]common.Destination, common.SyncServiceError) { return store.Store.GetObjectDestinations(metaData) } func (store *Cache) UpdateObjectDeliveryStatus(status string, message string, orgID string, objectType string, objectID string, destType string, destID string) (bool, common.SyncServiceError) { return store.Store.UpdateObjectDeliveryStatus(status, message, orgID, objectType, objectID, destType, destID) } func (store *Cache) UpdateObjectDelivering(orgID string, objectType string, objectID string) common.SyncServiceError { return store.Store.UpdateObjectDelivering(orgID, objectType, objectID) } func (store *Cache) GetObjectDestinationsList(orgID string, objectType string, objectID string) ([]common.StoreDestinationStatus, common.SyncServiceError) { return store.Store.GetObjectDestinationsList(orgID, objectType, objectID) } func (store *Cache) UpdateObjectDestinations(orgID string, objectType string, objectID string, destinationsList []string) (*common.MetaData, string, []common.StoreDestinationStatus, []common.StoreDestinationStatus, common.SyncServiceError) { return store.Store.UpdateObjectDestinations(orgID, objectType, objectID, destinationsList) } func (store *Cache) AddObjectDestinations(orgID string, objectType string, objectID string, destinationsList []string) (*common.MetaData, string, []common.StoreDestinationStatus, common.SyncServiceError) { return store.Store.AddObjectDestinations(orgID, objectType, objectID, destinationsList) } func (store *Cache) DeleteObjectDestinations(orgID string, objectType string, objectID string, destinationsList []string) (*common.MetaData, string, []common.StoreDestinationStatus, common.SyncServiceError) { return store.Store.DeleteObjectDestinations(orgID, objectType, objectID, destinationsList) } func (store *Cache) GetNumberOfStoredObjects() (uint32, common.SyncServiceError) { return store.Store.GetNumberOfStoredObjects() } func (store *Cache) AddWebhook(orgID string, objectType string, url string) common.SyncServiceError { return store.Store.AddWebhook(orgID, objectType, url) } func (store *Cache) DeleteWebhook(orgID string, objectType string, url string) common.SyncServiceError { return store.Store.DeleteWebhook(orgID, objectType, url) } func (store *Cache) RetrieveWebhooks(orgID string, objectType string) ([]string, common.SyncServiceError) { return store.Store.RetrieveWebhooks(orgID, objectType) } func (store *Cache) RetrieveDestinations(orgID string, destType string) ([]common.Destination, common.SyncServiceError) { store.lock.RLock() defer store.lock.RUnlock() result := make([]common.Destination, 0) if orgID == "" { for _, orgDests := range store.destinations { for _, value := range orgDests { if destType == "" || value.DestType == destType { result = append(result, value) } } } } else { for _, value := range store.destinations[orgID] { if destType == "" || value.DestType == destType { result = append(result, value) } } } return result, nil } func (store *Cache) DestinationExists(orgID string, destType string, destID string) (bool, common.SyncServiceError) { store.lock.RLock() defer store.lock.RUnlock() if _, ok := store.destinations[orgID][destType+":"+destID]; ok { return true, nil } return false, nil } func (store *Cache) StoreDestination(dest common.Destination) common.SyncServiceError { if err := store.Store.StoreDestination(dest); err != nil { return err } store.lock.Lock() defer store.lock.Unlock() if store.destinations[dest.DestOrgID] == nil { store.destinations[dest.DestOrgID] = make(map[string]common.Destination, 0) } store.destinations[dest.DestOrgID][dest.DestType+":"+dest.DestID] = dest return nil } func (store *Cache) DeleteDestination(orgID string, destType string, destID string) common.SyncServiceError { if err := store.Store.DeleteDestination(orgID, destType, destID); err != nil { return err } store.lock.Lock() defer store.lock.Unlock() delete(store.destinations[orgID], destType+":"+destID) return nil } func (store *Cache) UpdateDestinationLastPingTime(destination common.Destination) common.SyncServiceError { return store.Store.UpdateDestinationLastPingTime(destination) } func (store *Cache) RemoveInactiveDestinations(lastTimestamp time.Time) { store.Store.RemoveInactiveDestinations(lastTimestamp) store.cacheDestinations() } func (store *Cache) GetNumberOfDestinations() (uint32, common.SyncServiceError) { return uint32(len(store.destinations)), nil } func (store *Cache) RetrieveDestination(orgID string, destType string, destID string) (*common.Destination, common.SyncServiceError) { store.lock.RLock() defer store.lock.RUnlock() if d, ok := store.destinations[orgID][destType+":"+destID]; ok { return &d, nil } return nil, &Error{fmt.Sprintf("Destination %s not found.", orgID+":"+destType+":"+destID)} } func (store *Cache) RetrieveDestinationProtocol(orgID string, destType string, destID string) (string, common.SyncServiceError) { store.lock.RLock() defer store.lock.RUnlock() if d, ok := store.destinations[orgID][destType+":"+destID]; ok { return d.Communication, nil } return "", &Error{fmt.Sprintf("Destination %s not found.", orgID+":"+destType+":"+destID)} } func (store *Cache) GetObjectsForDestination(orgID string, destType string, destID string) ([]common.ObjectStatus, common.SyncServiceError) { return store.Store.GetObjectsForDestination(orgID, destType, destID) }
Apache License 2.0
ulule/gokvstores
redis.go
Exists
go
func (r RedisPipeline) Exists(key string) *redis.BoolCmd { return r.pipeline.Exists(key) }
Exists implements RedisClient Exists for pipeline
https://github.com/ulule/gokvstores/blob/5572537a9d7d767690079a68337ff9bdd71fef91/redis.go#L379-L381
package gokvstores import ( "fmt" "net" "time" redis "gopkg.in/redis.v5" ) type RedisClient interface { Ping() *redis.StatusCmd Exists(key string) *redis.BoolCmd Del(keys ...string) *redis.IntCmd FlushDb() *redis.StatusCmd Close() error Process(cmd redis.Cmder) error Get(key string) *redis.StringCmd Set(key string, value interface{}, expiration time.Duration) *redis.StatusCmd MGet(keys ...string) *redis.SliceCmd HDel(key string, fields ...string) *redis.IntCmd HGetAll(key string) *redis.StringStringMapCmd HMSet(key string, fields map[string]string) *redis.StatusCmd SMembers(key string) *redis.StringSliceCmd SAdd(key string, members ...interface{}) *redis.IntCmd Keys(pattern string) *redis.StringSliceCmd Pipeline() *redis.Pipeline } type RedisPipeline struct { pipeline *redis.Pipeline } type RedisClientOptions struct { Network string Addr string Dialer func() (net.Conn, error) Password string DB int MaxRetries int DialTimeout time.Duration ReadTimeout time.Duration WriteTimeout time.Duration PoolSize int PoolTimeout time.Duration IdleTimeout time.Duration IdleCheckFrequency time.Duration ReadOnly bool } type RedisClusterOptions struct { Addrs []string MaxRedirects int ReadOnly bool RouteByLatency bool Password string DialTimeout time.Duration ReadTimeout time.Duration WriteTimeout time.Duration PoolSize int PoolTimeout time.Duration IdleTimeout time.Duration IdleCheckFrequency time.Duration } type RedisStore struct { client RedisClient expiration time.Duration } func (r *RedisStore) Get(key string) (interface{}, error) { cmd := redis.NewCmd("get", key) if err := r.client.Process(cmd); err != nil { if err == redis.Nil { return nil, nil } return nil, err } return cmd.Val(), cmd.Err() } func (r *RedisStore) MGet(keys []string) (map[string]interface{}, error) { values, err := r.client.MGet(keys...).Result() newValues := make(map[string]interface{}, len(keys)) for k, v := range keys { value := values[k] if err != nil { return nil, err } newValues[v] = value } return newValues, nil } func (r *RedisStore) Set(key string, value interface{}) error { return r.client.Set(key, value, r.expiration).Err() } func (r *RedisStore) SetWithExpiration(key string, value interface{}, expiration time.Duration) error { return r.client.Set(key, value, expiration).Err() } func (r *RedisStore) GetMap(key string) (map[string]interface{}, error) { values, err := r.client.HGetAll(key).Result() if err != nil { return nil, err } if len(values) == 0 { return nil, nil } newValues := make(map[string]interface{}, len(values)) for k, v := range values { newValues[k] = v } return newValues, nil } func (r *RedisStore) SetMap(key string, values map[string]interface{}) error { newValues := make(map[string]string, len(values)) for k, v := range values { switch vv := v.(type) { case string: newValues[k] = vv default: newValues[k] = fmt.Sprintf("%v", vv) } } return r.client.HMSet(key, newValues).Err() } func (r *RedisStore) DeleteMap(key string, fields ...string) error { return r.client.HDel(key, fields...).Err() } func (r *RedisStore) GetSlice(key string) ([]interface{}, error) { values, err := r.client.SMembers(key).Result() if err != nil { return nil, err } if len(values) == 0 { return nil, nil } newValues := make([]interface{}, len(values)) for i := range values { newValues[i] = values[i] } return newValues, nil } func (r *RedisStore) SetSlice(key string, values []interface{}) error { for _, v := range values { if v != nil { if err := r.client.SAdd(key, v).Err(); err != nil { return err } } } return nil } func (r *RedisStore) AppendSlice(key string, values ...interface{}) error { return r.SetSlice(key, values) } func (r *RedisStore) Exists(key string) (bool, error) { cmd := r.client.Exists(key) return cmd.Val(), cmd.Err() } func (r *RedisStore) Delete(key string) error { return r.client.Del(key).Err() } func (r *RedisStore) Keys(pattern string) ([]interface{}, error) { values, err := r.client.Keys(pattern).Result() if len(values) == 0 { return nil, err } newValues := make([]interface{}, len(values)) for k, v := range values { newValues[k] = v } return newValues, err } func (r *RedisStore) Flush() error { return r.client.FlushDb().Err() } func (r *RedisStore) Close() error { return r.client.Close() } func NewRedisClientStore(options *RedisClientOptions, expiration time.Duration) (KVStore, error) { opts := &redis.Options{ Network: options.Network, Addr: options.Addr, Dialer: options.Dialer, Password: options.Password, DB: options.DB, MaxRetries: options.MaxRetries, DialTimeout: options.DialTimeout, ReadTimeout: options.ReadTimeout, WriteTimeout: options.WriteTimeout, PoolSize: options.PoolSize, PoolTimeout: options.PoolTimeout, IdleTimeout: options.IdleTimeout, IdleCheckFrequency: options.IdleCheckFrequency, ReadOnly: options.ReadOnly, } client := redis.NewClient(opts) if err := client.Ping().Err(); err != nil { return nil, err } return &RedisStore{ client: client, expiration: expiration, }, nil } func NewRedisClusterStore(options *RedisClusterOptions, expiration time.Duration) (KVStore, error) { opts := &redis.ClusterOptions{ Addrs: options.Addrs, MaxRedirects: options.MaxRedirects, ReadOnly: options.ReadOnly, RouteByLatency: options.RouteByLatency, Password: options.Password, DialTimeout: options.DialTimeout, ReadTimeout: options.ReadTimeout, WriteTimeout: options.WriteTimeout, PoolSize: options.PoolSize, PoolTimeout: options.PoolTimeout, IdleTimeout: options.IdleTimeout, IdleCheckFrequency: options.IdleCheckFrequency, } client := redis.NewClusterClient(opts) if err := client.Ping().Err(); err != nil { return nil, err } return &RedisStore{ client: client, expiration: expiration, }, nil } func (r *RedisStore) Pipeline(f func(r *RedisStore) error) ([]redis.Cmder, error) { pipe := r.client.Pipeline() redisPipeline := RedisPipeline{ pipeline: pipe, } store := &RedisStore{ client: redisPipeline, expiration: r.expiration, } err := f(store) if err != nil { return nil, err } cmds, err := pipe.Exec() return cmds, err } func (r *RedisStore) GetMaps(keys []string) (map[string]map[string]interface{}, error) { commands, err := r.Pipeline(func(r *RedisStore) error { for _, key := range keys { r.client.HGetAll(key) } return nil }) if err != nil { return nil, err } newValues := make(map[string]map[string]interface{}, len(keys)) for i, key := range keys { cmd := commands[i] values, _ := cmd.(*redis.StringStringMapCmd).Result() if values != nil { valueMap := make(map[string]interface{}, len(values)) for k, v := range values { valueMap[k] = v } newValues[key] = valueMap } else { newValues[key] = nil } } return newValues, nil } func (r *RedisStore) SetMaps(maps map[string]map[string]interface{}) error { _, err := r.Pipeline(func(r *RedisStore) error { for k, v := range maps { r.SetMap(k, v) } return nil }) return err } func (r RedisPipeline) Pipeline() *redis.Pipeline { return r.pipeline } func (r RedisPipeline) Ping() *redis.StatusCmd { return r.pipeline.Ping() }
MIT License
dsoprea/go-exfat
navigator.go
GetFile
go
func (dei DirectoryEntryIndex) GetFile(i int) (filename string, fdf *ExfatFileDirectoryEntry) { ide := dei["File"][i] return ide.Extra["complete_filename"].(string), ide.PrimaryEntry.(*ExfatFileDirectoryEntry) }
GetFile returns the file directory-entry with index `i`.
https://github.com/dsoprea/go-exfat/blob/5e932fbdb58948a1ef31ad85afe1f5ac82c50688/navigator.go#L266-L269
package exfat import ( "fmt" "reflect" "strings" "github.com/dsoprea/go-logging" ) const ( directoryEntryBytesCount = 32 ) type ExfatNavigator struct { er *ExfatReader firstClusterNumber uint32 } func NewExfatNavigator(er *ExfatReader, firstClusterNumber uint32) (en *ExfatNavigator) { return &ExfatNavigator{ er: er, firstClusterNumber: firstClusterNumber, } } type DirectoryEntryVisitorFunc func(primaryEntry DirectoryEntry, secondaryEntries []DirectoryEntry) (err error) func (en *ExfatNavigator) EnumerateDirectoryEntries(cb DirectoryEntryVisitorFunc) (visitedClusters, visitedSectors []uint32, err error) { defer func() { if errRaw := recover(); errRaw != nil { err = log.Wrap(errRaw.(error)) } }() entryNumber := 0 isDone := false var primaryEntry DirectoryEntry var secondaryEntries []DirectoryEntry visitedClusters = make([]uint32, 0) visitedSectors = make([]uint32, 0) cvf := func(ec *ExfatCluster) (doContinue bool, err error) { defer func() { if errRaw := recover(); errRaw != nil { var ok bool if err, ok = errRaw.(error); ok == true { err = log.Wrap(err) } else { err = log.Errorf("Error not an error: [%s] [%v]", reflect.TypeOf(err).Name(), err) } } }() visitedClusters = append(visitedClusters, ec.ClusterNumber()) svf := func(sectorNumber uint32, data []byte) (doContinue bool, err error) { defer func() { if errRaw := recover(); errRaw != nil { var ok bool if err, ok = errRaw.(error); ok == true { err = log.Wrap(err) } else { err = log.Errorf("Error not an error: [%s] [%v]", reflect.TypeOf(err).Name(), err) } } }() visitedSectors = append(visitedSectors, sectorNumber) sectorSize := en.er.SectorSize() i := 0 for { directoryEntryData := data[i*directoryEntryBytesCount : (i+1)*directoryEntryBytesCount] entryType := EntryType(directoryEntryData[0]) if entryType.IsEndOfDirectory() == true { isDone = true return false, nil } de, err := parseDirectoryEntry(entryType, directoryEntryData) log.PanicIf(err) if entryType.IsPrimary() == true { primaryEntry = de secondaryEntries = make([]DirectoryEntry, 0) } else { secondaryEntries = append(secondaryEntries, de) } if pde, ok := primaryEntry.(PrimaryDirectoryEntry); ok == true { if len(secondaryEntries) == int(pde.SecondaryCount()) { err := cb(primaryEntry, secondaryEntries) log.PanicIf(err) } } else if entryType.IsPrimary() == true { err := cb(primaryEntry, secondaryEntries) log.PanicIf(err) } entryNumber++ i++ if uint32(i*directoryEntryBytesCount) >= sectorSize { break } } return true, nil } err = ec.EnumerateSectors(svf) log.PanicIf(err) if isDone == true { return false, nil } return true, nil } useFat := false err = en.er.EnumerateClusters(en.firstClusterNumber, cvf, useFat) log.PanicIf(err) return visitedClusters, visitedSectors, nil } type IndexedDirectoryEntry struct { PrimaryEntry DirectoryEntry SecondaryEntries []DirectoryEntry Extra map[string]interface{} } type DirectoryEntryIndex map[string][]IndexedDirectoryEntry func (dei DirectoryEntryIndex) Dump() { fmt.Printf("Directory Entry Index\n") fmt.Printf("=====================\n") fmt.Printf("\n") for typeName, ideList := range dei { fmt.Printf("%s\n", typeName) fmt.Println(strings.Repeat("-", len(typeName))) fmt.Printf("\n") for i, ide := range ideList { fmt.Printf("# %d\n", i) fmt.Printf("\n") fmt.Printf(" Primary: %s\n", ide.PrimaryEntry) for j, secondaryEntry := range ide.SecondaryEntries { fmt.Printf(" Secondary (%d): %s\n", j, secondaryEntry) } fmt.Printf("\n") if len(ide.Extra) > 0 { fmt.Printf(" Extra:\n") for k, v := range ide.Extra { fmt.Printf(" %s: %s\n", k, v) } fmt.Printf("\n") } if fdf, ok := ide.PrimaryEntry.(*ExfatFileDirectoryEntry); ok == true { fmt.Printf(" Attributes:\n") fdf.FileAttributes.DumpBareIndented(" ") fmt.Printf("\n") } } } } func (dei DirectoryEntryIndex) Filenames() (filenames map[string]bool) { fileIdeList, found := dei["File"] if found == true { filenames = make(map[string]bool, len(fileIdeList)) for _, ide := range fileIdeList { filename := ide.Extra["complete_filename"].(string) filenames[filename] = ide.PrimaryEntry.(*ExfatFileDirectoryEntry).FileAttributes.IsDirectory() } } else { filenames = make(map[string]bool, 0) } return filenames } func (dei DirectoryEntryIndex) FileCount() (count int) { if fileIdeList, found := dei["File"]; found == true { count = len(fileIdeList) } return count }
MIT License
kubernetes-csi/csi-lib-utils
vendor/k8s.io/client-go/kubernetes/typed/rbac/v1/clusterrolebinding.go
Patch
go
func (c *clusterRoleBindings) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts metav1.PatchOptions, subresources ...string) (result *v1.ClusterRoleBinding, err error) { result = &v1.ClusterRoleBinding{} err = c.client.Patch(pt). Resource("clusterrolebindings"). Name(name). SubResource(subresources...). VersionedParams(&opts, scheme.ParameterCodec). Body(data). Do(ctx). Into(result) return }
Patch applies the patch and returns the patched clusterRoleBinding.
https://github.com/kubernetes-csi/csi-lib-utils/blob/a2ccb594bb74b61a0655d3431c6365a6a567c7af/vendor/k8s.io/client-go/kubernetes/typed/rbac/v1/clusterrolebinding.go#L161-L172
package v1 import ( "context" json "encoding/json" "fmt" "time" v1 "k8s.io/api/rbac/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" types "k8s.io/apimachinery/pkg/types" watch "k8s.io/apimachinery/pkg/watch" rbacv1 "k8s.io/client-go/applyconfigurations/rbac/v1" scheme "k8s.io/client-go/kubernetes/scheme" rest "k8s.io/client-go/rest" ) type ClusterRoleBindingsGetter interface { ClusterRoleBindings() ClusterRoleBindingInterface } type ClusterRoleBindingInterface interface { Create(ctx context.Context, clusterRoleBinding *v1.ClusterRoleBinding, opts metav1.CreateOptions) (*v1.ClusterRoleBinding, error) Update(ctx context.Context, clusterRoleBinding *v1.ClusterRoleBinding, opts metav1.UpdateOptions) (*v1.ClusterRoleBinding, error) Delete(ctx context.Context, name string, opts metav1.DeleteOptions) error DeleteCollection(ctx context.Context, opts metav1.DeleteOptions, listOpts metav1.ListOptions) error Get(ctx context.Context, name string, opts metav1.GetOptions) (*v1.ClusterRoleBinding, error) List(ctx context.Context, opts metav1.ListOptions) (*v1.ClusterRoleBindingList, error) Watch(ctx context.Context, opts metav1.ListOptions) (watch.Interface, error) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts metav1.PatchOptions, subresources ...string) (result *v1.ClusterRoleBinding, err error) Apply(ctx context.Context, clusterRoleBinding *rbacv1.ClusterRoleBindingApplyConfiguration, opts metav1.ApplyOptions) (result *v1.ClusterRoleBinding, err error) ClusterRoleBindingExpansion } type clusterRoleBindings struct { client rest.Interface } func newClusterRoleBindings(c *RbacV1Client) *clusterRoleBindings { return &clusterRoleBindings{ client: c.RESTClient(), } } func (c *clusterRoleBindings) Get(ctx context.Context, name string, options metav1.GetOptions) (result *v1.ClusterRoleBinding, err error) { result = &v1.ClusterRoleBinding{} err = c.client.Get(). Resource("clusterrolebindings"). Name(name). VersionedParams(&options, scheme.ParameterCodec). Do(ctx). Into(result) return } func (c *clusterRoleBindings) List(ctx context.Context, opts metav1.ListOptions) (result *v1.ClusterRoleBindingList, err error) { var timeout time.Duration if opts.TimeoutSeconds != nil { timeout = time.Duration(*opts.TimeoutSeconds) * time.Second } result = &v1.ClusterRoleBindingList{} err = c.client.Get(). Resource("clusterrolebindings"). VersionedParams(&opts, scheme.ParameterCodec). Timeout(timeout). Do(ctx). Into(result) return } func (c *clusterRoleBindings) Watch(ctx context.Context, opts metav1.ListOptions) (watch.Interface, error) { var timeout time.Duration if opts.TimeoutSeconds != nil { timeout = time.Duration(*opts.TimeoutSeconds) * time.Second } opts.Watch = true return c.client.Get(). Resource("clusterrolebindings"). VersionedParams(&opts, scheme.ParameterCodec). Timeout(timeout). Watch(ctx) } func (c *clusterRoleBindings) Create(ctx context.Context, clusterRoleBinding *v1.ClusterRoleBinding, opts metav1.CreateOptions) (result *v1.ClusterRoleBinding, err error) { result = &v1.ClusterRoleBinding{} err = c.client.Post(). Resource("clusterrolebindings"). VersionedParams(&opts, scheme.ParameterCodec). Body(clusterRoleBinding). Do(ctx). Into(result) return } func (c *clusterRoleBindings) Update(ctx context.Context, clusterRoleBinding *v1.ClusterRoleBinding, opts metav1.UpdateOptions) (result *v1.ClusterRoleBinding, err error) { result = &v1.ClusterRoleBinding{} err = c.client.Put(). Resource("clusterrolebindings"). Name(clusterRoleBinding.Name). VersionedParams(&opts, scheme.ParameterCodec). Body(clusterRoleBinding). Do(ctx). Into(result) return } func (c *clusterRoleBindings) Delete(ctx context.Context, name string, opts metav1.DeleteOptions) error { return c.client.Delete(). Resource("clusterrolebindings"). Name(name). Body(&opts). Do(ctx). Error() } func (c *clusterRoleBindings) DeleteCollection(ctx context.Context, opts metav1.DeleteOptions, listOpts metav1.ListOptions) error { var timeout time.Duration if listOpts.TimeoutSeconds != nil { timeout = time.Duration(*listOpts.TimeoutSeconds) * time.Second } return c.client.Delete(). Resource("clusterrolebindings"). VersionedParams(&listOpts, scheme.ParameterCodec). Timeout(timeout). Body(&opts). Do(ctx). Error() }
Apache License 2.0
gopasspw/gopass
internal/store/mockstore/store.go
Set
go
func (m *MockStore) Set(ctx context.Context, name string, sec gopass.Byter) error { return m.storage.Set(ctx, name, sec.Bytes()) }
Set does nothing
https://github.com/gopasspw/gopass/blob/a4ee6a191c07429a07fc2bf1be83866d07c00868/internal/store/mockstore/store.go#L210-L212
package mockstore import ( "context" "fmt" "github.com/gopasspw/gopass/internal/backend" "github.com/gopasspw/gopass/internal/backend/crypto/plain" "github.com/gopasspw/gopass/internal/store/mockstore/inmem" "github.com/gopasspw/gopass/internal/tree" "github.com/gopasspw/gopass/pkg/gopass" "github.com/gopasspw/gopass/pkg/gopass/secrets/secparse" ) type MockStore struct { alias string storage backend.Storage } func New(alias string) *MockStore { return &MockStore{ alias: alias, storage: inmem.New(), } } func (m *MockStore) String() string { return "mockstore" } func (m *MockStore) GetTemplate(context.Context, string) ([]byte, error) { return []byte{}, nil } func (m *MockStore) HasTemplate(context.Context, string) bool { return false } func (m *MockStore) ListTemplates(context.Context, string) []string { return nil } func (m *MockStore) LookupTemplate(context.Context, string) ([]byte, bool) { return []byte{}, false } func (m *MockStore) RemoveTemplate(context.Context, string) error { return nil } func (m *MockStore) SetTemplate(context.Context, string, []byte) error { return nil } func (m *MockStore) TemplateTree(context.Context) (*tree.Root, error) { return nil, nil } func (m *MockStore) AddRecipient(context.Context, string) error { return nil } func (m *MockStore) GetRecipients(context.Context, string) ([]string, error) { return nil, nil } func (m *MockStore) RemoveRecipient(context.Context, string) error { return nil } func (m *MockStore) SaveRecipients(context.Context) error { return nil } func (m *MockStore) Recipients(context.Context) []string { return nil } func (m *MockStore) ImportMissingPublicKeys(context.Context) error { return nil } func (m *MockStore) ExportMissingPublicKeys(context.Context, []string) (bool, error) { return false, nil } func (m *MockStore) Fsck(context.Context, string) error { return nil } func (m *MockStore) Path() string { return "" } func (m *MockStore) URL() string { return "mockstore://" } func (m *MockStore) Crypto() backend.Crypto { return plain.New() } func (m *MockStore) Storage() backend.Storage { return m.storage } func (m *MockStore) GitInit(context.Context, string, string) error { return nil } func (m *MockStore) Alias() string { return m.alias } func (m *MockStore) Copy(ctx context.Context, from string, to string) error { content, err := m.storage.Get(ctx, from) if err != nil { return err } return m.storage.Set(ctx, to, content) } func (m *MockStore) Delete(ctx context.Context, name string) error { return m.storage.Delete(ctx, name) } func (m *MockStore) Equals(other *MockStore) bool { return false } func (m *MockStore) Exists(ctx context.Context, name string) bool { return m.storage.Exists(ctx, name) } func (m *MockStore) Get(ctx context.Context, name string) (gopass.Secret, error) { content, err := m.storage.Get(ctx, name) if err != nil { return nil, err } return secparse.Parse(content) } func (m *MockStore) GetRevision(context.Context, string, string) (gopass.Secret, error) { return nil, fmt.Errorf("not supported") } func (m *MockStore) Init(context.Context, string, ...string) error { return nil } func (m *MockStore) Initialized(context.Context) bool { return true } func (m *MockStore) IsDir(ctx context.Context, name string) bool { return m.storage.IsDir(ctx, name) } func (m *MockStore) List(ctx context.Context, name string) ([]string, error) { return m.storage.List(ctx, name) } func (m *MockStore) ListRevisions(context.Context, string) ([]backend.Revision, error) { return nil, nil } func (m *MockStore) Move(ctx context.Context, from string, to string) error { content, _ := m.storage.Get(ctx, from) m.storage.Set(ctx, to, content) return m.storage.Delete(ctx, from) }
MIT License
genkami/kiara
options.go
PublishChannelSize
go
func PublishChannelSize(size int) Option { return optionFunc(func(opts *options) { opts.publishChSize = size }) }
PublishChannelSize sets the size of a channel that contains messages that will be sent later.
https://github.com/genkami/kiara/blob/19c6cc0e27c799abf8f14235fd93bb48d6e2e19a/options.go#L52-L56
package kiara import ( "github.com/genkami/kiara/codec/gob" "github.com/genkami/kiara/types" ) const ( defaultPublishChannelSize = 100 defaultDeliveredChannelSize = 100 defaultErrorChannelSize = 100 ) type options struct { publishChSize int deliveredChSize int errorChSize int codec types.Codec } func defaultOptions() options { return options{ publishChSize: defaultPublishChannelSize, deliveredChSize: defaultDeliveredChannelSize, errorChSize: defaultErrorChannelSize, codec: gob.Codec, } } type Option interface { apply(*options) } type optionFunc func(*options) func (f optionFunc) apply(opts *options) { f(opts) } func WithCodec(codec types.Codec) Option { return optionFunc(func(opts *options) { opts.codec = codec }) }
MIT License
blacktop/ipsw
pkg/kernelcache/kext.go
KextList
go
func KextList(kernel string) error { m, err := macho.Open(kernel) if err != nil { return err } defer m.Close() kextStartAdddrs, err := getKextStartVMAddrs(m) if err != nil { log.Debugf("failed to get kext start addresses: %v", err) } if infoSec := m.Section("__PRELINK_INFO", "__info"); infoSec != nil { data, err := infoSec.Data() if err != nil { return err } var prelink PrelinkInfo decoder := plist.NewDecoder(bytes.NewReader(bytes.Trim([]byte(data), "\x00"))) err = decoder.Decode(&prelink) if err != nil { return err } fmt.Println("FOUND:", len(prelink.PrelinkInfoDictionary)) for _, bundle := range prelink.PrelinkInfoDictionary { if !bundle.OSKernelResource && len(kextStartAdddrs) > 0 { fmt.Printf("%#x: %s (%s)\n", kextStartAdddrs[bundle.ModuleIndex]|tagPtrMask, bundle.ID, bundle.Version) } else { fmt.Printf("%#x: %s (%s)\n", bundle.ExecutableLoadAddr, bundle.ID, bundle.Version) } } } return nil }
KextList lists all the kernel extensions in the kernelcache
https://github.com/blacktop/ipsw/blob/fe2be834be254fc265c995a83ec4d56bc79e26c5/pkg/kernelcache/kext.go#L186-L224
package kernelcache import ( "bytes" "encoding/binary" "fmt" "io" "strings" "github.com/apex/log" "github.com/blacktop/go-macho" "github.com/blacktop/go-macho/pkg/fixupchains" "github.com/blacktop/go-plist" ) const tagPtrMask = 0xffff000000000000 type PrelinkInfo struct { PrelinkInfoDictionary []CFBundle `plist:"_PrelinkInfoDictionary,omitempty"` } type CFBundle struct { ID string `plist:"CFBundleIdentifier,omitempty"` Name string `plist:"CFBundleName,omitempty"` SDK string `plist:"DTSDKName,omitempty"` SDKBuild string `plist:"DTSDKBuild,omitempty"` Xcode string `plist:"DTXcode,omitempty"` XcodeBuild string `plist:"DTXcodeBuild,omitempty"` Copyright string `plist:"NSHumanReadableCopyright,omitempty"` BuildMachineOSBuild string `plist:"BuildMachineOSBuild,omitempty"` DevelopmentRegion string `plist:"CFBundleDevelopmentRegion,omitempty"` PlatformName string `plist:"DTPlatformName,omitempty"` PlatformVersion string `plist:"DTPlatformVersion,omitempty"` PlatformBuild string `plist:"DTPlatformBuild,omitempty"` PackageType string `plist:"CFBundlePackageType,omitempty"` Version string `plist:"CFBundleVersion,omitempty"` ShortVersionString string `plist:"CFBundleShortVersionString,omitempty"` CompatibleVersion string `plist:"OSBundleCompatibleVersion,omitempty"` MinimumOSVersion string `plist:"MinimumOSVersion,omitempty"` SupportedPlatforms []string `plist:"CFBundleSupportedPlatforms,omitempty"` Signature string `plist:"CFBundleSignature,omitempty"` IOKitPersonalities map[string]interface{} `plist:"IOKitPersonalities,omitempty"` OSBundleLibraries map[string]string `plist:"OSBundleLibraries,omitempty"` UIDeviceFamily []int `plist:"UIDeviceFamily,omitempty"` OSBundleRequired string `plist:"OSBundleRequired,omitempty"` UIRequiredDeviceCapabilities []string `plist:"UIRequiredDeviceCapabilities,omitempty"` AppleSecurityExtension bool `plist:"AppleSecurityExtension,omitempty"` InfoDictionaryVersion string `plist:"CFBundleInfoDictionaryVersion,omitempty"` OSKernelResource bool `plist:"OSKernelResource,omitempty"` GetInfoString string `plist:"CFBundleGetInfoString,omitempty"` AllowUserLoad bool `plist:"OSBundleAllowUserLoad,omitempty"` ExecutableLoadAddr uint64 `plist:"_PrelinkExecutableLoadAddr,omitempty"` ModuleIndex uint64 `plist:"ModuleIndex,omitempty"` Executable string `plist:"CFBundleExecutable,omitempty"` BundlePath string `plist:"_PrelinkBundlePath,omitempty"` RelativePath string `plist:"_PrelinkExecutableRelativePath,omitempty"` } type KmodInfoT struct { NextAddr uint64 InfoVersion int32 ID uint32 Name [64]byte Version [64]byte ReferenceCount int32 ReferenceListAddr uint64 Address uint64 Size uint64 HeaderSize uint64 StartAddr uint64 StopAddr uint64 } func (i KmodInfoT) String() string { return fmt.Sprintf("id: %#x, name: %s, version: %s, ref_cnt: %d, ref_list: %#x, addr: %#x, size: %#x, header_size: %#x, start: %#x, stop: %#x, next: %#x, info_ver: %d", i.ID, string(i.Name[:]), string(i.Version[:]), i.ReferenceCount, i.ReferenceListAddr, i.Address, i.Size, i.HeaderSize, i.StartAddr, i.StopAddr, i.NextAddr, i.InfoVersion, ) } func getKextStartVMAddrs(m *macho.File) ([]uint64, error) { if kmodStart := m.Section("__PRELINK_INFO", "__kmod_start"); kmodStart != nil { data, err := kmodStart.Data() if err != nil { return nil, err } ptrs := make([]uint64, kmodStart.Size/8) if err := binary.Read(bytes.NewReader(data), binary.LittleEndian, &ptrs); err != nil { return nil, err } return ptrs, nil } return nil, fmt.Errorf("section __PRELINK_INFO.__kmod_start not found") } func getKextInfos(m *macho.File) ([]KmodInfoT, error) { var infos []KmodInfoT if kmodStart := m.Section("__PRELINK_INFO", "__kmod_info"); kmodStart != nil { data, err := kmodStart.Data() if err != nil { return nil, err } ptrs := make([]uint64, kmodStart.Size/8) if err := binary.Read(bytes.NewReader(data), binary.LittleEndian, &ptrs); err != nil { return nil, err } for _, ptr := range ptrs { off, err := m.GetOffset(ptr | tagPtrMask) if err != nil { return nil, err } info := KmodInfoT{} infoBytes := make([]byte, binary.Size(info)) _, err = m.ReadAt(infoBytes, int64(off)) if err != nil { return nil, err } if err := binary.Read(bytes.NewReader(infoBytes), binary.LittleEndian, &info); err != nil { return nil, fmt.Errorf("failed to read KmodInfoT at %#x: %v", off, err) } info.StartAddr = fixupchains.DyldChainedPtr64KernelCacheRebase{Pointer: info.StartAddr}.Target() + m.GetBaseAddress() info.StopAddr = fixupchains.DyldChainedPtr64KernelCacheRebase{Pointer: info.StopAddr}.Target() + m.GetBaseAddress() infos = append(infos, info) } return infos, nil } return nil, fmt.Errorf("section __PRELINK_INFO.__kmod_start not found") } func findCStringVMaddr(m *macho.File, cstr string) (uint64, error) { for _, sec := range m.Sections { if sec.Flags.IsCstringLiterals() || strings.Contains(sec.Name, "cstring") { dat, err := sec.Data() if err != nil { return 0, fmt.Errorf("failed to read cstrings in %s.%s: %v", sec.Seg, sec.Name, err) } csr := bytes.NewBuffer(dat[:]) for { pos := sec.Addr + uint64(csr.Cap()-csr.Len()) s, err := csr.ReadString('\x00') if err == io.EOF { break } if err != nil { return 0, fmt.Errorf("failed to read string: %v", err) } if len(s) > 0 && strings.EqualFold(strings.Trim(s, "\x00"), cstr) { return pos, nil } } } } return 0, fmt.Errorf("string not found in MachO") }
MIT License
trustbloc/sidetree-fabric
pkg/rest/authhandler/authhandler.go
New
go
func New(channelID string, tokens []string, handler common.HTTPHandler) common.HTTPHandler { if len(tokens) == 0 { logger.Debugf("[%s] No authorization token(s) specified. Authorization will NOT be performed for %s on path [%s]", channelID, handler.Method(), handler.Path()) return handler } logger.Debugf("[%s] Creating authorization handler for %s on path [%s]", channelID, handler.Method(), handler.Path()) return &Handler{ HTTPHandler: handler, channelID: channelID, tokens: tokens, } }
New returns a new auth handler
https://github.com/trustbloc/sidetree-fabric/blob/bf329950d91652fc687994196d9e0d279add4ea1/pkg/rest/authhandler/authhandler.go#L32-L45
package authhandler import ( "crypto/subtle" "net/http" "github.com/hyperledger/fabric/common/flogging" "github.com/trustbloc/sidetree-core-go/pkg/restapi/common" ) var logger = flogging.MustGetLogger("sidetree_peer") const ( authHeader = "Authorization" tokenPrefix = "Bearer " ) type Handler struct { common.HTTPHandler channelID string tokens []string }
Apache License 2.0
qubitproducts/bamboo
vendor/github.com/kardianos/osext/osext.go
GetExePath
go
func GetExePath() (exePath string, err error) { return Executable() }
Depricated. Same as Executable().
https://github.com/qubitproducts/bamboo/blob/5ffa22e2a4e48276626a6dae4926440ee260d607/vendor/github.com/kardianos/osext/osext.go#L30-L32
package osext import "path/filepath" func Executable() (string, error) { p, err := executable() return filepath.Clean(p), err } func ExecutableFolder() (string, error) { p, err := Executable() if err != nil { return "", err } folder, _ := filepath.Split(p) return folder, nil }
Apache License 2.0
aptly-dev/aptly
swift/public.go
Remove
go
func (storage *PublishedStorage) Remove(path string) error { err := storage.conn.ObjectDelete(storage.container, filepath.Join(storage.prefix, path)) if err != nil { return fmt.Errorf("error deleting %s from %s: %s", path, storage, err) } return nil }
Remove removes single file under public path
https://github.com/aptly-dev/aptly/blob/0bc66032d2bcbb57b059be5b127d6bcdac7969b8/swift/public.go#L148-L155
package swift import ( "encoding/json" "fmt" "io" "net/http" "os" "path/filepath" "time" "github.com/aptly-dev/aptly/aptly" "github.com/aptly-dev/aptly/utils" "github.com/ncw/swift" "github.com/pkg/errors" ) type PublishedStorage struct { conn *swift.Connection container string prefix string supportBulkDelete bool } type swiftInfo map[string]interface{} var ( _ aptly.PublishedStorage = (*PublishedStorage)(nil) ) func NewPublishedStorage(username string, password string, authURL string, tenant string, tenantID string, domain string, domainID string, tenantDomain string, tenantDomainID string, container string, prefix string) (*PublishedStorage, error) { if username == "" { if username = os.Getenv("OS_USERNAME"); username == "" { username = os.Getenv("ST_USER") } } if password == "" { if password = os.Getenv("OS_PASSWORD"); password == "" { password = os.Getenv("ST_KEY") } } if authURL == "" { if authURL = os.Getenv("OS_AUTH_URL"); authURL == "" { authURL = os.Getenv("ST_AUTH") } } if tenant == "" { tenant = os.Getenv("OS_TENANT_NAME") } if tenantID == "" { tenantID = os.Getenv("OS_TENANT_ID") } if domain == "" { domain = os.Getenv("OS_USER_DOMAIN_NAME") } if domainID == "" { domainID = os.Getenv("OS_USER_DOMAIN_ID") } if tenantDomain == "" { tenantDomain = os.Getenv("OS_PROJECT_DOMAIN") } if tenantDomainID == "" { tenantDomainID = os.Getenv("OS_PROJECT_DOMAIN_ID") } ct := &swift.Connection{ UserName: username, ApiKey: password, AuthUrl: authURL, UserAgent: "aptly/" + aptly.Version, Tenant: tenant, TenantId: tenantID, Domain: domain, DomainId: domainID, TenantDomain: tenantDomain, TenantDomainId: tenantDomainID, ConnectTimeout: 60 * time.Second, Timeout: 60 * time.Second, } err := ct.Authenticate() if err != nil { return nil, fmt.Errorf("swift authentication failed: %s", err) } var bulkDelete bool resp, err := http.Get(filepath.Join(ct.StorageUrl, "..", "..") + "/info") if err == nil { defer resp.Body.Close() decoder := json.NewDecoder(resp.Body) var infos swiftInfo if decoder.Decode(&infos) == nil { _, bulkDelete = infos["bulk_delete"] } } result := &PublishedStorage{ conn: ct, container: container, prefix: prefix, supportBulkDelete: bulkDelete, } return result, nil } func (storage *PublishedStorage) String() string { return fmt.Sprintf("Swift: %s/%s/%s", storage.conn.StorageUrl, storage.container, storage.prefix) } func (storage *PublishedStorage) MkDir(path string) error { return nil } func (storage *PublishedStorage) PutFile(path string, sourceFilename string) error { var ( source *os.File err error ) source, err = os.Open(sourceFilename) if err != nil { return err } defer source.Close() err = storage.putFile(path, source) if err != nil { err = errors.Wrap(err, fmt.Sprintf("error uploading %s to %s", sourceFilename, storage)) } return err } func (storage *PublishedStorage) putFile(path string, source io.Reader) error { _, err := storage.conn.ObjectPut(storage.container, filepath.Join(storage.prefix, path), source, false, "", "", nil) return err }
MIT License
crossplane/provider-azure
apis/network/v1alpha3/zz_generated.deepcopy.go
DeepCopyInto
go
func (in *SubnetSpec) DeepCopyInto(out *SubnetSpec) { *out = *in in.ResourceSpec.DeepCopyInto(&out.ResourceSpec) if in.VirtualNetworkNameRef != nil { in, out := &in.VirtualNetworkNameRef, &out.VirtualNetworkNameRef *out = new(v1.Reference) **out = **in } if in.VirtualNetworkNameSelector != nil { in, out := &in.VirtualNetworkNameSelector, &out.VirtualNetworkNameSelector *out = new(v1.Selector) (*in).DeepCopyInto(*out) } if in.ResourceGroupNameRef != nil { in, out := &in.ResourceGroupNameRef, &out.ResourceGroupNameRef *out = new(v1.Reference) **out = **in } if in.ResourceGroupNameSelector != nil { in, out := &in.ResourceGroupNameSelector, &out.ResourceGroupNameSelector *out = new(v1.Selector) (*in).DeepCopyInto(*out) } in.SubnetPropertiesFormat.DeepCopyInto(&out.SubnetPropertiesFormat) }
DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
https://github.com/crossplane/provider-azure/blob/3a2c932bb9e0557b72541f2ad851666b645de4cf/apis/network/v1alpha3/zz_generated.deepcopy.go#L150-L174
package v1alpha3 import ( "github.com/crossplane/crossplane-runtime/apis/common/v1" runtime "k8s.io/apimachinery/pkg/runtime" ) func (in *AddressSpace) DeepCopyInto(out *AddressSpace) { *out = *in if in.AddressPrefixes != nil { in, out := &in.AddressPrefixes, &out.AddressPrefixes *out = make([]string, len(*in)) copy(*out, *in) } } func (in *AddressSpace) DeepCopy() *AddressSpace { if in == nil { return nil } out := new(AddressSpace) in.DeepCopyInto(out) return out } func (in *ServiceEndpointPropertiesFormat) DeepCopyInto(out *ServiceEndpointPropertiesFormat) { *out = *in if in.Locations != nil { in, out := &in.Locations, &out.Locations *out = make([]string, len(*in)) copy(*out, *in) } } func (in *ServiceEndpointPropertiesFormat) DeepCopy() *ServiceEndpointPropertiesFormat { if in == nil { return nil } out := new(ServiceEndpointPropertiesFormat) in.DeepCopyInto(out) return out } func (in *Subnet) DeepCopyInto(out *Subnet) { *out = *in out.TypeMeta = in.TypeMeta in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) in.Spec.DeepCopyInto(&out.Spec) in.Status.DeepCopyInto(&out.Status) } func (in *Subnet) DeepCopy() *Subnet { if in == nil { return nil } out := new(Subnet) in.DeepCopyInto(out) return out } func (in *Subnet) DeepCopyObject() runtime.Object { if c := in.DeepCopy(); c != nil { return c } return nil } func (in *SubnetList) DeepCopyInto(out *SubnetList) { *out = *in out.TypeMeta = in.TypeMeta in.ListMeta.DeepCopyInto(&out.ListMeta) if in.Items != nil { in, out := &in.Items, &out.Items *out = make([]Subnet, len(*in)) for i := range *in { (*in)[i].DeepCopyInto(&(*out)[i]) } } } func (in *SubnetList) DeepCopy() *SubnetList { if in == nil { return nil } out := new(SubnetList) in.DeepCopyInto(out) return out } func (in *SubnetList) DeepCopyObject() runtime.Object { if c := in.DeepCopy(); c != nil { return c } return nil } func (in *SubnetPropertiesFormat) DeepCopyInto(out *SubnetPropertiesFormat) { *out = *in if in.ServiceEndpoints != nil { in, out := &in.ServiceEndpoints, &out.ServiceEndpoints *out = make([]ServiceEndpointPropertiesFormat, len(*in)) for i := range *in { (*in)[i].DeepCopyInto(&(*out)[i]) } } } func (in *SubnetPropertiesFormat) DeepCopy() *SubnetPropertiesFormat { if in == nil { return nil } out := new(SubnetPropertiesFormat) in.DeepCopyInto(out) return out }
Apache License 2.0
admiraltyio/admiralty
pkg/apis/multicluster/v1alpha1/zz_generated.deepcopy.go
DeepCopyInto
go
func (in *TargetList) DeepCopyInto(out *TargetList) { *out = *in out.TypeMeta = in.TypeMeta in.ListMeta.DeepCopyInto(&out.ListMeta) if in.Items != nil { in, out := &in.Items, &out.Items *out = make([]Target, len(*in)) for i := range *in { (*in)[i].DeepCopyInto(&(*out)[i]) } } return }
DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
https://github.com/admiraltyio/admiralty/blob/8a2183fac758bb028d5f409252e0231c16d9e1d7/pkg/apis/multicluster/v1alpha1/zz_generated.deepcopy.go#L533-L545
package v1alpha1 import ( v1 "k8s.io/api/core/v1" runtime "k8s.io/apimachinery/pkg/runtime" ) func (in *ClusterKubeconfigSecret) DeepCopyInto(out *ClusterKubeconfigSecret) { *out = *in return } func (in *ClusterKubeconfigSecret) DeepCopy() *ClusterKubeconfigSecret { if in == nil { return nil } out := new(ClusterKubeconfigSecret) in.DeepCopyInto(out) return out } func (in *ClusterSource) DeepCopyInto(out *ClusterSource) { *out = *in out.TypeMeta = in.TypeMeta in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) in.Spec.DeepCopyInto(&out.Spec) out.Status = in.Status return } func (in *ClusterSource) DeepCopy() *ClusterSource { if in == nil { return nil } out := new(ClusterSource) in.DeepCopyInto(out) return out } func (in *ClusterSource) DeepCopyObject() runtime.Object { if c := in.DeepCopy(); c != nil { return c } return nil } func (in *ClusterSourceList) DeepCopyInto(out *ClusterSourceList) { *out = *in out.TypeMeta = in.TypeMeta in.ListMeta.DeepCopyInto(&out.ListMeta) if in.Items != nil { in, out := &in.Items, &out.Items *out = make([]ClusterSource, len(*in)) for i := range *in { (*in)[i].DeepCopyInto(&(*out)[i]) } } return } func (in *ClusterSourceList) DeepCopy() *ClusterSourceList { if in == nil { return nil } out := new(ClusterSourceList) in.DeepCopyInto(out) return out } func (in *ClusterSourceList) DeepCopyObject() runtime.Object { if c := in.DeepCopy(); c != nil { return c } return nil } func (in *ClusterSourceSpec) DeepCopyInto(out *ClusterSourceSpec) { *out = *in if in.ServiceAccount != nil { in, out := &in.ServiceAccount, &out.ServiceAccount *out = new(ServiceAccountReference) **out = **in } return } func (in *ClusterSourceSpec) DeepCopy() *ClusterSourceSpec { if in == nil { return nil } out := new(ClusterSourceSpec) in.DeepCopyInto(out) return out } func (in *ClusterSourceStatus) DeepCopyInto(out *ClusterSourceStatus) { *out = *in return } func (in *ClusterSourceStatus) DeepCopy() *ClusterSourceStatus { if in == nil { return nil } out := new(ClusterSourceStatus) in.DeepCopyInto(out) return out } func (in *ClusterSummary) DeepCopyInto(out *ClusterSummary) { *out = *in out.TypeMeta = in.TypeMeta in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) if in.Capacity != nil { in, out := &in.Capacity, &out.Capacity *out = make(v1.ResourceList, len(*in)) for key, val := range *in { (*out)[key] = val.DeepCopy() } } if in.Allocatable != nil { in, out := &in.Allocatable, &out.Allocatable *out = make(v1.ResourceList, len(*in)) for key, val := range *in { (*out)[key] = val.DeepCopy() } } return } func (in *ClusterSummary) DeepCopy() *ClusterSummary { if in == nil { return nil } out := new(ClusterSummary) in.DeepCopyInto(out) return out } func (in *ClusterSummary) DeepCopyObject() runtime.Object { if c := in.DeepCopy(); c != nil { return c } return nil } func (in *ClusterSummaryList) DeepCopyInto(out *ClusterSummaryList) { *out = *in out.TypeMeta = in.TypeMeta in.ListMeta.DeepCopyInto(&out.ListMeta) if in.Items != nil { in, out := &in.Items, &out.Items *out = make([]ClusterSummary, len(*in)) for i := range *in { (*in)[i].DeepCopyInto(&(*out)[i]) } } return } func (in *ClusterSummaryList) DeepCopy() *ClusterSummaryList { if in == nil { return nil } out := new(ClusterSummaryList) in.DeepCopyInto(out) return out } func (in *ClusterSummaryList) DeepCopyObject() runtime.Object { if c := in.DeepCopy(); c != nil { return c } return nil } func (in *ClusterTarget) DeepCopyInto(out *ClusterTarget) { *out = *in out.TypeMeta = in.TypeMeta in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) in.Spec.DeepCopyInto(&out.Spec) out.Status = in.Status return } func (in *ClusterTarget) DeepCopy() *ClusterTarget { if in == nil { return nil } out := new(ClusterTarget) in.DeepCopyInto(out) return out } func (in *ClusterTarget) DeepCopyObject() runtime.Object { if c := in.DeepCopy(); c != nil { return c } return nil } func (in *ClusterTargetList) DeepCopyInto(out *ClusterTargetList) { *out = *in out.TypeMeta = in.TypeMeta in.ListMeta.DeepCopyInto(&out.ListMeta) if in.Items != nil { in, out := &in.Items, &out.Items *out = make([]ClusterTarget, len(*in)) for i := range *in { (*in)[i].DeepCopyInto(&(*out)[i]) } } return } func (in *ClusterTargetList) DeepCopy() *ClusterTargetList { if in == nil { return nil } out := new(ClusterTargetList) in.DeepCopyInto(out) return out } func (in *ClusterTargetList) DeepCopyObject() runtime.Object { if c := in.DeepCopy(); c != nil { return c } return nil } func (in *ClusterTargetSpec) DeepCopyInto(out *ClusterTargetSpec) { *out = *in if in.KubeconfigSecret != nil { in, out := &in.KubeconfigSecret, &out.KubeconfigSecret *out = new(ClusterKubeconfigSecret) **out = **in } if in.ExcludedLabelsRegexp != nil { in, out := &in.ExcludedLabelsRegexp, &out.ExcludedLabelsRegexp *out = new(string) **out = **in } return } func (in *ClusterTargetSpec) DeepCopy() *ClusterTargetSpec { if in == nil { return nil } out := new(ClusterTargetSpec) in.DeepCopyInto(out) return out } func (in *ClusterTargetStatus) DeepCopyInto(out *ClusterTargetStatus) { *out = *in return } func (in *ClusterTargetStatus) DeepCopy() *ClusterTargetStatus { if in == nil { return nil } out := new(ClusterTargetStatus) in.DeepCopyInto(out) return out } func (in *KubeconfigSecret) DeepCopyInto(out *KubeconfigSecret) { *out = *in return } func (in *KubeconfigSecret) DeepCopy() *KubeconfigSecret { if in == nil { return nil } out := new(KubeconfigSecret) in.DeepCopyInto(out) return out } func (in *PodChaperon) DeepCopyInto(out *PodChaperon) { *out = *in out.TypeMeta = in.TypeMeta in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) in.Spec.DeepCopyInto(&out.Spec) in.Status.DeepCopyInto(&out.Status) return } func (in *PodChaperon) DeepCopy() *PodChaperon { if in == nil { return nil } out := new(PodChaperon) in.DeepCopyInto(out) return out } func (in *PodChaperon) DeepCopyObject() runtime.Object { if c := in.DeepCopy(); c != nil { return c } return nil } func (in *PodChaperonList) DeepCopyInto(out *PodChaperonList) { *out = *in out.TypeMeta = in.TypeMeta in.ListMeta.DeepCopyInto(&out.ListMeta) if in.Items != nil { in, out := &in.Items, &out.Items *out = make([]PodChaperon, len(*in)) for i := range *in { (*in)[i].DeepCopyInto(&(*out)[i]) } } return } func (in *PodChaperonList) DeepCopy() *PodChaperonList { if in == nil { return nil } out := new(PodChaperonList) in.DeepCopyInto(out) return out } func (in *PodChaperonList) DeepCopyObject() runtime.Object { if c := in.DeepCopy(); c != nil { return c } return nil } func (in *ServiceAccountReference) DeepCopyInto(out *ServiceAccountReference) { *out = *in return } func (in *ServiceAccountReference) DeepCopy() *ServiceAccountReference { if in == nil { return nil } out := new(ServiceAccountReference) in.DeepCopyInto(out) return out } func (in *Source) DeepCopyInto(out *Source) { *out = *in out.TypeMeta = in.TypeMeta in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) out.Spec = in.Spec out.Status = in.Status return } func (in *Source) DeepCopy() *Source { if in == nil { return nil } out := new(Source) in.DeepCopyInto(out) return out } func (in *Source) DeepCopyObject() runtime.Object { if c := in.DeepCopy(); c != nil { return c } return nil } func (in *SourceList) DeepCopyInto(out *SourceList) { *out = *in out.TypeMeta = in.TypeMeta in.ListMeta.DeepCopyInto(&out.ListMeta) if in.Items != nil { in, out := &in.Items, &out.Items *out = make([]Source, len(*in)) for i := range *in { (*in)[i].DeepCopyInto(&(*out)[i]) } } return } func (in *SourceList) DeepCopy() *SourceList { if in == nil { return nil } out := new(SourceList) in.DeepCopyInto(out) return out } func (in *SourceList) DeepCopyObject() runtime.Object { if c := in.DeepCopy(); c != nil { return c } return nil } func (in *SourceSpec) DeepCopyInto(out *SourceSpec) { *out = *in return } func (in *SourceSpec) DeepCopy() *SourceSpec { if in == nil { return nil } out := new(SourceSpec) in.DeepCopyInto(out) return out } func (in *SourceStatus) DeepCopyInto(out *SourceStatus) { *out = *in return } func (in *SourceStatus) DeepCopy() *SourceStatus { if in == nil { return nil } out := new(SourceStatus) in.DeepCopyInto(out) return out } func (in *Target) DeepCopyInto(out *Target) { *out = *in out.TypeMeta = in.TypeMeta in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) in.Spec.DeepCopyInto(&out.Spec) out.Status = in.Status return } func (in *Target) DeepCopy() *Target { if in == nil { return nil } out := new(Target) in.DeepCopyInto(out) return out } func (in *Target) DeepCopyObject() runtime.Object { if c := in.DeepCopy(); c != nil { return c } return nil }
Apache License 2.0
trivago/gollum
vendor/github.com/aws/aws-sdk-go/private/protocol/eventstream/eventstreamapi/stream_writer.go
ErrorSet
go
func (w *StreamWriter) ErrorSet() <-chan struct{} { return w.err.ErrorSet() }
ErrorSet returns a channel which will be closed if an error occurs.
https://github.com/trivago/gollum/blob/2a759eddbc38e38bec55d1318cd887c11d0bb82e/vendor/github.com/aws/aws-sdk-go/private/protocol/eventstream/eventstreamapi/stream_writer.go#L51-L53
package eventstreamapi import ( "fmt" "io" "sync" "github.com/aws/aws-sdk-go/aws" ) type StreamWriter struct { eventWriter *EventWriter stream chan eventWriteAsyncReport done chan struct{} closeOnce sync.Once err *OnceError streamCloser io.Closer } func NewStreamWriter(eventWriter *EventWriter, streamCloser io.Closer) *StreamWriter { w := &StreamWriter{ eventWriter: eventWriter, streamCloser: streamCloser, stream: make(chan eventWriteAsyncReport), done: make(chan struct{}), err: NewOnceError(), } go w.writeStream() return w } func (w *StreamWriter) Close() error { w.closeOnce.Do(w.safeClose) return w.Err() } func (w *StreamWriter) safeClose() { close(w.done) }
Apache License 2.0
square/certigo
lib/encoder.go
hexify
go
func hexify(arr []byte) string { var hexed bytes.Buffer for i := 0; i < len(arr); i++ { hexed.WriteString(strings.ToUpper(hex.EncodeToString(arr[i : i+1]))) if i < len(arr)-1 { hexed.WriteString(":") } } return hexed.String() }
hexify returns a colon separated, hexadecimal representation of a given byte array.
https://github.com/square/certigo/blob/eb0d9f461bf04cb80145e0b964c8e04f0eebb5ec/lib/encoder.go#L323-L332
package lib import ( "bytes" "crypto/dsa" "crypto/ecdsa" "crypto/rsa" "crypto/tls" "crypto/x509" "crypto/x509/pkix" "encoding/hex" "encoding/json" "encoding/pem" "fmt" "net" "strconv" "strings" "time" ) var keyUsages = []x509.KeyUsage{ x509.KeyUsageDigitalSignature, x509.KeyUsageContentCommitment, x509.KeyUsageKeyEncipherment, x509.KeyUsageDataEncipherment, x509.KeyUsageKeyAgreement, x509.KeyUsageCertSign, x509.KeyUsageCRLSign, x509.KeyUsageEncipherOnly, x509.KeyUsageDecipherOnly, } var signatureSchemeStrings = map[tls.SignatureScheme]string{ tls.PKCS1WithSHA1: "RSA-PKCS1 with SHA1", tls.PKCS1WithSHA256: "RSA-PKCS1 with SHA256", tls.PKCS1WithSHA384: "RSA-PKCS1 with SHA384", tls.PKCS1WithSHA512: "RSA-PKCS1 with SHA512", tls.PSSWithSHA256: "RSA-PSS with SHA256", tls.PSSWithSHA384: "RSA-PSS with SHA384", tls.PSSWithSHA512: "RSA-PSS with SHA512", tls.ECDSAWithP256AndSHA256: "ECDSA with P256 and SHA256", tls.ECDSAWithP384AndSHA384: "ECDSA with P384 and SHA384", tls.ECDSAWithP521AndSHA512: "ECDSA with P521 and SHA512", 0x807: "ED25519", 0x808: "ED448", 0x203: "ECDSA with SHA1", 0x303: "ECDSA with SHA224", 0x101: "RSA-PKCS1 with MD5", 0x301: "RSA-PKCS1 with SHA224", 0x102: "DSA with MD5", 0x202: "DSA with SHA1", 0x302: "DSA with SHA224", 0x402: "DSA with SHA256", 0x502: "DSA with SHA384", 0x602: "DSA with SHA512", 0xeeee: "GOST 34.10-2012 (256)", 0xefef: "GOST 34.10-2012 (512)", 0xeded: "GOST 34.10-2001", } var keyUsageStrings = map[x509.KeyUsage]string{ x509.KeyUsageDigitalSignature: "Digital Signature", x509.KeyUsageContentCommitment: "Content Commitment", x509.KeyUsageKeyEncipherment: "Key Encipherment", x509.KeyUsageDataEncipherment: "Data Encipherment", x509.KeyUsageKeyAgreement: "Key Agreement", x509.KeyUsageCertSign: "Cert Sign", x509.KeyUsageCRLSign: "CRL Sign", x509.KeyUsageEncipherOnly: "Encipher Only", x509.KeyUsageDecipherOnly: "Decipher Only", } var extKeyUsageStrings = map[x509.ExtKeyUsage]string{ x509.ExtKeyUsageAny: "Any", x509.ExtKeyUsageServerAuth: "Server Auth", x509.ExtKeyUsageClientAuth: "Client Auth", x509.ExtKeyUsageCodeSigning: "Code Signing", x509.ExtKeyUsageEmailProtection: "Email Protection", x509.ExtKeyUsageIPSECEndSystem: "IPSEC End System", x509.ExtKeyUsageIPSECTunnel: "IPSEC Tunnel", x509.ExtKeyUsageIPSECUser: "IPSEC User", x509.ExtKeyUsageTimeStamping: "Time Stamping", x509.ExtKeyUsageOCSPSigning: "OCSP Signing", x509.ExtKeyUsageMicrosoftServerGatedCrypto: "Microsoft ServerGatedCrypto", x509.ExtKeyUsageNetscapeServerGatedCrypto: "Netscape ServerGatedCrypto", } var algoName = [...]string{ x509.MD2WithRSA: "MD2-RSA", x509.MD5WithRSA: "MD5-RSA", x509.SHA1WithRSA: "SHA1-RSA", x509.SHA256WithRSA: "SHA256-RSA", x509.SHA384WithRSA: "SHA384-RSA", x509.SHA512WithRSA: "SHA512-RSA", x509.DSAWithSHA1: "DSA-SHA1", x509.DSAWithSHA256: "DSA-SHA256", x509.ECDSAWithSHA1: "ECDSA-SHA1", x509.ECDSAWithSHA256: "ECDSA-SHA256", x509.ECDSAWithSHA384: "ECDSA-SHA384", x509.ECDSAWithSHA512: "ECDSA-SHA512", } type basicConstraints struct { IsCA bool `json:"is_ca"` MaxPathLen *int `json:"pathlen,omitempty"` } type nameConstraints struct { Critical bool `json:"critical,omitempty"` PermittedDNSDomains []string `json:"permitted_dns_domains,omitempty"` ExcludedDNSDomains []string `json:"excluded_dns_domains,omitempty"` PermittedIPRanges []*net.IPNet `json:"permitted_ip_ranges,omitempty"` ExcludedIPRanges []*net.IPNet `json:"excluded_ip_ranges,omitempty"` PermittedEmailAddresses []string `json:"permitted_email_addresses,omitempty"` ExcludedEmailAddresses []string `json:"excluded_email_addresses,omitempty"` PermittedURIDomains []string `json:"permitted_uri_domains,omitempty"` ExcludedURIDomains []string `json:"excluded_uri_domains,omitempty"` } type simpleCertificate struct { Alias string `json:"alias,omitempty"` SerialNumber string `json:"serial"` NotBefore time.Time `json:"not_before"` NotAfter time.Time `json:"not_after"` SignatureAlgorithm simpleSigAlg `json:"signature_algorithm"` IsSelfSigned bool `json:"is_self_signed"` Subject simplePKIXName `json:"subject"` Issuer simplePKIXName `json:"issuer"` BasicConstraints *basicConstraints `json:"basic_constraints,omitempty"` NameConstraints *nameConstraints `json:"name_constraints,omitempty"` OCSPServer []string `json:"ocsp_server,omitempty"` IssuingCertificateURL []string `json:"issuing_certificate,omitempty"` KeyUsage simpleKeyUsage `json:"key_usage,omitempty"` ExtKeyUsage []simpleExtKeyUsage `json:"extended_key_usage,omitempty"` AltDNSNames []string `json:"dns_names,omitempty"` AltIPAddresses []net.IP `json:"ip_addresses,omitempty"` URINames []string `json:"uri_names,omitempty"` EmailAddresses []string `json:"email_addresses,omitempty"` Warnings []string `json:"warnings,omitempty"` PEM string `json:"pem,omitempty"` Width int `json:"-"` } type simplePKIXName struct { Name pkix.Name KeyID []byte } type simpleKeyUsage x509.KeyUsage type simpleExtKeyUsage x509.ExtKeyUsage type simpleSigAlg x509.SignatureAlgorithm func createSimpleCertificate(name string, cert *x509.Certificate) simpleCertificate { out := simpleCertificate{ Alias: name, SerialNumber: cert.SerialNumber.String(), NotBefore: cert.NotBefore, NotAfter: cert.NotAfter, SignatureAlgorithm: simpleSigAlg(cert.SignatureAlgorithm), IsSelfSigned: IsSelfSigned(cert), Subject: simplePKIXName{ Name: cert.Subject, KeyID: cert.SubjectKeyId, }, Issuer: simplePKIXName{ Name: cert.Issuer, KeyID: cert.AuthorityKeyId, }, KeyUsage: simpleKeyUsage(cert.KeyUsage), OCSPServer: cert.OCSPServer, IssuingCertificateURL: cert.IssuingCertificateURL, AltDNSNames: cert.DNSNames, AltIPAddresses: cert.IPAddresses, EmailAddresses: cert.EmailAddresses, PEM: string(pem.EncodeToMemory(EncodeX509ToPEM(cert, nil))), } for _, uri := range cert.URIs { out.URINames = append(out.URINames, uri.String()) } out.Warnings = certWarnings(cert, out.URINames) if cert.BasicConstraintsValid { out.BasicConstraints = &basicConstraints{ IsCA: cert.IsCA, } if cert.MaxPathLen > 0 || cert.MaxPathLenZero { out.BasicConstraints.MaxPathLen = &cert.MaxPathLen } } if len(cert.PermittedDNSDomains) > 0 || len(cert.ExcludedDNSDomains) > 0 || len(cert.PermittedIPRanges) > 0 || len(cert.ExcludedIPRanges) > 0 || len(cert.PermittedEmailAddresses) > 0 || len(cert.ExcludedEmailAddresses) > 0 || len(cert.PermittedURIDomains) > 0 || len(cert.ExcludedURIDomains) > 0 { out.NameConstraints = &nameConstraints{ Critical: cert.PermittedDNSDomainsCritical, PermittedDNSDomains: cert.PermittedDNSDomains, ExcludedDNSDomains: cert.ExcludedDNSDomains, PermittedIPRanges: cert.PermittedIPRanges, ExcludedIPRanges: cert.ExcludedIPRanges, PermittedEmailAddresses: cert.PermittedEmailAddresses, ExcludedEmailAddresses: cert.ExcludedEmailAddresses, PermittedURIDomains: cert.PermittedURIDomains, ExcludedURIDomains: cert.ExcludedURIDomains, } } simpleEku := []simpleExtKeyUsage{} for _, eku := range cert.ExtKeyUsage { simpleEku = append(simpleEku, simpleExtKeyUsage(eku)) } out.ExtKeyUsage = simpleEku return out } func (p simplePKIXName) MarshalJSON() ([]byte, error) { out := map[string]interface{}{} for _, rdn := range p.Name.Names { oid := describeOid(rdn.Type) if prev, ok := out[oid.Slug]; oid.Multiple && ok { l := prev.([]interface{}) out[oid.Slug] = append(l, rdn.Value) } else if oid.Multiple { out[oid.Slug] = []interface{}{rdn.Value} } else { out[oid.Slug] = rdn.Value } } if len(p.KeyID) > 0 { out["key_id"] = hexify(p.KeyID) } return json.Marshal(out) } func (k simpleKeyUsage) MarshalJSON() ([]byte, error) { return json.Marshal(keyUsage(k)) } func (e simpleExtKeyUsage) MarshalJSON() ([]byte, error) { return json.Marshal(extKeyUsage(e)) } func (s simpleSigAlg) MarshalJSON() ([]byte, error) { return json.Marshal(algString(x509.SignatureAlgorithm(s))) }
Apache License 2.0
m-lab/tcp-info
eventsocket/server.go
Serve
go
func (s *server) Serve(ctx context.Context) error { defer s.servingWG.Done() derivedCtx, derivedCancel := context.WithCancel(ctx) defer derivedCancel() go s.notifyClients(derivedCtx) s.servingWG.Add(1) go func() { <-derivedCtx.Done() s.unixListener.Close() close(s.eventC) s.servingWG.Done() }() var err error for derivedCtx.Err() == nil { var conn net.Conn conn, err = s.unixListener.Accept() if err != nil { log.Printf("Could not Accept on socket %q: %s\n", s.filename, err) continue } s.addClient(conn) } return err }
Serve all clients that connect to this server until the context is canceled. It is expected that this will be called in a goroutine, after Listen has been called. This function should only be called once for a given server.
https://github.com/m-lab/tcp-info/blob/601890bc98b74ea56965215cb4383bccd33a3c84/eventsocket/server.go#L135-L165
package eventsocket import ( "context" "encoding/json" "fmt" "log" "net" "os" "sync" "time" "github.com/m-lab/tcp-info/inetdiag" ) type TCPEvent int const ( Open = TCPEvent(iota) Close ) type FlowEvent struct { Event TCPEvent Timestamp time.Time UUID string ID *inetdiag.SockID } type Server interface { Listen() error Serve(context.Context) error FlowCreated(timestamp time.Time, uuid string, sockid inetdiag.SockID) FlowDeleted(timestamp time.Time, uuid string) } type server struct { eventC chan *FlowEvent filename string clients map[net.Conn]struct{} unixListener net.Listener mutex sync.Mutex servingWG sync.WaitGroup } func (s *server) addClient(c net.Conn) { log.Println("Adding new TCP event client", c) s.mutex.Lock() defer s.mutex.Unlock() s.clients[c] = struct{}{} } func (s *server) removeClient(c net.Conn) { s.servingWG.Add(1) defer s.servingWG.Done() s.mutex.Lock() defer s.mutex.Unlock() _, ok := s.clients[c] if !ok { log.Println("Tried to remove TCP event client", c, "that was not present") return } delete(s.clients, c) } func (s *server) sendToAllListeners(data string) { s.mutex.Lock() defer s.mutex.Unlock() for c := range s.clients { _, err := fmt.Fprintln(c, data) if err != nil { log.Println("Write to client", c, "failed with error", err, " - removing the client.") go s.removeClient(c) go c.Close() } } } func (s *server) notifyClients(ctx context.Context) { s.servingWG.Add(1) defer s.servingWG.Done() for ctx.Err() == nil { event := <-s.eventC var b []byte var err error if event != nil { b, err = json.Marshal(*event) } if event == nil || err != nil { log.Printf("WARNING: Bad event received %v (err: %v)\n", event, err) continue } s.sendToAllListeners(string(b)) } } func (s *server) Listen() error { s.servingWG.Add(1) var err error os.Remove(s.filename) s.unixListener, err = net.Listen("unix", s.filename) return err }
Apache License 2.0
prep/beanstalk
conn_test.go
accept
go
func (server *Server) accept() { defer server.listener.Close() for { conn, err := server.listener.Accept() if err != nil { return } server.handleConn(textproto.NewConn(conn)) } }
accept incoming connections.
https://github.com/prep/beanstalk/blob/4f1a0d7e59fe876f19cf8f344118924f73ab9ae6/conn_test.go#L57-L68
package beanstalk import ( "bytes" "context" "errors" "net" "net/textproto" "sync" "testing" "time" ) type Line struct { lineno int line string } func (line Line) At(lineno int, s string) bool { return lineno == line.lineno && s == line.line } type Server struct { listener net.Listener mu sync.RWMutex lineno int handler func(line Line) string closeC chan struct{} closeOnce sync.Once } func NewServer() *Server { listener, err := net.Listen("tcp", "localhost:0") if err != nil { panic("Unable to set up listening socket for text beanstalk server: " + err.Error()) } server := &Server{listener: listener, closeC: make(chan struct{})} go server.accept() return server } func (server *Server) Close() { server.closeOnce.Do(func() { close(server.closeC) _ = server.listener.Close() }) }
BSD 3-Clause New or Revised License
containx/depcon
cliconfig/config.go
Filename
go
func (configFile *ConfigFile) Filename() string { return configFile.filename }
Filename returns the name of the configuration file
https://github.com/containx/depcon/blob/0020ef367850d26ad9baebb78e3945920eba605a/cliconfig/config.go#L312-L314
package cliconfig import ( "encoding/base64" "encoding/json" "errors" "fmt" "github.com/ContainX/depcon/pkg/userdir" "io" "os" "path/filepath" "strings" ) const ( ConfigFileName = "config.json" DotConfigDir = ".depcon" TypeMarathon = "marathon" TypeKubernetes = "kubernetes" TypeECS = "ecs" ) var ( configDir = os.Getenv("DEPCON_CONFIG") ErrEnvNotFound = errors.New("Specified environment was not found") ) func init() { if configDir == "" { configDir = filepath.Join(userdir.Get(), DotConfigDir) } } func ConfigDir() string { return configDir } func SetConfigDir(dir string) { configDir = dir } type ConfigFile struct { Format string `json:"format,omitempty"` RootService bool `json:"rootservice"` Environments map[string]*ConfigEnvironment `json:"environments,omitempty"` DefaultEnv string `json:"default,omitempty"` filename string } type ConfigEnvironment struct { Marathon *ServiceConfig `json:"marathon,omitempty"` } type ServiceConfig struct { Username string `json:"username,omitempty"` Password string `json:"password,omitempty"` Token string `json:"token"` HostUrl string `json:"serveraddress,omitempty"` Features map[string]string `json:"features,omitempty"` Name string `json:"-"` } func HasExistingConfig() (*ConfigFile, bool) { configFile, err := Load("") return configFile, err == nil } func (configFile *ConfigFile) LoadFromReader(configData io.Reader) error { if err := json.NewDecoder(configData).Decode(&configFile); err != nil { return err } var err error for _, configEnv := range configFile.Environments { configEnv.Marathon.Password, err = DecodePassword(configEnv.Marathon.Password) if err != nil { return err } } return nil } func Load(configDir string) (*ConfigFile, error) { if configDir == "" { configDir = ConfigDir() } configFile := ConfigFile{ Format: "column", Environments: make(map[string]*ConfigEnvironment), filename: filepath.Join(configDir, ConfigFileName), } _, err := os.Stat(configFile.filename) if err == nil { file, err := os.Open(configFile.filename) if err != nil { return &configFile, err } defer file.Close() err = configFile.LoadFromReader(file) return &configFile, err } return &configFile, err } func (configFile *ConfigFile) DetermineIfServiceIsRooted() (string, bool) { if len(configFile.Environments) > 1 { return "", false } return TypeMarathon, configFile.RootService } func (configEnv *ConfigEnvironment) EnvironmentType() string { return TypeMarathon } func (configFile *ConfigFile) AddEnvironment() { serviceEnv := createEnvironment() configEnv := &ConfigEnvironment{ Marathon: serviceEnv, } configFile.Environments[serviceEnv.Name] = configEnv configFile.Save() } func (configFile *ConfigFile) AddMarathonEnvironment(name, host, user, pass, token string) { service := &ServiceConfig{} service.Name = name service.HostUrl = host service.Username = user service.Password = pass service.Token = token configEnv := &ConfigEnvironment{ Marathon: service, } if len(configFile.Environments) == 0 { configFile.DefaultEnv = name configFile.RootService = true } configFile.Environments[name] = configEnv configFile.Save() } func (configFile *ConfigFile) RemoveEnvironment(name string, force bool) error { configEnv := configFile.Environments[name] if configEnv == nil { return ErrEnvNotFound } if !force { if !getBoolAnswer(fmt.Sprintf("Are you sure you would like to remove '%s'", name), true) { return nil } } if configFile.DefaultEnv == name { configFile.DefaultEnv = "" } delete(configFile.Environments, name) configFile.Save() return nil } func (configFile *ConfigFile) SetDefaultEnvironment(name string) error { configEnv := configFile.Environments[name] if configEnv == nil { return ErrEnvNotFound } configFile.DefaultEnv = name configFile.Save() return nil } func (configFile *ConfigFile) RenameEnvironment(oldName, newName string) error { configEnv := configFile.Environments[oldName] if configEnv == nil { return ErrEnvNotFound } delete(configFile.Environments, oldName) configFile.Environments[newName] = configEnv if configFile.DefaultEnv == oldName { configFile.DefaultEnv = newName } configFile.Save() return nil } func (configFile *ConfigFile) GetEnvironment(name string) (*ConfigEnvironment, error) { configEnv := configFile.Environments[name] if configEnv == nil { return nil, ErrEnvNotFound } return configEnv, nil } func (configFile *ConfigFile) GetEnvironments() []string { keys := make([]string, 0, len(configFile.Environments)) for k := range configFile.Environments { keys = append(keys, k) } return keys } func (configFile *ConfigFile) SaveToWriter(writer io.Writer) error { tmpEnvConfigs := make(map[string]*ConfigEnvironment, len(configFile.Environments)) for k, configEnv := range configFile.Environments { configEnvCopy := configEnv if configEnvCopy.Marathon != nil { configEnvCopy.Marathon.Password = EncodePassword(configEnvCopy.Marathon) configEnvCopy.Marathon.Name = "" } tmpEnvConfigs[k] = configEnvCopy } saveEnvConfigs := configFile.Environments configFile.Environments = tmpEnvConfigs defer func() { configFile.Environments = saveEnvConfigs }() data, err := json.MarshalIndent(configFile, "", "\t") if err != nil { return err } _, err = writer.Write(data) return err } func (configFile *ConfigFile) Save() error { if configFile.Filename() == "" { configFile.filename = filepath.Join(configDir, ConfigFileName) } if err := os.MkdirAll(filepath.Dir(configFile.filename), 0700); err != nil { return err } f, err := os.OpenFile(configFile.filename, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600) if err != nil { return err } defer f.Close() return configFile.SaveToWriter(f) } func EncodePassword(auth *ServiceConfig) string { if auth.Username == "" { return "" } authStr := auth.Username + ":" + auth.Password msg := []byte(authStr) encoded := make([]byte, base64.StdEncoding.EncodedLen(len(msg))) base64.StdEncoding.Encode(encoded, msg) return string(encoded) } func DecodePassword(authStr string) (string, error) { if authStr == "" { return "", nil } decLen := base64.StdEncoding.DecodedLen(len(authStr)) decoded := make([]byte, decLen) authByte := []byte(authStr) n, err := base64.StdEncoding.Decode(decoded, authByte) if err != nil { return "", err } if n > decLen { return "", fmt.Errorf("Something went wrong decoding service authentication") } arr := strings.SplitN(string(decoded), ":", 2) if len(arr) != 2 { return "", fmt.Errorf("Invalid auth configuration file") } password := strings.Trim(arr[1], "\x00") return password, nil }
Apache License 2.0
haproxytech/dataplaneapi
operations/stick_rule/get_stick_rule_responses.go
WithConfigurationVersion
go
func (o *GetStickRuleNotFound) WithConfigurationVersion(configurationVersion string) *GetStickRuleNotFound { o.ConfigurationVersion = configurationVersion return o }
WithConfigurationVersion adds the configurationVersion to the get stick rule not found response
https://github.com/haproxytech/dataplaneapi/blob/b362aae0b04d0e330bd9dcfbf9f315b670de013b/operations/stick_rule/get_stick_rule_responses.go#L123-L126
package stick_rule import ( "net/http" "github.com/go-openapi/runtime" "github.com/haproxytech/client-native/v2/models" ) const GetStickRuleOKCode int = 200 type GetStickRuleOK struct { ConfigurationVersion string `json:"Configuration-Version"` Payload *GetStickRuleOKBody `json:"body,omitempty"` } func NewGetStickRuleOK() *GetStickRuleOK { return &GetStickRuleOK{} } func (o *GetStickRuleOK) WithConfigurationVersion(configurationVersion string) *GetStickRuleOK { o.ConfigurationVersion = configurationVersion return o } func (o *GetStickRuleOK) SetConfigurationVersion(configurationVersion string) { o.ConfigurationVersion = configurationVersion } func (o *GetStickRuleOK) WithPayload(payload *GetStickRuleOKBody) *GetStickRuleOK { o.Payload = payload return o } func (o *GetStickRuleOK) SetPayload(payload *GetStickRuleOKBody) { o.Payload = payload } func (o *GetStickRuleOK) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { configurationVersion := o.ConfigurationVersion if configurationVersion != "" { rw.Header().Set("Configuration-Version", configurationVersion) } rw.WriteHeader(200) if o.Payload != nil { payload := o.Payload if err := producer.Produce(rw, payload); err != nil { panic(err) } } } const GetStickRuleNotFoundCode int = 404 type GetStickRuleNotFound struct { ConfigurationVersion string `json:"Configuration-Version"` Payload *models.Error `json:"body,omitempty"` } func NewGetStickRuleNotFound() *GetStickRuleNotFound { return &GetStickRuleNotFound{} }
Apache License 2.0
solo-io/skv2
pkg/multicluster/internal/k8s/admissionregistration.k8s.io/v1/sets/mocks/sets.go
Delta
go
func (mr *MockValidatingWebhookConfigurationSetMockRecorder) Delta(newSet interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Delta", reflect.TypeOf((*MockValidatingWebhookConfigurationSet)(nil).Delta), newSet) }
Delta indicates an expected call of Delta
https://github.com/solo-io/skv2/blob/a7d0c83004bb24051a91e35fca7d04d788967f17/pkg/multicluster/internal/k8s/admissionregistration.k8s.io/v1/sets/mocks/sets.go#L255-L258
package mock_v1sets import ( reflect "reflect" gomock "github.com/golang/mock/gomock" sets "github.com/solo-io/skv2/contrib/pkg/sets" ezkube "github.com/solo-io/skv2/pkg/ezkube" v1sets "github.com/solo-io/skv2/pkg/multicluster/internal/k8s/admissionregistration.k8s.io/v1/sets" v1 "k8s.io/api/admissionregistration/v1" sets0 "k8s.io/apimachinery/pkg/util/sets" ) type MockValidatingWebhookConfigurationSet struct { ctrl *gomock.Controller recorder *MockValidatingWebhookConfigurationSetMockRecorder } type MockValidatingWebhookConfigurationSetMockRecorder struct { mock *MockValidatingWebhookConfigurationSet } func NewMockValidatingWebhookConfigurationSet(ctrl *gomock.Controller) *MockValidatingWebhookConfigurationSet { mock := &MockValidatingWebhookConfigurationSet{ctrl: ctrl} mock.recorder = &MockValidatingWebhookConfigurationSetMockRecorder{mock} return mock } func (m *MockValidatingWebhookConfigurationSet) EXPECT() *MockValidatingWebhookConfigurationSetMockRecorder { return m.recorder } func (m *MockValidatingWebhookConfigurationSet) Keys() sets0.String { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Keys") ret0, _ := ret[0].(sets0.String) return ret0 } func (mr *MockValidatingWebhookConfigurationSetMockRecorder) Keys() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Keys", reflect.TypeOf((*MockValidatingWebhookConfigurationSet)(nil).Keys)) } func (m *MockValidatingWebhookConfigurationSet) List(filterResource ...func(*v1.ValidatingWebhookConfiguration) bool) []*v1.ValidatingWebhookConfiguration { m.ctrl.T.Helper() varargs := []interface{}{} for _, a := range filterResource { varargs = append(varargs, a) } ret := m.ctrl.Call(m, "List", varargs...) ret0, _ := ret[0].([]*v1.ValidatingWebhookConfiguration) return ret0 } func (mr *MockValidatingWebhookConfigurationSetMockRecorder) List(filterResource ...interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "List", reflect.TypeOf((*MockValidatingWebhookConfigurationSet)(nil).List), filterResource...) } func (m *MockValidatingWebhookConfigurationSet) UnsortedList(filterResource ...func(*v1.ValidatingWebhookConfiguration) bool) []*v1.ValidatingWebhookConfiguration { m.ctrl.T.Helper() varargs := []interface{}{} for _, a := range filterResource { varargs = append(varargs, a) } ret := m.ctrl.Call(m, "UnsortedList", varargs...) ret0, _ := ret[0].([]*v1.ValidatingWebhookConfiguration) return ret0 } func (mr *MockValidatingWebhookConfigurationSetMockRecorder) UnsortedList(filterResource ...interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "UnsortedList", reflect.TypeOf((*MockValidatingWebhookConfigurationSet)(nil).UnsortedList), filterResource...) } func (m *MockValidatingWebhookConfigurationSet) Map() map[string]*v1.ValidatingWebhookConfiguration { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Map") ret0, _ := ret[0].(map[string]*v1.ValidatingWebhookConfiguration) return ret0 } func (mr *MockValidatingWebhookConfigurationSetMockRecorder) Map() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Map", reflect.TypeOf((*MockValidatingWebhookConfigurationSet)(nil).Map)) } func (m *MockValidatingWebhookConfigurationSet) Insert(validatingWebhookConfiguration ...*v1.ValidatingWebhookConfiguration) { m.ctrl.T.Helper() varargs := []interface{}{} for _, a := range validatingWebhookConfiguration { varargs = append(varargs, a) } m.ctrl.Call(m, "Insert", varargs...) } func (mr *MockValidatingWebhookConfigurationSetMockRecorder) Insert(validatingWebhookConfiguration ...interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Insert", reflect.TypeOf((*MockValidatingWebhookConfigurationSet)(nil).Insert), validatingWebhookConfiguration...) } func (m *MockValidatingWebhookConfigurationSet) Equal(validatingWebhookConfigurationSet v1sets.ValidatingWebhookConfigurationSet) bool { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Equal", validatingWebhookConfigurationSet) ret0, _ := ret[0].(bool) return ret0 } func (mr *MockValidatingWebhookConfigurationSetMockRecorder) Equal(validatingWebhookConfigurationSet interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Equal", reflect.TypeOf((*MockValidatingWebhookConfigurationSet)(nil).Equal), validatingWebhookConfigurationSet) } func (m *MockValidatingWebhookConfigurationSet) Has(validatingWebhookConfiguration ezkube.ResourceId) bool { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Has", validatingWebhookConfiguration) ret0, _ := ret[0].(bool) return ret0 } func (mr *MockValidatingWebhookConfigurationSetMockRecorder) Has(validatingWebhookConfiguration interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Has", reflect.TypeOf((*MockValidatingWebhookConfigurationSet)(nil).Has), validatingWebhookConfiguration) } func (m *MockValidatingWebhookConfigurationSet) Delete(validatingWebhookConfiguration ezkube.ResourceId) { m.ctrl.T.Helper() m.ctrl.Call(m, "Delete", validatingWebhookConfiguration) } func (mr *MockValidatingWebhookConfigurationSetMockRecorder) Delete(validatingWebhookConfiguration interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Delete", reflect.TypeOf((*MockValidatingWebhookConfigurationSet)(nil).Delete), validatingWebhookConfiguration) } func (m *MockValidatingWebhookConfigurationSet) Union(set v1sets.ValidatingWebhookConfigurationSet) v1sets.ValidatingWebhookConfigurationSet { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Union", set) ret0, _ := ret[0].(v1sets.ValidatingWebhookConfigurationSet) return ret0 } func (mr *MockValidatingWebhookConfigurationSetMockRecorder) Union(set interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Union", reflect.TypeOf((*MockValidatingWebhookConfigurationSet)(nil).Union), set) } func (m *MockValidatingWebhookConfigurationSet) Difference(set v1sets.ValidatingWebhookConfigurationSet) v1sets.ValidatingWebhookConfigurationSet { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Difference", set) ret0, _ := ret[0].(v1sets.ValidatingWebhookConfigurationSet) return ret0 } func (mr *MockValidatingWebhookConfigurationSetMockRecorder) Difference(set interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Difference", reflect.TypeOf((*MockValidatingWebhookConfigurationSet)(nil).Difference), set) } func (m *MockValidatingWebhookConfigurationSet) Intersection(set v1sets.ValidatingWebhookConfigurationSet) v1sets.ValidatingWebhookConfigurationSet { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Intersection", set) ret0, _ := ret[0].(v1sets.ValidatingWebhookConfigurationSet) return ret0 } func (mr *MockValidatingWebhookConfigurationSetMockRecorder) Intersection(set interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Intersection", reflect.TypeOf((*MockValidatingWebhookConfigurationSet)(nil).Intersection), set) } func (m *MockValidatingWebhookConfigurationSet) Find(id ezkube.ResourceId) (*v1.ValidatingWebhookConfiguration, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Find", id) ret0, _ := ret[0].(*v1.ValidatingWebhookConfiguration) ret1, _ := ret[1].(error) return ret0, ret1 } func (mr *MockValidatingWebhookConfigurationSetMockRecorder) Find(id interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Find", reflect.TypeOf((*MockValidatingWebhookConfigurationSet)(nil).Find), id) } func (m *MockValidatingWebhookConfigurationSet) Length() int { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Length") ret0, _ := ret[0].(int) return ret0 } func (mr *MockValidatingWebhookConfigurationSetMockRecorder) Length() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Length", reflect.TypeOf((*MockValidatingWebhookConfigurationSet)(nil).Length)) } func (m *MockValidatingWebhookConfigurationSet) Generic() sets.ResourceSet { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Generic") ret0, _ := ret[0].(sets.ResourceSet) return ret0 } func (mr *MockValidatingWebhookConfigurationSetMockRecorder) Generic() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Generic", reflect.TypeOf((*MockValidatingWebhookConfigurationSet)(nil).Generic)) } func (m *MockValidatingWebhookConfigurationSet) Delta(newSet v1sets.ValidatingWebhookConfigurationSet) sets.ResourceDelta { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Delta", newSet) ret0, _ := ret[0].(sets.ResourceDelta) return ret0 }
Apache License 2.0
jmhodges/howsmyssl
vendor/google.golang.org/protobuf/internal/impl/codec_gen.go
consumeEnumSliceValue
go
func consumeEnumSliceValue(b []byte, listv protoreflect.Value, _ protowire.Number, wtyp protowire.Type, _ unmarshalOptions) (_ protoreflect.Value, out unmarshalOutput, err error) { list := listv.List() if wtyp == protowire.BytesType { b, n := protowire.ConsumeBytes(b) if n < 0 { return protoreflect.Value{}, out, protowire.ParseError(n) } for len(b) > 0 { var v uint64 var n int if len(b) >= 1 && b[0] < 0x80 { v = uint64(b[0]) n = 1 } else if len(b) >= 2 && b[1] < 128 { v = uint64(b[0]&0x7f) + uint64(b[1])<<7 n = 2 } else { v, n = protowire.ConsumeVarint(b) } if n < 0 { return protoreflect.Value{}, out, protowire.ParseError(n) } list.Append(protoreflect.ValueOfEnum(protoreflect.EnumNumber(v))) b = b[n:] } out.n = n return listv, out, nil } if wtyp != protowire.VarintType { return protoreflect.Value{}, out, errUnknown } var v uint64 var n int if len(b) >= 1 && b[0] < 0x80 { v = uint64(b[0]) n = 1 } else if len(b) >= 2 && b[1] < 128 { v = uint64(b[0]&0x7f) + uint64(b[1])<<7 n = 2 } else { v, n = protowire.ConsumeVarint(b) } if n < 0 { return protoreflect.Value{}, out, protowire.ParseError(n) } list.Append(protoreflect.ValueOfEnum(protoreflect.EnumNumber(v))) out.n = n return listv, out, nil }
consumeEnumSliceValue wire decodes a [] value as a repeated Enum.
https://github.com/jmhodges/howsmyssl/blob/b72af40d21cbb12b85932ef1bc18e50459f39263/vendor/google.golang.org/protobuf/internal/impl/codec_gen.go#L487-L535
package impl import ( "math" "unicode/utf8" "google.golang.org/protobuf/encoding/protowire" "google.golang.org/protobuf/reflect/protoreflect" ) func sizeBool(p pointer, f *coderFieldInfo, _ marshalOptions) (size int) { v := *p.Bool() return f.tagsize + protowire.SizeVarint(protowire.EncodeBool(v)) } func appendBool(b []byte, p pointer, f *coderFieldInfo, _ marshalOptions) ([]byte, error) { v := *p.Bool() b = protowire.AppendVarint(b, f.wiretag) b = protowire.AppendVarint(b, protowire.EncodeBool(v)) return b, nil } func consumeBool(b []byte, p pointer, wtyp protowire.Type, f *coderFieldInfo, _ unmarshalOptions) (out unmarshalOutput, err error) { if wtyp != protowire.VarintType { return out, errUnknown } var v uint64 var n int if len(b) >= 1 && b[0] < 0x80 { v = uint64(b[0]) n = 1 } else if len(b) >= 2 && b[1] < 128 { v = uint64(b[0]&0x7f) + uint64(b[1])<<7 n = 2 } else { v, n = protowire.ConsumeVarint(b) } if n < 0 { return out, protowire.ParseError(n) } *p.Bool() = protowire.DecodeBool(v) out.n = n return out, nil } var coderBool = pointerCoderFuncs{ size: sizeBool, marshal: appendBool, unmarshal: consumeBool, merge: mergeBool, } func sizeBoolNoZero(p pointer, f *coderFieldInfo, _ marshalOptions) (size int) { v := *p.Bool() if v == false { return 0 } return f.tagsize + protowire.SizeVarint(protowire.EncodeBool(v)) } func appendBoolNoZero(b []byte, p pointer, f *coderFieldInfo, _ marshalOptions) ([]byte, error) { v := *p.Bool() if v == false { return b, nil } b = protowire.AppendVarint(b, f.wiretag) b = protowire.AppendVarint(b, protowire.EncodeBool(v)) return b, nil } var coderBoolNoZero = pointerCoderFuncs{ size: sizeBoolNoZero, marshal: appendBoolNoZero, unmarshal: consumeBool, merge: mergeBoolNoZero, } func sizeBoolPtr(p pointer, f *coderFieldInfo, _ marshalOptions) (size int) { v := **p.BoolPtr() return f.tagsize + protowire.SizeVarint(protowire.EncodeBool(v)) } func appendBoolPtr(b []byte, p pointer, f *coderFieldInfo, _ marshalOptions) ([]byte, error) { v := **p.BoolPtr() b = protowire.AppendVarint(b, f.wiretag) b = protowire.AppendVarint(b, protowire.EncodeBool(v)) return b, nil } func consumeBoolPtr(b []byte, p pointer, wtyp protowire.Type, f *coderFieldInfo, _ unmarshalOptions) (out unmarshalOutput, err error) { if wtyp != protowire.VarintType { return out, errUnknown } var v uint64 var n int if len(b) >= 1 && b[0] < 0x80 { v = uint64(b[0]) n = 1 } else if len(b) >= 2 && b[1] < 128 { v = uint64(b[0]&0x7f) + uint64(b[1])<<7 n = 2 } else { v, n = protowire.ConsumeVarint(b) } if n < 0 { return out, protowire.ParseError(n) } vp := p.BoolPtr() if *vp == nil { *vp = new(bool) } **vp = protowire.DecodeBool(v) out.n = n return out, nil } var coderBoolPtr = pointerCoderFuncs{ size: sizeBoolPtr, marshal: appendBoolPtr, unmarshal: consumeBoolPtr, merge: mergeBoolPtr, } func sizeBoolSlice(p pointer, f *coderFieldInfo, _ marshalOptions) (size int) { s := *p.BoolSlice() for _, v := range s { size += f.tagsize + protowire.SizeVarint(protowire.EncodeBool(v)) } return size } func appendBoolSlice(b []byte, p pointer, f *coderFieldInfo, _ marshalOptions) ([]byte, error) { s := *p.BoolSlice() for _, v := range s { b = protowire.AppendVarint(b, f.wiretag) b = protowire.AppendVarint(b, protowire.EncodeBool(v)) } return b, nil } func consumeBoolSlice(b []byte, p pointer, wtyp protowire.Type, f *coderFieldInfo, _ unmarshalOptions) (out unmarshalOutput, err error) { sp := p.BoolSlice() if wtyp == protowire.BytesType { s := *sp b, n := protowire.ConsumeBytes(b) if n < 0 { return out, protowire.ParseError(n) } for len(b) > 0 { var v uint64 var n int if len(b) >= 1 && b[0] < 0x80 { v = uint64(b[0]) n = 1 } else if len(b) >= 2 && b[1] < 128 { v = uint64(b[0]&0x7f) + uint64(b[1])<<7 n = 2 } else { v, n = protowire.ConsumeVarint(b) } if n < 0 { return out, protowire.ParseError(n) } s = append(s, protowire.DecodeBool(v)) b = b[n:] } *sp = s out.n = n return out, nil } if wtyp != protowire.VarintType { return out, errUnknown } var v uint64 var n int if len(b) >= 1 && b[0] < 0x80 { v = uint64(b[0]) n = 1 } else if len(b) >= 2 && b[1] < 128 { v = uint64(b[0]&0x7f) + uint64(b[1])<<7 n = 2 } else { v, n = protowire.ConsumeVarint(b) } if n < 0 { return out, protowire.ParseError(n) } *sp = append(*sp, protowire.DecodeBool(v)) out.n = n return out, nil } var coderBoolSlice = pointerCoderFuncs{ size: sizeBoolSlice, marshal: appendBoolSlice, unmarshal: consumeBoolSlice, merge: mergeBoolSlice, } func sizeBoolPackedSlice(p pointer, f *coderFieldInfo, _ marshalOptions) (size int) { s := *p.BoolSlice() if len(s) == 0 { return 0 } n := 0 for _, v := range s { n += protowire.SizeVarint(protowire.EncodeBool(v)) } return f.tagsize + protowire.SizeBytes(n) } func appendBoolPackedSlice(b []byte, p pointer, f *coderFieldInfo, _ marshalOptions) ([]byte, error) { s := *p.BoolSlice() if len(s) == 0 { return b, nil } b = protowire.AppendVarint(b, f.wiretag) n := 0 for _, v := range s { n += protowire.SizeVarint(protowire.EncodeBool(v)) } b = protowire.AppendVarint(b, uint64(n)) for _, v := range s { b = protowire.AppendVarint(b, protowire.EncodeBool(v)) } return b, nil } var coderBoolPackedSlice = pointerCoderFuncs{ size: sizeBoolPackedSlice, marshal: appendBoolPackedSlice, unmarshal: consumeBoolSlice, merge: mergeBoolSlice, } func sizeBoolValue(v protoreflect.Value, tagsize int, _ marshalOptions) int { return tagsize + protowire.SizeVarint(protowire.EncodeBool(v.Bool())) } func appendBoolValue(b []byte, v protoreflect.Value, wiretag uint64, _ marshalOptions) ([]byte, error) { b = protowire.AppendVarint(b, wiretag) b = protowire.AppendVarint(b, protowire.EncodeBool(v.Bool())) return b, nil } func consumeBoolValue(b []byte, _ protoreflect.Value, _ protowire.Number, wtyp protowire.Type, _ unmarshalOptions) (_ protoreflect.Value, out unmarshalOutput, err error) { if wtyp != protowire.VarintType { return protoreflect.Value{}, out, errUnknown } var v uint64 var n int if len(b) >= 1 && b[0] < 0x80 { v = uint64(b[0]) n = 1 } else if len(b) >= 2 && b[1] < 128 { v = uint64(b[0]&0x7f) + uint64(b[1])<<7 n = 2 } else { v, n = protowire.ConsumeVarint(b) } if n < 0 { return protoreflect.Value{}, out, protowire.ParseError(n) } out.n = n return protoreflect.ValueOfBool(protowire.DecodeBool(v)), out, nil } var coderBoolValue = valueCoderFuncs{ size: sizeBoolValue, marshal: appendBoolValue, unmarshal: consumeBoolValue, merge: mergeScalarValue, } func sizeBoolSliceValue(listv protoreflect.Value, tagsize int, _ marshalOptions) (size int) { list := listv.List() for i, llen := 0, list.Len(); i < llen; i++ { v := list.Get(i) size += tagsize + protowire.SizeVarint(protowire.EncodeBool(v.Bool())) } return size } func appendBoolSliceValue(b []byte, listv protoreflect.Value, wiretag uint64, _ marshalOptions) ([]byte, error) { list := listv.List() for i, llen := 0, list.Len(); i < llen; i++ { v := list.Get(i) b = protowire.AppendVarint(b, wiretag) b = protowire.AppendVarint(b, protowire.EncodeBool(v.Bool())) } return b, nil } func consumeBoolSliceValue(b []byte, listv protoreflect.Value, _ protowire.Number, wtyp protowire.Type, _ unmarshalOptions) (_ protoreflect.Value, out unmarshalOutput, err error) { list := listv.List() if wtyp == protowire.BytesType { b, n := protowire.ConsumeBytes(b) if n < 0 { return protoreflect.Value{}, out, protowire.ParseError(n) } for len(b) > 0 { var v uint64 var n int if len(b) >= 1 && b[0] < 0x80 { v = uint64(b[0]) n = 1 } else if len(b) >= 2 && b[1] < 128 { v = uint64(b[0]&0x7f) + uint64(b[1])<<7 n = 2 } else { v, n = protowire.ConsumeVarint(b) } if n < 0 { return protoreflect.Value{}, out, protowire.ParseError(n) } list.Append(protoreflect.ValueOfBool(protowire.DecodeBool(v))) b = b[n:] } out.n = n return listv, out, nil } if wtyp != protowire.VarintType { return protoreflect.Value{}, out, errUnknown } var v uint64 var n int if len(b) >= 1 && b[0] < 0x80 { v = uint64(b[0]) n = 1 } else if len(b) >= 2 && b[1] < 128 { v = uint64(b[0]&0x7f) + uint64(b[1])<<7 n = 2 } else { v, n = protowire.ConsumeVarint(b) } if n < 0 { return protoreflect.Value{}, out, protowire.ParseError(n) } list.Append(protoreflect.ValueOfBool(protowire.DecodeBool(v))) out.n = n return listv, out, nil } var coderBoolSliceValue = valueCoderFuncs{ size: sizeBoolSliceValue, marshal: appendBoolSliceValue, unmarshal: consumeBoolSliceValue, merge: mergeListValue, } func sizeBoolPackedSliceValue(listv protoreflect.Value, tagsize int, _ marshalOptions) (size int) { list := listv.List() llen := list.Len() if llen == 0 { return 0 } n := 0 for i, llen := 0, llen; i < llen; i++ { v := list.Get(i) n += protowire.SizeVarint(protowire.EncodeBool(v.Bool())) } return tagsize + protowire.SizeBytes(n) } func appendBoolPackedSliceValue(b []byte, listv protoreflect.Value, wiretag uint64, _ marshalOptions) ([]byte, error) { list := listv.List() llen := list.Len() if llen == 0 { return b, nil } b = protowire.AppendVarint(b, wiretag) n := 0 for i := 0; i < llen; i++ { v := list.Get(i) n += protowire.SizeVarint(protowire.EncodeBool(v.Bool())) } b = protowire.AppendVarint(b, uint64(n)) for i := 0; i < llen; i++ { v := list.Get(i) b = protowire.AppendVarint(b, protowire.EncodeBool(v.Bool())) } return b, nil } var coderBoolPackedSliceValue = valueCoderFuncs{ size: sizeBoolPackedSliceValue, marshal: appendBoolPackedSliceValue, unmarshal: consumeBoolSliceValue, merge: mergeListValue, } func sizeEnumValue(v protoreflect.Value, tagsize int, _ marshalOptions) int { return tagsize + protowire.SizeVarint(uint64(v.Enum())) } func appendEnumValue(b []byte, v protoreflect.Value, wiretag uint64, _ marshalOptions) ([]byte, error) { b = protowire.AppendVarint(b, wiretag) b = protowire.AppendVarint(b, uint64(v.Enum())) return b, nil } func consumeEnumValue(b []byte, _ protoreflect.Value, _ protowire.Number, wtyp protowire.Type, _ unmarshalOptions) (_ protoreflect.Value, out unmarshalOutput, err error) { if wtyp != protowire.VarintType { return protoreflect.Value{}, out, errUnknown } var v uint64 var n int if len(b) >= 1 && b[0] < 0x80 { v = uint64(b[0]) n = 1 } else if len(b) >= 2 && b[1] < 128 { v = uint64(b[0]&0x7f) + uint64(b[1])<<7 n = 2 } else { v, n = protowire.ConsumeVarint(b) } if n < 0 { return protoreflect.Value{}, out, protowire.ParseError(n) } out.n = n return protoreflect.ValueOfEnum(protoreflect.EnumNumber(v)), out, nil } var coderEnumValue = valueCoderFuncs{ size: sizeEnumValue, marshal: appendEnumValue, unmarshal: consumeEnumValue, merge: mergeScalarValue, } func sizeEnumSliceValue(listv protoreflect.Value, tagsize int, _ marshalOptions) (size int) { list := listv.List() for i, llen := 0, list.Len(); i < llen; i++ { v := list.Get(i) size += tagsize + protowire.SizeVarint(uint64(v.Enum())) } return size } func appendEnumSliceValue(b []byte, listv protoreflect.Value, wiretag uint64, _ marshalOptions) ([]byte, error) { list := listv.List() for i, llen := 0, list.Len(); i < llen; i++ { v := list.Get(i) b = protowire.AppendVarint(b, wiretag) b = protowire.AppendVarint(b, uint64(v.Enum())) } return b, nil }
MIT License
intel/cri-resource-manager
pkg/cri/resource-manager/policy/builtin/topology-aware/node.go
GetMemset
go
func (n *socketnode) GetMemset(mtype memoryType) idset.IDSet { mset := idset.NewIDSet() if mtype&memoryDRAM != 0 { mset.Add(n.mem.Members()...) } if mtype&memoryHBM != 0 { mset.Add(n.hbm.Members()...) } if mtype&memoryPMEM != 0 { mset.Add(n.pMem.Members()...) } return mset }
GetMemset returns the set of memory attached to this socket.
https://github.com/intel/cri-resource-manager/blob/21ed50ef93b8153aedc298a07a806f19e3e94825/pkg/cri/resource-manager/policy/builtin/topology-aware/node.go#L780-L794
package topologyaware import ( "fmt" system "github.com/intel/cri-resource-manager/pkg/sysfs" "github.com/intel/cri-resource-manager/pkg/topology" idset "github.com/intel/goresctrl/pkg/utils" "k8s.io/kubernetes/pkg/kubelet/cm/cpuset" "github.com/intel/cri-resource-manager/pkg/cri/resource-manager/kubernetes" ) type NodeKind string const ( NilNode NodeKind = "" UnknownNode NodeKind = "unknown" SocketNode NodeKind = "socket" DieNode NodeKind = "die" NumaNode NodeKind = "numa node" VirtualNode NodeKind = "virtual node" ) const ( OverfitPenalty = 0.9 ) type Node interface { IsNil() bool Name() string Kind() NodeKind NodeID() int Parent() Node Children() []Node LinkParent(Node) AddChildren([]Node) IsSameNode(Node) bool IsRootNode() bool IsLeafNode() bool RootDistance() int NodeHeight() int System() system.System Policy() *policy DiscoverSupply(assignedNUMANodes []idset.ID) Supply GetSupply() Supply FreeSupply() Supply GrantedReservedCPU() int GrantedSharedCPU() int GetMemset(mtype memoryType) idset.IDSet AssignNUMANodes(ids []idset.ID) DepthFirst(func(Node) error) error BreadthFirst(func(Node) error) error Dump(string, ...int) dump(string, ...int) GetMemoryType() memoryType HasMemoryType(memoryType) bool GetPhysicalNodeIDs() []idset.ID GetScore(Request) Score HintScore(topology.Hint) float64 } type node struct { policy *policy self nodeself name string id int kind NodeKind depth int parent Node children []Node noderes Supply freeres Supply mem idset.IDSet pMem idset.IDSet hbm idset.IDSet } type nodeself struct { node Node } type socketnode struct { node id idset.ID syspkg system.CPUPackage } type dienode struct { node id idset.ID syspkg system.CPUPackage } type numanode struct { node id idset.ID sysnode system.Node } type virtualnode struct { node } var nilnode Node = &node{ name: "<nil node>", id: -1, kind: NilNode, depth: -1, children: nil, } func (n *node) init(p *policy, name string, kind NodeKind, parent Node) { n.policy = p n.name = name n.kind = kind n.parent = parent n.id = -1 n.LinkParent(parent) n.mem = idset.NewIDSet() n.pMem = idset.NewIDSet() n.hbm = idset.NewIDSet() } func (n *node) IsNil() bool { return n.kind == NilNode } func (n *node) Name() string { if n.IsNil() { return "<nil node>" } return n.name } func (n *node) Kind() NodeKind { return n.kind } func (n *node) NodeID() int { if n.IsNil() { return -1 } return n.id } func (n *node) IsSameNode(other Node) bool { return n.NodeID() == other.NodeID() } func (n *node) IsRootNode() bool { return n.parent.IsNil() } func (n *node) IsLeafNode() bool { return len(n.children) == 0 } func (n *node) RootDistance() int { if n.IsNil() { return -1 } return n.depth } func (n *node) NodeHeight() int { if n.IsNil() { return -1 } return n.policy.depth - n.depth } func (n *node) Parent() Node { if n.IsNil() { return nil } return n.parent } func (n *node) Children() []Node { if n.IsNil() { return nil } return n.children } func (n *node) LinkParent(parent Node) { n.parent = parent if !parent.IsNil() { parent.AddChildren([]Node{n}) } n.depth = parent.RootDistance() + 1 } func (n *node) AddChildren(nodes []Node) { n.children = append(n.children, nodes...) } func (n *node) Dump(prefix string, level ...int) { if !log.DebugEnabled() { return } lvl := 0 if len(level) > 0 { lvl = level[0] } idt := indent(prefix, lvl) n.self.node.dump(prefix, lvl) log.Debug("%s - %s", idt, n.noderes.DumpCapacity()) log.Debug("%s - %s", idt, n.freeres.DumpAllocatable()) n.freeres.DumpMemoryState(idt + " ") if n.mem.Size() > 0 { log.Debug("%s - normal memory: %v", idt, n.mem) } if n.hbm.Size() > 0 { log.Debug("%s - HBM memory: %v", idt, n.hbm) } if n.pMem.Size() > 0 { log.Debug("%s - PMEM memory: %v", idt, n.pMem) } for _, grant := range n.policy.allocations.grants { cpuNodeID := grant.GetCPUNode().NodeID() memNodeID := grant.GetMemoryNode().NodeID() switch { case cpuNodeID == n.id && memNodeID == n.id: log.Debug("%s + cpu+mem %s", idt, grant) case cpuNodeID == n.id: log.Debug("%s + cpuonly %s", idt, grant) case memNodeID == n.id: log.Debug("%s + memonly %s", idt, grant) } } if !n.Parent().IsNil() { log.Debug("%s - parent: <%s>", idt, n.Parent().Name()) } if len(n.children) > 0 { log.Debug("%s - children:", idt) for _, c := range n.children { c.Dump(prefix, lvl+1) } } } func (n *node) dump(prefix string, level ...int) { n.self.node.dump(prefix, level...) } func (n *node) DepthFirst(fn func(Node) error) error { for _, c := range n.children { if err := c.DepthFirst(fn); err != nil { return err } } return fn(n) } func (n *node) BreadthFirst(fn func(Node) error) error { if err := fn(n); err != nil { return err } for _, c := range n.children { if err := c.BreadthFirst(fn); err != nil { return err } } return nil } func (n *node) System() system.System { return n.policy.sys } func (n *node) Policy() *policy { return n.policy } func (n *node) GetSupply() Supply { return n.self.node.GetSupply() } func (n *node) DiscoverSupply(assignedNUMANodes []idset.ID) Supply { return n.self.node.DiscoverSupply(assignedNUMANodes) } func (n *node) discoverSupply(assignedNUMANodes []idset.ID) Supply { if n.noderes != nil { return n.noderes.Clone() } if !n.IsLeafNode() { log.Debug("%s: cumulating child resources...", n.Name()) if len(assignedNUMANodes) > 0 { log.Fatal("invalid pool setup: trying to attach NUMA nodes to non-leaf node %s", n.Name()) } n.noderes = newSupply(n, cpuset.NewCPUSet(), cpuset.NewCPUSet(), cpuset.NewCPUSet(), 0, 0, nil, nil) for _, c := range n.children { supply := c.GetSupply() n.noderes.Cumulate(supply) n.mem.Add(c.GetMemset(memoryDRAM).Members()...) n.hbm.Add(c.GetMemset(memoryHBM).Members()...) n.pMem.Add(c.GetMemset(memoryPMEM).Members()...) log.Debug(" + %s", supply.DumpCapacity()) } log.Debug(" = %s", n.noderes.DumpCapacity()) } else { log.Debug("%s: discovering attached/assigned resources...", n.Name()) mmap := createMemoryMap(0, 0, 0) cpus := cpuset.NewCPUSet() for _, nodeID := range assignedNUMANodes { node := n.System().Node(nodeID) nodeCPUs := node.CPUSet() meminfo, err := node.MemoryInfo() if err != nil { log.Fatal("%s: failed to get memory info for NUMA node #%d", n.Name(), nodeID) } switch node.GetMemoryType() { case system.MemoryTypeDRAM: n.mem.Add(nodeID) mmap.AddDRAM(meminfo.MemTotal) shortCPUs := kubernetes.ShortCPUSet(nodeCPUs) log.Debug(" + assigned DRAM NUMA node #%d (cpuset: %s, DRAM %.2fM)", nodeID, shortCPUs, float64(meminfo.MemTotal)/float64(1024*1024)) case system.MemoryTypePMEM: n.pMem.Add(nodeID) mmap.AddPMEM(meminfo.MemTotal) log.Debug(" + assigned PMEM NUMA node #%d (DRAM %.2fM)", nodeID, float64(meminfo.MemTotal)/float64(1024*1024)) case system.MemoryTypeHBM: n.hbm.Add(nodeID) mmap.AddHBM(meminfo.MemTotal) log.Debug(" + assigned HBMEM NUMA node #%d (DRAM %.2fM)", nodeID, float64(meminfo.MemTotal)/float64(1024*1024)) default: log.Fatal("NUMA node #%d with unknown memory type %v", node.GetMemoryType()) } allowed := nodeCPUs.Intersection(n.policy.allowed) isolated := allowed.Intersection(n.policy.isolated) reserved := allowed.Intersection(n.policy.reserved).Difference(isolated) sharable := allowed.Difference(isolated).Difference(reserved) if !reserved.IsEmpty() { log.Debug(" allowed reserved CPUs: %s", kubernetes.ShortCPUSet(reserved)) } if !sharable.IsEmpty() { log.Debug(" allowed sharable CPUs: %s", kubernetes.ShortCPUSet(sharable)) } if !isolated.IsEmpty() { log.Debug(" allowed isolated CPUs: %s", kubernetes.ShortCPUSet(isolated)) } cpus = cpus.Union(allowed) } isolated := cpus.Intersection(n.policy.isolated) reserved := cpus.Intersection(n.policy.reserved).Difference(isolated) sharable := cpus.Difference(isolated).Difference(reserved) n.noderes = newSupply(n, isolated, reserved, sharable, 0, 0, mmap, nil) log.Debug(" = %s", n.noderes.DumpCapacity()) } n.freeres = n.noderes.Clone() return n.noderes.Clone() } func (n *node) FreeSupply() Supply { return n.freeres } func (n *node) GetMemset(mtype memoryType) idset.IDSet { if n.self.node == nil { return idset.NewIDSet() } return n.self.node.GetMemset(mtype) } func (n *node) AssignNUMANodes(ids []idset.ID) { n.self.node.AssignNUMANodes(ids) } func (n *node) assignNUMANodes(ids []idset.ID) { mem := createMemoryMap(0, 0, 0) for _, numaNodeID := range ids { if n.mem.Has(numaNodeID) || n.pMem.Has(numaNodeID) || n.hbm.Has(numaNodeID) { log.Warn("*** NUMA node #%d already discovered by or assigned to %s", numaNodeID, n.Name()) continue } numaNode := n.policy.sys.Node(numaNodeID) memTotal := uint64(0) if meminfo, err := numaNode.MemoryInfo(); err != nil { log.Error("%s: failed to get memory info for NUMA node #%d", n.Name(), numaNodeID) } else { memTotal = meminfo.MemTotal } switch numaNode.GetMemoryType() { case system.MemoryTypeDRAM: mem.Add(memTotal, 0, 0) n.mem.Add(numaNodeID) log.Info("*** DRAM NUMA node #%d assigned to pool node %q", numaNodeID, n.Name()) case system.MemoryTypePMEM: n.pMem.Add(numaNodeID) mem.Add(0, memTotal, 0) log.Info("*** PMEM NUMA node #%d assigned to pool node %q", numaNodeID, n.Name()) case system.MemoryTypeHBM: n.hbm.Add(numaNodeID) mem.Add(0, 0, memTotal) log.Info("*** HBM NUMA node #%d assigned to pool node %q", numaNodeID, n.Name()) default: log.Fatal("can't assign NUMA node #%d of type %v to pool node %q", numaNodeID, numaNode.GetMemoryType()) } } n.noderes.AssignMemory(mem) n.freeres.AssignMemory(mem) } func (n *node) GetPhysicalNodeIDs() []idset.ID { return n.self.node.GetPhysicalNodeIDs() } func (n *node) GrantedReservedCPU() int { grantedReserved := n.freeres.GrantedReserved() for _, c := range n.children { grantedReserved += c.GrantedReservedCPU() } return grantedReserved } func (n *node) GrantedSharedCPU() int { grantedShared := n.freeres.GrantedShared() for _, c := range n.children { grantedShared += c.GrantedSharedCPU() } return grantedShared } func (n *node) GetScore(req Request) Score { f := n.FreeSupply() return f.GetScore(req) } func (n *node) HintScore(hint topology.Hint) float64 { return n.self.node.HintScore(hint) } func (n *node) GetMemoryType() memoryType { var memoryMask memoryType = 0x0 if n.pMem.Size() > 0 { memoryMask |= memoryPMEM } if n.mem.Size() > 0 { memoryMask |= memoryDRAM } if n.hbm.Size() > 0 { memoryMask |= memoryHBM } return memoryMask } func (n *node) HasMemoryType(reqType memoryType) bool { nodeType := n.GetMemoryType() return (nodeType & reqType) == reqType } func (p *policy) NewNumaNode(id idset.ID, parent Node) Node { n := &numanode{} n.self.node = n n.node.init(p, fmt.Sprintf("NUMA node #%v", id), NumaNode, parent) n.id = id n.sysnode = p.sys.Node(id) return n } func (n *numanode) dump(prefix string, level ...int) { log.Debug("%s<NUMA node #%v>", indent(prefix, level...), n.id) } func (n *numanode) GetSupply() Supply { return n.noderes.Clone() } func (n *numanode) GetPhysicalNodeIDs() []idset.ID { return []idset.ID{n.id} } func (n *numanode) DiscoverSupply(assignedNUMANodes []idset.ID) Supply { return n.node.discoverSupply(assignedNUMANodes) } func (n *numanode) GetMemset(mtype memoryType) idset.IDSet { mset := idset.NewIDSet() if mtype&memoryDRAM != 0 { mset.Add(n.mem.Members()...) } if mtype&memoryHBM != 0 { mset.Add(n.hbm.Members()...) } if mtype&memoryPMEM != 0 { mset.Add(n.pMem.Members()...) } return mset } func (n *numanode) AssignNUMANodes(ids []idset.ID) { n.node.assignNUMANodes(ids) } func (n *numanode) HintScore(hint topology.Hint) float64 { switch { case hint.CPUs != "": return cpuHintScore(hint, n.sysnode.CPUSet()) case hint.NUMAs != "": return numaHintScore(hint, n.id) case hint.Sockets != "": pkgID := n.sysnode.PackageID() score := socketHintScore(hint, n.sysnode.PackageID()) if score > 0.0 { score /= float64(len(n.System().Package(pkgID).NodeIDs())) } return score } return 0.0 } func (p *policy) NewDieNode(id idset.ID, parent Node) Node { pkg := parent.(*socketnode) n := &dienode{} n.self.node = n n.node.init(p, fmt.Sprintf("die #%v/%v", pkg.id, id), DieNode, parent) n.id = id n.syspkg = p.sys.Package(pkg.id) return n } func (n *dienode) dump(prefix string, level ...int) { log.Debug("%s<die #%v/%v>", indent(prefix, level...), n.syspkg.ID(), n.id) } func (n *dienode) GetSupply() Supply { return n.noderes.Clone() } func (n *dienode) GetPhysicalNodeIDs() []idset.ID { ids := make([]idset.ID, 0) ids = append(ids, n.id) for _, c := range n.children { cIds := c.GetPhysicalNodeIDs() ids = append(ids, cIds...) } return ids } func (n *dienode) DiscoverSupply(assignedNUMANodes []idset.ID) Supply { return n.node.discoverSupply(assignedNUMANodes) } func (n *dienode) GetMemset(mtype memoryType) idset.IDSet { mset := idset.NewIDSet() if mtype&memoryDRAM != 0 { mset.Add(n.mem.Members()...) } if mtype&memoryHBM != 0 { mset.Add(n.hbm.Members()...) } if mtype&memoryPMEM != 0 { mset.Add(n.pMem.Members()...) } return mset } func (n *dienode) AssignNUMANodes(ids []idset.ID) { n.node.assignNUMANodes(ids) } func (n *dienode) HintScore(hint topology.Hint) float64 { switch { case hint.CPUs != "": return cpuHintScore(hint, n.syspkg.CPUSet()) case hint.NUMAs != "": return OverfitPenalty * dieHintScore(hint, n.id, n.syspkg) case hint.Sockets != "": score := socketHintScore(hint, n.syspkg.ID()) if score > 0.0 { score /= float64(len(n.syspkg.DieNodeIDs(n.id))) } return score } return 0.0 } func (p *policy) NewSocketNode(id idset.ID, parent Node) Node { n := &socketnode{} n.self.node = n n.node.init(p, fmt.Sprintf("socket #%v", id), SocketNode, parent) n.id = id n.syspkg = p.sys.Package(id) return n } func (n *socketnode) dump(prefix string, level ...int) { log.Debug("%s<socket #%v>", indent(prefix, level...), n.id) } func (n *socketnode) GetSupply() Supply { return n.noderes.Clone() } func (n *socketnode) GetPhysicalNodeIDs() []idset.ID { ids := make([]idset.ID, 0) ids = append(ids, n.id) for _, c := range n.children { cIds := c.GetPhysicalNodeIDs() ids = append(ids, cIds...) } return ids } func (n *socketnode) DiscoverSupply(assignedNUMANodes []idset.ID) Supply { return n.node.discoverSupply(assignedNUMANodes) }
Apache License 2.0
thethingsnetwork/lorawan-stack
pkg/ttnpb/rights.go
MarshalText
go
func (v Right) MarshalText() ([]byte, error) { return []byte(v.String()), nil }
MarshalText implements encoding.TextMarshaler interface.
https://github.com/thethingsnetwork/lorawan-stack/blob/228c615c0d55ce2eb21c750d644d9e9dd73d9f77/pkg/ttnpb/rights.go#L25-L27
package ttnpb import ( "fmt" "sort" "strconv" "strings" )
Apache License 2.0
wujunze/pandaproxy
vendor/golang.org/x/net/http/httpproxy/proxy.go
FromEnvironment
go
func FromEnvironment() *Config { return &Config{ HTTPProxy: getEnvAny("HTTP_PROXY", "http_proxy"), HTTPSProxy: getEnvAny("HTTPS_PROXY", "https_proxy"), NoProxy: getEnvAny("NO_PROXY", "no_proxy"), CGI: os.Getenv("REQUEST_METHOD") != "", } }
FromEnvironment returns a Config instance populated from the environment variables HTTP_PROXY, HTTPS_PROXY and NO_PROXY (or the lowercase versions thereof). HTTPS_PROXY takes precedence over HTTP_PROXY for https requests. The environment values may be either a complete URL or a "host[:port]", in which case the "http" scheme is assumed. An error is returned if the value is a different form.
https://github.com/wujunze/pandaproxy/blob/7166d298566dd7e8d0565ed45645c212324b063f/vendor/golang.org/x/net/http/httpproxy/proxy.go#L91-L98
package httpproxy import ( "errors" "fmt" "net" "net/url" "os" "strings" "unicode/utf8" "golang.org/x/net/idna" ) type Config struct { HTTPProxy string HTTPSProxy string NoProxy string CGI bool } type config struct { Config httpsProxy *url.URL httpProxy *url.URL ipMatchers []matcher domainMatchers []matcher }
MIT License
govim/govim
cmd/govim/internal/golang_org_x_tools/lsp/cmd/cmd.go
CloseTestConnections
go
func CloseTestConnections(ctx context.Context) { for _, c := range internalConnections { c.Shutdown(ctx) c.Exit(ctx) } }
CloseTestConnections terminates shared connections used in command tests. It should only be called from tests.
https://github.com/govim/govim/blob/439cd42f65315656bcce82188d48309c1ef649ed/cmd/govim/internal/golang_org_x_tools/lsp/cmd/cmd.go#L241-L246
package cmd import ( "context" "flag" "fmt" "go/token" "io/ioutil" "log" "os" "strings" "sync" "time" "github.com/govim/govim/cmd/govim/internal/golang_org_x_tools/jsonrpc2" "github.com/govim/govim/cmd/govim/internal/golang_org_x_tools/lsp" "github.com/govim/govim/cmd/govim/internal/golang_org_x_tools/lsp/cache" "github.com/govim/govim/cmd/govim/internal/golang_org_x_tools/lsp/debug" "github.com/govim/govim/cmd/govim/internal/golang_org_x_tools/lsp/lsprpc" "github.com/govim/govim/cmd/govim/internal/golang_org_x_tools/lsp/protocol" "github.com/govim/govim/cmd/govim/internal/golang_org_x_tools/lsp/source" "github.com/govim/govim/cmd/govim/internal/golang_org_x_tools/span" "github.com/govim/govim/cmd/govim/internal/golang_org_x_tools/tool" "github.com/govim/govim/cmd/govim/internal/golang_org_x_tools/xcontext" errors "golang.org/x/xerrors" ) type Application struct { tool.Profile Serve Serve options func(*source.Options) name string wd string env []string Remote string `flag:"remote" help:"forward all commands to a remote lsp specified by this flag. With no special prefix, this is assumed to be a TCP address. If prefixed by 'unix;', the subsequent address is assumed to be a unix domain socket. If 'auto', or prefixed by 'auto;', the remote address is automatically resolved based on the executing environment."` Verbose bool `flag:"v" help:"verbose output"` VeryVerbose bool `flag:"vv" help:"very verbose output"` OCAgent string `flag:"ocagent" help:"the address of the ocagent (e.g. http://localhost:55678), or off"` PrepareOptions func(*source.Options) } func (app *Application) verbose() bool { return app.Verbose || app.VeryVerbose } func New(name, wd string, env []string, options func(*source.Options)) *Application { if wd == "" { wd, _ = os.Getwd() } app := &Application{ options: options, name: name, wd: wd, env: env, OCAgent: "off", Serve: Serve{ RemoteListenTimeout: 1 * time.Minute, }, } return app } func (app *Application) Name() string { return app.name } func (app *Application) Usage() string { return "<command> [command-flags] [command-args]" } func (app *Application) ShortHelp() string { return "The Go Language source tools." } func (app *Application) DetailedHelp(f *flag.FlagSet) { fmt.Fprint(f.Output(), ` gopls is a Go language server. It is typically used with an editor to provide language features. When no command is specified, gopls will default to the 'serve' command. The language features can also be accessed via the gopls command-line interface. Available commands are: `) fmt.Fprint(f.Output(), ` main: `) for _, c := range app.mainCommands() { fmt.Fprintf(f.Output(), " %s : %v\n", c.Name(), c.ShortHelp()) } fmt.Fprint(f.Output(), ` features: `) for _, c := range app.featureCommands() { fmt.Fprintf(f.Output(), " %s : %v\n", c.Name(), c.ShortHelp()) } fmt.Fprint(f.Output(), ` gopls flags are: `) f.PrintDefaults() } func (app *Application) Run(ctx context.Context, args ...string) error { ctx = debug.WithInstance(ctx, app.wd, app.OCAgent) app.Serve.app = app if len(args) == 0 { return tool.Run(ctx, &app.Serve, args) } command, args := args[0], args[1:] for _, c := range app.commands() { if c.Name() == command { return tool.Run(ctx, c, args) } } return tool.CommandLineErrorf("Unknown command %v", command) } func (app *Application) commands() []tool.Application { var commands []tool.Application commands = append(commands, app.mainCommands()...) commands = append(commands, app.featureCommands()...) return commands } func (app *Application) mainCommands() []tool.Application { return []tool.Application{ &app.Serve, &version{app: app}, &bug{}, &apiJSON{}, &licenses{app: app}, } } func (app *Application) featureCommands() []tool.Application { return []tool.Application{ &callHierarchy{app: app}, &check{app: app}, &definition{app: app}, &foldingRanges{app: app}, &format{app: app}, &highlight{app: app}, &implementation{app: app}, &imports{app: app}, newRemote(app, ""), newRemote(app, "inspect"), &links{app: app}, &prepareRename{app: app}, &references{app: app}, &rename{app: app}, &semtok{app: app}, &signature{app: app}, &suggestedFix{app: app}, &symbols{app: app}, newWorkspace(app), &workspaceSymbol{app: app}, } } var ( internalMu sync.Mutex internalConnections = make(map[string]*connection) ) func (app *Application) connect(ctx context.Context) (*connection, error) { switch { case app.Remote == "": connection := newConnection(app) connection.Server = lsp.NewServer(cache.New(app.options).NewSession(ctx), connection.Client) ctx = protocol.WithClient(ctx, connection.Client) return connection, connection.initialize(ctx, app.options) case strings.HasPrefix(app.Remote, "internal@"): internalMu.Lock() defer internalMu.Unlock() opts := source.DefaultOptions().Clone() if app.options != nil { app.options(opts) } key := fmt.Sprintf("%s %v %v %v", app.wd, opts.PreferredContentFormat, opts.HierarchicalDocumentSymbolSupport, opts.SymbolMatcher) if c := internalConnections[key]; c != nil { return c, nil } remote := app.Remote[len("internal@"):] ctx := xcontext.Detach(ctx) connection, err := app.connectRemote(ctx, remote) if err != nil { return nil, err } internalConnections[key] = connection return connection, nil default: return app.connectRemote(ctx, app.Remote) } }
BSD 3-Clause New or Revised License
gwanted/fabric-sdk-go-gm
api/apiconfig/mocks/mockconfig.gen.go
CAKeyStorePath
go
func (m *MockConfig) CAKeyStorePath() string { ret := m.ctrl.Call(m, "CAKeyStorePath") ret0, _ := ret[0].(string) return ret0 }
CAKeyStorePath mocks base method
https://github.com/gwanted/fabric-sdk-go-gm/blob/7e175f64fc44caa8b619e8c6e0aa689f4b7b5e0f/api/apiconfig/mocks/mockconfig.gen.go#L106-L110
package mock_apiconfig import ( tls "crypto/tls" x509 "crypto/x509" reflect "reflect" time "time" gomock "github.com/golang/mock/gomock" apiconfig "github.com/hyperledger/fabric-sdk-go/api/apiconfig" ) type MockConfig struct { ctrl *gomock.Controller recorder *MockConfigMockRecorder } type MockConfigMockRecorder struct { mock *MockConfig } func NewMockConfig(ctrl *gomock.Controller) *MockConfig { mock := &MockConfig{ctrl: ctrl} mock.recorder = &MockConfigMockRecorder{mock} return mock } func (m *MockConfig) EXPECT() *MockConfigMockRecorder { return m.recorder } func (m *MockConfig) CAClientCertPath(arg0 string) (string, error) { ret := m.ctrl.Call(m, "CAClientCertPath", arg0) ret0, _ := ret[0].(string) ret1, _ := ret[1].(error) return ret0, ret1 } func (mr *MockConfigMockRecorder) CAClientCertPath(arg0 interface{}) *gomock.Call { return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CAClientCertPath", reflect.TypeOf((*MockConfig)(nil).CAClientCertPath), arg0) } func (m *MockConfig) CAClientCertPem(arg0 string) (string, error) { ret := m.ctrl.Call(m, "CAClientCertPem", arg0) ret0, _ := ret[0].(string) ret1, _ := ret[1].(error) return ret0, ret1 } func (mr *MockConfigMockRecorder) CAClientCertPem(arg0 interface{}) *gomock.Call { return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CAClientCertPem", reflect.TypeOf((*MockConfig)(nil).CAClientCertPem), arg0) } func (m *MockConfig) CAClientKeyPath(arg0 string) (string, error) { ret := m.ctrl.Call(m, "CAClientKeyPath", arg0) ret0, _ := ret[0].(string) ret1, _ := ret[1].(error) return ret0, ret1 } func (mr *MockConfigMockRecorder) CAClientKeyPath(arg0 interface{}) *gomock.Call { return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CAClientKeyPath", reflect.TypeOf((*MockConfig)(nil).CAClientKeyPath), arg0) } func (m *MockConfig) CAClientKeyPem(arg0 string) (string, error) { ret := m.ctrl.Call(m, "CAClientKeyPem", arg0) ret0, _ := ret[0].(string) ret1, _ := ret[1].(error) return ret0, ret1 } func (mr *MockConfigMockRecorder) CAClientKeyPem(arg0 interface{}) *gomock.Call { return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CAClientKeyPem", reflect.TypeOf((*MockConfig)(nil).CAClientKeyPem), arg0) } func (m *MockConfig) CAConfig(arg0 string) (*apiconfig.CAConfig, error) { ret := m.ctrl.Call(m, "CAConfig", arg0) ret0, _ := ret[0].(*apiconfig.CAConfig) ret1, _ := ret[1].(error) return ret0, ret1 } func (mr *MockConfigMockRecorder) CAConfig(arg0 interface{}) *gomock.Call { return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CAConfig", reflect.TypeOf((*MockConfig)(nil).CAConfig), arg0) }
Apache License 2.0
256dpi/gomqtt
client/service.go
Start
go
func (s *Service) Start(config *Config) bool { if config == nil { panic("missing config") } s.mutex.Lock() defer s.mutex.Unlock() if s.started { return false } s.started = true s.config = config s.backoff = &backoff.Backoff{ Min: s.MinReconnectDelay, Max: s.MaxReconnectDelay, Factor: 2, } s.futureStore.Protect(true) s.tomb = new(tomb.Tomb) s.tomb.Go(s.supervisor) return true }
Start will start the service with the specified configuration. From now on the service will automatically reconnect on any error until Stop is called. It returns false if the service was already started.
https://github.com/256dpi/gomqtt/blob/0b2f9402f51636cbd907f528c3389aa2216d55d8/client/service.go#L142-L180
package client import ( "fmt" "sort" "sync" "time" "github.com/256dpi/gomqtt/client/future" "github.com/256dpi/gomqtt/packet" "github.com/256dpi/gomqtt/session" "github.com/256dpi/gomqtt/topic" "github.com/jpillora/backoff" "gopkg.in/tomb.v2" ) type command struct { publish bool subscribe bool unsubscribe bool future *future.Future message *packet.Message subscriptions []packet.Subscription topics []string } type Service struct { Session Session OnlineCallback func(resumed bool) MessageCallback func(*packet.Message) error ErrorCallback func(error) OfflineCallback func() Logger func(msg string) MinReconnectDelay time.Duration MaxReconnectDelay time.Duration ConnectTimeout time.Duration DisconnectTimeout time.Duration ResubscribeTimeout time.Duration ResubscribeAllSubscriptions bool QueueTimeout time.Duration config *Config started bool backoff *backoff.Backoff subscriptions *topic.Tree commandQueue chan *command futureStore *future.Store mutex sync.Mutex tomb *tomb.Tomb } func NewService(queueSize ...int) *Service { var qs = 100 if len(queueSize) > 0 { qs = queueSize[0] } return &Service{ Session: session.NewMemorySession(), MinReconnectDelay: 50 * time.Millisecond, MaxReconnectDelay: 10 * time.Second, ConnectTimeout: 5 * time.Second, DisconnectTimeout: 10 * time.Second, ResubscribeTimeout: 5 * time.Second, QueueTimeout: 10 * time.Second, ResubscribeAllSubscriptions: true, subscriptions: topic.NewStandardTree(), commandQueue: make(chan *command, qs), futureStore: future.NewStore(), } }
Apache License 2.0
joyrex2001/nightshift
internal/scanner/deployment.go
getDeployments
go
func (s *DeploymentScanner) getDeployments() (*v1.DeploymentList, error) { apps, err := kubernetes.NewForConfig(s.kubernetes) if err != nil { return nil, err } return apps.AppsV1().Deployments(s.config.Namespace).List(metav1.ListOptions{ LabelSelector: s.config.Label, }) }
getDeployments will return all deploymentconfigs in the namespace that match the label selector.
https://github.com/joyrex2001/nightshift/blob/ef1fb3cd5b8bf4135e12a3384ab3e4034444df91/internal/scanner/deployment.go#L99-L107
package scanner import ( "fmt" "github.com/golang/glog" v1 "k8s.io/api/apps/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/watch" "k8s.io/client-go/kubernetes" "k8s.io/client-go/rest" _ "k8s.io/client-go/plugin/pkg/client/auth/azure" ) type DeploymentScanner struct { config Config kubernetes *rest.Config } func init() { RegisterModule("deployment", NewDeploymentScanner) } func NewDeploymentScanner() (Scanner, error) { kubernetes, err := getKubernetes() if err != nil { return nil, fmt.Errorf("failed instantiating k8s client: %s", err) } return &DeploymentScanner{ kubernetes: kubernetes, }, nil } func (s *DeploymentScanner) SetConfig(cfg Config) { s.config = cfg } func (s *DeploymentScanner) GetConfig() Config { return s.config } func (s *DeploymentScanner) GetObjects() ([]*Object, error) { rcs, err := s.getDeployments() if err != nil { return nil, err } return s.getObjects(rcs) } func (s *DeploymentScanner) Scale(obj *Object, state *int, replicas int) error { glog.Infof("Scaling %s/%s to %d replicas", obj.Namespace, obj.Name, replicas) apps, err := kubernetes.NewForConfig(s.kubernetes) if err != nil { return err } dp, err := apps.AppsV1().Deployments(obj.Namespace).Get(obj.Name, metav1.GetOptions{}) if err != nil { return fmt.Errorf("GetScale failed with: %s", err) } repl := int32(replicas) dp.Spec.Replicas = &repl if state != nil { dp.ObjectMeta = updateState(dp.ObjectMeta, *state) } _, err = apps.AppsV1().Deployments(obj.Namespace).Update(dp) return err } func (s *DeploymentScanner) GetState(obj *Object) (int, error) { dc, err := s.getDeployment(obj) if err != nil { return 0, err } repl := int(*dc.Spec.Replicas) return repl, err } func (s *DeploymentScanner) getDeployment(obj *Object) (*v1.Deployment, error) { apps, err := kubernetes.NewForConfig(s.kubernetes) if err != nil { return nil, err } return apps.AppsV1().Deployments(obj.Namespace).Get(obj.Name, metav1.GetOptions{}) }
MIT License
ent/contrib
schemast/internal/mutatetest/ent/withfields_query.go
StringsX
go
func (wfs *WithFieldsSelect) StringsX(ctx context.Context) []string { v, err := wfs.Strings(ctx) if err != nil { panic(err) } return v }
StringsX is like Strings, but panics if an error occurs.
https://github.com/ent/contrib/blob/2f98d3a15e7dfcc96aa696a5aceb0c8b1249f9e4/schemast/internal/mutatetest/ent/withfields_query.go#L732-L738
package ent import ( "context" "errors" "fmt" "math" "entgo.io/contrib/schemast/internal/mutatetest/ent/predicate" "entgo.io/contrib/schemast/internal/mutatetest/ent/withfields" "entgo.io/ent/dialect/sql" "entgo.io/ent/dialect/sql/sqlgraph" "entgo.io/ent/schema/field" ) type WithFieldsQuery struct { config limit *int offset *int unique *bool order []OrderFunc fields []string predicates []predicate.WithFields sql *sql.Selector path func(context.Context) (*sql.Selector, error) } func (wfq *WithFieldsQuery) Where(ps ...predicate.WithFields) *WithFieldsQuery { wfq.predicates = append(wfq.predicates, ps...) return wfq } func (wfq *WithFieldsQuery) Limit(limit int) *WithFieldsQuery { wfq.limit = &limit return wfq } func (wfq *WithFieldsQuery) Offset(offset int) *WithFieldsQuery { wfq.offset = &offset return wfq } func (wfq *WithFieldsQuery) Unique(unique bool) *WithFieldsQuery { wfq.unique = &unique return wfq } func (wfq *WithFieldsQuery) Order(o ...OrderFunc) *WithFieldsQuery { wfq.order = append(wfq.order, o...) return wfq } func (wfq *WithFieldsQuery) First(ctx context.Context) (*WithFields, error) { nodes, err := wfq.Limit(1).All(ctx) if err != nil { return nil, err } if len(nodes) == 0 { return nil, &NotFoundError{withfields.Label} } return nodes[0], nil } func (wfq *WithFieldsQuery) FirstX(ctx context.Context) *WithFields { node, err := wfq.First(ctx) if err != nil && !IsNotFound(err) { panic(err) } return node } func (wfq *WithFieldsQuery) FirstID(ctx context.Context) (id int, err error) { var ids []int if ids, err = wfq.Limit(1).IDs(ctx); err != nil { return } if len(ids) == 0 { err = &NotFoundError{withfields.Label} return } return ids[0], nil } func (wfq *WithFieldsQuery) FirstIDX(ctx context.Context) int { id, err := wfq.FirstID(ctx) if err != nil && !IsNotFound(err) { panic(err) } return id } func (wfq *WithFieldsQuery) Only(ctx context.Context) (*WithFields, error) { nodes, err := wfq.Limit(2).All(ctx) if err != nil { return nil, err } switch len(nodes) { case 1: return nodes[0], nil case 0: return nil, &NotFoundError{withfields.Label} default: return nil, &NotSingularError{withfields.Label} } } func (wfq *WithFieldsQuery) OnlyX(ctx context.Context) *WithFields { node, err := wfq.Only(ctx) if err != nil { panic(err) } return node } func (wfq *WithFieldsQuery) OnlyID(ctx context.Context) (id int, err error) { var ids []int if ids, err = wfq.Limit(2).IDs(ctx); err != nil { return } switch len(ids) { case 1: id = ids[0] case 0: err = &NotFoundError{withfields.Label} default: err = &NotSingularError{withfields.Label} } return } func (wfq *WithFieldsQuery) OnlyIDX(ctx context.Context) int { id, err := wfq.OnlyID(ctx) if err != nil { panic(err) } return id } func (wfq *WithFieldsQuery) All(ctx context.Context) ([]*WithFields, error) { if err := wfq.prepareQuery(ctx); err != nil { return nil, err } return wfq.sqlAll(ctx) } func (wfq *WithFieldsQuery) AllX(ctx context.Context) []*WithFields { nodes, err := wfq.All(ctx) if err != nil { panic(err) } return nodes } func (wfq *WithFieldsQuery) IDs(ctx context.Context) ([]int, error) { var ids []int if err := wfq.Select(withfields.FieldID).Scan(ctx, &ids); err != nil { return nil, err } return ids, nil } func (wfq *WithFieldsQuery) IDsX(ctx context.Context) []int { ids, err := wfq.IDs(ctx) if err != nil { panic(err) } return ids } func (wfq *WithFieldsQuery) Count(ctx context.Context) (int, error) { if err := wfq.prepareQuery(ctx); err != nil { return 0, err } return wfq.sqlCount(ctx) } func (wfq *WithFieldsQuery) CountX(ctx context.Context) int { count, err := wfq.Count(ctx) if err != nil { panic(err) } return count } func (wfq *WithFieldsQuery) Exist(ctx context.Context) (bool, error) { if err := wfq.prepareQuery(ctx); err != nil { return false, err } return wfq.sqlExist(ctx) } func (wfq *WithFieldsQuery) ExistX(ctx context.Context) bool { exist, err := wfq.Exist(ctx) if err != nil { panic(err) } return exist } func (wfq *WithFieldsQuery) Clone() *WithFieldsQuery { if wfq == nil { return nil } return &WithFieldsQuery{ config: wfq.config, limit: wfq.limit, offset: wfq.offset, order: append([]OrderFunc{}, wfq.order...), predicates: append([]predicate.WithFields{}, wfq.predicates...), sql: wfq.sql.Clone(), path: wfq.path, } } func (wfq *WithFieldsQuery) GroupBy(field string, fields ...string) *WithFieldsGroupBy { group := &WithFieldsGroupBy{config: wfq.config} group.fields = append([]string{field}, fields...) group.path = func(ctx context.Context) (prev *sql.Selector, err error) { if err := wfq.prepareQuery(ctx); err != nil { return nil, err } return wfq.sqlQuery(ctx), nil } return group } func (wfq *WithFieldsQuery) Select(fields ...string) *WithFieldsSelect { wfq.fields = append(wfq.fields, fields...) return &WithFieldsSelect{WithFieldsQuery: wfq} } func (wfq *WithFieldsQuery) prepareQuery(ctx context.Context) error { for _, f := range wfq.fields { if !withfields.ValidColumn(f) { return &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)} } } if wfq.path != nil { prev, err := wfq.path(ctx) if err != nil { return err } wfq.sql = prev } return nil } func (wfq *WithFieldsQuery) sqlAll(ctx context.Context) ([]*WithFields, error) { var ( nodes = []*WithFields{} _spec = wfq.querySpec() ) _spec.ScanValues = func(columns []string) ([]interface{}, error) { node := &WithFields{config: wfq.config} nodes = append(nodes, node) return node.scanValues(columns) } _spec.Assign = func(columns []string, values []interface{}) error { if len(nodes) == 0 { return fmt.Errorf("ent: Assign called without calling ScanValues") } node := nodes[len(nodes)-1] return node.assignValues(columns, values) } if err := sqlgraph.QueryNodes(ctx, wfq.driver, _spec); err != nil { return nil, err } if len(nodes) == 0 { return nodes, nil } return nodes, nil } func (wfq *WithFieldsQuery) sqlCount(ctx context.Context) (int, error) { _spec := wfq.querySpec() return sqlgraph.CountNodes(ctx, wfq.driver, _spec) } func (wfq *WithFieldsQuery) sqlExist(ctx context.Context) (bool, error) { n, err := wfq.sqlCount(ctx) if err != nil { return false, fmt.Errorf("ent: check existence: %w", err) } return n > 0, nil } func (wfq *WithFieldsQuery) querySpec() *sqlgraph.QuerySpec { _spec := &sqlgraph.QuerySpec{ Node: &sqlgraph.NodeSpec{ Table: withfields.Table, Columns: withfields.Columns, ID: &sqlgraph.FieldSpec{ Type: field.TypeInt, Column: withfields.FieldID, }, }, From: wfq.sql, Unique: true, } if unique := wfq.unique; unique != nil { _spec.Unique = *unique } if fields := wfq.fields; len(fields) > 0 { _spec.Node.Columns = make([]string, 0, len(fields)) _spec.Node.Columns = append(_spec.Node.Columns, withfields.FieldID) for i := range fields { if fields[i] != withfields.FieldID { _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) } } } if ps := wfq.predicates; len(ps) > 0 { _spec.Predicate = func(selector *sql.Selector) { for i := range ps { ps[i](selector) } } } if limit := wfq.limit; limit != nil { _spec.Limit = *limit } if offset := wfq.offset; offset != nil { _spec.Offset = *offset } if ps := wfq.order; len(ps) > 0 { _spec.Order = func(selector *sql.Selector) { for i := range ps { ps[i](selector) } } } return _spec } func (wfq *WithFieldsQuery) sqlQuery(ctx context.Context) *sql.Selector { builder := sql.Dialect(wfq.driver.Dialect()) t1 := builder.Table(withfields.Table) columns := wfq.fields if len(columns) == 0 { columns = withfields.Columns } selector := builder.Select(t1.Columns(columns...)...).From(t1) if wfq.sql != nil { selector = wfq.sql selector.Select(selector.Columns(columns...)...) } for _, p := range wfq.predicates { p(selector) } for _, p := range wfq.order { p(selector) } if offset := wfq.offset; offset != nil { selector.Offset(*offset).Limit(math.MaxInt32) } if limit := wfq.limit; limit != nil { selector.Limit(*limit) } return selector } type WithFieldsGroupBy struct { config fields []string fns []AggregateFunc sql *sql.Selector path func(context.Context) (*sql.Selector, error) } func (wfgb *WithFieldsGroupBy) Aggregate(fns ...AggregateFunc) *WithFieldsGroupBy { wfgb.fns = append(wfgb.fns, fns...) return wfgb } func (wfgb *WithFieldsGroupBy) Scan(ctx context.Context, v interface{}) error { query, err := wfgb.path(ctx) if err != nil { return err } wfgb.sql = query return wfgb.sqlScan(ctx, v) } func (wfgb *WithFieldsGroupBy) ScanX(ctx context.Context, v interface{}) { if err := wfgb.Scan(ctx, v); err != nil { panic(err) } } func (wfgb *WithFieldsGroupBy) Strings(ctx context.Context) ([]string, error) { if len(wfgb.fields) > 1 { return nil, errors.New("ent: WithFieldsGroupBy.Strings is not achievable when grouping more than 1 field") } var v []string if err := wfgb.Scan(ctx, &v); err != nil { return nil, err } return v, nil } func (wfgb *WithFieldsGroupBy) StringsX(ctx context.Context) []string { v, err := wfgb.Strings(ctx) if err != nil { panic(err) } return v } func (wfgb *WithFieldsGroupBy) String(ctx context.Context) (_ string, err error) { var v []string if v, err = wfgb.Strings(ctx); err != nil { return } switch len(v) { case 1: return v[0], nil case 0: err = &NotFoundError{withfields.Label} default: err = fmt.Errorf("ent: WithFieldsGroupBy.Strings returned %d results when one was expected", len(v)) } return } func (wfgb *WithFieldsGroupBy) StringX(ctx context.Context) string { v, err := wfgb.String(ctx) if err != nil { panic(err) } return v } func (wfgb *WithFieldsGroupBy) Ints(ctx context.Context) ([]int, error) { if len(wfgb.fields) > 1 { return nil, errors.New("ent: WithFieldsGroupBy.Ints is not achievable when grouping more than 1 field") } var v []int if err := wfgb.Scan(ctx, &v); err != nil { return nil, err } return v, nil } func (wfgb *WithFieldsGroupBy) IntsX(ctx context.Context) []int { v, err := wfgb.Ints(ctx) if err != nil { panic(err) } return v } func (wfgb *WithFieldsGroupBy) Int(ctx context.Context) (_ int, err error) { var v []int if v, err = wfgb.Ints(ctx); err != nil { return } switch len(v) { case 1: return v[0], nil case 0: err = &NotFoundError{withfields.Label} default: err = fmt.Errorf("ent: WithFieldsGroupBy.Ints returned %d results when one was expected", len(v)) } return } func (wfgb *WithFieldsGroupBy) IntX(ctx context.Context) int { v, err := wfgb.Int(ctx) if err != nil { panic(err) } return v } func (wfgb *WithFieldsGroupBy) Float64s(ctx context.Context) ([]float64, error) { if len(wfgb.fields) > 1 { return nil, errors.New("ent: WithFieldsGroupBy.Float64s is not achievable when grouping more than 1 field") } var v []float64 if err := wfgb.Scan(ctx, &v); err != nil { return nil, err } return v, nil } func (wfgb *WithFieldsGroupBy) Float64sX(ctx context.Context) []float64 { v, err := wfgb.Float64s(ctx) if err != nil { panic(err) } return v } func (wfgb *WithFieldsGroupBy) Float64(ctx context.Context) (_ float64, err error) { var v []float64 if v, err = wfgb.Float64s(ctx); err != nil { return } switch len(v) { case 1: return v[0], nil case 0: err = &NotFoundError{withfields.Label} default: err = fmt.Errorf("ent: WithFieldsGroupBy.Float64s returned %d results when one was expected", len(v)) } return } func (wfgb *WithFieldsGroupBy) Float64X(ctx context.Context) float64 { v, err := wfgb.Float64(ctx) if err != nil { panic(err) } return v } func (wfgb *WithFieldsGroupBy) Bools(ctx context.Context) ([]bool, error) { if len(wfgb.fields) > 1 { return nil, errors.New("ent: WithFieldsGroupBy.Bools is not achievable when grouping more than 1 field") } var v []bool if err := wfgb.Scan(ctx, &v); err != nil { return nil, err } return v, nil } func (wfgb *WithFieldsGroupBy) BoolsX(ctx context.Context) []bool { v, err := wfgb.Bools(ctx) if err != nil { panic(err) } return v } func (wfgb *WithFieldsGroupBy) Bool(ctx context.Context) (_ bool, err error) { var v []bool if v, err = wfgb.Bools(ctx); err != nil { return } switch len(v) { case 1: return v[0], nil case 0: err = &NotFoundError{withfields.Label} default: err = fmt.Errorf("ent: WithFieldsGroupBy.Bools returned %d results when one was expected", len(v)) } return } func (wfgb *WithFieldsGroupBy) BoolX(ctx context.Context) bool { v, err := wfgb.Bool(ctx) if err != nil { panic(err) } return v } func (wfgb *WithFieldsGroupBy) sqlScan(ctx context.Context, v interface{}) error { for _, f := range wfgb.fields { if !withfields.ValidColumn(f) { return &ValidationError{Name: f, err: fmt.Errorf("invalid field %q for group-by", f)} } } selector := wfgb.sqlQuery() if err := selector.Err(); err != nil { return err } rows := &sql.Rows{} query, args := selector.Query() if err := wfgb.driver.Query(ctx, query, args, rows); err != nil { return err } defer rows.Close() return sql.ScanSlice(rows, v) } func (wfgb *WithFieldsGroupBy) sqlQuery() *sql.Selector { selector := wfgb.sql.Select() aggregation := make([]string, 0, len(wfgb.fns)) for _, fn := range wfgb.fns { aggregation = append(aggregation, fn(selector)) } if len(selector.SelectedColumns()) == 0 { columns := make([]string, 0, len(wfgb.fields)+len(wfgb.fns)) for _, f := range wfgb.fields { columns = append(columns, selector.C(f)) } for _, c := range aggregation { columns = append(columns, c) } selector.Select(columns...) } return selector.GroupBy(selector.Columns(wfgb.fields...)...) } type WithFieldsSelect struct { *WithFieldsQuery sql *sql.Selector } func (wfs *WithFieldsSelect) Scan(ctx context.Context, v interface{}) error { if err := wfs.prepareQuery(ctx); err != nil { return err } wfs.sql = wfs.WithFieldsQuery.sqlQuery(ctx) return wfs.sqlScan(ctx, v) } func (wfs *WithFieldsSelect) ScanX(ctx context.Context, v interface{}) { if err := wfs.Scan(ctx, v); err != nil { panic(err) } } func (wfs *WithFieldsSelect) Strings(ctx context.Context) ([]string, error) { if len(wfs.fields) > 1 { return nil, errors.New("ent: WithFieldsSelect.Strings is not achievable when selecting more than 1 field") } var v []string if err := wfs.Scan(ctx, &v); err != nil { return nil, err } return v, nil }
Apache License 2.0
ibm-silvergate/netcomposer
sample-chaincodes/go/kv_chaincode_go_example01/kv_chaincode_go_example01.go
query
go
func (t *SimpleChaincode) query(stub shim.ChaincodeStubInterface, args []string) pb.Response { var A string var err error if len(args) != 1 { return shim.Error("Incorrect number of arguments. Expecting name of the person to query") } A = args[0] Avalbytes, err := stub.GetState(A) if err != nil { jsonResp := "{\"Error\":\"Failed to get state for " + A + "\"}" return shim.Error(jsonResp) } if Avalbytes == nil { jsonResp := "{\"Error\":\"Nil amount for " + A + "\"}" return shim.Error(jsonResp) } jsonResp := "{\"Name\":\"" + A + "\",\"Amount\":\"" + string(Avalbytes) + "\"}" fmt.Printf("Query Response:%s\n", jsonResp) return shim.Success(Avalbytes) }
query callback representing the query of a chaincode
https://github.com/ibm-silvergate/netcomposer/blob/c72e0fb6492ff4ae6a3352f552e0235e4d6360a7/sample-chaincodes/go/kv_chaincode_go_example01/kv_chaincode_go_example01.go#L164-L189
package main import ( "fmt" "strconv" "github.com/hyperledger/fabric/core/chaincode/shim" pb "github.com/hyperledger/fabric/protos/peer" ) type SimpleChaincode struct { } func (t *SimpleChaincode) Init(stub shim.ChaincodeStubInterface) pb.Response { fmt.Println("ex02 Init") _, args := stub.GetFunctionAndParameters() var A, B string var Aval, Bval int var err error if len(args) != 4 { return shim.Error("Incorrect number of arguments. Expecting 4") } A = args[0] Aval, err = strconv.Atoi(args[1]) if err != nil { return shim.Error("Expecting integer value for asset holding") } B = args[2] Bval, err = strconv.Atoi(args[3]) if err != nil { return shim.Error("Expecting integer value for asset holding") } fmt.Printf("Aval = %d, Bval = %d\n", Aval, Bval) err = stub.PutState(A, []byte(strconv.Itoa(Aval))) if err != nil { return shim.Error(err.Error()) } err = stub.PutState(B, []byte(strconv.Itoa(Bval))) if err != nil { return shim.Error(err.Error()) } return shim.Success(nil) } func (t *SimpleChaincode) Invoke(stub shim.ChaincodeStubInterface) pb.Response { fmt.Println("ex02 Invoke") function, args := stub.GetFunctionAndParameters() if function == "invoke" { return t.invoke(stub, args) } else if function == "delete" { return t.delete(stub, args) } else if function == "query" { return t.query(stub, args) } return shim.Error("Invalid invoke function name. Expecting \"invoke\" \"delete\" \"query\"") } func (t *SimpleChaincode) invoke(stub shim.ChaincodeStubInterface, args []string) pb.Response { var A, B string var Aval, Bval int var X int var err error if len(args) != 3 { return shim.Error("Incorrect number of arguments. Expecting 3") } A = args[0] B = args[1] Avalbytes, err := stub.GetState(A) if err != nil { return shim.Error("Failed to get state") } if Avalbytes == nil { return shim.Error("Entity not found") } Aval, _ = strconv.Atoi(string(Avalbytes)) Bvalbytes, err := stub.GetState(B) if err != nil { return shim.Error("Failed to get state") } if Bvalbytes == nil { return shim.Error("Entity not found") } Bval, _ = strconv.Atoi(string(Bvalbytes)) X, err = strconv.Atoi(args[2]) if err != nil { return shim.Error("Invalid transaction amount, expecting a integer value") } Aval = Aval - X Bval = Bval + X fmt.Printf("Aval = %d, Bval = %d\n", Aval, Bval) err = stub.PutState(A, []byte(strconv.Itoa(Aval))) if err != nil { return shim.Error(err.Error()) } err = stub.PutState(B, []byte(strconv.Itoa(Bval))) if err != nil { return shim.Error(err.Error()) } return shim.Success(nil) } func (t *SimpleChaincode) delete(stub shim.ChaincodeStubInterface, args []string) pb.Response { if len(args) != 1 { return shim.Error("Incorrect number of arguments. Expecting 1") } A := args[0] err := stub.DelState(A) if err != nil { return shim.Error("Failed to delete state") } return shim.Success(nil) }
Apache License 2.0
c2fo/vfs
mocks/S3API.go
DeleteBucketIntelligentTieringConfiguration
go
func (_m *S3API) DeleteBucketIntelligentTieringConfiguration(_a0 *s3.DeleteBucketIntelligentTieringConfigurationInput) (*s3.DeleteBucketIntelligentTieringConfigurationOutput, error) { ret := _m.Called(_a0) var r0 *s3.DeleteBucketIntelligentTieringConfigurationOutput if rf, ok := ret.Get(0).(func(*s3.DeleteBucketIntelligentTieringConfigurationInput) *s3.DeleteBucketIntelligentTieringConfigurationOutput); ok { r0 = rf(_a0) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*s3.DeleteBucketIntelligentTieringConfigurationOutput) } } var r1 error if rf, ok := ret.Get(1).(func(*s3.DeleteBucketIntelligentTieringConfigurationInput) error); ok { r1 = rf(_a0) } else { r1 = ret.Error(1) } return r0, r1 }
DeleteBucketIntelligentTieringConfiguration provides a mock function with given fields: _a0
https://github.com/c2fo/vfs/blob/f53cb6dea1e771a0feee36fd82a83d8d5fae1066/mocks/S3API.go#L667-L687
package mocks import ( context "context" request "github.com/aws/aws-sdk-go/aws/request" mock "github.com/stretchr/testify/mock" s3 "github.com/aws/aws-sdk-go/service/s3" ) type S3API struct { mock.Mock } func (_m *S3API) AbortMultipartUpload(_a0 *s3.AbortMultipartUploadInput) (*s3.AbortMultipartUploadOutput, error) { ret := _m.Called(_a0) var r0 *s3.AbortMultipartUploadOutput if rf, ok := ret.Get(0).(func(*s3.AbortMultipartUploadInput) *s3.AbortMultipartUploadOutput); ok { r0 = rf(_a0) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*s3.AbortMultipartUploadOutput) } } var r1 error if rf, ok := ret.Get(1).(func(*s3.AbortMultipartUploadInput) error); ok { r1 = rf(_a0) } else { r1 = ret.Error(1) } return r0, r1 } func (_m *S3API) AbortMultipartUploadRequest(_a0 *s3.AbortMultipartUploadInput) (*request.Request, *s3.AbortMultipartUploadOutput) { ret := _m.Called(_a0) var r0 *request.Request if rf, ok := ret.Get(0).(func(*s3.AbortMultipartUploadInput) *request.Request); ok { r0 = rf(_a0) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*request.Request) } } var r1 *s3.AbortMultipartUploadOutput if rf, ok := ret.Get(1).(func(*s3.AbortMultipartUploadInput) *s3.AbortMultipartUploadOutput); ok { r1 = rf(_a0) } else { if ret.Get(1) != nil { r1 = ret.Get(1).(*s3.AbortMultipartUploadOutput) } } return r0, r1 } func (_m *S3API) AbortMultipartUploadWithContext(_a0 context.Context, _a1 *s3.AbortMultipartUploadInput, _a2 ...request.Option) (*s3.AbortMultipartUploadOutput, error) { _va := make([]interface{}, len(_a2)) for _i := range _a2 { _va[_i] = _a2[_i] } var _ca []interface{} _ca = append(_ca, _a0, _a1) _ca = append(_ca, _va...) ret := _m.Called(_ca...) var r0 *s3.AbortMultipartUploadOutput if rf, ok := ret.Get(0).(func(context.Context, *s3.AbortMultipartUploadInput, ...request.Option) *s3.AbortMultipartUploadOutput); ok { r0 = rf(_a0, _a1, _a2...) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*s3.AbortMultipartUploadOutput) } } var r1 error if rf, ok := ret.Get(1).(func(context.Context, *s3.AbortMultipartUploadInput, ...request.Option) error); ok { r1 = rf(_a0, _a1, _a2...) } else { r1 = ret.Error(1) } return r0, r1 } func (_m *S3API) CompleteMultipartUpload(_a0 *s3.CompleteMultipartUploadInput) (*s3.CompleteMultipartUploadOutput, error) { ret := _m.Called(_a0) var r0 *s3.CompleteMultipartUploadOutput if rf, ok := ret.Get(0).(func(*s3.CompleteMultipartUploadInput) *s3.CompleteMultipartUploadOutput); ok { r0 = rf(_a0) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*s3.CompleteMultipartUploadOutput) } } var r1 error if rf, ok := ret.Get(1).(func(*s3.CompleteMultipartUploadInput) error); ok { r1 = rf(_a0) } else { r1 = ret.Error(1) } return r0, r1 } func (_m *S3API) CompleteMultipartUploadRequest(_a0 *s3.CompleteMultipartUploadInput) (*request.Request, *s3.CompleteMultipartUploadOutput) { ret := _m.Called(_a0) var r0 *request.Request if rf, ok := ret.Get(0).(func(*s3.CompleteMultipartUploadInput) *request.Request); ok { r0 = rf(_a0) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*request.Request) } } var r1 *s3.CompleteMultipartUploadOutput if rf, ok := ret.Get(1).(func(*s3.CompleteMultipartUploadInput) *s3.CompleteMultipartUploadOutput); ok { r1 = rf(_a0) } else { if ret.Get(1) != nil { r1 = ret.Get(1).(*s3.CompleteMultipartUploadOutput) } } return r0, r1 } func (_m *S3API) CompleteMultipartUploadWithContext(_a0 context.Context, _a1 *s3.CompleteMultipartUploadInput, _a2 ...request.Option) (*s3.CompleteMultipartUploadOutput, error) { _va := make([]interface{}, len(_a2)) for _i := range _a2 { _va[_i] = _a2[_i] } var _ca []interface{} _ca = append(_ca, _a0, _a1) _ca = append(_ca, _va...) ret := _m.Called(_ca...) var r0 *s3.CompleteMultipartUploadOutput if rf, ok := ret.Get(0).(func(context.Context, *s3.CompleteMultipartUploadInput, ...request.Option) *s3.CompleteMultipartUploadOutput); ok { r0 = rf(_a0, _a1, _a2...) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*s3.CompleteMultipartUploadOutput) } } var r1 error if rf, ok := ret.Get(1).(func(context.Context, *s3.CompleteMultipartUploadInput, ...request.Option) error); ok { r1 = rf(_a0, _a1, _a2...) } else { r1 = ret.Error(1) } return r0, r1 } func (_m *S3API) CopyObject(_a0 *s3.CopyObjectInput) (*s3.CopyObjectOutput, error) { ret := _m.Called(_a0) var r0 *s3.CopyObjectOutput if rf, ok := ret.Get(0).(func(*s3.CopyObjectInput) *s3.CopyObjectOutput); ok { r0 = rf(_a0) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*s3.CopyObjectOutput) } } var r1 error if rf, ok := ret.Get(1).(func(*s3.CopyObjectInput) error); ok { r1 = rf(_a0) } else { r1 = ret.Error(1) } return r0, r1 } func (_m *S3API) CopyObjectRequest(_a0 *s3.CopyObjectInput) (*request.Request, *s3.CopyObjectOutput) { ret := _m.Called(_a0) var r0 *request.Request if rf, ok := ret.Get(0).(func(*s3.CopyObjectInput) *request.Request); ok { r0 = rf(_a0) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*request.Request) } } var r1 *s3.CopyObjectOutput if rf, ok := ret.Get(1).(func(*s3.CopyObjectInput) *s3.CopyObjectOutput); ok { r1 = rf(_a0) } else { if ret.Get(1) != nil { r1 = ret.Get(1).(*s3.CopyObjectOutput) } } return r0, r1 } func (_m *S3API) CopyObjectWithContext(_a0 context.Context, _a1 *s3.CopyObjectInput, _a2 ...request.Option) (*s3.CopyObjectOutput, error) { _va := make([]interface{}, len(_a2)) for _i := range _a2 { _va[_i] = _a2[_i] } var _ca []interface{} _ca = append(_ca, _a0, _a1) _ca = append(_ca, _va...) ret := _m.Called(_ca...) var r0 *s3.CopyObjectOutput if rf, ok := ret.Get(0).(func(context.Context, *s3.CopyObjectInput, ...request.Option) *s3.CopyObjectOutput); ok { r0 = rf(_a0, _a1, _a2...) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*s3.CopyObjectOutput) } } var r1 error if rf, ok := ret.Get(1).(func(context.Context, *s3.CopyObjectInput, ...request.Option) error); ok { r1 = rf(_a0, _a1, _a2...) } else { r1 = ret.Error(1) } return r0, r1 } func (_m *S3API) CreateBucket(_a0 *s3.CreateBucketInput) (*s3.CreateBucketOutput, error) { ret := _m.Called(_a0) var r0 *s3.CreateBucketOutput if rf, ok := ret.Get(0).(func(*s3.CreateBucketInput) *s3.CreateBucketOutput); ok { r0 = rf(_a0) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*s3.CreateBucketOutput) } } var r1 error if rf, ok := ret.Get(1).(func(*s3.CreateBucketInput) error); ok { r1 = rf(_a0) } else { r1 = ret.Error(1) } return r0, r1 } func (_m *S3API) CreateBucketRequest(_a0 *s3.CreateBucketInput) (*request.Request, *s3.CreateBucketOutput) { ret := _m.Called(_a0) var r0 *request.Request if rf, ok := ret.Get(0).(func(*s3.CreateBucketInput) *request.Request); ok { r0 = rf(_a0) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*request.Request) } } var r1 *s3.CreateBucketOutput if rf, ok := ret.Get(1).(func(*s3.CreateBucketInput) *s3.CreateBucketOutput); ok { r1 = rf(_a0) } else { if ret.Get(1) != nil { r1 = ret.Get(1).(*s3.CreateBucketOutput) } } return r0, r1 } func (_m *S3API) CreateBucketWithContext(_a0 context.Context, _a1 *s3.CreateBucketInput, _a2 ...request.Option) (*s3.CreateBucketOutput, error) { _va := make([]interface{}, len(_a2)) for _i := range _a2 { _va[_i] = _a2[_i] } var _ca []interface{} _ca = append(_ca, _a0, _a1) _ca = append(_ca, _va...) ret := _m.Called(_ca...) var r0 *s3.CreateBucketOutput if rf, ok := ret.Get(0).(func(context.Context, *s3.CreateBucketInput, ...request.Option) *s3.CreateBucketOutput); ok { r0 = rf(_a0, _a1, _a2...) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*s3.CreateBucketOutput) } } var r1 error if rf, ok := ret.Get(1).(func(context.Context, *s3.CreateBucketInput, ...request.Option) error); ok { r1 = rf(_a0, _a1, _a2...) } else { r1 = ret.Error(1) } return r0, r1 } func (_m *S3API) CreateMultipartUpload(_a0 *s3.CreateMultipartUploadInput) (*s3.CreateMultipartUploadOutput, error) { ret := _m.Called(_a0) var r0 *s3.CreateMultipartUploadOutput if rf, ok := ret.Get(0).(func(*s3.CreateMultipartUploadInput) *s3.CreateMultipartUploadOutput); ok { r0 = rf(_a0) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*s3.CreateMultipartUploadOutput) } } var r1 error if rf, ok := ret.Get(1).(func(*s3.CreateMultipartUploadInput) error); ok { r1 = rf(_a0) } else { r1 = ret.Error(1) } return r0, r1 } func (_m *S3API) CreateMultipartUploadRequest(_a0 *s3.CreateMultipartUploadInput) (*request.Request, *s3.CreateMultipartUploadOutput) { ret := _m.Called(_a0) var r0 *request.Request if rf, ok := ret.Get(0).(func(*s3.CreateMultipartUploadInput) *request.Request); ok { r0 = rf(_a0) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*request.Request) } } var r1 *s3.CreateMultipartUploadOutput if rf, ok := ret.Get(1).(func(*s3.CreateMultipartUploadInput) *s3.CreateMultipartUploadOutput); ok { r1 = rf(_a0) } else { if ret.Get(1) != nil { r1 = ret.Get(1).(*s3.CreateMultipartUploadOutput) } } return r0, r1 } func (_m *S3API) CreateMultipartUploadWithContext(_a0 context.Context, _a1 *s3.CreateMultipartUploadInput, _a2 ...request.Option) (*s3.CreateMultipartUploadOutput, error) { _va := make([]interface{}, len(_a2)) for _i := range _a2 { _va[_i] = _a2[_i] } var _ca []interface{} _ca = append(_ca, _a0, _a1) _ca = append(_ca, _va...) ret := _m.Called(_ca...) var r0 *s3.CreateMultipartUploadOutput if rf, ok := ret.Get(0).(func(context.Context, *s3.CreateMultipartUploadInput, ...request.Option) *s3.CreateMultipartUploadOutput); ok { r0 = rf(_a0, _a1, _a2...) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*s3.CreateMultipartUploadOutput) } } var r1 error if rf, ok := ret.Get(1).(func(context.Context, *s3.CreateMultipartUploadInput, ...request.Option) error); ok { r1 = rf(_a0, _a1, _a2...) } else { r1 = ret.Error(1) } return r0, r1 } func (_m *S3API) DeleteBucket(_a0 *s3.DeleteBucketInput) (*s3.DeleteBucketOutput, error) { ret := _m.Called(_a0) var r0 *s3.DeleteBucketOutput if rf, ok := ret.Get(0).(func(*s3.DeleteBucketInput) *s3.DeleteBucketOutput); ok { r0 = rf(_a0) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*s3.DeleteBucketOutput) } } var r1 error if rf, ok := ret.Get(1).(func(*s3.DeleteBucketInput) error); ok { r1 = rf(_a0) } else { r1 = ret.Error(1) } return r0, r1 } func (_m *S3API) DeleteBucketAnalyticsConfiguration(_a0 *s3.DeleteBucketAnalyticsConfigurationInput) (*s3.DeleteBucketAnalyticsConfigurationOutput, error) { ret := _m.Called(_a0) var r0 *s3.DeleteBucketAnalyticsConfigurationOutput if rf, ok := ret.Get(0).(func(*s3.DeleteBucketAnalyticsConfigurationInput) *s3.DeleteBucketAnalyticsConfigurationOutput); ok { r0 = rf(_a0) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*s3.DeleteBucketAnalyticsConfigurationOutput) } } var r1 error if rf, ok := ret.Get(1).(func(*s3.DeleteBucketAnalyticsConfigurationInput) error); ok { r1 = rf(_a0) } else { r1 = ret.Error(1) } return r0, r1 } func (_m *S3API) DeleteBucketAnalyticsConfigurationRequest(_a0 *s3.DeleteBucketAnalyticsConfigurationInput) (*request.Request, *s3.DeleteBucketAnalyticsConfigurationOutput) { ret := _m.Called(_a0) var r0 *request.Request if rf, ok := ret.Get(0).(func(*s3.DeleteBucketAnalyticsConfigurationInput) *request.Request); ok { r0 = rf(_a0) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*request.Request) } } var r1 *s3.DeleteBucketAnalyticsConfigurationOutput if rf, ok := ret.Get(1).(func(*s3.DeleteBucketAnalyticsConfigurationInput) *s3.DeleteBucketAnalyticsConfigurationOutput); ok { r1 = rf(_a0) } else { if ret.Get(1) != nil { r1 = ret.Get(1).(*s3.DeleteBucketAnalyticsConfigurationOutput) } } return r0, r1 } func (_m *S3API) DeleteBucketAnalyticsConfigurationWithContext(_a0 context.Context, _a1 *s3.DeleteBucketAnalyticsConfigurationInput, _a2 ...request.Option) (*s3.DeleteBucketAnalyticsConfigurationOutput, error) { _va := make([]interface{}, len(_a2)) for _i := range _a2 { _va[_i] = _a2[_i] } var _ca []interface{} _ca = append(_ca, _a0, _a1) _ca = append(_ca, _va...) ret := _m.Called(_ca...) var r0 *s3.DeleteBucketAnalyticsConfigurationOutput if rf, ok := ret.Get(0).(func(context.Context, *s3.DeleteBucketAnalyticsConfigurationInput, ...request.Option) *s3.DeleteBucketAnalyticsConfigurationOutput); ok { r0 = rf(_a0, _a1, _a2...) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*s3.DeleteBucketAnalyticsConfigurationOutput) } } var r1 error if rf, ok := ret.Get(1).(func(context.Context, *s3.DeleteBucketAnalyticsConfigurationInput, ...request.Option) error); ok { r1 = rf(_a0, _a1, _a2...) } else { r1 = ret.Error(1) } return r0, r1 } func (_m *S3API) DeleteBucketCors(_a0 *s3.DeleteBucketCorsInput) (*s3.DeleteBucketCorsOutput, error) { ret := _m.Called(_a0) var r0 *s3.DeleteBucketCorsOutput if rf, ok := ret.Get(0).(func(*s3.DeleteBucketCorsInput) *s3.DeleteBucketCorsOutput); ok { r0 = rf(_a0) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*s3.DeleteBucketCorsOutput) } } var r1 error if rf, ok := ret.Get(1).(func(*s3.DeleteBucketCorsInput) error); ok { r1 = rf(_a0) } else { r1 = ret.Error(1) } return r0, r1 } func (_m *S3API) DeleteBucketCorsRequest(_a0 *s3.DeleteBucketCorsInput) (*request.Request, *s3.DeleteBucketCorsOutput) { ret := _m.Called(_a0) var r0 *request.Request if rf, ok := ret.Get(0).(func(*s3.DeleteBucketCorsInput) *request.Request); ok { r0 = rf(_a0) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*request.Request) } } var r1 *s3.DeleteBucketCorsOutput if rf, ok := ret.Get(1).(func(*s3.DeleteBucketCorsInput) *s3.DeleteBucketCorsOutput); ok { r1 = rf(_a0) } else { if ret.Get(1) != nil { r1 = ret.Get(1).(*s3.DeleteBucketCorsOutput) } } return r0, r1 } func (_m *S3API) DeleteBucketCorsWithContext(_a0 context.Context, _a1 *s3.DeleteBucketCorsInput, _a2 ...request.Option) (*s3.DeleteBucketCorsOutput, error) { _va := make([]interface{}, len(_a2)) for _i := range _a2 { _va[_i] = _a2[_i] } var _ca []interface{} _ca = append(_ca, _a0, _a1) _ca = append(_ca, _va...) ret := _m.Called(_ca...) var r0 *s3.DeleteBucketCorsOutput if rf, ok := ret.Get(0).(func(context.Context, *s3.DeleteBucketCorsInput, ...request.Option) *s3.DeleteBucketCorsOutput); ok { r0 = rf(_a0, _a1, _a2...) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*s3.DeleteBucketCorsOutput) } } var r1 error if rf, ok := ret.Get(1).(func(context.Context, *s3.DeleteBucketCorsInput, ...request.Option) error); ok { r1 = rf(_a0, _a1, _a2...) } else { r1 = ret.Error(1) } return r0, r1 } func (_m *S3API) DeleteBucketEncryption(_a0 *s3.DeleteBucketEncryptionInput) (*s3.DeleteBucketEncryptionOutput, error) { ret := _m.Called(_a0) var r0 *s3.DeleteBucketEncryptionOutput if rf, ok := ret.Get(0).(func(*s3.DeleteBucketEncryptionInput) *s3.DeleteBucketEncryptionOutput); ok { r0 = rf(_a0) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*s3.DeleteBucketEncryptionOutput) } } var r1 error if rf, ok := ret.Get(1).(func(*s3.DeleteBucketEncryptionInput) error); ok { r1 = rf(_a0) } else { r1 = ret.Error(1) } return r0, r1 } func (_m *S3API) DeleteBucketEncryptionRequest(_a0 *s3.DeleteBucketEncryptionInput) (*request.Request, *s3.DeleteBucketEncryptionOutput) { ret := _m.Called(_a0) var r0 *request.Request if rf, ok := ret.Get(0).(func(*s3.DeleteBucketEncryptionInput) *request.Request); ok { r0 = rf(_a0) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*request.Request) } } var r1 *s3.DeleteBucketEncryptionOutput if rf, ok := ret.Get(1).(func(*s3.DeleteBucketEncryptionInput) *s3.DeleteBucketEncryptionOutput); ok { r1 = rf(_a0) } else { if ret.Get(1) != nil { r1 = ret.Get(1).(*s3.DeleteBucketEncryptionOutput) } } return r0, r1 } func (_m *S3API) DeleteBucketEncryptionWithContext(_a0 context.Context, _a1 *s3.DeleteBucketEncryptionInput, _a2 ...request.Option) (*s3.DeleteBucketEncryptionOutput, error) { _va := make([]interface{}, len(_a2)) for _i := range _a2 { _va[_i] = _a2[_i] } var _ca []interface{} _ca = append(_ca, _a0, _a1) _ca = append(_ca, _va...) ret := _m.Called(_ca...) var r0 *s3.DeleteBucketEncryptionOutput if rf, ok := ret.Get(0).(func(context.Context, *s3.DeleteBucketEncryptionInput, ...request.Option) *s3.DeleteBucketEncryptionOutput); ok { r0 = rf(_a0, _a1, _a2...) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*s3.DeleteBucketEncryptionOutput) } } var r1 error if rf, ok := ret.Get(1).(func(context.Context, *s3.DeleteBucketEncryptionInput, ...request.Option) error); ok { r1 = rf(_a0, _a1, _a2...) } else { r1 = ret.Error(1) } return r0, r1 }
MIT License
ineversleeeeep/inserver
src/proto/config/scene.pb.json.go
UnmarshalJSON
go
func (msg *Scene) UnmarshalJSON(b []byte) error { return jsonpb.Unmarshal(bytes.NewReader(b), msg) }
UnmarshalJSON implements json.Unmarshaler
https://github.com/ineversleeeeep/inserver/blob/1bb1cdacf09df9b12d43ba007c057a8f25f1e765/src/proto/config/scene.pb.json.go#L24-L26
package config import ( "bytes" "github.com/golang/protobuf/jsonpb" ) func (msg *Scene) MarshalJSON() ([]byte, error) { var buf bytes.Buffer err := (&jsonpb.Marshaler{ EnumsAsInts: false, EmitDefaults: false, OrigName: false, }).Marshal(&buf, msg) return buf.Bytes(), err }
MIT License
presslabs/wordpress-operator
pkg/controller/wordpress/internal/sync/deploy.go
NewDeploymentSyncer
go
func NewDeploymentSyncer(wp *wordpress.Wordpress, secret *corev1.Secret, c client.Client) syncer.Interface { objLabels := wp.ComponentLabels(wordpress.WordpressDeployment) obj := &appsv1.Deployment{ ObjectMeta: metav1.ObjectMeta{ Name: wp.ComponentName(wordpress.WordpressDeployment), Namespace: wp.Namespace, }, } return syncer.NewObjectSyncer("Deployment", wp.Unwrap(), obj, c, func() error { obj.Labels = labels.Merge(labels.Merge(obj.Labels, objLabels), controllerLabels) template := wp.WebPodTemplateSpec() if len(template.Annotations) == 0 { template.Annotations = make(map[string]string) } template.Annotations["wordpress.presslabs.org/secretVersion"] = secret.ResourceVersion obj.Spec.Template.ObjectMeta = template.ObjectMeta selector := metav1.SetAsLabelSelector(wp.WebPodLabels()) if !reflect.DeepEqual(selector, obj.Spec.Selector) { if obj.ObjectMeta.CreationTimestamp.IsZero() { obj.Spec.Selector = selector } else { return errImmutableDeploymentSelector } } err := mergo.Merge(&obj.Spec.Template.Spec, template.Spec, mergo.WithTransformers(transformers.PodSpec)) if err != nil { return err } obj.Spec.Template.Spec.NodeSelector = wp.Spec.NodeSelector obj.Spec.Template.Spec.Tolerations = wp.Spec.Tolerations if wp.Spec.Replicas != nil { obj.Spec.Replicas = wp.Spec.Replicas } if wp.Spec.DeploymentStrategy != nil { obj.Spec.Strategy = *wp.Spec.DeploymentStrategy } return nil }) }
NewDeploymentSyncer returns a new sync.Interface for reconciling web Deployment.
https://github.com/presslabs/wordpress-operator/blob/64c53835d38e7315a456e58e7ac3a219895b5b38/pkg/controller/wordpress/internal/sync/deploy.go#L40-L89
package sync import ( "errors" "reflect" appsv1 "k8s.io/api/apps/v1" corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/labels" "sigs.k8s.io/controller-runtime/pkg/client" "github.com/appscode/mergo" "github.com/presslabs/controller-util/mergo/transformers" "github.com/presslabs/controller-util/syncer" "github.com/bitpoke/wordpress-operator/pkg/internal/wordpress" ) var errImmutableDeploymentSelector = errors.New("deployment selector is immutable")
Apache License 2.0
dewey/feedbridge
vendor/github.com/gobuffalo/packr/walk.go
WalkPrefix
go
func (b Box) WalkPrefix(prefix string, wf WalkFunc) error { opre := osPath(prefix) return b.Walk(func(path string, f File) error { if strings.HasPrefix(osPath(path), opre) { if err := wf(path, f); err != nil { return err } } return nil }) }
WalkPrefix will call box.Walk and call the WalkFunc when it finds paths that have a matching prefix
https://github.com/dewey/feedbridge/blob/ee9fbbcc430654770c3ea26fa0bdea49bd044243/vendor/github.com/gobuffalo/packr/walk.go#L53-L63
package packr import ( "os" "path/filepath" "strings" "github.com/gobuffalo/packd" ) type WalkFunc = packd.WalkFunc func (b Box) Walk(wf WalkFunc) error { if data[b.Path] == nil { base, err := filepath.EvalSymlinks(filepath.Join(b.callingDir, b.Path)) if err != nil { return err } return filepath.Walk(base, func(path string, info os.FileInfo, err error) error { cleanName, err := filepath.Rel(base, path) if err != nil { cleanName = strings.TrimPrefix(path, base) } cleanName = filepath.ToSlash(filepath.Clean(cleanName)) cleanName = strings.TrimPrefix(cleanName, "/") cleanName = filepath.FromSlash(cleanName) if info == nil || info.IsDir() { return nil } file, err := fileFor(path, cleanName) if err != nil { return err } return wf(cleanName, file) }) } for n := range data[b.Path] { f, err := b.find(n) if err != nil { return err } err = wf(n, f) if err != nil { return err } } return nil }
MIT License
gowebapi/webapi
file/file_js.go
OnLoadStart
go
func (_this *FileReader) OnLoadStart() domcore.EventHandlerFunc { var ret domcore.EventHandlerFunc value := _this.Value_JS.Get("onloadstart") if value.Type() != js.TypeNull && value.Type() != js.TypeUndefined { ret = domcore.EventHandlerFromJS(value) } return ret }
OnLoadStart returning attribute 'onloadstart' with type domcore.EventHandler (idl: EventHandlerNonNull).
https://github.com/gowebapi/webapi/blob/704d94b49d10bd459e9a1367a4f614909e09c241/file/file_js.go#L612-L619
package file import "syscall/js" import ( "github.com/gowebapi/webapi/communication/xhr" "github.com/gowebapi/webapi/dom/domcore" "github.com/gowebapi/webapi/javascript" ) func unused(value interface{}) { } type Union struct { Value js.Value } func (u *Union) JSValue() js.Value { return u.Value } func UnionFromJS(value js.Value) *Union { return &Union{Value: value} } type EndingType int const ( TransparentEndingType EndingType = iota NativeEndingType ) var endingTypeToWasmTable = []string{ "transparent", "native", } var endingTypeFromWasmTable = map[string]EndingType{ "transparent": TransparentEndingType, "native": NativeEndingType, } func (this *EndingType) JSValue() js.Value { return js.ValueOf(this.Value()) } func (this EndingType) Value() string { idx := int(this) if idx >= 0 && idx < len(endingTypeToWasmTable) { return endingTypeToWasmTable[idx] } panic("unknown input value") } func EndingTypeFromJS(value js.Value) EndingType { key := value.String() conv, ok := endingTypeFromWasmTable[key] if !ok { panic("unable to convert '" + key + "'") } return conv } type BlobCallbackFunc func(blob *Blob) type BlobCallback js.Func func BlobCallbackToJS(callback BlobCallbackFunc) *BlobCallback { if callback == nil { return nil } ret := BlobCallback(js.FuncOf(func(this js.Value, args []js.Value) interface{} { var ( _p0 *Blob ) if args[0].Type() != js.TypeNull && args[0].Type() != js.TypeUndefined { _p0 = BlobFromJS(args[0]) } callback(_p0) return nil })) return &ret } func BlobCallbackFromJS(_value js.Value) BlobCallbackFunc { return func(blob *Blob) { var ( _args [1]interface{} _end int ) _p0 := blob.JSValue() _args[0] = _p0 _end++ _value.Invoke(_args[0:_end]...) return } } type PromiseBlobOnFulfilledFunc func(value *Blob) type PromiseBlobOnFulfilled js.Func func PromiseBlobOnFulfilledToJS(callback PromiseBlobOnFulfilledFunc) *PromiseBlobOnFulfilled { if callback == nil { return nil } ret := PromiseBlobOnFulfilled(js.FuncOf(func(this js.Value, args []js.Value) interface{} { var ( _p0 *Blob ) _p0 = BlobFromJS(args[0]) callback(_p0) return nil })) return &ret } func PromiseBlobOnFulfilledFromJS(_value js.Value) PromiseBlobOnFulfilledFunc { return func(value *Blob) { var ( _args [1]interface{} _end int ) _p0 := value.JSValue() _args[0] = _p0 _end++ _value.Invoke(_args[0:_end]...) return } } type PromiseBlobOnRejectedFunc func(reason js.Value) type PromiseBlobOnRejected js.Func func PromiseBlobOnRejectedToJS(callback PromiseBlobOnRejectedFunc) *PromiseBlobOnRejected { if callback == nil { return nil } ret := PromiseBlobOnRejected(js.FuncOf(func(this js.Value, args []js.Value) interface{} { var ( _p0 js.Value ) _p0 = args[0] callback(_p0) return nil })) return &ret } func PromiseBlobOnRejectedFromJS(_value js.Value) PromiseBlobOnRejectedFunc { return func(reason js.Value) { var ( _args [1]interface{} _end int ) _p0 := reason _args[0] = _p0 _end++ _value.Invoke(_args[0:_end]...) return } } type BlobPropertyBag struct { Type string Endings EndingType } func (_this *BlobPropertyBag) JSValue() js.Value { out := js.Global().Get("Object").New() value0 := _this.Type out.Set("type", value0) value1 := _this.Endings.JSValue() out.Set("endings", value1) return out } func BlobPropertyBagFromJS(value js.Wrapper) *BlobPropertyBag { input := value.JSValue() var out BlobPropertyBag var ( value0 string value1 EndingType ) value0 = (input.Get("type")).String() out.Type = value0 value1 = EndingTypeFromJS(input.Get("endings")) out.Endings = value1 return &out } type FilePropertyBag struct { Type string Endings EndingType LastModified int } func (_this *FilePropertyBag) JSValue() js.Value { out := js.Global().Get("Object").New() value0 := _this.Type out.Set("type", value0) value1 := _this.Endings.JSValue() out.Set("endings", value1) value2 := _this.LastModified out.Set("lastModified", value2) return out } func FilePropertyBagFromJS(value js.Wrapper) *FilePropertyBag { input := value.JSValue() var out FilePropertyBag var ( value0 string value1 EndingType value2 int ) value0 = (input.Get("type")).String() out.Type = value0 value1 = EndingTypeFromJS(input.Get("endings")) out.Endings = value1 value2 = (input.Get("lastModified")).Int() out.LastModified = value2 return &out } type Blob struct { Value_JS js.Value } func (_this *Blob) JSValue() js.Value { return _this.Value_JS } func BlobFromJS(value js.Wrapper) *Blob { input := value.JSValue() if typ := input.Type(); typ == js.TypeNull || typ == js.TypeUndefined { return nil } ret := &Blob{} ret.Value_JS = input return ret } func NewBlob(blobParts []*Union, options *BlobPropertyBag) (_result *Blob) { _klass := js.Global().Get("Blob") var ( _args [2]interface{} _end int ) if blobParts != nil { _p0 := js.Global().Get("Array").New(len(blobParts)) for __idx0, __seq_in0 := range blobParts { __seq_out0 := __seq_in0.JSValue() _p0.SetIndex(__idx0, __seq_out0) } _args[0] = _p0 _end++ } if options != nil { _p1 := options.JSValue() _args[1] = _p1 _end++ } _returned := _klass.New(_args[0:_end]...) var ( _converted *Blob ) _converted = BlobFromJS(_returned) _result = _converted return } func (_this *Blob) Size() int { var ret int value := _this.Value_JS.Get("size") ret = (value).Int() return ret } func (_this *Blob) Type() string { var ret string value := _this.Value_JS.Get("type") ret = (value).String() return ret } func (_this *Blob) Slice(start *int, end *int, contentType *string) (_result *Blob) { var ( _args [3]interface{} _end int ) if start != nil { var _p0 interface{} if start != nil { _p0 = *(start) } else { _p0 = nil } _args[0] = _p0 _end++ } if end != nil { var _p1 interface{} if end != nil { _p1 = *(end) } else { _p1 = nil } _args[1] = _p1 _end++ } if contentType != nil { var _p2 interface{} if contentType != nil { _p2 = *(contentType) } else { _p2 = nil } _args[2] = _p2 _end++ } _returned := _this.Value_JS.Call("slice", _args[0:_end]...) var ( _converted *Blob ) _converted = BlobFromJS(_returned) _result = _converted return } type File struct { Blob } func FileFromJS(value js.Wrapper) *File { input := value.JSValue() if typ := input.Type(); typ == js.TypeNull || typ == js.TypeUndefined { return nil } ret := &File{} ret.Value_JS = input return ret } func NewFile(fileBits []*Union, fileName string, options *FilePropertyBag) (_result *File) { _klass := js.Global().Get("File") var ( _args [3]interface{} _end int ) _p0 := js.Global().Get("Array").New(len(fileBits)) for __idx0, __seq_in0 := range fileBits { __seq_out0 := __seq_in0.JSValue() _p0.SetIndex(__idx0, __seq_out0) } _args[0] = _p0 _end++ _p1 := fileName _args[1] = _p1 _end++ if options != nil { _p2 := options.JSValue() _args[2] = _p2 _end++ } _returned := _klass.New(_args[0:_end]...) var ( _converted *File ) _converted = FileFromJS(_returned) _result = _converted return } func (_this *File) Name() string { var ret string value := _this.Value_JS.Get("name") ret = (value).String() return ret } func (_this *File) LastModified() int { var ret int value := _this.Value_JS.Get("lastModified") ret = (value).Int() return ret } func (_this *File) WebkitRelativePath() string { var ret string value := _this.Value_JS.Get("webkitRelativePath") ret = (value).String() return ret } type FileList struct { Value_JS js.Value } func (_this *FileList) JSValue() js.Value { return _this.Value_JS } func FileListFromJS(value js.Wrapper) *FileList { input := value.JSValue() if typ := input.Type(); typ == js.TypeNull || typ == js.TypeUndefined { return nil } ret := &FileList{} ret.Value_JS = input return ret } func (_this *FileList) Length() uint { var ret uint value := _this.Value_JS.Get("length") ret = (uint)((value).Int()) return ret } func (_this *FileList) Index(index uint) (_result *File) { var ( _args [1]interface{} _end int ) _p0 := index _args[0] = _p0 _end++ _returned := _this.Value_JS.Call("item", _args[0:_end]...) var ( _converted *File ) if _returned.Type() != js.TypeNull && _returned.Type() != js.TypeUndefined { _converted = FileFromJS(_returned) } _result = _converted return } func (_this *FileList) Item(index uint) (_result *File) { var ( _args [1]interface{} _end int ) _p0 := index _args[0] = _p0 _end++ _returned := _this.Value_JS.Call("item", _args[0:_end]...) var ( _converted *File ) if _returned.Type() != js.TypeNull && _returned.Type() != js.TypeUndefined { _converted = FileFromJS(_returned) } _result = _converted return } type FileReader struct { domcore.EventTarget } func FileReaderFromJS(value js.Wrapper) *FileReader { input := value.JSValue() if typ := input.Type(); typ == js.TypeNull || typ == js.TypeUndefined { return nil } ret := &FileReader{} ret.Value_JS = input return ret } const ( EMPTY int = 0 LOADING int = 1 DONE int = 2 ) func NewFileReader() (_result *FileReader) { _klass := js.Global().Get("FileReader") var ( _args [0]interface{} _end int ) _returned := _klass.New(_args[0:_end]...) var ( _converted *FileReader ) _converted = FileReaderFromJS(_returned) _result = _converted return } func (_this *FileReader) ReadyState() int { var ret int value := _this.Value_JS.Get("readyState") ret = (value).Int() return ret } func (_this *FileReader) Result() *Union { var ret *Union value := _this.Value_JS.Get("result") if value.Type() != js.TypeNull && value.Type() != js.TypeUndefined { ret = UnionFromJS(value) } return ret } func (_this *FileReader) Error() *domcore.DOMException { var ret *domcore.DOMException value := _this.Value_JS.Get("error") if value.Type() != js.TypeNull && value.Type() != js.TypeUndefined { ret = domcore.DOMExceptionFromJS(value) } return ret }
BSD 3-Clause New or Revised License
haproxytech/dataplaneapi
operations/transactions/commit_transaction_parameters.go
bindForceReload
go
func (o *CommitTransactionParams) bindForceReload(rawData []string, hasKey bool, formats strfmt.Registry) error { var raw string if len(rawData) > 0 { raw = rawData[len(rawData)-1] } if raw == "" { return nil } value, err := swag.ConvertBool(raw) if err != nil { return errors.InvalidType("force_reload", "query", "bool", raw) } o.ForceReload = &value return nil }
bindForceReload binds and validates parameter ForceReload from query.
https://github.com/haproxytech/dataplaneapi/blob/b362aae0b04d0e330bd9dcfbf9f315b670de013b/operations/transactions/commit_transaction_parameters.go#L97-L117
package transactions import ( "net/http" "github.com/go-openapi/errors" "github.com/go-openapi/runtime" "github.com/go-openapi/runtime/middleware" "github.com/go-openapi/strfmt" "github.com/go-openapi/swag" ) func NewCommitTransactionParams() CommitTransactionParams { var ( forceReloadDefault = bool(false) ) return CommitTransactionParams{ ForceReload: &forceReloadDefault, } } type CommitTransactionParams struct { HTTPRequest *http.Request `json:"-"` ForceReload *bool ID string } func (o *CommitTransactionParams) BindRequest(r *http.Request, route *middleware.MatchedRoute) error { var res []error o.HTTPRequest = r qs := runtime.Values(r.URL.Query()) qForceReload, qhkForceReload, _ := qs.GetOK("force_reload") if err := o.bindForceReload(qForceReload, qhkForceReload, route.Formats); err != nil { res = append(res, err) } rID, rhkID, _ := route.Params.GetOK("id") if err := o.bindID(rID, rhkID, route.Formats); err != nil { res = append(res, err) } if len(res) > 0 { return errors.CompositeValidationError(res...) } return nil }
Apache License 2.0
gowebapi/webapi
fetch/fetch.go
Value
go
func (this RequestMode) Value() string { idx := int(this) if idx >= 0 && idx < len(requestModeToWasmTable) { return requestModeToWasmTable[idx] } panic("unknown input value") }
Value is converting this into javascript defined string value
https://github.com/gowebapi/webapi/blob/704d94b49d10bd459e9a1367a4f614909e09c241/fetch/fetch.go#L276-L282
package fetch import js "github.com/gowebapi/webapi/core/js" import ( "github.com/gowebapi/webapi/dom/domcore" "github.com/gowebapi/webapi/file" "github.com/gowebapi/webapi/html" "github.com/gowebapi/webapi/javascript" "github.com/gowebapi/webapi/patch" ) func unused(value interface{}) { } type Union struct { Value js.Value } func (u *Union) JSValue() js.Value { return u.Value } func UnionFromJS(value js.Value) *Union { return &Union{Value: value} } type ReferrerPolicy int const ( EmptyString0ReferrerPolicy ReferrerPolicy = iota NoReferrerReferrerPolicy NoReferrerWhenDowngradeReferrerPolicy SameOriginReferrerPolicy OriginReferrerPolicy StrictOriginReferrerPolicy OriginWhenCrossOriginReferrerPolicy StrictOriginWhenCrossOriginReferrerPolicy UnsafeUrlReferrerPolicy ) var referrerPolicyToWasmTable = []string{ "", "no-referrer", "no-referrer-when-downgrade", "same-origin", "origin", "strict-origin", "origin-when-cross-origin", "strict-origin-when-cross-origin", "unsafe-url", } var referrerPolicyFromWasmTable = map[string]ReferrerPolicy{ "": EmptyString0ReferrerPolicy, "no-referrer": NoReferrerReferrerPolicy, "no-referrer-when-downgrade": NoReferrerWhenDowngradeReferrerPolicy, "same-origin": SameOriginReferrerPolicy, "origin": OriginReferrerPolicy, "strict-origin": StrictOriginReferrerPolicy, "origin-when-cross-origin": OriginWhenCrossOriginReferrerPolicy, "strict-origin-when-cross-origin": StrictOriginWhenCrossOriginReferrerPolicy, "unsafe-url": UnsafeUrlReferrerPolicy, } func (this *ReferrerPolicy) JSValue() js.Value { return js.ValueOf(this.Value()) } func (this ReferrerPolicy) Value() string { idx := int(this) if idx >= 0 && idx < len(referrerPolicyToWasmTable) { return referrerPolicyToWasmTable[idx] } panic("unknown input value") } func ReferrerPolicyFromJS(value js.Value) ReferrerPolicy { key := value.String() conv, ok := referrerPolicyFromWasmTable[key] if !ok { panic("unable to convert '" + key + "'") } return conv } type RequestCache int const ( DefaultRequestCache RequestCache = iota NoStoreRequestCache ReloadRequestCache NoCacheRequestCache ForceCacheRequestCache OnlyIfCachedRequestCache ) var requestCacheToWasmTable = []string{ "default", "no-store", "reload", "no-cache", "force-cache", "only-if-cached", } var requestCacheFromWasmTable = map[string]RequestCache{ "default": DefaultRequestCache, "no-store": NoStoreRequestCache, "reload": ReloadRequestCache, "no-cache": NoCacheRequestCache, "force-cache": ForceCacheRequestCache, "only-if-cached": OnlyIfCachedRequestCache, } func (this *RequestCache) JSValue() js.Value { return js.ValueOf(this.Value()) } func (this RequestCache) Value() string { idx := int(this) if idx >= 0 && idx < len(requestCacheToWasmTable) { return requestCacheToWasmTable[idx] } panic("unknown input value") } func RequestCacheFromJS(value js.Value) RequestCache { key := value.String() conv, ok := requestCacheFromWasmTable[key] if !ok { panic("unable to convert '" + key + "'") } return conv } type RequestCredentials int const ( OmitRequestCredentials RequestCredentials = iota SameOriginRequestCredentials IncludeRequestCredentials ) var requestCredentialsToWasmTable = []string{ "omit", "same-origin", "include", } var requestCredentialsFromWasmTable = map[string]RequestCredentials{ "omit": OmitRequestCredentials, "same-origin": SameOriginRequestCredentials, "include": IncludeRequestCredentials, } func (this *RequestCredentials) JSValue() js.Value { return js.ValueOf(this.Value()) } func (this RequestCredentials) Value() string { idx := int(this) if idx >= 0 && idx < len(requestCredentialsToWasmTable) { return requestCredentialsToWasmTable[idx] } panic("unknown input value") } func RequestCredentialsFromJS(value js.Value) RequestCredentials { key := value.String() conv, ok := requestCredentialsFromWasmTable[key] if !ok { panic("unable to convert '" + key + "'") } return conv } type RequestDestination int const ( EmptyString0RequestDestination RequestDestination = iota AudioRequestDestination AudioworkletRequestDestination DocumentRequestDestination EmbedRequestDestination FontRequestDestination ImageRequestDestination ManifestRequestDestination ObjectRequestDestination PaintworkletRequestDestination ReportRequestDestination ScriptRequestDestination SharedworkerRequestDestination StyleRequestDestination TrackRequestDestination VideoRequestDestination WorkerRequestDestination XsltRequestDestination ) var requestDestinationToWasmTable = []string{ "", "audio", "audioworklet", "document", "embed", "font", "image", "manifest", "object", "paintworklet", "report", "script", "sharedworker", "style", "track", "video", "worker", "xslt", } var requestDestinationFromWasmTable = map[string]RequestDestination{ "": EmptyString0RequestDestination, "audio": AudioRequestDestination, "audioworklet": AudioworkletRequestDestination, "document": DocumentRequestDestination, "embed": EmbedRequestDestination, "font": FontRequestDestination, "image": ImageRequestDestination, "manifest": ManifestRequestDestination, "object": ObjectRequestDestination, "paintworklet": PaintworkletRequestDestination, "report": ReportRequestDestination, "script": ScriptRequestDestination, "sharedworker": SharedworkerRequestDestination, "style": StyleRequestDestination, "track": TrackRequestDestination, "video": VideoRequestDestination, "worker": WorkerRequestDestination, "xslt": XsltRequestDestination, } func (this *RequestDestination) JSValue() js.Value { return js.ValueOf(this.Value()) } func (this RequestDestination) Value() string { idx := int(this) if idx >= 0 && idx < len(requestDestinationToWasmTable) { return requestDestinationToWasmTable[idx] } panic("unknown input value") } func RequestDestinationFromJS(value js.Value) RequestDestination { key := value.String() conv, ok := requestDestinationFromWasmTable[key] if !ok { panic("unable to convert '" + key + "'") } return conv } type RequestMode int const ( NavigateRequestMode RequestMode = iota SameOriginRequestMode NoCorsRequestMode CorsRequestMode ) var requestModeToWasmTable = []string{ "navigate", "same-origin", "no-cors", "cors", } var requestModeFromWasmTable = map[string]RequestMode{ "navigate": NavigateRequestMode, "same-origin": SameOriginRequestMode, "no-cors": NoCorsRequestMode, "cors": CorsRequestMode, } func (this *RequestMode) JSValue() js.Value { return js.ValueOf(this.Value()) }
BSD 3-Clause New or Revised License
icecrime/poule
vendor/src/github.com/mreiferson/go-snappystream/writer.go
NewBufferedWriter
go
func NewBufferedWriter(w io.Writer) *BufferedWriter { _w := NewWriter(w).(*writer) return &BufferedWriter{ w: _w, bw: bufio.NewWriterSize(_w, MaxBlockSize), } }
NewBufferedWriter allocates and returns a BufferedWriter with an internal buffer of MaxBlockSize bytes. If an error occurs writing a block to w, all future writes will fail with the same error. After all data has been written, the client should call the Flush method to guarantee all data has been forwarded to the underlying io.Writer.
https://github.com/icecrime/poule/blob/8fb40443d3e0448656479ccf6cb5b923321625d7/vendor/src/github.com/mreiferson/go-snappystream/writer.go#L38-L44
package snappystream import ( "bufio" "errors" "fmt" "hash/crc32" "io" "github.com/mreiferson/go-snappystream/snappy-go" ) var errClosed = fmt.Errorf("closed") type BufferedWriter struct { err error w *writer bw *bufio.Writer }
Apache License 2.0
nknorg/nnet
message.go
SendBytesRelayAsync
go
func (nn *NNet) SendBytesRelayAsync(data, key []byte) (bool, error) { msg, err := nn.NewRelayBytesMessage(data, nn.GetLocalNode().Id, key) if err != nil { return false, err } return nn.SendMessageAsync(msg, protobuf.RELAY) }
SendBytesRelayAsync sends bytes data to the remote node that has smallest distance to the key, returns if send success (which is true if successfully send message to at least one next hop), and aggregated error during message sending
https://github.com/nknorg/nnet/blob/f80d3763d1bdc3fdfc7f1d97dc3fd92d596536a2/message.go#L152-L159
package nnet import ( "time" "github.com/gogo/protobuf/proto" "github.com/nknorg/nnet/message" "github.com/nknorg/nnet/node" "github.com/nknorg/nnet/protobuf" ) func (nn *NNet) NewDirectBytesMessage(data []byte) (*protobuf.Message, error) { id, err := message.GenID(nn.GetLocalNode().MessageIDBytes) if err != nil { return nil, err } msgBody := &protobuf.Bytes{ Data: data, } buf, err := proto.Marshal(msgBody) if err != nil { return nil, err } msg := &protobuf.Message{ MessageType: protobuf.BYTES, RoutingType: protobuf.DIRECT, MessageId: id, Message: buf, } return msg, nil } func (nn *NNet) NewRelayBytesMessage(data, srcID, key []byte) (*protobuf.Message, error) { id, err := message.GenID(nn.GetLocalNode().MessageIDBytes) if err != nil { return nil, err } msgBody := &protobuf.Bytes{ Data: data, } buf, err := proto.Marshal(msgBody) if err != nil { return nil, err } msg := &protobuf.Message{ MessageType: protobuf.BYTES, RoutingType: protobuf.RELAY, MessageId: id, Message: buf, SrcId: srcID, DestId: key, } return msg, nil } func (nn *NNet) NewBroadcastBytesMessage(data, srcID []byte, routingType protobuf.RoutingType) (*protobuf.Message, error) { id, err := message.GenID(nn.GetLocalNode().MessageIDBytes) if err != nil { return nil, err } msgBody := &protobuf.Bytes{ Data: data, } buf, err := proto.Marshal(msgBody) if err != nil { return nil, err } msg := &protobuf.Message{ MessageType: protobuf.BYTES, RoutingType: routingType, MessageId: id, Message: buf, SrcId: srcID, } return msg, nil } func (nn *NNet) SendBytesDirectAsync(data []byte, remoteNode *node.RemoteNode) error { msg, err := nn.NewDirectBytesMessage(data) if err != nil { return err } return remoteNode.SendMessageAsync(msg) } func (nn *NNet) SendBytesDirectSync(data []byte, remoteNode *node.RemoteNode) ([]byte, *node.RemoteNode, error) { return nn.SendBytesDirectSyncWithTimeout(data, remoteNode, 0) } func (nn *NNet) SendBytesDirectSyncWithTimeout(data []byte, remoteNode *node.RemoteNode, replyTimeout time.Duration) ([]byte, *node.RemoteNode, error) { msg, err := nn.NewDirectBytesMessage(data) if err != nil { return nil, nil, err } reply, err := remoteNode.SendMessageSync(msg, replyTimeout) if err != nil { return nil, nil, err } replyBody := &protobuf.Bytes{} err = proto.Unmarshal(reply.Msg.Message, replyBody) if err != nil { return nil, reply.RemoteNode, err } return replyBody.Data, reply.RemoteNode, nil } func (nn *NNet) SendBytesDirectReply(replyToID, data []byte, remoteNode *node.RemoteNode) error { msg, err := nn.NewDirectBytesMessage(data) if err != nil { return err } msg.ReplyToId = replyToID return remoteNode.SendMessageAsync(msg) }
Apache License 2.0
kube-node/nodeset
pkg/client/clientset/versioned/typed/nodeset/v1alpha1/fake/fake_nodeclass.go
Create
go
func (c *FakeNodeClasses) Create(nodeClass *v1alpha1.NodeClass) (result *v1alpha1.NodeClass, err error) { obj, err := c.Fake. Invokes(testing.NewRootCreateAction(nodeclassesResource, nodeClass), &v1alpha1.NodeClass{}) if obj == nil { return nil, err } return obj.(*v1alpha1.NodeClass), err }
Create takes the representation of a nodeClass and creates it. Returns the server's representation of the nodeClass, and an error, if there is any.
https://github.com/kube-node/nodeset/blob/6a55101a96e59a3fd67bf011061df017dcc2c22b/pkg/client/clientset/versioned/typed/nodeset/v1alpha1/fake/fake_nodeclass.go#L76-L83
package fake import ( v1alpha1 "github.com/kube-node/nodeset/pkg/nodeset/v1alpha1" v1 "k8s.io/apimachinery/pkg/apis/meta/v1" labels "k8s.io/apimachinery/pkg/labels" schema "k8s.io/apimachinery/pkg/runtime/schema" types "k8s.io/apimachinery/pkg/types" watch "k8s.io/apimachinery/pkg/watch" testing "k8s.io/client-go/testing" ) type FakeNodeClasses struct { Fake *FakeNodesetV1alpha1 } var nodeclassesResource = schema.GroupVersionResource{Group: "nodeset.k8s.io", Version: "v1alpha1", Resource: "nodeclasses"} var nodeclassesKind = schema.GroupVersionKind{Group: "nodeset.k8s.io", Version: "v1alpha1", Kind: "NodeClass"} func (c *FakeNodeClasses) Get(name string, options v1.GetOptions) (result *v1alpha1.NodeClass, err error) { obj, err := c.Fake. Invokes(testing.NewRootGetAction(nodeclassesResource, name), &v1alpha1.NodeClass{}) if obj == nil { return nil, err } return obj.(*v1alpha1.NodeClass), err } func (c *FakeNodeClasses) List(opts v1.ListOptions) (result *v1alpha1.NodeClassList, err error) { obj, err := c.Fake. Invokes(testing.NewRootListAction(nodeclassesResource, nodeclassesKind, opts), &v1alpha1.NodeClassList{}) if obj == nil { return nil, err } label, _, _ := testing.ExtractFromListOptions(opts) if label == nil { label = labels.Everything() } list := &v1alpha1.NodeClassList{} for _, item := range obj.(*v1alpha1.NodeClassList).Items { if label.Matches(labels.Set(item.Labels)) { list.Items = append(list.Items, item) } } return list, err } func (c *FakeNodeClasses) Watch(opts v1.ListOptions) (watch.Interface, error) { return c.Fake. InvokesWatch(testing.NewRootWatchAction(nodeclassesResource, opts)) }
Apache License 2.0
agoalofalife/event
event.go
Untie
go
func (dispatcher *Dispatcher) Untie(pointer interface{}) { for _, event := range dispatcher.listeners { for key, iterate := range event { if reflect.ValueOf(iterate[perform]).Pointer() == reflect.ValueOf(pointer).Pointer() { delete(event, key) } } } }
Untie Listeners events
https://github.com/agoalofalife/event/blob/5819560c67496e424df623ffb0dbe9dbbe29d832/event.go#L92-L100
package event import ( "fmt" "github.com/pkg/errors" "reflect" ) const ( typing = "type" perform = "perform" arguments = "arguments" ) type Dispatcher struct { listeners map[string]map[int]map[string]interface{} } func New() *Dispatcher { d := &Dispatcher{} d.listeners = map[string]map[int]map[string]interface{}{} return d } func (dispatcher *Dispatcher) Add(name interface{}, performing interface{}, parameters ...interface{}) (flag bool, err error) { subscriber, err := factoryNames(name) if err == nil { flag = true } nameType := getType(performing) if _, exist := dispatcher.listeners[subscriber]; !exist { dispatcher.listeners[subscriber] = make(map[int]map[string]interface{}) } dispatcher.listeners[subscriber][len(dispatcher.listeners[subscriber])] = map[string]interface{}{ typing: nameType.String(), perform: performing, arguments: parameters, } return flag, err } func (dispatcher *Dispatcher) Go(event interface{}, parameters ...interface{}) (err error) { subscriber, err := factoryNames(event) if err != nil { return err } if dispatcher.existEvent(subscriber) { for _, iterate := range dispatcher.listeners[subscriber] { if parameters != nil { iterate[arguments] = parameters } resolver(iterate[typing].(string), iterate[perform], iterate[arguments].([]interface{})) } } else { panic(fmt.Sprintf(eventNotExist, subscriber)) } return } func (dispatcher *Dispatcher) Fire(event interface{}, parameters ...interface{}) (err error) { return dispatcher.Go(event, parameters...) } func (dispatcher *Dispatcher) Destroy(event string) { if dispatcher.existEvent(event) { delete(dispatcher.listeners, event) } else { panic(fmt.Sprintf(eventNotExist, event)) } }
MIT License
schmorrison/zoho
crm/notes.go
DeleteNotes
go
func (c *API) DeleteNotes(IDs ...string) (data DeleteNoteResponse, err error) { idStr := "" for i, a := range IDs { idStr += a if i < len(IDs)-1 { idStr += "," } } endpoint := zoho.Endpoint{ Name: "notes", URL: fmt.Sprintf("https://www.zohoapis.%s/crm/v2/Notes", c.ZohoTLD), Method: zoho.HTTPDelete, ResponseData: &DeleteNoteResponse{}, URLParameters: map[string]zoho.Parameter{ "ids": "", }, } err = c.Zoho.HTTPRequest(&endpoint) if err != nil { return DeleteNoteResponse{}, fmt.Errorf("Failed to delete notes: %s", err) } if v, ok := endpoint.ResponseData.(*DeleteNoteResponse); ok { return *v, nil } return DeleteNoteResponse{}, fmt.Errorf("Data returned was not 'DeleteNoteResponse'") }
DeleteNotes will delete all notes specified in the IDs https://www.zoho.com/crm/help/api/v2/#delete-bulk-notes
https://github.com/schmorrison/zoho/blob/14581a166a2b038d69ff1d572dc19ca8fff259f2/crm/notes.go#L238-L266
package crm import ( "fmt" zoho "github.com/schmorrison/Zoho" ) func (c *API) GetNotes(params map[string]zoho.Parameter) (data NotesResponse, err error) { endpoint := zoho.Endpoint{ Name: "notes", URL: fmt.Sprintf("https://www.zohoapis.%s/crm/v2/Notes", c.ZohoTLD), Method: zoho.HTTPGet, ResponseData: &NotesResponse{}, URLParameters: map[string]zoho.Parameter{ "page": "", "per_page": "200", }, } if len(params) > 0 { for k, v := range params { endpoint.URLParameters[k] = v } } err = c.Zoho.HTTPRequest(&endpoint) if err != nil { return NotesResponse{}, fmt.Errorf("Failed to retrieve notes: %s", err) } if v, ok := endpoint.ResponseData.(*NotesResponse); ok { return *v, nil } return NotesResponse{}, fmt.Errorf("Data returned was not 'NotesResponse'") } func (c *API) GetNote(module Module, id string) (data NotesResponse, err error) { endpoint := zoho.Endpoint{ Name: "notes", URL: fmt.Sprintf("https://www.zohoapis.%s/crm/v2/%s/%s/Notes", c.ZohoTLD, module, id), Method: zoho.HTTPGet, ResponseData: &NotesResponse{}, } err = c.Zoho.HTTPRequest(&endpoint) if err != nil { return NotesResponse{}, fmt.Errorf("Failed to retrieve notes: %s", err) } if v, ok := endpoint.ResponseData.(*NotesResponse); ok { return *v, nil } return NotesResponse{}, fmt.Errorf("Data returned was not 'NotesResponse'") } type NotesResponse struct { Data []struct { Owner struct { Name string `json:"name,omitempty"` ID string `json:"id,omitempty"` } `json:"Owner,omitempty"` SeModule string `json:"$se_module,omitempty"` Approval struct { Delegate bool `json:"delegate,omitempty"` Approve bool `json:"approve,omitempty"` Reject bool `json:"reject,omitempty"` } `json:"$approval,omitempty"` ModifiedBy struct { Name string `json:"name,omitempty"` ID string `json:"id,omitempty"` } `json:"Modified_By,omitempty"` ModifiedTime Time `json:"Modified_Time,omitempty"` CreatedTime Time `json:"Created_Time,omitempty"` Followed bool `json:"$followed,omitempty"` ParentID struct { Name string `json:"name,omitempty"` ID string `json:"id,omitempty"` } `json:"Parent_Id,omitempty"` ID string `json:"id,omitempty"` CreatedBy struct { Name string `json:"name,omitempty"` ID string `json:"id,omitempty"` } `json:"Created_By,omitempty"` NoteTitle string `json:"Note_Title,omitempty"` NoteContent string `json:"Note_Content,omitempty"` } `json:"data,omitempty"` Info PageInfo `json:"info,omitempty"` } func (c *API) CreateNotes(request CreateNoteData) (data CreateNoteResponse, err error) { endpoint := zoho.Endpoint{ Name: "notes", URL: fmt.Sprintf("https://www.zohoapis.%s/crm/v2/Notes", c.ZohoTLD), Method: zoho.HTTPPost, ResponseData: &CreateNoteResponse{}, RequestBody: request, } err = c.Zoho.HTTPRequest(&endpoint) if err != nil { return CreateNoteResponse{}, fmt.Errorf("Failed to create notes: %s", err) } if v, ok := endpoint.ResponseData.(*CreateNoteResponse); ok { return *v, nil } return CreateNoteResponse{}, fmt.Errorf("Data returned was not 'CreateNoteResponse'") } type CreateNoteData struct { Data []struct { NoteTitle string `json:"Note_Title,omitempty"` NoteContent string `json:"Note_Content,omitempty"` ParentID string `json:"Parent_Id,omitempty"` SeModule string `json:"se_module,omitempty"` } `json:"data,omitempty"` } type CreateNoteResponse struct { Data []struct { Message string `json:"message,omitempty"` Details struct { CreatedBy struct { ID string `json:"id,omitempty"` Name string `json:"name,omitempty"` } `json:"created_by,omitempty"` ID string `json:"id,omitempty"` ModifiedBy struct { ID string `json:"id,omitempty"` Name string `json:"name,omitempty"` } `json:"modified_by,omitempty"` ModifiedTime Time `json:"modified_time,omitempty"` CreatedTime Time `json:"created_time,omitempty"` } `json:"details,omitempty"` Status string `json:"status,omitempty"` Code string `json:"code,omitempty"` } `json:"data,omitempty"` } func (c *API) CreateRecordNote(request CreateRecordNoteData, module Module, recordID string) (data CreateRecordNoteResponse, err error) { endpoint := zoho.Endpoint{ Name: "notes", URL: fmt.Sprintf("https://www.zohoapis.%s/crm/v2/%s/%s/Notes", c.ZohoTLD, module, recordID), Method: zoho.HTTPPost, ResponseData: &CreateRecordNoteResponse{}, RequestBody: request, } err = c.Zoho.HTTPRequest(&endpoint) if err != nil { return CreateRecordNoteResponse{}, fmt.Errorf("Failed to retrieve notes: %s", err) } if v, ok := endpoint.ResponseData.(*CreateRecordNoteResponse); ok { return *v, nil } return CreateRecordNoteResponse{}, fmt.Errorf("Data returned was not 'CreateRecordNoteResponse'") } type CreateRecordNoteResponse = CreateNoteResponse type CreateRecordNoteData struct { Data []struct { NoteTitle string `json:"Note_Title,omitempty"` NoteContent string `json:"Note_Content,omitempty"` } `json:"data,omitempty"` } func (c *API) UpdateNote(request UpdateNoteData, module Module, recordID, noteID string) (data UpdateNoteResponse, err error) { endpoint := zoho.Endpoint{ Name: "notes", URL: fmt.Sprintf("https://www.zohoapis.%s/crm/v2/%s/%s/Notes/%s", c.ZohoTLD, module, recordID, noteID), Method: zoho.HTTPPut, ResponseData: &UpdateNoteResponse{}, RequestBody: request, } err = c.Zoho.HTTPRequest(&endpoint) if err != nil { return UpdateNoteResponse{}, fmt.Errorf("Failed to update notes: %s", err) } if v, ok := endpoint.ResponseData.(*UpdateNoteResponse); ok { return *v, nil } return UpdateNoteResponse{}, fmt.Errorf("Data returned was not 'UpdateNoteResponse'") } type UpdateNoteResponse = CreateNoteResponse type UpdateNoteData = CreateRecordNoteData func (c *API) DeleteNote(module Module, recordID, noteID string) (data DeleteNoteResponse, err error) { endpoint := zoho.Endpoint{ Name: "notes", URL: fmt.Sprintf("https://www.zohoapis.%s/crm/v2/%s/%s/Notes/%s", c.ZohoTLD, module, recordID, noteID), Method: zoho.HTTPDelete, ResponseData: &DeleteNoteResponse{}, } err = c.Zoho.HTTPRequest(&endpoint) if err != nil { return DeleteNoteResponse{}, fmt.Errorf("Failed to delete note: %s", err) } if v, ok := endpoint.ResponseData.(*DeleteNoteResponse); ok { return *v, nil } return DeleteNoteResponse{}, fmt.Errorf("Data returned was not 'DeleteNoteResponse'") }
MIT License
vito/booklit
errors.go
Error
go
func (err TitleTwiceError) Error() string { return "cannot set title twice" }
Error returns a 'cannot set title twice' message.
https://github.com/vito/booklit/blob/f2f26aa3ef5ab94603abee238d7f262f5eb6bd66/errors.go#L284-L286
package booklit import ( "bufio" "bytes" "fmt" "html/template" "io" "net/http" "os" "path/filepath" "strings" "github.com/segmentio/textio" "github.com/vito/booklit/ast" "github.com/vito/booklit/errhtml" ) var errorTmpl *template.Template func init() { errorTmpl = template.New("errors").Funcs(template.FuncMap{ "error": func(err error) (template.HTML, error) { buf := new(bytes.Buffer) if prettyErr, ok := err.(PrettyError); ok { renderErr := prettyErr.PrettyHTML(buf) if renderErr != nil { return "", renderErr } return template.HTML(buf.String()), nil } return template.HTML( `<pre class="raw-error">` + template.HTMLEscapeString(err.Error()) + `</pre>`, ), nil }, "annotate": func(loc ErrorLocation) (template.HTML, error) { buf := new(bytes.Buffer) err := loc.AnnotatedHTML(buf) if err != nil { return "", err } return template.HTML(buf.String()), nil }, }) for _, asset := range errhtml.AssetNames() { info, err := errhtml.AssetInfo(asset) if err != nil { panic(err) } content := strings.TrimRight(string(errhtml.MustAsset(asset)), "\n") _, err = errorTmpl.New(filepath.Base(info.Name())).Parse(content) if err != nil { panic(err) } } } func ErrorResponse(w http.ResponseWriter, err error) { renderErr := errorTmpl.Lookup("page.tmpl").Execute(w, err) if renderErr != nil { fmt.Fprintf(w, "failed to render error page: %s", renderErr) } } type PrettyError interface { error PrettyPrint(io.Writer) PrettyHTML(io.Writer) error } type ParseError struct { Err error ErrorLocation } func (err ParseError) Error() string { return fmt.Sprintf("parse error: %s", err.Err) } func (err ParseError) PrettyPrint(out io.Writer) { fmt.Fprintln(out, err.Annotate("%s", err)) fmt.Fprintln(out) err.AnnotateLocation(out) } func (err ParseError) PrettyHTML(out io.Writer) error { return errorTmpl.Lookup("parse-error.tmpl").Execute(out, err) } type UnknownTagError struct { TagName string SimilarTags []Tag ErrorLocation } func (err UnknownTagError) Error() string { return fmt.Sprintf("unknown tag '%s'", err.TagName) } func (err UnknownTagError) PrettyPrint(out io.Writer) { fmt.Fprintln(out, err.Annotate("%s", err)) fmt.Fprintln(out) err.AnnotateLocation(out) if len(err.SimilarTags) == 0 { fmt.Fprintf(out, "I couldn't find any similar tags. :(\n") } else { fmt.Fprintf(out, "These tags seem similar:\n\n") for _, tag := range err.SimilarTags { fmt.Fprintf(out, "- %s\n", tag.Name) } fmt.Fprintf(out, "\nDid you mean one of these?\n") } } func (err UnknownTagError) PrettyHTML(out io.Writer) error { return errorTmpl.Lookup("unknown-tag.tmpl").Execute(out, err) } type AmbiguousReferenceError struct { TagName string DefinedLocations []ErrorLocation ErrorLocation } func (err AmbiguousReferenceError) Error() string { return fmt.Sprintf( "ambiguous target for tag '%s'", err.TagName, ) } func (err AmbiguousReferenceError) PrettyPrint(out io.Writer) { fmt.Fprintln(out, err.Annotate("%s", err)) fmt.Fprintln(out) err.AnnotateLocation(out) fmt.Fprintf(out, "The same tag was defined in the following locations:\n\n") for _, loc := range err.DefinedLocations { fmt.Fprintf(out, "- %s:\n", loc.FilePath) loc.AnnotateLocation(textio.NewPrefixWriter(out, " ")) } fmt.Fprintf(out, "Tags must be unique so I know where to link to!\n") } func (err AmbiguousReferenceError) PrettyHTML(out io.Writer) error { return errorTmpl.Lookup("ambiguous-reference.tmpl").Execute(out, err) } type UndefinedFunctionError struct { Function string ErrorLocation } func (err UndefinedFunctionError) Error() string { return fmt.Sprintf( "undefined function \\%s", err.Function, ) } func (err UndefinedFunctionError) PrettyPrint(out io.Writer) { fmt.Fprintln(out, err.Annotate("%s", err)) fmt.Fprintln(out) err.AnnotateLocation(out) } func (err UndefinedFunctionError) PrettyHTML(out io.Writer) error { return errorTmpl.Lookup("undefined-function.tmpl").Execute(out, err) } type FailedFunctionError struct { Function string Err error ErrorLocation } func (err FailedFunctionError) Error() string { return fmt.Sprintf( "function \\%s returned an error: %s", err.Function, err.Err, ) } func (err FailedFunctionError) PrettyPrint(out io.Writer) { fmt.Fprintln(out, err.Annotate("function \\%s returned an error", err.Function)) fmt.Fprintln(out) err.AnnotateLocation(out) if prettyErr, ok := err.Err.(PrettyError); ok { prettyErr.PrettyPrint(textio.NewPrefixWriter(out, " ")) } else { fmt.Fprintf(out, "\x1b[33m%s\x1b[0m\n", err.Err) } } func (err FailedFunctionError) PrettyHTML(out io.Writer) error { return errorTmpl.Lookup("function-error.tmpl").Execute(out, err) } type TitleTwiceError struct { TitleLocation ErrorLocation ErrorLocation }
MIT License
gravitational/robotest
lib/ssh/ssh.go
RunCommandWithOutput
go
func RunCommandWithOutput(session *ssh.Session, log logrus.FieldLogger, command string, w io.Writer) (err error) { defer func() { if err != nil && session != nil { errClose := session.Close() if errClose != nil { log.WithError(err).Error("failed to close SSH session") } } }() var stderr io.Reader stderr, err = session.StderrPipe() if err != nil { return trace.Wrap(err) } var stdout io.Reader stdout, err = session.StdoutPipe() if err != nil { return trace.Wrap(err) } var wg sync.WaitGroup wg.Add(2) errCh := make(chan error, 2) sink := make(chan string) done := make(chan struct{}) go func() { errCh <- stream(stdout, sink) wg.Done() }() go func() { errCh <- stream(stderr, sink) wg.Done() }() go func() { wg.Wait() close(errCh) }() go func() { w := bufio.NewWriter(w) for line := range sink { _, err := w.Write([]byte(line)) if err != nil { log.Errorf("failed to write to w: %v", err) } } w.Flush() close(done) }() err = session.Start(command) if err != nil { return trace.Wrap(err, "failed to start %q", command) } err = session.Wait() session.Close() session = nil for err := range errCh { if err != nil { log.Errorf("failed to stream: %v", err) } } close(sink) <-done return trace.Wrap(err) }
RunCommandWithOutput executes the specified command in given session and streams session's Stderr/Stdout into w. The function takes ownership of session and will destroy it upon completion of the command
https://github.com/gravitational/robotest/blob/ea78dcf03ebe3bd8a75dfac658f84993b9468bee/lib/ssh/ssh.go#L61-L129
package sshutils import ( "bufio" "io" "io/ioutil" "net" "os" "sync" "time" "github.com/gravitational/robotest/lib/defaults" "github.com/gravitational/trace" "github.com/sirupsen/logrus" "golang.org/x/crypto/ssh" ) func Client(addr, user string, signer ssh.Signer) (*ssh.Client, error) { return client(addr, user, signer, realTimeoutDialer) } func Connect(addr, user string, signer ssh.Signer) (*ssh.Session, error) { client, err := Client(addr, user, signer) if err != nil { return nil, trace.Wrap(err) } session, err := client.NewSession() if err != nil { return nil, trace.Wrap(err) } return session, nil }
Apache License 2.0
logic-building/functional-go
fp/subset.go
SubsetFloat64
go
func SubsetFloat64(list1, list2 []float64) bool { if list1 == nil || len(list1) == 0 || list2 == nil || len(list2) == 0 { return false } resultMap := make(map[float64]struct{}) for i := 0; i < len(list1); i++ { _, ok := resultMap[list1[i]] if !ok { found := false resultMap[list1[i]] = struct{}{} for j := 0; j < len(list2); j++ { if list1[i] == list2[j] { found = true break } } if !found { return false } } } return true }
SubsetFloat64 returns true or false by checking if set1 is a subset of set2 repeated value within list parameter will be ignored
https://github.com/logic-building/functional-go/blob/ddc2c536394ce31c027f7dc42396296afe6a9965/fp/subset.go#L707-L730
package fp func SubsetInt(list1, list2 []int) bool { if list1 == nil || len(list1) == 0 || list2 == nil || len(list2) == 0 { return false } resultMap := make(map[int]struct{}) for i := 0; i < len(list1); i++ { _, ok := resultMap[list1[i]] if !ok { found := false resultMap[list1[i]] = struct{}{} for j := 0; j < len(list2); j++ { if list1[i] == list2[j] { found = true break } } if !found { return false } } } return true } func SubsetIntPtr(list1, list2 []*int) bool { if list1 == nil || len(list1) == 0 || list2 == nil || len(list2) == 0 { return false } resultMap := make(map[int]struct{}) for i := 0; i < len(list1); i++ { _, ok := resultMap[*list1[i]] if !ok { found := false resultMap[*list1[i]] = struct{}{} for j := 0; j < len(list2); j++ { if list1[i] == list2[j] { found = true break } } if !found { return false } } } return true } func SubsetInt64(list1, list2 []int64) bool { if list1 == nil || len(list1) == 0 || list2 == nil || len(list2) == 0 { return false } resultMap := make(map[int64]struct{}) for i := 0; i < len(list1); i++ { _, ok := resultMap[list1[i]] if !ok { found := false resultMap[list1[i]] = struct{}{} for j := 0; j < len(list2); j++ { if list1[i] == list2[j] { found = true break } } if !found { return false } } } return true } func SubsetInt64Ptr(list1, list2 []*int64) bool { if list1 == nil || len(list1) == 0 || list2 == nil || len(list2) == 0 { return false } resultMap := make(map[int64]struct{}) for i := 0; i < len(list1); i++ { _, ok := resultMap[*list1[i]] if !ok { found := false resultMap[*list1[i]] = struct{}{} for j := 0; j < len(list2); j++ { if list1[i] == list2[j] { found = true break } } if !found { return false } } } return true } func SubsetInt32(list1, list2 []int32) bool { if list1 == nil || len(list1) == 0 || list2 == nil || len(list2) == 0 { return false } resultMap := make(map[int32]struct{}) for i := 0; i < len(list1); i++ { _, ok := resultMap[list1[i]] if !ok { found := false resultMap[list1[i]] = struct{}{} for j := 0; j < len(list2); j++ { if list1[i] == list2[j] { found = true break } } if !found { return false } } } return true } func SubsetInt32Ptr(list1, list2 []*int32) bool { if list1 == nil || len(list1) == 0 || list2 == nil || len(list2) == 0 { return false } resultMap := make(map[int32]struct{}) for i := 0; i < len(list1); i++ { _, ok := resultMap[*list1[i]] if !ok { found := false resultMap[*list1[i]] = struct{}{} for j := 0; j < len(list2); j++ { if list1[i] == list2[j] { found = true break } } if !found { return false } } } return true } func SubsetInt16(list1, list2 []int16) bool { if list1 == nil || len(list1) == 0 || list2 == nil || len(list2) == 0 { return false } resultMap := make(map[int16]struct{}) for i := 0; i < len(list1); i++ { _, ok := resultMap[list1[i]] if !ok { found := false resultMap[list1[i]] = struct{}{} for j := 0; j < len(list2); j++ { if list1[i] == list2[j] { found = true break } } if !found { return false } } } return true } func SubsetInt16Ptr(list1, list2 []*int16) bool { if list1 == nil || len(list1) == 0 || list2 == nil || len(list2) == 0 { return false } resultMap := make(map[int16]struct{}) for i := 0; i < len(list1); i++ { _, ok := resultMap[*list1[i]] if !ok { found := false resultMap[*list1[i]] = struct{}{} for j := 0; j < len(list2); j++ { if list1[i] == list2[j] { found = true break } } if !found { return false } } } return true } func SubsetInt8(list1, list2 []int8) bool { if list1 == nil || len(list1) == 0 || list2 == nil || len(list2) == 0 { return false } resultMap := make(map[int8]struct{}) for i := 0; i < len(list1); i++ { _, ok := resultMap[list1[i]] if !ok { found := false resultMap[list1[i]] = struct{}{} for j := 0; j < len(list2); j++ { if list1[i] == list2[j] { found = true break } } if !found { return false } } } return true } func SubsetInt8Ptr(list1, list2 []*int8) bool { if list1 == nil || len(list1) == 0 || list2 == nil || len(list2) == 0 { return false } resultMap := make(map[int8]struct{}) for i := 0; i < len(list1); i++ { _, ok := resultMap[*list1[i]] if !ok { found := false resultMap[*list1[i]] = struct{}{} for j := 0; j < len(list2); j++ { if list1[i] == list2[j] { found = true break } } if !found { return false } } } return true } func SubsetUint(list1, list2 []uint) bool { if list1 == nil || len(list1) == 0 || list2 == nil || len(list2) == 0 { return false } resultMap := make(map[uint]struct{}) for i := 0; i < len(list1); i++ { _, ok := resultMap[list1[i]] if !ok { found := false resultMap[list1[i]] = struct{}{} for j := 0; j < len(list2); j++ { if list1[i] == list2[j] { found = true break } } if !found { return false } } } return true } func SubsetUintPtr(list1, list2 []*uint) bool { if list1 == nil || len(list1) == 0 || list2 == nil || len(list2) == 0 { return false } resultMap := make(map[uint]struct{}) for i := 0; i < len(list1); i++ { _, ok := resultMap[*list1[i]] if !ok { found := false resultMap[*list1[i]] = struct{}{} for j := 0; j < len(list2); j++ { if list1[i] == list2[j] { found = true break } } if !found { return false } } } return true } func SubsetUint64(list1, list2 []uint64) bool { if list1 == nil || len(list1) == 0 || list2 == nil || len(list2) == 0 { return false } resultMap := make(map[uint64]struct{}) for i := 0; i < len(list1); i++ { _, ok := resultMap[list1[i]] if !ok { found := false resultMap[list1[i]] = struct{}{} for j := 0; j < len(list2); j++ { if list1[i] == list2[j] { found = true break } } if !found { return false } } } return true } func SubsetUint64Ptr(list1, list2 []*uint64) bool { if list1 == nil || len(list1) == 0 || list2 == nil || len(list2) == 0 { return false } resultMap := make(map[uint64]struct{}) for i := 0; i < len(list1); i++ { _, ok := resultMap[*list1[i]] if !ok { found := false resultMap[*list1[i]] = struct{}{} for j := 0; j < len(list2); j++ { if list1[i] == list2[j] { found = true break } } if !found { return false } } } return true } func SubsetUint32(list1, list2 []uint32) bool { if list1 == nil || len(list1) == 0 || list2 == nil || len(list2) == 0 { return false } resultMap := make(map[uint32]struct{}) for i := 0; i < len(list1); i++ { _, ok := resultMap[list1[i]] if !ok { found := false resultMap[list1[i]] = struct{}{} for j := 0; j < len(list2); j++ { if list1[i] == list2[j] { found = true break } } if !found { return false } } } return true } func SubsetUint32Ptr(list1, list2 []*uint32) bool { if list1 == nil || len(list1) == 0 || list2 == nil || len(list2) == 0 { return false } resultMap := make(map[uint32]struct{}) for i := 0; i < len(list1); i++ { _, ok := resultMap[*list1[i]] if !ok { found := false resultMap[*list1[i]] = struct{}{} for j := 0; j < len(list2); j++ { if list1[i] == list2[j] { found = true break } } if !found { return false } } } return true } func SubsetUint16(list1, list2 []uint16) bool { if list1 == nil || len(list1) == 0 || list2 == nil || len(list2) == 0 { return false } resultMap := make(map[uint16]struct{}) for i := 0; i < len(list1); i++ { _, ok := resultMap[list1[i]] if !ok { found := false resultMap[list1[i]] = struct{}{} for j := 0; j < len(list2); j++ { if list1[i] == list2[j] { found = true break } } if !found { return false } } } return true } func SubsetUint16Ptr(list1, list2 []*uint16) bool { if list1 == nil || len(list1) == 0 || list2 == nil || len(list2) == 0 { return false } resultMap := make(map[uint16]struct{}) for i := 0; i < len(list1); i++ { _, ok := resultMap[*list1[i]] if !ok { found := false resultMap[*list1[i]] = struct{}{} for j := 0; j < len(list2); j++ { if list1[i] == list2[j] { found = true break } } if !found { return false } } } return true } func SubsetUint8(list1, list2 []uint8) bool { if list1 == nil || len(list1) == 0 || list2 == nil || len(list2) == 0 { return false } resultMap := make(map[uint8]struct{}) for i := 0; i < len(list1); i++ { _, ok := resultMap[list1[i]] if !ok { found := false resultMap[list1[i]] = struct{}{} for j := 0; j < len(list2); j++ { if list1[i] == list2[j] { found = true break } } if !found { return false } } } return true } func SubsetUint8Ptr(list1, list2 []*uint8) bool { if list1 == nil || len(list1) == 0 || list2 == nil || len(list2) == 0 { return false } resultMap := make(map[uint8]struct{}) for i := 0; i < len(list1); i++ { _, ok := resultMap[*list1[i]] if !ok { found := false resultMap[*list1[i]] = struct{}{} for j := 0; j < len(list2); j++ { if list1[i] == list2[j] { found = true break } } if !found { return false } } } return true } func SubsetStr(list1, list2 []string) bool { if list1 == nil || len(list1) == 0 || list2 == nil || len(list2) == 0 { return false } resultMap := make(map[string]struct{}) for i := 0; i < len(list1); i++ { _, ok := resultMap[list1[i]] if !ok { found := false resultMap[list1[i]] = struct{}{} for j := 0; j < len(list2); j++ { if list1[i] == list2[j] { found = true break } } if !found { return false } } } return true } func SubsetStrPtr(list1, list2 []*string) bool { if list1 == nil || len(list1) == 0 || list2 == nil || len(list2) == 0 { return false } resultMap := make(map[string]struct{}) for i := 0; i < len(list1); i++ { _, ok := resultMap[*list1[i]] if !ok { found := false resultMap[*list1[i]] = struct{}{} for j := 0; j < len(list2); j++ { if list1[i] == list2[j] { found = true break } } if !found { return false } } } return true } func SubsetBool(list1, list2 []bool) bool { if list1 == nil || len(list1) == 0 || list2 == nil || len(list2) == 0 { return false } resultMap := make(map[bool]struct{}) for i := 0; i < len(list1); i++ { _, ok := resultMap[list1[i]] if !ok { found := false resultMap[list1[i]] = struct{}{} for j := 0; j < len(list2); j++ { if list1[i] == list2[j] { found = true break } } if !found { return false } } } return true } func SubsetBoolPtr(list1, list2 []*bool) bool { if list1 == nil || len(list1) == 0 || list2 == nil || len(list2) == 0 { return false } resultMap := make(map[bool]struct{}) for i := 0; i < len(list1); i++ { _, ok := resultMap[*list1[i]] if !ok { found := false resultMap[*list1[i]] = struct{}{} for j := 0; j < len(list2); j++ { if list1[i] == list2[j] { found = true break } } if !found { return false } } } return true } func SubsetFloat32(list1, list2 []float32) bool { if list1 == nil || len(list1) == 0 || list2 == nil || len(list2) == 0 { return false } resultMap := make(map[float32]struct{}) for i := 0; i < len(list1); i++ { _, ok := resultMap[list1[i]] if !ok { found := false resultMap[list1[i]] = struct{}{} for j := 0; j < len(list2); j++ { if list1[i] == list2[j] { found = true break } } if !found { return false } } } return true } func SubsetFloat32Ptr(list1, list2 []*float32) bool { if list1 == nil || len(list1) == 0 || list2 == nil || len(list2) == 0 { return false } resultMap := make(map[float32]struct{}) for i := 0; i < len(list1); i++ { _, ok := resultMap[*list1[i]] if !ok { found := false resultMap[*list1[i]] = struct{}{} for j := 0; j < len(list2); j++ { if list1[i] == list2[j] { found = true break } } if !found { return false } } } return true }
Apache License 2.0
minight/h2csmuggler
internal/paths/paths.go
Prefix
go
func Prefix(prefix []string, paths []string) (ret []string) { for _, pre := range prefix { if len(pre) == 0 { continue } for _, p := range paths { ret = append(ret, fmt.Sprintf("%s/%s", pre, p)) } } return }
Prefix will cross multiply the prefix and paths. If either is empty an empty slice will be returned
https://github.com/minight/h2csmuggler/blob/bf23437d7b8dce2d3f03c3ce2c61e13691bb4021/internal/paths/paths.go#L27-L37
package paths import ( "fmt" "net/url" "github.com/pkg/errors" ) func Pitchfork(base string, paths []string) (ret []string, err error) { parsed, err := url.Parse(base) if err != nil { return nil, errors.Wrap(err, "failed to parse base url") } for _, p := range paths { parsed.Path = p ret = append(ret, parsed.String()) } return }
MIT License