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 |
---|---|---|---|---|---|---|---|---|
solo-io/skv2 | pkg/multicluster/internal/k8s/core/v1/sets/mocks/sets.go | Has | go | func (m *MockServiceAccountSet) Has(serviceAccount ezkube.ResourceId) bool {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "Has", serviceAccount)
ret0, _ := ret[0].(bool)
return ret0
} | Has mocks base method | https://github.com/solo-io/skv2/blob/a7d0c83004bb24051a91e35fca7d04d788967f17/pkg/multicluster/internal/k8s/core/v1/sets/mocks/sets.go#L392-L397 | 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/core/v1/sets"
v1 "k8s.io/api/core/v1"
sets0 "k8s.io/apimachinery/pkg/util/sets"
)
type MockSecretSet struct {
ctrl *gomock.Controller
recorder *MockSecretSetMockRecorder
}
type MockSecretSetMockRecorder struct {
mock *MockSecretSet
}
func NewMockSecretSet(ctrl *gomock.Controller) *MockSecretSet {
mock := &MockSecretSet{ctrl: ctrl}
mock.recorder = &MockSecretSetMockRecorder{mock}
return mock
}
func (m *MockSecretSet) EXPECT() *MockSecretSetMockRecorder {
return m.recorder
}
func (m *MockSecretSet) Keys() sets0.String {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "Keys")
ret0, _ := ret[0].(sets0.String)
return ret0
}
func (mr *MockSecretSetMockRecorder) Keys() *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Keys", reflect.TypeOf((*MockSecretSet)(nil).Keys))
}
func (m *MockSecretSet) List(filterResource ...func(*v1.Secret) bool) []*v1.Secret {
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.Secret)
return ret0
}
func (mr *MockSecretSetMockRecorder) List(filterResource ...interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "List", reflect.TypeOf((*MockSecretSet)(nil).List), filterResource...)
}
func (m *MockSecretSet) UnsortedList(filterResource ...func(*v1.Secret) bool) []*v1.Secret {
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.Secret)
return ret0
}
func (mr *MockSecretSetMockRecorder) UnsortedList(filterResource ...interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "UnsortedList", reflect.TypeOf((*MockSecretSet)(nil).UnsortedList), filterResource...)
}
func (m *MockSecretSet) Map() map[string]*v1.Secret {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "Map")
ret0, _ := ret[0].(map[string]*v1.Secret)
return ret0
}
func (mr *MockSecretSetMockRecorder) Map() *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Map", reflect.TypeOf((*MockSecretSet)(nil).Map))
}
func (m *MockSecretSet) Insert(secret ...*v1.Secret) {
m.ctrl.T.Helper()
varargs := []interface{}{}
for _, a := range secret {
varargs = append(varargs, a)
}
m.ctrl.Call(m, "Insert", varargs...)
}
func (mr *MockSecretSetMockRecorder) Insert(secret ...interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Insert", reflect.TypeOf((*MockSecretSet)(nil).Insert), secret...)
}
func (m *MockSecretSet) Equal(secretSet v1sets.SecretSet) bool {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "Equal", secretSet)
ret0, _ := ret[0].(bool)
return ret0
}
func (mr *MockSecretSetMockRecorder) Equal(secretSet interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Equal", reflect.TypeOf((*MockSecretSet)(nil).Equal), secretSet)
}
func (m *MockSecretSet) Has(secret ezkube.ResourceId) bool {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "Has", secret)
ret0, _ := ret[0].(bool)
return ret0
}
func (mr *MockSecretSetMockRecorder) Has(secret interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Has", reflect.TypeOf((*MockSecretSet)(nil).Has), secret)
}
func (m *MockSecretSet) Delete(secret ezkube.ResourceId) {
m.ctrl.T.Helper()
m.ctrl.Call(m, "Delete", secret)
}
func (mr *MockSecretSetMockRecorder) Delete(secret interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Delete", reflect.TypeOf((*MockSecretSet)(nil).Delete), secret)
}
func (m *MockSecretSet) Union(set v1sets.SecretSet) v1sets.SecretSet {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "Union", set)
ret0, _ := ret[0].(v1sets.SecretSet)
return ret0
}
func (mr *MockSecretSetMockRecorder) Union(set interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Union", reflect.TypeOf((*MockSecretSet)(nil).Union), set)
}
func (m *MockSecretSet) Difference(set v1sets.SecretSet) v1sets.SecretSet {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "Difference", set)
ret0, _ := ret[0].(v1sets.SecretSet)
return ret0
}
func (mr *MockSecretSetMockRecorder) Difference(set interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Difference", reflect.TypeOf((*MockSecretSet)(nil).Difference), set)
}
func (m *MockSecretSet) Intersection(set v1sets.SecretSet) v1sets.SecretSet {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "Intersection", set)
ret0, _ := ret[0].(v1sets.SecretSet)
return ret0
}
func (mr *MockSecretSetMockRecorder) Intersection(set interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Intersection", reflect.TypeOf((*MockSecretSet)(nil).Intersection), set)
}
func (m *MockSecretSet) Find(id ezkube.ResourceId) (*v1.Secret, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "Find", id)
ret0, _ := ret[0].(*v1.Secret)
ret1, _ := ret[1].(error)
return ret0, ret1
}
func (mr *MockSecretSetMockRecorder) Find(id interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Find", reflect.TypeOf((*MockSecretSet)(nil).Find), id)
}
func (m *MockSecretSet) Length() int {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "Length")
ret0, _ := ret[0].(int)
return ret0
}
func (mr *MockSecretSetMockRecorder) Length() *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Length", reflect.TypeOf((*MockSecretSet)(nil).Length))
}
func (m *MockSecretSet) Generic() sets.ResourceSet {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "Generic")
ret0, _ := ret[0].(sets.ResourceSet)
return ret0
}
func (mr *MockSecretSetMockRecorder) Generic() *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Generic", reflect.TypeOf((*MockSecretSet)(nil).Generic))
}
func (m *MockSecretSet) Delta(newSet v1sets.SecretSet) sets.ResourceDelta {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "Delta", newSet)
ret0, _ := ret[0].(sets.ResourceDelta)
return ret0
}
func (mr *MockSecretSetMockRecorder) Delta(newSet interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Delta", reflect.TypeOf((*MockSecretSet)(nil).Delta), newSet)
}
func (m *MockSecretSet) Clone() v1sets.SecretSet {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "Clone")
ret0, _ := ret[0].(v1sets.SecretSet)
return ret0
}
func (mr *MockSecretSetMockRecorder) Clone() *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Clone", reflect.TypeOf((*MockSecretSet)(nil).Clone))
}
type MockServiceAccountSet struct {
ctrl *gomock.Controller
recorder *MockServiceAccountSetMockRecorder
}
type MockServiceAccountSetMockRecorder struct {
mock *MockServiceAccountSet
}
func NewMockServiceAccountSet(ctrl *gomock.Controller) *MockServiceAccountSet {
mock := &MockServiceAccountSet{ctrl: ctrl}
mock.recorder = &MockServiceAccountSetMockRecorder{mock}
return mock
}
func (m *MockServiceAccountSet) EXPECT() *MockServiceAccountSetMockRecorder {
return m.recorder
}
func (m *MockServiceAccountSet) Keys() sets0.String {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "Keys")
ret0, _ := ret[0].(sets0.String)
return ret0
}
func (mr *MockServiceAccountSetMockRecorder) Keys() *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Keys", reflect.TypeOf((*MockServiceAccountSet)(nil).Keys))
}
func (m *MockServiceAccountSet) List(filterResource ...func(*v1.ServiceAccount) bool) []*v1.ServiceAccount {
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.ServiceAccount)
return ret0
}
func (mr *MockServiceAccountSetMockRecorder) List(filterResource ...interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "List", reflect.TypeOf((*MockServiceAccountSet)(nil).List), filterResource...)
}
func (m *MockServiceAccountSet) UnsortedList(filterResource ...func(*v1.ServiceAccount) bool) []*v1.ServiceAccount {
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.ServiceAccount)
return ret0
}
func (mr *MockServiceAccountSetMockRecorder) UnsortedList(filterResource ...interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "UnsortedList", reflect.TypeOf((*MockServiceAccountSet)(nil).UnsortedList), filterResource...)
}
func (m *MockServiceAccountSet) Map() map[string]*v1.ServiceAccount {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "Map")
ret0, _ := ret[0].(map[string]*v1.ServiceAccount)
return ret0
}
func (mr *MockServiceAccountSetMockRecorder) Map() *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Map", reflect.TypeOf((*MockServiceAccountSet)(nil).Map))
}
func (m *MockServiceAccountSet) Insert(serviceAccount ...*v1.ServiceAccount) {
m.ctrl.T.Helper()
varargs := []interface{}{}
for _, a := range serviceAccount {
varargs = append(varargs, a)
}
m.ctrl.Call(m, "Insert", varargs...)
}
func (mr *MockServiceAccountSetMockRecorder) Insert(serviceAccount ...interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Insert", reflect.TypeOf((*MockServiceAccountSet)(nil).Insert), serviceAccount...)
}
func (m *MockServiceAccountSet) Equal(serviceAccountSet v1sets.ServiceAccountSet) bool {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "Equal", serviceAccountSet)
ret0, _ := ret[0].(bool)
return ret0
}
func (mr *MockServiceAccountSetMockRecorder) Equal(serviceAccountSet interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Equal", reflect.TypeOf((*MockServiceAccountSet)(nil).Equal), serviceAccountSet)
} | Apache License 2.0 |
containerbuilding/cbi | vendor/k8s.io/api/authentication/v1/zz_generated.deepcopy.go | DeepCopyInto | go | func (in *UserInfo) DeepCopyInto(out *UserInfo) {
*out = *in
if in.Groups != nil {
in, out := &in.Groups, &out.Groups
*out = make([]string, len(*in))
copy(*out, *in)
}
if in.Extra != nil {
in, out := &in.Extra, &out.Extra
*out = make(map[string]ExtraValue, len(*in))
for key, val := range *in {
if val == nil {
(*out)[key] = nil
} else {
(*out)[key] = make([]string, len(val))
copy((*out)[key], val)
}
}
}
return
} | DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. | https://github.com/containerbuilding/cbi/blob/1f3ccebc2b71abfa108e48071bf1009e5f68016c/vendor/k8s.io/api/authentication/v1/zz_generated.deepcopy.go#L209-L229 | package v1
import (
runtime "k8s.io/apimachinery/pkg/runtime"
)
func (in *BoundObjectReference) DeepCopyInto(out *BoundObjectReference) {
*out = *in
return
}
func (in *BoundObjectReference) DeepCopy() *BoundObjectReference {
if in == nil {
return nil
}
out := new(BoundObjectReference)
in.DeepCopyInto(out)
return out
}
func (in ExtraValue) DeepCopyInto(out *ExtraValue) {
{
in := &in
*out = make(ExtraValue, len(*in))
copy(*out, *in)
return
}
}
func (in ExtraValue) DeepCopy() ExtraValue {
if in == nil {
return nil
}
out := new(ExtraValue)
in.DeepCopyInto(out)
return *out
}
func (in *TokenRequest) DeepCopyInto(out *TokenRequest) {
*out = *in
out.TypeMeta = in.TypeMeta
in.ObjectMeta.DeepCopyInto(&out.ObjectMeta)
in.Spec.DeepCopyInto(&out.Spec)
in.Status.DeepCopyInto(&out.Status)
return
}
func (in *TokenRequest) DeepCopy() *TokenRequest {
if in == nil {
return nil
}
out := new(TokenRequest)
in.DeepCopyInto(out)
return out
}
func (in *TokenRequest) DeepCopyObject() runtime.Object {
if c := in.DeepCopy(); c != nil {
return c
}
return nil
}
func (in *TokenRequestSpec) DeepCopyInto(out *TokenRequestSpec) {
*out = *in
if in.Audiences != nil {
in, out := &in.Audiences, &out.Audiences
*out = make([]string, len(*in))
copy(*out, *in)
}
if in.ExpirationSeconds != nil {
in, out := &in.ExpirationSeconds, &out.ExpirationSeconds
if *in == nil {
*out = nil
} else {
*out = new(int64)
**out = **in
}
}
if in.BoundObjectRef != nil {
in, out := &in.BoundObjectRef, &out.BoundObjectRef
if *in == nil {
*out = nil
} else {
*out = new(BoundObjectReference)
**out = **in
}
}
return
}
func (in *TokenRequestSpec) DeepCopy() *TokenRequestSpec {
if in == nil {
return nil
}
out := new(TokenRequestSpec)
in.DeepCopyInto(out)
return out
}
func (in *TokenRequestStatus) DeepCopyInto(out *TokenRequestStatus) {
*out = *in
in.ExpirationTimestamp.DeepCopyInto(&out.ExpirationTimestamp)
return
}
func (in *TokenRequestStatus) DeepCopy() *TokenRequestStatus {
if in == nil {
return nil
}
out := new(TokenRequestStatus)
in.DeepCopyInto(out)
return out
}
func (in *TokenReview) DeepCopyInto(out *TokenReview) {
*out = *in
out.TypeMeta = in.TypeMeta
in.ObjectMeta.DeepCopyInto(&out.ObjectMeta)
out.Spec = in.Spec
in.Status.DeepCopyInto(&out.Status)
return
}
func (in *TokenReview) DeepCopy() *TokenReview {
if in == nil {
return nil
}
out := new(TokenReview)
in.DeepCopyInto(out)
return out
}
func (in *TokenReview) DeepCopyObject() runtime.Object {
if c := in.DeepCopy(); c != nil {
return c
}
return nil
}
func (in *TokenReviewSpec) DeepCopyInto(out *TokenReviewSpec) {
*out = *in
return
}
func (in *TokenReviewSpec) DeepCopy() *TokenReviewSpec {
if in == nil {
return nil
}
out := new(TokenReviewSpec)
in.DeepCopyInto(out)
return out
}
func (in *TokenReviewStatus) DeepCopyInto(out *TokenReviewStatus) {
*out = *in
in.User.DeepCopyInto(&out.User)
return
}
func (in *TokenReviewStatus) DeepCopy() *TokenReviewStatus {
if in == nil {
return nil
}
out := new(TokenReviewStatus)
in.DeepCopyInto(out)
return out
} | Apache License 2.0 |
opensearch-project/opensearch-go | opensearchapi/api.cat.nodes.go | WithFilterPath | go | func (f CatNodes) WithFilterPath(v ...string) func(*CatNodesRequest) {
return func(r *CatNodesRequest) {
r.FilterPath = v
}
} | WithFilterPath filters the properties of the response body. | https://github.com/opensearch-project/opensearch-go/blob/fb1709a85d8d92ab3fcd153d54a561965e9c4f36/opensearchapi/api.cat.nodes.go#L320-L324 | package opensearchapi
import (
"context"
"net/http"
"strconv"
"strings"
"time"
)
func newCatNodesFunc(t Transport) CatNodes {
return func(o ...func(*CatNodesRequest)) (*Response, error) {
var r = CatNodesRequest{}
for _, f := range o {
f(&r)
}
return r.Do(r.ctx, t)
}
}
type CatNodes func(o ...func(*CatNodesRequest)) (*Response, error)
type CatNodesRequest struct {
Bytes string
Format string
FullID *bool
H []string
Help *bool
IncludeUnloadedSegments *bool
Local *bool
MasterTimeout time.Duration
S []string
Time string
V *bool
Pretty bool
Human bool
ErrorTrace bool
FilterPath []string
Header http.Header
ctx context.Context
}
func (r CatNodesRequest) Do(ctx context.Context, transport Transport) (*Response, error) {
var (
method string
path strings.Builder
params map[string]string
)
method = "GET"
path.Grow(len("/_cat/nodes"))
path.WriteString("/_cat/nodes")
params = make(map[string]string)
if r.Bytes != "" {
params["bytes"] = r.Bytes
}
if r.Format != "" {
params["format"] = r.Format
}
if r.FullID != nil {
params["full_id"] = strconv.FormatBool(*r.FullID)
}
if len(r.H) > 0 {
params["h"] = strings.Join(r.H, ",")
}
if r.Help != nil {
params["help"] = strconv.FormatBool(*r.Help)
}
if r.IncludeUnloadedSegments != nil {
params["include_unloaded_segments"] = strconv.FormatBool(*r.IncludeUnloadedSegments)
}
if r.Local != nil {
params["local"] = strconv.FormatBool(*r.Local)
}
if r.MasterTimeout != 0 {
params["master_timeout"] = formatDuration(r.MasterTimeout)
}
if len(r.S) > 0 {
params["s"] = strings.Join(r.S, ",")
}
if r.Time != "" {
params["time"] = r.Time
}
if r.V != nil {
params["v"] = strconv.FormatBool(*r.V)
}
if r.Pretty {
params["pretty"] = "true"
}
if r.Human {
params["human"] = "true"
}
if r.ErrorTrace {
params["error_trace"] = "true"
}
if len(r.FilterPath) > 0 {
params["filter_path"] = strings.Join(r.FilterPath, ",")
}
req, err := newRequest(method, path.String(), nil)
if err != nil {
return nil, err
}
if len(params) > 0 {
q := req.URL.Query()
for k, v := range params {
q.Set(k, v)
}
req.URL.RawQuery = q.Encode()
}
if len(r.Header) > 0 {
if len(req.Header) == 0 {
req.Header = r.Header
} else {
for k, vv := range r.Header {
for _, v := range vv {
req.Header.Add(k, v)
}
}
}
}
if ctx != nil {
req = req.WithContext(ctx)
}
res, err := transport.Perform(req)
if err != nil {
return nil, err
}
response := Response{
StatusCode: res.StatusCode,
Body: res.Body,
Header: res.Header,
}
return &response, nil
}
func (f CatNodes) WithContext(v context.Context) func(*CatNodesRequest) {
return func(r *CatNodesRequest) {
r.ctx = v
}
}
func (f CatNodes) WithBytes(v string) func(*CatNodesRequest) {
return func(r *CatNodesRequest) {
r.Bytes = v
}
}
func (f CatNodes) WithFormat(v string) func(*CatNodesRequest) {
return func(r *CatNodesRequest) {
r.Format = v
}
}
func (f CatNodes) WithFullID(v bool) func(*CatNodesRequest) {
return func(r *CatNodesRequest) {
r.FullID = &v
}
}
func (f CatNodes) WithH(v ...string) func(*CatNodesRequest) {
return func(r *CatNodesRequest) {
r.H = v
}
}
func (f CatNodes) WithHelp(v bool) func(*CatNodesRequest) {
return func(r *CatNodesRequest) {
r.Help = &v
}
}
func (f CatNodes) WithIncludeUnloadedSegments(v bool) func(*CatNodesRequest) {
return func(r *CatNodesRequest) {
r.IncludeUnloadedSegments = &v
}
}
func (f CatNodes) WithLocal(v bool) func(*CatNodesRequest) {
return func(r *CatNodesRequest) {
r.Local = &v
}
}
func (f CatNodes) WithMasterTimeout(v time.Duration) func(*CatNodesRequest) {
return func(r *CatNodesRequest) {
r.MasterTimeout = v
}
}
func (f CatNodes) WithS(v ...string) func(*CatNodesRequest) {
return func(r *CatNodesRequest) {
r.S = v
}
}
func (f CatNodes) WithTime(v string) func(*CatNodesRequest) {
return func(r *CatNodesRequest) {
r.Time = v
}
}
func (f CatNodes) WithV(v bool) func(*CatNodesRequest) {
return func(r *CatNodesRequest) {
r.V = &v
}
}
func (f CatNodes) WithPretty() func(*CatNodesRequest) {
return func(r *CatNodesRequest) {
r.Pretty = true
}
}
func (f CatNodes) WithHuman() func(*CatNodesRequest) {
return func(r *CatNodesRequest) {
r.Human = true
}
}
func (f CatNodes) WithErrorTrace() func(*CatNodesRequest) {
return func(r *CatNodesRequest) {
r.ErrorTrace = true
}
} | Apache License 2.0 |
gopasspw/gopass | internal/action/binary.go | binaryCopy | go | func (s *Action) binaryCopy(ctx context.Context, c *cli.Context, from, to string, deleteSource bool) error {
if from == "" || to == "" {
op := "copy"
if deleteSource {
op = "move"
}
return fmt.Errorf("usage: %s fs%s from to", c.App.Name, op)
}
switch {
case fsutil.IsFile(from) && fsutil.IsFile(to):
return fmt.Errorf("ambiguity detected. Only from or to can be a file")
case s.Store.Exists(ctx, from) && s.Store.Exists(ctx, to):
return fmt.Errorf("ambiguity detected. Either from or to must be a file")
case fsutil.IsFile(from) && !fsutil.IsFile(to):
return s.binaryCopyFromFileToStore(ctx, from, to, deleteSource)
case !fsutil.IsFile(from):
return s.binaryCopyFromStoreToFile(ctx, from, to, deleteSource)
default:
return fmt.Errorf("ambiguity detected. Unhandled case. Please report a bug")
}
} | binaryCopy implements the control flow for copy and move. We support two
workflows:
1. From the filesystem to the store
2. From the store to the filesystem
Copying secrets in the store must be done through the regular copy command | https://github.com/gopasspw/gopass/blob/a4ee6a191c07429a07fc2bf1be83866d07c00868/internal/action/binary.go#L117-L140 | package action
import (
"bytes"
"context"
"crypto/sha256"
"encoding/base64"
"fmt"
"io"
"os"
"path/filepath"
"github.com/gopasspw/gopass/internal/out"
"github.com/gopasspw/gopass/pkg/ctxutil"
"github.com/gopasspw/gopass/pkg/debug"
"github.com/gopasspw/gopass/pkg/fsutil"
"github.com/gopasspw/gopass/pkg/gopass"
"github.com/gopasspw/gopass/pkg/gopass/secrets"
"github.com/urfave/cli/v2"
)
var (
binstdin = os.Stdin
)
func (s *Action) Cat(c *cli.Context) error {
ctx := ctxutil.WithGlobalFlags(c)
name := c.Args().First()
if name == "" {
return ExitError(ExitNoName, nil, "Usage: %s cat <NAME>", c.App.Name)
}
info, err := binstdin.Stat()
if err != nil {
return ExitError(ExitIO, err, "failed to stat stdin: %s", err)
}
if info.Mode()&os.ModeCharDevice == 0 {
debug.Log("Reading from STDIN ...")
content := &bytes.Buffer{}
if written, err := io.Copy(content, binstdin); err != nil {
return ExitError(ExitIO, err, "Failed to copy after %d bytes: %s", written, err)
}
return s.Store.Set(
ctxutil.WithCommitMessage(ctx, "Read secret from STDIN"),
name,
secFromBytes(name, "STDIN", content.Bytes()),
)
}
buf, err := s.binaryGet(ctx, name)
if err != nil {
return ExitError(ExitDecrypt, err, "failed to read secret: %s", err)
}
fmt.Fprint(stdout, string(buf))
return nil
}
func secFromBytes(dst, src string, in []byte) gopass.Secret {
debug.Log("Read %d bytes from %s to %s", len(in), src, dst)
sec := secrets.NewKV()
if err := sec.Set("Content-Disposition", fmt.Sprintf("attachment; filename=\"%s\"", filepath.Base(src))); err != nil {
debug.Log("Failed to set Content-Disposition: %q", err)
}
sec.Write([]byte(base64.StdEncoding.EncodeToString(in)))
if err := sec.Set("Content-Transfer-Encoding", "Base64"); err != nil {
debug.Log("Failed to set Content-Transfer-Encoding: %q", err)
}
return sec
}
func (s *Action) BinaryCopy(c *cli.Context) error {
ctx := ctxutil.WithGlobalFlags(c)
from := c.Args().Get(0)
to := c.Args().Get(1)
if err := s.binaryCopy(ctx, c, from, to, false); err != nil {
return ExitError(ExitUnknown, err, "%s", err)
}
return nil
}
func (s *Action) BinaryMove(c *cli.Context) error {
ctx := ctxutil.WithGlobalFlags(c)
from := c.Args().Get(0)
to := c.Args().Get(1)
if err := s.binaryCopy(ctx, c, from, to, true); err != nil {
return ExitError(ExitUnknown, err, "%s", err)
}
return nil
} | MIT License |
openaccounting/oa-server | vendor/github.com/ant0ine/go-json-rest/rest/access_log_apache.go | ApacheRemoteAddr | go | func (u *accessLogUtil) ApacheRemoteAddr() string {
remoteAddr := u.R.RemoteAddr
if remoteAddr != "" {
if ip, _, err := net.SplitHostPort(remoteAddr); err == nil {
return ip
}
}
return ""
} | If remoteAddr is set then return is without the port number, apache log style. | https://github.com/openaccounting/oa-server/blob/4821cbca623f3439a37a7ee6965a287fc6fb59c6/vendor/github.com/ant0ine/go-json-rest/rest/access_log_apache.go#L199-L207 | package rest
import (
"bytes"
"fmt"
"log"
"net"
"os"
"strings"
"text/template"
"time"
)
type AccessLogFormat string
const (
CommonLogFormat = "%h %l %u %t \"%r\" %s %b"
CombinedLogFormat = "%h %l %u %t \"%r\" %s %b \"%{Referer}i\" \"%{User-Agent}i\""
DefaultLogFormat = "%t %S\033[0m \033[36;1m%Dμs\033[0m \"%r\" \033[1;30m%u \"%{User-Agent}i\"\033[0m"
)
type AccessLogApacheMiddleware struct {
Logger *log.Logger
Format AccessLogFormat
textTemplate *template.Template
}
func (mw *AccessLogApacheMiddleware) MiddlewareFunc(h HandlerFunc) HandlerFunc {
if mw.Logger == nil {
mw.Logger = log.New(os.Stderr, "", 0)
}
if mw.Format == "" {
mw.Format = DefaultLogFormat
}
mw.convertFormat()
return func(w ResponseWriter, r *Request) {
h(w, r)
util := &accessLogUtil{w, r}
mw.Logger.Print(mw.executeTextTemplate(util))
}
}
var apacheAdapter = strings.NewReplacer(
"%b", "{{.BytesWritten | dashIf0}}",
"%B", "{{.BytesWritten}}",
"%D", "{{.ResponseTime | microseconds}}",
"%h", "{{.ApacheRemoteAddr}}",
"%H", "{{.R.Proto}}",
"%l", "-",
"%m", "{{.R.Method}}",
"%P", "{{.Pid}}",
"%q", "{{.ApacheQueryString}}",
"%r", "{{.R.Method}} {{.R.URL.RequestURI}} {{.R.Proto}}",
"%s", "{{.StatusCode}}",
"%S", "\033[{{.StatusCode | statusCodeColor}}m{{.StatusCode}}",
"%t", "{{if .StartTime}}{{.StartTime.Format \"02/Jan/2006:15:04:05 -0700\"}}{{end}}",
"%T", "{{if .ResponseTime}}{{.ResponseTime.Seconds | printf \"%.3f\"}}{{end}}",
"%u", "{{.RemoteUser | dashIfEmptyStr}}",
"%{User-Agent}i", "{{.R.UserAgent | dashIfEmptyStr}}",
"%{Referer}i", "{{.R.Referer | dashIfEmptyStr}}",
)
func (mw *AccessLogApacheMiddleware) convertFormat() {
tmplText := apacheAdapter.Replace(string(mw.Format))
funcMap := template.FuncMap{
"dashIfEmptyStr": func(value string) string {
if value == "" {
return "-"
}
return value
},
"dashIf0": func(value int64) string {
if value == 0 {
return "-"
}
return fmt.Sprintf("%d", value)
},
"microseconds": func(dur *time.Duration) string {
if dur != nil {
return fmt.Sprintf("%d", dur.Nanoseconds()/1000)
}
return ""
},
"statusCodeColor": func(statusCode int) string {
if statusCode >= 400 && statusCode < 500 {
return "1;33"
} else if statusCode >= 500 {
return "0;31"
}
return "0;32"
},
}
var err error
mw.textTemplate, err = template.New("accessLog").Funcs(funcMap).Parse(tmplText)
if err != nil {
panic(err)
}
}
func (mw *AccessLogApacheMiddleware) executeTextTemplate(util *accessLogUtil) string {
buf := bytes.NewBufferString("")
err := mw.textTemplate.Execute(buf, util)
if err != nil {
panic(err)
}
return buf.String()
}
type accessLogUtil struct {
W ResponseWriter
R *Request
}
func (u *accessLogUtil) RemoteUser() string {
if u.R.Env["REMOTE_USER"] != nil {
return u.R.Env["REMOTE_USER"].(string)
}
return ""
}
func (u *accessLogUtil) ApacheQueryString() string {
if u.R.URL.RawQuery != "" {
return "?" + u.R.URL.RawQuery
}
return ""
}
func (u *accessLogUtil) StartTime() *time.Time {
if u.R.Env["START_TIME"] != nil {
return u.R.Env["START_TIME"].(*time.Time)
}
return nil
} | MIT License |
crazy-max/diun | internal/msg/client.go | New | go | func New(opts Options) (*Client, error) {
return &Client{
opts,
}, nil
} | New initializes a new msg client | https://github.com/crazy-max/diun/blob/fa8137d28aa2b4b9feedc86d2f2b737d1bae4ad9/internal/msg/client.go#L33-L37 | package msg
import (
"bytes"
"encoding/json"
"fmt"
"strings"
"text/template"
"time"
"github.com/crazy-max/diun/v4/internal/model"
"github.com/microcosm-cc/bluemonday"
"github.com/opencontainers/go-digest"
"github.com/pkg/errors"
"github.com/russross/blackfriday/v2"
)
type Client struct {
opts Options
}
type Options struct {
Meta model.Meta
Entry model.NotifEntry
TemplateTitle string
TemplateBody string
TemplateFuncs template.FuncMap
} | MIT License |
containerbuilding/cbi | vendor/k8s.io/client-go/kubernetes/typed/batch/v2alpha1/batch_client.go | RESTClient | go | func (c *BatchV2alpha1Client) RESTClient() rest.Interface {
if c == nil {
return nil
}
return c.restClient
} | RESTClient returns a RESTClient that is used to communicate
with API server by this client implementation. | https://github.com/containerbuilding/cbi/blob/1f3ccebc2b71abfa108e48071bf1009e5f68016c/vendor/k8s.io/client-go/kubernetes/typed/batch/v2alpha1/batch_client.go#L85-L90 | package v2alpha1
import (
v2alpha1 "k8s.io/api/batch/v2alpha1"
serializer "k8s.io/apimachinery/pkg/runtime/serializer"
"k8s.io/client-go/kubernetes/scheme"
rest "k8s.io/client-go/rest"
)
type BatchV2alpha1Interface interface {
RESTClient() rest.Interface
CronJobsGetter
}
type BatchV2alpha1Client struct {
restClient rest.Interface
}
func (c *BatchV2alpha1Client) CronJobs(namespace string) CronJobInterface {
return newCronJobs(c, namespace)
}
func NewForConfig(c *rest.Config) (*BatchV2alpha1Client, error) {
config := *c
if err := setConfigDefaults(&config); err != nil {
return nil, err
}
client, err := rest.RESTClientFor(&config)
if err != nil {
return nil, err
}
return &BatchV2alpha1Client{client}, nil
}
func NewForConfigOrDie(c *rest.Config) *BatchV2alpha1Client {
client, err := NewForConfig(c)
if err != nil {
panic(err)
}
return client
}
func New(c rest.Interface) *BatchV2alpha1Client {
return &BatchV2alpha1Client{c}
}
func setConfigDefaults(config *rest.Config) error {
gv := v2alpha1.SchemeGroupVersion
config.GroupVersion = &gv
config.APIPath = "/apis"
config.NegotiatedSerializer = serializer.DirectCodecFactory{CodecFactory: scheme.Codecs}
if config.UserAgent == "" {
config.UserAgent = rest.DefaultKubernetesUserAgent()
}
return nil
} | Apache License 2.0 |
nccloud/fluid | internal/ingress/controller/template/template.go | buildResolvers | go | func buildResolvers(res interface{}, disableIpv6 interface{}) string {
nss, ok := res.([]net.IP)
if !ok {
glog.Errorf("expected a '[]net.IP' type but %T was returned", res)
return ""
}
no6, ok := disableIpv6.(bool)
if !ok {
glog.Errorf("expected a 'bool' type but %T was returned", disableIpv6)
return ""
}
if len(nss) == 0 {
return ""
}
r := []string{"resolver"}
for _, ns := range nss {
if ing_net.IsIPV6(ns) {
if no6 {
continue
}
r = append(r, fmt.Sprintf("[%v]", ns))
} else {
r = append(r, fmt.Sprintf("%v", ns))
}
}
r = append(r, "valid=30s")
if no6 {
r = append(r, "ipv6=off")
}
return strings.Join(r, " ") + ";"
} | buildResolvers returns the resolvers reading the /etc/resolv.conf file | https://github.com/nccloud/fluid/blob/1167665ac94e07c04ad868381192090a2b51679b/internal/ingress/controller/template/template.go#L169-L204 | package template
import (
"bytes"
"encoding/base64"
"encoding/json"
"fmt"
"math/rand"
"net"
"net/url"
"os"
"os/exec"
"strconv"
"strings"
text_template "text/template"
"time"
"github.com/golang/glog"
"github.com/pkg/errors"
"github.com/NCCloud/fluid/internal/file"
"github.com/NCCloud/fluid/internal/ingress"
"github.com/NCCloud/fluid/internal/ingress/annotations/ratelimit"
"github.com/NCCloud/fluid/internal/ingress/controller/config"
ing_net "github.com/NCCloud/fluid/internal/net"
extensions "k8s.io/api/extensions/v1beta1"
"k8s.io/apimachinery/pkg/util/sets"
)
const (
slash = "/"
nonIdempotent = "non_idempotent"
defBufferSize = 65535
)
type Template struct {
tmpl *text_template.Template
bp *BufferPool
}
func NewTemplate(file string, fs file.Filesystem) (*Template, error) {
data, err := fs.ReadFile(file)
if err != nil {
return nil, errors.Wrapf(err, "unexpected error reading template %v", file)
}
tmpl, err := text_template.New("nginx.tmpl").Funcs(funcMap).Parse(string(data))
if err != nil {
return nil, err
}
return &Template{
tmpl: tmpl,
bp: NewBufferPool(defBufferSize),
}, nil
}
func (t *Template) Write(conf config.TemplateConfig) ([]byte, error) {
tmplBuf := t.bp.Get()
defer t.bp.Put(tmplBuf)
outCmdBuf := t.bp.Get()
defer t.bp.Put(outCmdBuf)
if glog.V(3) {
b, err := json.Marshal(conf)
if err != nil {
glog.Errorf("unexpected error: %v", err)
}
glog.Infof("NGINX configuration: %v", string(b))
}
err := t.tmpl.Execute(tmplBuf, conf)
if err != nil {
return nil, err
}
cmd := exec.Command("/ingress-controller/clean-nginx-conf.sh")
cmd.Stdin = tmplBuf
cmd.Stdout = outCmdBuf
if err := cmd.Run(); err != nil {
glog.Warningf("unexpected error cleaning template: %v", err)
return tmplBuf.Bytes(), nil
}
return outCmdBuf.Bytes(), nil
}
var (
funcMap = text_template.FuncMap{
"empty": func(input interface{}) bool {
check, ok := input.(string)
if ok {
return len(check) == 0
}
return true
},
"buildLocation": buildLocation,
"buildAuthLocation": buildAuthLocation,
"buildAuthResponseHeaders": buildAuthResponseHeaders,
"filterRateLimits": filterRateLimits,
"buildRateLimitZones": buildRateLimitZones,
"buildRateLimit": buildRateLimit,
"buildResolvers": buildResolvers,
"buildUpstreamName": buildUpstreamName,
"isLocationInLocationList": isLocationInLocationList,
"isLocationAllowed": isLocationAllowed,
"buildLogFormatUpstream": buildLogFormatUpstream,
"buildDenyVariable": buildDenyVariable,
"getenv": os.Getenv,
"contains": strings.Contains,
"hasPrefix": strings.HasPrefix,
"hasSuffix": strings.HasSuffix,
"toUpper": strings.ToUpper,
"toLower": strings.ToLower,
"formatIP": formatIP,
"buildNextUpstream": buildNextUpstream,
"getIngressInformation": getIngressInformation,
"serverConfig": func(all config.TemplateConfig, server *ingress.Server) interface{} {
return struct{ First, Second interface{} }{all, server}
},
"isValidClientBodyBufferSize": isValidClientBodyBufferSize,
"buildForwardedFor": buildForwardedFor,
"buildAuthSignURL": buildAuthSignURL,
"buildOpentracingLoad": buildOpentracingLoad,
"buildOpentracing": buildOpentracing,
}
)
func formatIP(input string) string {
ip := net.ParseIP(input)
if ip == nil {
return input
}
if v4 := ip.To4(); v4 != nil {
return input
}
return fmt.Sprintf("[%s]", input)
} | Apache License 2.0 |
victorkt/flaggio | internal/operator/contains.go | DoesntContain | go | func DoesntContain(usrValue interface{}, validValues []interface{}) (bool, error) {
for _, v := range validValues {
ok, err := contains(v, usrValue)
if err != nil {
return false, err
}
if ok {
return false, nil
}
}
return true, nil
} | DoesntContain operator will check if the value from the user context doesn't contain
any of the configured values on the flag. | https://github.com/victorkt/flaggio/blob/4c7acbcf677309e29614612bc5b4f26ab201ec21/internal/operator/contains.go#L25-L36 | package operator
import (
"errors"
"strings"
)
func Contains(usrValue interface{}, validValues []interface{}) (bool, error) {
for _, v := range validValues {
ok, err := contains(v, usrValue)
if err != nil {
return false, err
}
if ok {
return true, nil
}
}
return false, nil
} | Apache License 2.0 |
asutorufa/yuhaiin | internal/config/setting.go | SettingDecodeJSON | go | func SettingDecodeJSON(dir string) (*Setting, error) {
pa := &Setting{
SystemProxy: &SystemProxy{
HTTP: true,
Socks5: false,
},
Bypass: &Bypass{
Enabled: true,
BypassFile: path.Join(dir, "yuhaiin.conf"),
},
Proxy: &Proxy{
HTTP: "127.0.0.1:8188",
Socks5: "127.0.0.1:1080",
Redir: "127.0.0.1:8088",
},
Dns: &DnsSetting{
Remote: &DNS{
Host: "cloudflare-dns.com",
Type: DNS_doh,
Proxy: false,
Subnet: "0.0.0.0/32",
},
Local: &DNS{
Host: "223.5.5.5",
Type: DNS_doh,
},
},
}
data, err := ioutil.ReadFile(filepath.Join(dir, "yuhaiinConfig.json"))
if err != nil {
if os.IsNotExist(err) {
return pa, SettingEnCodeJSON(pa, dir)
}
return pa, fmt.Errorf("read config file failed: %v", err)
}
err = protojson.UnmarshalOptions{DiscardUnknown: true}.Unmarshal(data, pa)
return pa, err
} | SettingDecodeJSON decode setting json to struct | https://github.com/asutorufa/yuhaiin/blob/39fd8693d2e541aab0f21e0cbaa0a6b0d455060e/internal/config/setting.go#L17-L56 | package config
import (
context "context"
"fmt"
"io/ioutil"
"os"
"path"
"path/filepath"
"sync"
"google.golang.org/protobuf/encoding/protojson"
emptypb "google.golang.org/protobuf/types/known/emptypb"
) | MIT License |
git-lfs/lfs-test-server | vendor/github.com/boltdb/bolt/tx.go | WriteTo | go | func (tx *Tx) WriteTo(w io.Writer) (n int64, err error) {
var f *os.File
if f, err = os.OpenFile(tx.db.path, os.O_RDONLY|odirect, 0); err != nil {
if f, err = os.OpenFile(tx.db.path, os.O_RDONLY, 0); err != nil {
return 0, err
}
}
tx.db.metalock.Lock()
n, err = io.CopyN(w, f, int64(tx.db.pageSize*2))
tx.db.metalock.Unlock()
if err != nil {
_ = f.Close()
return n, fmt.Errorf("meta copy: %s", err)
}
wn, err := io.CopyN(w, f, tx.Size()-int64(tx.db.pageSize*2))
n += wn
if err != nil {
_ = f.Close()
return n, err
}
return n, f.Close()
} | WriteTo writes the entire database to a writer.
If err == nil then exactly tx.Size() bytes will be written into the writer. | https://github.com/git-lfs/lfs-test-server/blob/74a6f6dd62b093ad266097be49e118030f5fe827/vendor/github.com/boltdb/bolt/tx.go#L263-L291 | package bolt
import (
"fmt"
"io"
"os"
"sort"
"time"
"unsafe"
)
type txid uint64
type Tx struct {
writable bool
managed bool
db *DB
meta *meta
root Bucket
pages map[pgid]*page
stats TxStats
commitHandlers []func()
}
func (tx *Tx) init(db *DB) {
tx.db = db
tx.pages = nil
tx.meta = &meta{}
db.meta().copy(tx.meta)
tx.root = newBucket(tx)
tx.root.bucket = &bucket{}
*tx.root.bucket = tx.meta.root
if tx.writable {
tx.pages = make(map[pgid]*page)
tx.meta.txid += txid(1)
}
}
func (tx *Tx) ID() int {
return int(tx.meta.txid)
}
func (tx *Tx) DB() *DB {
return tx.db
}
func (tx *Tx) Size() int64 {
return int64(tx.meta.pgid) * int64(tx.db.pageSize)
}
func (tx *Tx) Writable() bool {
return tx.writable
}
func (tx *Tx) Cursor() *Cursor {
return tx.root.Cursor()
}
func (tx *Tx) Stats() TxStats {
return tx.stats
}
func (tx *Tx) Bucket(name []byte) *Bucket {
return tx.root.Bucket(name)
}
func (tx *Tx) CreateBucket(name []byte) (*Bucket, error) {
return tx.root.CreateBucket(name)
}
func (tx *Tx) CreateBucketIfNotExists(name []byte) (*Bucket, error) {
return tx.root.CreateBucketIfNotExists(name)
}
func (tx *Tx) DeleteBucket(name []byte) error {
return tx.root.DeleteBucket(name)
}
func (tx *Tx) ForEach(fn func(name []byte, b *Bucket) error) error {
return tx.root.ForEach(func(k, v []byte) error {
if err := fn(k, tx.root.Bucket(k)); err != nil {
return err
}
return nil
})
}
func (tx *Tx) OnCommit(fn func()) {
tx.commitHandlers = append(tx.commitHandlers, fn)
}
func (tx *Tx) Commit() error {
_assert(!tx.managed, "managed tx commit not allowed")
if tx.db == nil {
return ErrTxClosed
} else if !tx.writable {
return ErrTxNotWritable
}
var startTime = time.Now()
tx.root.rebalance()
if tx.stats.Rebalance > 0 {
tx.stats.RebalanceTime += time.Since(startTime)
}
startTime = time.Now()
if err := tx.root.spill(); err != nil {
tx.rollback()
return err
}
tx.stats.SpillTime += time.Since(startTime)
tx.meta.root.root = tx.root.root
tx.db.freelist.free(tx.meta.txid, tx.db.page(tx.meta.freelist))
p, err := tx.allocate((tx.db.freelist.size() / tx.db.pageSize) + 1)
if err != nil {
tx.rollback()
return err
}
if err := tx.db.freelist.write(p); err != nil {
tx.rollback()
return err
}
tx.meta.freelist = p.id
startTime = time.Now()
if err := tx.write(); err != nil {
tx.rollback()
return err
}
if tx.db.StrictMode {
if err, ok := <-tx.Check(); ok {
panic("check fail: " + err.Error())
}
}
if err := tx.writeMeta(); err != nil {
tx.rollback()
return err
}
tx.stats.WriteTime += time.Since(startTime)
tx.close()
for _, fn := range tx.commitHandlers {
fn()
}
return nil
}
func (tx *Tx) Rollback() error {
_assert(!tx.managed, "managed tx rollback not allowed")
if tx.db == nil {
return ErrTxClosed
}
tx.rollback()
return nil
}
func (tx *Tx) rollback() {
if tx.db == nil {
return
}
if tx.writable {
tx.db.freelist.rollback(tx.meta.txid)
tx.db.freelist.reload(tx.db.page(tx.db.meta().freelist))
}
tx.close()
}
func (tx *Tx) close() {
if tx.db == nil {
return
}
if tx.writable {
var freelistFreeN = tx.db.freelist.free_count()
var freelistPendingN = tx.db.freelist.pending_count()
var freelistAlloc = tx.db.freelist.size()
tx.db.rwlock.Unlock()
tx.db.statlock.Lock()
tx.db.stats.FreePageN = freelistFreeN
tx.db.stats.PendingPageN = freelistPendingN
tx.db.stats.FreeAlloc = (freelistFreeN + freelistPendingN) * tx.db.pageSize
tx.db.stats.FreelistInuse = freelistAlloc
tx.db.stats.TxStats.add(&tx.stats)
tx.db.statlock.Unlock()
} else {
tx.db.removeTx(tx)
}
tx.db = nil
}
func (tx *Tx) Copy(w io.Writer) error {
_, err := tx.WriteTo(w)
return err
} | MIT License |
ent/contrib | entproto/internal/todo/ent/group_update.go | Select | go | func (guo *GroupUpdateOne) Select(field string, fields ...string) *GroupUpdateOne {
guo.fields = append([]string{field}, fields...)
return guo
} | Select allows selecting one or more fields (columns) of the returned entity.
The default is selecting all fields defined in the entity schema. | https://github.com/ent/contrib/blob/2f98d3a15e7dfcc96aa696a5aceb0c8b1249f9e4/entproto/internal/todo/ent/group_update.go#L278-L281 | package ent
import (
"context"
"fmt"
"entgo.io/contrib/entproto/internal/todo/ent/group"
"entgo.io/contrib/entproto/internal/todo/ent/predicate"
"entgo.io/contrib/entproto/internal/todo/ent/user"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field"
)
type GroupUpdate struct {
config
hooks []Hook
mutation *GroupMutation
}
func (gu *GroupUpdate) Where(ps ...predicate.Group) *GroupUpdate {
gu.mutation.Where(ps...)
return gu
}
func (gu *GroupUpdate) SetName(s string) *GroupUpdate {
gu.mutation.SetName(s)
return gu
}
func (gu *GroupUpdate) AddUserIDs(ids ...int) *GroupUpdate {
gu.mutation.AddUserIDs(ids...)
return gu
}
func (gu *GroupUpdate) AddUsers(u ...*User) *GroupUpdate {
ids := make([]int, len(u))
for i := range u {
ids[i] = u[i].ID
}
return gu.AddUserIDs(ids...)
}
func (gu *GroupUpdate) Mutation() *GroupMutation {
return gu.mutation
}
func (gu *GroupUpdate) ClearUsers() *GroupUpdate {
gu.mutation.ClearUsers()
return gu
}
func (gu *GroupUpdate) RemoveUserIDs(ids ...int) *GroupUpdate {
gu.mutation.RemoveUserIDs(ids...)
return gu
}
func (gu *GroupUpdate) RemoveUsers(u ...*User) *GroupUpdate {
ids := make([]int, len(u))
for i := range u {
ids[i] = u[i].ID
}
return gu.RemoveUserIDs(ids...)
}
func (gu *GroupUpdate) Save(ctx context.Context) (int, error) {
var (
err error
affected int
)
if len(gu.hooks) == 0 {
affected, err = gu.sqlSave(ctx)
} else {
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
mutation, ok := m.(*GroupMutation)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T", m)
}
gu.mutation = mutation
affected, err = gu.sqlSave(ctx)
mutation.done = true
return affected, err
})
for i := len(gu.hooks) - 1; i >= 0; i-- {
if gu.hooks[i] == nil {
return 0, fmt.Errorf("ent: uninitialized hook (forgotten import ent/runtime?)")
}
mut = gu.hooks[i](mut)
}
if _, err := mut.Mutate(ctx, gu.mutation); err != nil {
return 0, err
}
}
return affected, err
}
func (gu *GroupUpdate) SaveX(ctx context.Context) int {
affected, err := gu.Save(ctx)
if err != nil {
panic(err)
}
return affected
}
func (gu *GroupUpdate) Exec(ctx context.Context) error {
_, err := gu.Save(ctx)
return err
}
func (gu *GroupUpdate) ExecX(ctx context.Context) {
if err := gu.Exec(ctx); err != nil {
panic(err)
}
}
func (gu *GroupUpdate) sqlSave(ctx context.Context) (n int, err error) {
_spec := &sqlgraph.UpdateSpec{
Node: &sqlgraph.NodeSpec{
Table: group.Table,
Columns: group.Columns,
ID: &sqlgraph.FieldSpec{
Type: field.TypeInt,
Column: group.FieldID,
},
},
}
if ps := gu.mutation.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
if value, ok := gu.mutation.Name(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: group.FieldName,
})
}
if gu.mutation.UsersCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.O2M,
Inverse: true,
Table: group.UsersTable,
Columns: []string{group.UsersColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: &sqlgraph.FieldSpec{
Type: field.TypeInt,
Column: user.FieldID,
},
},
}
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := gu.mutation.RemovedUsersIDs(); len(nodes) > 0 && !gu.mutation.UsersCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.O2M,
Inverse: true,
Table: group.UsersTable,
Columns: []string{group.UsersColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: &sqlgraph.FieldSpec{
Type: field.TypeInt,
Column: user.FieldID,
},
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := gu.mutation.UsersIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.O2M,
Inverse: true,
Table: group.UsersTable,
Columns: []string{group.UsersColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: &sqlgraph.FieldSpec{
Type: field.TypeInt,
Column: user.FieldID,
},
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges.Add = append(_spec.Edges.Add, edge)
}
if n, err = sqlgraph.UpdateNodes(ctx, gu.driver, _spec); err != nil {
if _, ok := err.(*sqlgraph.NotFoundError); ok {
err = &NotFoundError{group.Label}
} else if sqlgraph.IsConstraintError(err) {
err = &ConstraintError{err.Error(), err}
}
return 0, err
}
return n, nil
}
type GroupUpdateOne struct {
config
fields []string
hooks []Hook
mutation *GroupMutation
}
func (guo *GroupUpdateOne) SetName(s string) *GroupUpdateOne {
guo.mutation.SetName(s)
return guo
}
func (guo *GroupUpdateOne) AddUserIDs(ids ...int) *GroupUpdateOne {
guo.mutation.AddUserIDs(ids...)
return guo
}
func (guo *GroupUpdateOne) AddUsers(u ...*User) *GroupUpdateOne {
ids := make([]int, len(u))
for i := range u {
ids[i] = u[i].ID
}
return guo.AddUserIDs(ids...)
}
func (guo *GroupUpdateOne) Mutation() *GroupMutation {
return guo.mutation
}
func (guo *GroupUpdateOne) ClearUsers() *GroupUpdateOne {
guo.mutation.ClearUsers()
return guo
}
func (guo *GroupUpdateOne) RemoveUserIDs(ids ...int) *GroupUpdateOne {
guo.mutation.RemoveUserIDs(ids...)
return guo
}
func (guo *GroupUpdateOne) RemoveUsers(u ...*User) *GroupUpdateOne {
ids := make([]int, len(u))
for i := range u {
ids[i] = u[i].ID
}
return guo.RemoveUserIDs(ids...)
} | Apache License 2.0 |
awnumar/memguard | core/coffer.go | View | go | func (s *Coffer) View() (*Buffer, error) {
if s.Destroyed() {
return nil, ErrCofferExpired
}
b, _ := NewBuffer(32)
s.RLock()
defer s.RUnlock()
h := Hash(s.right.Data())
for i := range b.Data() {
b.Data()[i] = h[i] ^ s.left.Data()[i]
}
Wipe(h)
return b, nil
} | /*
View returns a snapshot of the contents of a Coffer inside a Buffer. As usual the Buffer should be destroyed as soon as possible after use by calling the Destroy method. | https://github.com/awnumar/memguard/blob/23560acda853b69986c0f01df950d7b0f8e139ba/core/coffer.go#L96-L132 | package core
import (
"errors"
"sync"
"time"
)
const interval = 500 * time.Millisecond
var ErrCofferExpired = errors.New("<memguard::core::ErrCofferExpired> attempted usage of destroyed key object")
type Coffer struct {
sync.RWMutex
left *Buffer
right *Buffer
rand *Buffer
}
func NewCoffer() *Coffer {
s := new(Coffer)
s.left, _ = NewBuffer(32)
s.right, _ = NewBuffer(32)
s.rand, _ = NewBuffer(32)
s.Initialise()
go func(s *Coffer) {
for {
time.Sleep(interval)
if err := s.Rekey(); err != nil {
break
}
}
}(s)
return s
}
func (s *Coffer) Initialise() error {
if s.Destroyed() {
return ErrCofferExpired
}
if err := s.initialise(); err != nil {
Panic(err)
}
return nil
}
func (s *Coffer) initialise() error {
s.Lock()
defer s.Unlock()
if err := Scramble(s.left.Data()); err != nil {
return err
}
if err := Scramble(s.right.Data()); err != nil {
return err
}
hr := Hash(s.right.Data())
for i := range hr {
s.left.Data()[i] ^= hr[i]
}
Wipe(hr)
return nil
} | Apache License 2.0 |
k-phoen/grabana | axis/axis.go | Max | go | func Max(max float64) Option {
return func(axis *Axis) {
axis.Builder.Max = sdk.NewFloatString(max)
}
} | Max sets the maximum value expected on this axis. | https://github.com/k-phoen/grabana/blob/ee4be8647e50d4a2479d8518d56076f84665fd32/axis/axis.go#L66-L70 | package axis
import (
"github.com/grafana-tools/sdk"
)
type Option func(axis *Axis)
type Axis struct {
Builder *sdk.Axis
}
func New(options ...Option) *Axis {
axis := &Axis{Builder: &sdk.Axis{
Format: "short",
Show: true,
LogBase: 1,
}}
for _, opt := range options {
opt(axis)
}
return axis
}
func Unit(unit string) Option {
return func(axis *Axis) {
axis.Builder.Format = unit
}
}
func Hide() Option {
return func(axis *Axis) {
axis.Builder.Show = false
}
}
func LogBase(base int) Option {
return func(axis *Axis) {
axis.Builder.LogBase = base
}
}
func Label(label string) Option {
return func(axis *Axis) {
axis.Builder.Label = label
}
}
func Min(min float64) Option {
return func(axis *Axis) {
axis.Builder.Min = sdk.NewFloatString(min)
}
} | MIT License |
mailgun/kafka-pixy | consumer/kazoo/kazoo.go | CreatePartitionOwner | go | func (m *Model) CreatePartitionOwner(topic string, partition int32) error {
path := m.partitionOwnerZNodePath(topic, partition)
err := m.durableCreateZNode(path, []byte(m.memberID), zk.FlagEphemeral)
if errors.Cause(err) == zk.ErrNodeExists {
rawOwnerID, _, err := m.zkConn.Get(path)
ownerID := string(rawOwnerID)
if err != nil {
return err
}
if ownerID != m.memberID {
return errors.Errorf("owned by %s", ownerID)
}
return nil
}
if err != nil {
return errors.Wrapf(err, "while deep creating %s", path)
}
return nil
} | CreatePartitionOwner creates a partition owner znode, but only if none
exists for the given topic-partition. An error is returned if a partition
owner znode exists but belongs to another member. | https://github.com/mailgun/kafka-pixy/blob/7bd192e7dbc99a405cdcaed5c077b32414339b99/consumer/kazoo/kazoo.go#L121-L139 | package kazoo
import (
"context"
"encoding/json"
"fmt"
"sort"
"strings"
"time"
"github.com/davecgh/go-spew/spew"
"github.com/mailgun/kafka-pixy/none"
"github.com/pkg/errors"
"github.com/samuel/go-zookeeper/zk"
"github.com/sirupsen/logrus"
)
const (
versionAny = -1
)
type Model struct {
zkConn *zk.Conn
log *logrus.Entry
groupPath string
membersPath string
ownersPath string
memberID string
memberPath string
}
func NewModel(zkConn *zk.Conn, chroot, group, memberID string, log *logrus.Entry) Model {
groupPath := fmt.Sprintf("%s/consumers/%s", chroot, group)
membersPath := groupPath + "/ids"
return Model{
zkConn: zkConn,
log: log,
groupPath: groupPath,
membersPath: membersPath,
ownersPath: groupPath + "/owners",
memberID: memberID,
memberPath: membersPath + "/" + memberID,
}
}
func (m *Model) EnsureMemberSubscription(topics []string) error {
if len(topics) == 0 {
if err := m.zkConn.Delete(m.memberPath, versionAny); err != nil {
if err == zk.ErrNoNode {
return nil
}
return errors.Wrapf(err, "while deleting %v", m.memberPath)
}
return nil
}
memberSpec := newMemberSpec(topics)
memberSpecJSON, err := json.Marshal(memberSpec)
if err != nil {
return errors.Wrapf(err, "while JSON encoding %s", spew.Sdump(memberSpec))
}
if err := m.durableUpsertZNode(m.memberPath, memberSpecJSON, zk.FlagEphemeral); err != nil {
return errors.WithStack(err)
}
return nil
}
func (m *Model) FetchGroupSubscriptions() (map[string][]string, <-chan none.T, context.CancelFunc, error) {
members, memberWatchCh, err := m.watchZNodeChildren(m.membersPath)
if err != nil {
return nil, nil, nil, errors.Wrapf(err, "failed to watch members")
}
memberUpdateWatchChs := make(map[string]<-chan zk.Event, len(members))
subscriptions := make(map[string][]string, len(members))
for _, memberID := range members {
memberPath := m.memberZNodePath(memberID)
jsonMemberSpec, _, memberUpdateWatchCh, err := m.zkConn.GetW(memberPath)
if err == zk.ErrNoNode {
continue
}
if err != nil {
return nil, nil, nil, errors.Wrapf(err, "while getting znode %s", memberPath)
}
var memberSpec memberSpec
if err := json.Unmarshal(jsonMemberSpec, &memberSpec); err != nil {
return nil, nil, nil, errors.Wrapf(err, "while parsing member %s, data=%s", memberID, string(jsonMemberSpec))
}
memberUpdateWatchChs[memberID] = memberUpdateWatchCh
subscriptions[memberID] = memberSpec.topics()
}
aggregateWatchCh := make(chan none.T)
ctx, cancel := context.WithCancel(context.Background())
go m.forwardWatch(ctx, "members", memberWatchCh, aggregateWatchCh)
for memberID, memberUpdateWatchCh := range memberUpdateWatchChs {
go m.forwardWatch(ctx, memberID, memberUpdateWatchCh, aggregateWatchCh)
}
return subscriptions, aggregateWatchCh, cancel, nil
} | Apache License 2.0 |
dirname/binance | futures/usd/websocket/account/listenKey.go | DeleteListenKey | go | func (b *listenKeyBuilder) DeleteListenKey(key string) (interface{}, error) {
var err error
if key == "" {
err = errors.New(futuresclient.MissParameters)
return nil, err
}
params := "listenKey=" + key
req, err := b.Builder.Build(http.MethodDelete, "/fapi/v1/listenKey", params, false, false, 0)
if err != nil {
logger.Error("Failed to build url: %s", err.Error())
}
res, err := binance.HttpRequest(req)
var parser map[string]interface{}
err = json.Unmarshal(res, &parser)
if _, ok := parser["code"]; ok {
result := model.APIErrorResponse{}
err = json.Unmarshal(res, &result)
return result.Message, err
}
if bytes.Equal(res, []byte{123, 125}) {
return true, err
}
return nil, err
} | DeleteListenKey Close out a user data stream. | https://github.com/dirname/binance/blob/463cf47db2ccda5e51678df87a38f2aaca30b882/futures/usd/websocket/account/listenKey.go#L81-L104 | package account
import (
"bytes"
"encoding/json"
"errors"
"github.com/dirname/binance"
"github.com/dirname/binance/futures/usd/client"
logger "github.com/dirname/binance/logging"
"github.com/dirname/binance/model"
"net/http"
)
type ListenKeyResponse struct {
ListenKey string `json:"listenKey"`
}
type listenKeyBuilder struct {
Builder *binance.PrivateUrlBuilder
}
func NewListenKeyBuilder(host, appKey, appSecret string) *listenKeyBuilder {
return &listenKeyBuilder{
Builder: binance.NewPrivateUrlBuilder(host, appKey, appSecret),
}
}
func (b *listenKeyBuilder) CreateListenKey() (string, error) {
var err error
req, err := b.Builder.Build(http.MethodPost, "/fapi/v1/listenKey", "", false, false, 0)
if err != nil {
logger.Error("Failed to build url: %s", err.Error())
}
res, err := binance.HttpRequest(req)
var parser map[string]interface{}
err = json.Unmarshal(res, &parser)
if _, ok := parser["code"]; ok {
result := model.APIErrorResponse{}
err = json.Unmarshal(res, &result)
if err == nil {
err = errors.New(result.Message)
}
return result.Message, err
}
result := ListenKeyResponse{}
err = json.Unmarshal(res, &result)
return result.ListenKey, err
}
func (b *listenKeyBuilder) PingListenKey(key string) (interface{}, error) {
var err error
if key == "" {
err = errors.New(futuresclient.MissParameters)
return nil, err
}
params := "listenKey=" + key
req, err := b.Builder.Build(http.MethodPut, "/fapi/v1/listenKey", params, false, false, 0)
if err != nil {
logger.Error("Failed to build url: %s", err.Error())
}
res, err := binance.HttpRequest(req)
var parser map[string]interface{}
err = json.Unmarshal(res, &parser)
if _, ok := parser["code"]; ok {
result := model.APIErrorResponse{}
err = json.Unmarshal(res, &result)
return result.Message, err
}
if bytes.Equal(res, []byte{123, 125}) {
return true, err
}
return nil, err
} | MIT License |
kelindar/column | txn.go | WithUint | go | func (txn *Txn) WithUint(column string, predicate func(v uint64) bool) *Txn {
c, ok := txn.columnAt(column)
if !ok || !c.IsNumeric() {
txn.index.Clear()
return txn
}
txn.rangeRead(func(offset uint32, index bitmap.Bitmap) {
c.Column.(Numeric).FilterUint64(offset, index, predicate)
})
return txn
} | WithUint filters down the values based on the specified predicate. The column for
this filter must be numerical and convertible to uint64. | https://github.com/kelindar/column/blob/0e307192292809b8debec69bedc3f83c74815d4a/txn.go#L221-L232 | package column
import (
"errors"
"sync"
"sync/atomic"
"time"
"github.com/kelindar/bitmap"
"github.com/kelindar/column/commit"
)
var (
errNoKey = errors.New("column: collection does not have a key column")
)
type txnPool struct {
txns sync.Pool
pages sync.Pool
}
func newTxnPool() *txnPool {
return &txnPool{
txns: sync.Pool{
New: func() interface{} {
return &Txn{
index: make(bitmap.Bitmap, 0, 4),
dirty: make(bitmap.Bitmap, 0, 4),
updates: make([]*commit.Buffer, 0, 256),
columns: make([]columnCache, 0, 16),
reader: commit.NewReader(),
}
},
},
pages: sync.Pool{
New: func() interface{} {
return commit.NewBuffer(chunkSize)
},
},
}
}
func (p *txnPool) acquire(owner *Collection) *Txn {
txn := p.txns.Get().(*Txn)
txn.owner = owner
txn.writer = owner.writer
txn.index.Grow(uint32(owner.size))
owner.fill.Clone(&txn.index)
return txn
}
func (p *txnPool) release(txn *Txn) {
p.txns.Put(txn)
}
func (p *txnPool) acquirePage(columnName string) *commit.Buffer {
page := p.pages.Get().(*commit.Buffer)
page.Reset(columnName)
return page
}
func (p *txnPool) releasePage(buffer *commit.Buffer) {
buffer.Reset("")
p.pages.Put(buffer)
}
type Txn struct {
owner *Collection
index bitmap.Bitmap
dirty bitmap.Bitmap
updates []*commit.Buffer
columns []columnCache
writer commit.Writer
reader *commit.Reader
}
func (txn *Txn) reset() {
for i := range txn.updates {
txn.owner.txns.releasePage(txn.updates[i])
}
txn.dirty.Clear()
txn.reader.Rewind()
txn.columns = txn.columns[:0]
txn.updates = txn.updates[:0]
}
type columnCache struct {
name string
col *column
}
func (txn *Txn) columnAt(columnName string) (*column, bool) {
for _, v := range txn.columns {
if v.name == columnName {
return v.col, true
}
}
column, ok := txn.owner.cols.Load(columnName)
if !ok {
return nil, false
}
txn.columns = append(txn.columns, columnCache{
name: columnName,
col: column,
})
return column, true
}
func (txn *Txn) With(columns ...string) *Txn {
for _, columnName := range columns {
if idx, ok := txn.columnAt(columnName); ok {
txn.rangeReadPair(*idx.Column.Index(), func(dst, src bitmap.Bitmap) {
dst.And(src)
})
} else {
txn.index.Clear()
}
}
return txn
}
func (txn *Txn) Without(columns ...string) *Txn {
for _, columnName := range columns {
if idx, ok := txn.columnAt(columnName); ok {
txn.rangeReadPair(*idx.Column.Index(), func(dst, src bitmap.Bitmap) {
dst.AndNot(src)
})
}
}
return txn
}
func (txn *Txn) Union(columns ...string) *Txn {
for _, columnName := range columns {
if idx, ok := txn.columnAt(columnName); ok {
txn.rangeReadPair(*idx.Column.Index(), func(dst, src bitmap.Bitmap) {
dst.Or(src)
})
}
}
return txn
}
func (txn *Txn) WithValue(column string, predicate func(v interface{}) bool) *Txn {
c, ok := txn.columnAt(column)
if !ok {
txn.index.Clear()
return txn
}
txn.rangeRead(func(offset uint32, index bitmap.Bitmap) {
index.Filter(func(x uint32) (match bool) {
if v, ok := c.Value(offset + x); ok {
match = predicate(v)
}
return
})
})
return txn
}
func (txn *Txn) WithFloat(column string, predicate func(v float64) bool) *Txn {
c, ok := txn.columnAt(column)
if !ok || !c.IsNumeric() {
txn.index.Clear()
return txn
}
txn.rangeRead(func(offset uint32, index bitmap.Bitmap) {
c.Column.(Numeric).FilterFloat64(offset, index, predicate)
})
return txn
}
func (txn *Txn) WithInt(column string, predicate func(v int64) bool) *Txn {
c, ok := txn.columnAt(column)
if !ok || !c.IsNumeric() {
txn.index.Clear()
return txn
}
txn.rangeRead(func(offset uint32, index bitmap.Bitmap) {
c.Column.(Numeric).FilterInt64(offset, index, predicate)
})
return txn
} | MIT License |
intel/cri-resource-manager | pkg/log/log.go | EnableDebug | go | func EnableDebug(source string) bool {
log.Lock()
defer log.Unlock()
return log.setDebug(source, true)
} | EnableDebug enables debug logging for the source. | https://github.com/intel/cri-resource-manager/blob/21ed50ef93b8153aedc298a07a806f19e3e94825/pkg/log/log.go#L137-L141 | package log
import (
"fmt"
"strings"
"sync"
"k8s.io/klog/v2"
)
type Level int
const (
levelUnset Level = iota
LevelDebug
LevelInfo
LevelWarn
LevelError
LevelPanic
LevelFatal
)
var levelTag = map[Level]string{
levelUnset: "?: ",
LevelDebug: "D: ",
LevelInfo: "I: ",
LevelWarn: "W: ",
LevelError: "E: ",
LevelFatal: "F: ",
LevelPanic: "P: ",
}
type Logger interface {
Debugf(format string, v ...interface{})
Infof(format string, v ...interface{})
Warnf(format string, v ...interface{})
Errorf(format string, v ...interface{})
Panicf(format string, v ...interface{})
Fatalf(format string, v ...interface{})
Debug(format string, args ...interface{})
Info(format string, args ...interface{})
Warn(format string, args ...interface{})
Error(format string, args ...interface{})
Panic(format string, args ...interface{})
Fatal(format string, args ...interface{})
DebugBlock(prefix string, format string, args ...interface{})
InfoBlock(prefix string, format string, args ...interface{})
WarnBlock(prefix string, format string, args ...interface{})
ErrorBlock(prefix string, format string, args ...interface{})
EnableDebug(bool) bool
DebugEnabled() bool
Source() string
}
type logger uint
type logging struct {
sync.RWMutex
level Level
dbgmap srcmap
loggers map[string]logger
sources map[logger]string
debug map[logger]struct{}
maxlen int
forced bool
prefix bool
aligned map[logger]string
}
var log = &logging{
level: DefaultLevel,
loggers: make(map[string]logger),
sources: make(map[logger]string),
aligned: make(map[logger]string),
debug: make(map[logger]struct{}),
}
func Get(source string) Logger {
log.Lock()
defer log.Unlock()
return log.get(source)
}
func NewLogger(source string) Logger {
return Get(source)
} | Apache License 2.0 |
manifoldco/torus-cli | daemon/logic/utils.go | fetchKeyPairs | go | func fetchKeyPairs(k *registry.Keypairs, orgID *identity.ID) (
*identity.ID, *identity.ID, *crypto.KeyPairs, error) {
enc, err := k.Select(orgID, primitive.EncryptionKeyType)
if err != nil {
return nil, nil, nil, err
}
sig, err := k.Select(orgID, primitive.SigningKeyType)
if err != nil {
return nil, nil, nil, err
}
kp := bundleKeypairs(sig, enc)
return sig.PublicKey.ID, enc.PublicKey.ID, kp, nil
} | fetchKeyPairs fetches and bundles the user's signing and encryption keypairs
from the given keypairs struct | https://github.com/manifoldco/torus-cli/blob/137599f985e6f676c081ffb4230aaad52fb7d26c/daemon/logic/utils.go#L350-L365 | package logic
import (
"context"
"encoding/json"
"log"
"strconv"
"time"
"golang.org/x/crypto/ed25519"
"github.com/manifoldco/go-base64"
"github.com/manifoldco/torus-cli/apitypes"
"github.com/manifoldco/torus-cli/envelope"
"github.com/manifoldco/torus-cli/identity"
"github.com/manifoldco/torus-cli/primitive"
"github.com/manifoldco/torus-cli/registry"
"github.com/manifoldco/torus-cli/daemon/crypto"
"github.com/manifoldco/torus-cli/daemon/crypto/secure"
"github.com/manifoldco/torus-cli/daemon/session"
)
func packageSigningKeypair(ctx context.Context, c *crypto.Engine, authID, orgID *identity.ID,
kp *crypto.KeyPairs) (*envelope.PublicKey, *envelope.PrivateKey, error) {
pubsig, err := packagePublicKey(ctx, c, authID, orgID,
primitive.SigningKeyType, kp.Signature.Public, nil, &kp.Signature)
if err != nil {
return nil, nil, err
}
privsig, err := packagePrivateKey(ctx, c, authID, orgID, kp.Signature.PNonce,
kp.Signature.Private, pubsig.ID, pubsig.ID, &kp.Signature)
if err != nil {
return nil, nil, err
}
return pubsig, privsig, nil
}
func packageEncryptionKeypair(ctx context.Context, c *crypto.Engine, authID, orgID *identity.ID,
kp *crypto.KeyPairs, pubsig *envelope.PublicKey) (*envelope.PublicKey, *envelope.PrivateKey, error) {
pubenc, err := packagePublicKey(ctx, c, authID, orgID, primitive.EncryptionKeyType,
kp.Encryption.Public[:], pubsig.ID, &kp.Signature)
if err != nil {
return nil, nil, err
}
privenc, err := packagePrivateKey(ctx, c, authID, orgID, kp.Encryption.PNonce,
kp.Encryption.Private, pubenc.ID, pubsig.ID, &kp.Signature)
if err != nil {
return nil, nil, err
}
return pubenc, privenc, nil
}
func packagePlaintextCred(c envelope.CredentialInf, value string) PlaintextCredentialEnvelope {
state := "set"
return PlaintextCredentialEnvelope{
ID: c.GetID(),
Version: c.GetVersion(),
Body: &PlaintextCredential{
Name: c.Name(),
PathExp: c.PathExp(),
ProjectID: c.ProjectID(),
OrgID: c.OrgID(),
Value: value,
State: &state,
},
}
}
func extractCredentialValue(pt []byte) (*apitypes.CredentialValue, error) {
cValue := &apitypes.CredentialValue{}
err := json.Unmarshal([]byte(strconv.Quote(string(pt))), cValue)
if err != nil {
return nil, err
}
return cValue, nil
}
func createCredentialGraph(ctx context.Context, credBody *PlaintextCredential,
parent registry.CredentialGraph, sigID *identity.ID, encID *identity.ID,
kp *crypto.KeyPairs, ct *registry.ClaimTree, client *registry.Client,
engine *crypto.Engine, g *secure.Guard) (*registry.CredentialGraphV2, error) {
pathExp, err := credBody.PathExp.WithInstance("*")
if err != nil {
return nil, err
}
keyringBody := primitive.NewKeyring(credBody.OrgID, credBody.ProjectID, pathExp)
if parent != nil {
keyringBody.Previous = parent.GetKeyring().GetID()
keyringBody.KeyringVersion = parent.KeyringVersion() + 1
}
keyring, err := engine.SignedKeyring(ctx, keyringBody, sigID, &kp.Signature)
if err != nil {
return nil, err
}
mek, err := g.Random(64)
defer mek.Destroy()
if err != nil {
return nil, err
}
subjects, err := getKeyringMembers(ctx, client, credBody.OrgID)
if err != nil {
return nil, err
}
members := []registry.KeyringMember{}
for _, subject := range subjects {
for _, id := range subject.KeyOwnerIDs() {
enc, err := ct.FindActive(&id, primitive.EncryptionKeyType)
if err == registry.ErrMissingKeyForOwner {
continue
}
if err != nil {
return nil, err
}
encPubKey := enc.PublicKey
encmek, nonce, err := engine.Box(ctx, mek, &kp.Encryption, []byte(*encPubKey.Body.Key.Value))
if err != nil {
return nil, err
}
key := &primitive.KeyringMemberKey{
Algorithm: crypto.EasyBox,
Nonce: base64.New(nonce),
Value: base64.New(encmek),
}
member, err := newV2KeyringMember(ctx, engine, credBody.OrgID, keyring.ID,
encPubKey.Body.OwnerID, encPubKey.ID, encID, sigID, key, kp)
if err != nil {
return nil, err
}
members = append(members, *member)
}
}
graph := registry.CredentialGraphV2{
KeyringSectionV2: registry.KeyringSectionV2{
Keyring: keyring,
Claims: []envelope.KeyringMemberClaim{},
Members: members,
},
}
return &graph, nil
}
func newV1KeyringMember(ctx context.Context, engine *crypto.Engine,
orgID, projectID, keyringID, ownerID, pubKeyID, encKeyID, sigID *identity.ID,
key *primitive.KeyringMemberKey, kp *crypto.KeyPairs) (*envelope.KeyringMemberV1, error) {
now := time.Now().UTC()
return engine.SignedKeyringMemberV1(ctx, &primitive.KeyringMemberV1{
Created: now,
OrgID: orgID,
ProjectID: projectID,
KeyringID: keyringID,
OwnerID: ownerID,
PublicKeyID: pubKeyID,
EncryptingKeyID: encKeyID,
Key: key,
}, sigID, &kp.Signature)
}
func newV2KeyringMember(ctx context.Context, engine *crypto.Engine,
orgID, keyringID, ownerID, pubKeyID, encKeyID, sigID *identity.ID,
key *primitive.KeyringMemberKey, kp *crypto.KeyPairs) (*registry.KeyringMember, error) {
now := time.Now().UTC()
member, err := engine.SignedKeyringMember(ctx, &primitive.KeyringMember{
Created: now,
OrgID: orgID,
KeyringID: keyringID,
OwnerID: ownerID,
PublicKeyID: pubKeyID,
EncryptingKeyID: encKeyID,
}, sigID, &kp.Signature)
if err != nil {
return nil, err
}
mekshare, err := engine.SignedMEKShare(ctx, &primitive.MEKShare{
Created: now,
OrgID: orgID,
OwnerID: ownerID,
KeyringID: keyringID,
KeyringMemberID: member.ID,
Key: key,
}, sigID, &kp.Signature)
if err != nil {
return nil, err
}
return ®istry.KeyringMember{
Member: member,
MEKShare: mekshare,
}, nil
}
func createKeyringMemberships(ctx context.Context, c *crypto.Engine, client *registry.Client,
s session.Session, orgID, ownerID *identity.ID) ([]envelope.KeyringMemberV1, []registry.KeyringMember, error) {
keypairs, err := client.KeyPairs.List(ctx, orgID)
if err != nil {
log.Printf("could not fetch keypairs for org: %s", err)
return nil, nil, err
}
sigID, encID, kp, err := fetchKeyPairs(keypairs, orgID)
if err != nil {
log.Printf("could not fetch keypairs for org: %s", err)
return nil, nil, err
}
claimTree, err := client.ClaimTree.Get(ctx, orgID, nil)
if err != nil {
log.Printf("could not retrieve claim tree for invite approval: %s", err)
return nil, nil, err
}
org, err := client.Orgs.Get(ctx, orgID)
if err != nil {
return nil, nil, err
}
projects, err := client.Projects.List(ctx, org.ID)
if err != nil {
return nil, nil, err
}
var graphs []registry.CredentialGraph
for _, project := range projects {
projGraphs, err := client.CredentialGraph.Search(ctx,
"/"+org.Body.Name+"/"+project.Body.Name+"/*/*/*/*", s.AuthID(), nil)
if err != nil {
log.Printf("Error retrieving credential graphs: %s", err)
return nil, nil, err
}
graphs = append(graphs, projGraphs...)
}
targetKeySegment, err := claimTree.FindActive(ownerID, primitive.EncryptionKeyType)
if err != nil {
log.Printf("could not find encryption key for owner id: %s", ownerID.String())
return nil, nil, err
}
targetPubKey := targetKeySegment.PublicKey
cgs := newCredentialGraphSet()
err = cgs.Add(graphs...)
if err != nil {
return nil, nil, err
}
activeGraphs, err := cgs.Active()
if err != nil {
return nil, nil, err
}
v1members := []envelope.KeyringMemberV1{}
v2members := []registry.KeyringMember{}
for _, graph := range activeGraphs {
krm, mekshare, err := graph.FindMember(s.AuthID())
if err != nil {
log.Printf("could not find keyring membership: %s", err)
return nil, nil, &apitypes.Error{
Type: apitypes.NotFoundError,
Err: []string{"Keyring membership not found."},
}
}
encPubKeySegment, err := claimTree.Find(krm.EncryptingKeyID, false)
if err != nil {
log.Printf("could not find encrypting public key for membership: %s", err)
return nil, nil, err
}
encPubKey := encPubKeySegment.PublicKey
encMek, nonce, err := c.CloneMembership(ctx, *mekshare.Key.Value,
*mekshare.Key.Nonce, &kp.Encryption, *encPubKey.Body.Key.Value, *targetPubKey.Body.Key.Value)
if err != nil {
log.Printf("could not clone keyring membership: %s", err)
return nil, nil, err
}
key := &primitive.KeyringMemberKey{
Algorithm: crypto.EasyBox,
Nonce: base64.New(nonce),
Value: base64.New(encMek),
}
switch k := graph.GetKeyring().(type) {
case *envelope.KeyringV1:
projectID := k.Body.ProjectID
member, err := newV1KeyringMember(ctx, c, krm.OrgID, projectID,
krm.KeyringID, ownerID, targetPubKey.ID, encID, sigID, key, kp)
if err != nil {
return nil, nil, err
}
v1members = append(v1members, *member)
case *envelope.Keyring:
member, err := newV2KeyringMember(ctx, c, krm.OrgID, krm.KeyringID,
ownerID, targetPubKey.ID, encID, sigID, key, kp)
if err != nil {
return nil, nil, err
}
v2members = append(v2members, *member)
default:
return nil, nil, &apitypes.Error{
Type: apitypes.InternalServerError,
Err: []string{"Unknown keyring schema version"},
}
}
}
return v1members, v2members, nil
} | BSD 3-Clause New or Revised License |
wirepair/gcd | v2/gcdapi/browser.go | GetWindowForTargetWithParams | go | func (c *Browser) GetWindowForTargetWithParams(ctx context.Context, v *BrowserGetWindowForTargetParams) (int, *BrowserBounds, error) {
resp, err := c.target.SendCustomReturn(ctx, &gcdmessage.ParamRequest{Id: c.target.GetId(), Method: "Browser.getWindowForTarget", Params: v})
if err != nil {
return 0, nil, err
}
var chromeData struct {
Result struct {
WindowId int
Bounds *BrowserBounds
}
}
if resp == nil {
return 0, nil, &gcdmessage.ChromeEmptyResponseErr{}
}
cerr := &gcdmessage.ChromeErrorResponse{}
json.Unmarshal(resp.Data, cerr)
if cerr != nil && cerr.Error != nil {
return 0, nil, &gcdmessage.ChromeRequestErr{Resp: cerr}
}
if err := json.Unmarshal(resp.Data, &chromeData); err != nil {
return 0, nil, err
}
return chromeData.Result.WindowId, chromeData.Result.Bounds, nil
} | GetWindowForTargetWithParams - Get the browser window that contains the devtools target.
Returns - windowId - Browser window id. bounds - Bounds information of the window. When window state is 'minimized', the restored window position and size are returned. | https://github.com/wirepair/gcd/blob/099a6ae3b2ee7e02fb282df646e77dc669c1003e/v2/gcdapi/browser.go#L438-L467 | package gcdapi
import (
"context"
"github.com/wirepair/gcd/v2/gcdmessage"
)
type BrowserBounds struct {
Left int `json:"left,omitempty"`
Top int `json:"top,omitempty"`
Width int `json:"width,omitempty"`
Height int `json:"height,omitempty"`
WindowState string `json:"windowState,omitempty"`
}
type BrowserPermissionDescriptor struct {
Name string `json:"name"`
Sysex bool `json:"sysex,omitempty"`
UserVisibleOnly bool `json:"userVisibleOnly,omitempty"`
AllowWithoutSanitization bool `json:"allowWithoutSanitization,omitempty"`
PanTiltZoom bool `json:"panTiltZoom,omitempty"`
}
type BrowserBucket struct {
Low int `json:"low"`
High int `json:"high"`
Count int `json:"count"`
}
type BrowserHistogram struct {
Name string `json:"name"`
Sum int `json:"sum"`
Count int `json:"count"`
Buckets []*BrowserBucket `json:"buckets"`
}
type BrowserDownloadWillBeginEvent struct {
Method string `json:"method"`
Params struct {
FrameId string `json:"frameId"`
Guid string `json:"guid"`
Url string `json:"url"`
SuggestedFilename string `json:"suggestedFilename"`
} `json:"Params,omitempty"`
}
type BrowserDownloadProgressEvent struct {
Method string `json:"method"`
Params struct {
Guid string `json:"guid"`
TotalBytes float64 `json:"totalBytes"`
ReceivedBytes float64 `json:"receivedBytes"`
State string `json:"state"`
} `json:"Params,omitempty"`
}
type Browser struct {
target gcdmessage.ChromeTargeter
}
func NewBrowser(target gcdmessage.ChromeTargeter) *Browser {
c := &Browser{target: target}
return c
}
type BrowserSetPermissionParams struct {
Permission *BrowserPermissionDescriptor `json:"permission"`
Setting string `json:"setting"`
Origin string `json:"origin,omitempty"`
BrowserContextId string `json:"browserContextId,omitempty"`
}
func (c *Browser) SetPermissionWithParams(ctx context.Context, v *BrowserSetPermissionParams) (*gcdmessage.ChromeResponse, error) {
return c.target.SendDefaultRequest(ctx, &gcdmessage.ParamRequest{Id: c.target.GetId(), Method: "Browser.setPermission", Params: v})
}
func (c *Browser) SetPermission(ctx context.Context, permission *BrowserPermissionDescriptor, setting string, origin string, browserContextId string) (*gcdmessage.ChromeResponse, error) {
var v BrowserSetPermissionParams
v.Permission = permission
v.Setting = setting
v.Origin = origin
v.BrowserContextId = browserContextId
return c.SetPermissionWithParams(ctx, &v)
}
type BrowserGrantPermissionsParams struct {
Permissions []string `json:"permissions"`
Origin string `json:"origin,omitempty"`
BrowserContextId string `json:"browserContextId,omitempty"`
}
func (c *Browser) GrantPermissionsWithParams(ctx context.Context, v *BrowserGrantPermissionsParams) (*gcdmessage.ChromeResponse, error) {
return c.target.SendDefaultRequest(ctx, &gcdmessage.ParamRequest{Id: c.target.GetId(), Method: "Browser.grantPermissions", Params: v})
}
func (c *Browser) GrantPermissions(ctx context.Context, permissions []string, origin string, browserContextId string) (*gcdmessage.ChromeResponse, error) {
var v BrowserGrantPermissionsParams
v.Permissions = permissions
v.Origin = origin
v.BrowserContextId = browserContextId
return c.GrantPermissionsWithParams(ctx, &v)
}
type BrowserResetPermissionsParams struct {
BrowserContextId string `json:"browserContextId,omitempty"`
}
func (c *Browser) ResetPermissionsWithParams(ctx context.Context, v *BrowserResetPermissionsParams) (*gcdmessage.ChromeResponse, error) {
return c.target.SendDefaultRequest(ctx, &gcdmessage.ParamRequest{Id: c.target.GetId(), Method: "Browser.resetPermissions", Params: v})
}
func (c *Browser) ResetPermissions(ctx context.Context, browserContextId string) (*gcdmessage.ChromeResponse, error) {
var v BrowserResetPermissionsParams
v.BrowserContextId = browserContextId
return c.ResetPermissionsWithParams(ctx, &v)
}
type BrowserSetDownloadBehaviorParams struct {
Behavior string `json:"behavior"`
BrowserContextId string `json:"browserContextId,omitempty"`
DownloadPath string `json:"downloadPath,omitempty"`
EventsEnabled bool `json:"eventsEnabled,omitempty"`
}
func (c *Browser) SetDownloadBehaviorWithParams(ctx context.Context, v *BrowserSetDownloadBehaviorParams) (*gcdmessage.ChromeResponse, error) {
return c.target.SendDefaultRequest(ctx, &gcdmessage.ParamRequest{Id: c.target.GetId(), Method: "Browser.setDownloadBehavior", Params: v})
}
func (c *Browser) SetDownloadBehavior(ctx context.Context, behavior string, browserContextId string, downloadPath string, eventsEnabled bool) (*gcdmessage.ChromeResponse, error) {
var v BrowserSetDownloadBehaviorParams
v.Behavior = behavior
v.BrowserContextId = browserContextId
v.DownloadPath = downloadPath
v.EventsEnabled = eventsEnabled
return c.SetDownloadBehaviorWithParams(ctx, &v)
}
type BrowserCancelDownloadParams struct {
Guid string `json:"guid"`
BrowserContextId string `json:"browserContextId,omitempty"`
}
func (c *Browser) CancelDownloadWithParams(ctx context.Context, v *BrowserCancelDownloadParams) (*gcdmessage.ChromeResponse, error) {
return c.target.SendDefaultRequest(ctx, &gcdmessage.ParamRequest{Id: c.target.GetId(), Method: "Browser.cancelDownload", Params: v})
}
func (c *Browser) CancelDownload(ctx context.Context, guid string, browserContextId string) (*gcdmessage.ChromeResponse, error) {
var v BrowserCancelDownloadParams
v.Guid = guid
v.BrowserContextId = browserContextId
return c.CancelDownloadWithParams(ctx, &v)
}
func (c *Browser) Close(ctx context.Context) (*gcdmessage.ChromeResponse, error) {
return c.target.SendDefaultRequest(ctx, &gcdmessage.ParamRequest{Id: c.target.GetId(), Method: "Browser.close"})
}
func (c *Browser) Crash(ctx context.Context) (*gcdmessage.ChromeResponse, error) {
return c.target.SendDefaultRequest(ctx, &gcdmessage.ParamRequest{Id: c.target.GetId(), Method: "Browser.crash"})
}
func (c *Browser) CrashGpuProcess(ctx context.Context) (*gcdmessage.ChromeResponse, error) {
return c.target.SendDefaultRequest(ctx, &gcdmessage.ParamRequest{Id: c.target.GetId(), Method: "Browser.crashGpuProcess"})
}
func (c *Browser) GetVersion(ctx context.Context) (string, string, string, string, string, error) {
resp, err := c.target.SendCustomReturn(ctx, &gcdmessage.ParamRequest{Id: c.target.GetId(), Method: "Browser.getVersion"})
if err != nil {
return "", "", "", "", "", err
}
var chromeData struct {
Result struct {
ProtocolVersion string
Product string
Revision string
UserAgent string
JsVersion string
}
}
if resp == nil {
return "", "", "", "", "", &gcdmessage.ChromeEmptyResponseErr{}
}
cerr := &gcdmessage.ChromeErrorResponse{}
json.Unmarshal(resp.Data, cerr)
if cerr != nil && cerr.Error != nil {
return "", "", "", "", "", &gcdmessage.ChromeRequestErr{Resp: cerr}
}
if err := json.Unmarshal(resp.Data, &chromeData); err != nil {
return "", "", "", "", "", err
}
return chromeData.Result.ProtocolVersion, chromeData.Result.Product, chromeData.Result.Revision, chromeData.Result.UserAgent, chromeData.Result.JsVersion, nil
}
func (c *Browser) GetBrowserCommandLine(ctx context.Context) ([]string, error) {
resp, err := c.target.SendCustomReturn(ctx, &gcdmessage.ParamRequest{Id: c.target.GetId(), Method: "Browser.getBrowserCommandLine"})
if err != nil {
return nil, err
}
var chromeData struct {
Result struct {
Arguments []string
}
}
if resp == nil {
return nil, &gcdmessage.ChromeEmptyResponseErr{}
}
cerr := &gcdmessage.ChromeErrorResponse{}
json.Unmarshal(resp.Data, cerr)
if cerr != nil && cerr.Error != nil {
return nil, &gcdmessage.ChromeRequestErr{Resp: cerr}
}
if err := json.Unmarshal(resp.Data, &chromeData); err != nil {
return nil, err
}
return chromeData.Result.Arguments, nil
}
type BrowserGetHistogramsParams struct {
Query string `json:"query,omitempty"`
Delta bool `json:"delta,omitempty"`
}
func (c *Browser) GetHistogramsWithParams(ctx context.Context, v *BrowserGetHistogramsParams) ([]*BrowserHistogram, error) {
resp, err := c.target.SendCustomReturn(ctx, &gcdmessage.ParamRequest{Id: c.target.GetId(), Method: "Browser.getHistograms", Params: v})
if err != nil {
return nil, err
}
var chromeData struct {
Result struct {
Histograms []*BrowserHistogram
}
}
if resp == nil {
return nil, &gcdmessage.ChromeEmptyResponseErr{}
}
cerr := &gcdmessage.ChromeErrorResponse{}
json.Unmarshal(resp.Data, cerr)
if cerr != nil && cerr.Error != nil {
return nil, &gcdmessage.ChromeRequestErr{Resp: cerr}
}
if err := json.Unmarshal(resp.Data, &chromeData); err != nil {
return nil, err
}
return chromeData.Result.Histograms, nil
}
func (c *Browser) GetHistograms(ctx context.Context, query string, delta bool) ([]*BrowserHistogram, error) {
var v BrowserGetHistogramsParams
v.Query = query
v.Delta = delta
return c.GetHistogramsWithParams(ctx, &v)
}
type BrowserGetHistogramParams struct {
Name string `json:"name"`
Delta bool `json:"delta,omitempty"`
}
func (c *Browser) GetHistogramWithParams(ctx context.Context, v *BrowserGetHistogramParams) (*BrowserHistogram, error) {
resp, err := c.target.SendCustomReturn(ctx, &gcdmessage.ParamRequest{Id: c.target.GetId(), Method: "Browser.getHistogram", Params: v})
if err != nil {
return nil, err
}
var chromeData struct {
Result struct {
Histogram *BrowserHistogram
}
}
if resp == nil {
return nil, &gcdmessage.ChromeEmptyResponseErr{}
}
cerr := &gcdmessage.ChromeErrorResponse{}
json.Unmarshal(resp.Data, cerr)
if cerr != nil && cerr.Error != nil {
return nil, &gcdmessage.ChromeRequestErr{Resp: cerr}
}
if err := json.Unmarshal(resp.Data, &chromeData); err != nil {
return nil, err
}
return chromeData.Result.Histogram, nil
}
func (c *Browser) GetHistogram(ctx context.Context, name string, delta bool) (*BrowserHistogram, error) {
var v BrowserGetHistogramParams
v.Name = name
v.Delta = delta
return c.GetHistogramWithParams(ctx, &v)
}
type BrowserGetWindowBoundsParams struct {
WindowId int `json:"windowId"`
}
func (c *Browser) GetWindowBoundsWithParams(ctx context.Context, v *BrowserGetWindowBoundsParams) (*BrowserBounds, error) {
resp, err := c.target.SendCustomReturn(ctx, &gcdmessage.ParamRequest{Id: c.target.GetId(), Method: "Browser.getWindowBounds", Params: v})
if err != nil {
return nil, err
}
var chromeData struct {
Result struct {
Bounds *BrowserBounds
}
}
if resp == nil {
return nil, &gcdmessage.ChromeEmptyResponseErr{}
}
cerr := &gcdmessage.ChromeErrorResponse{}
json.Unmarshal(resp.Data, cerr)
if cerr != nil && cerr.Error != nil {
return nil, &gcdmessage.ChromeRequestErr{Resp: cerr}
}
if err := json.Unmarshal(resp.Data, &chromeData); err != nil {
return nil, err
}
return chromeData.Result.Bounds, nil
}
func (c *Browser) GetWindowBounds(ctx context.Context, windowId int) (*BrowserBounds, error) {
var v BrowserGetWindowBoundsParams
v.WindowId = windowId
return c.GetWindowBoundsWithParams(ctx, &v)
}
type BrowserGetWindowForTargetParams struct {
TargetId string `json:"targetId,omitempty"`
} | MIT License |
xlab/android-go | android/cgo_helpers.go | Free | go | func (x *Looper) Free() {
if x != nil {
C.free(unsafe.Pointer(x))
}
} | Free cleanups the referenced memory using C free. | https://github.com/xlab/android-go/blob/ebf4d6dd1830d02eccda51fa12d4c7c57fc0e851/android/cgo_helpers.go#L545-L549 | package android
import "C"
import (
"sync"
"unsafe"
)
func (x *AssetManager) Ref() *C.AAssetManager {
if x == nil {
return nil
}
return (*C.AAssetManager)(unsafe.Pointer(x))
}
func (x *AssetManager) Free() {
if x != nil {
C.free(unsafe.Pointer(x))
}
}
func NewAssetManagerRef(ref unsafe.Pointer) *AssetManager {
return (*AssetManager)(ref)
}
func NewAssetManager() *AssetManager {
return (*AssetManager)(allocAssetManagerMemory(1))
}
func allocAssetManagerMemory(n int) unsafe.Pointer {
mem, err := C.calloc(C.size_t(n), (C.size_t)(sizeOfAssetManagerValue))
if err != nil {
panic("memory alloc error: " + err.Error())
}
return mem
}
const sizeOfAssetManagerValue = unsafe.Sizeof([1]C.AAssetManager{})
type cgoAllocMap struct {
mux sync.RWMutex
m map[unsafe.Pointer]struct{}
}
var cgoAllocsUnknown = new(cgoAllocMap)
func (a *cgoAllocMap) Add(ptr unsafe.Pointer) {
a.mux.Lock()
if a.m == nil {
a.m = make(map[unsafe.Pointer]struct{})
}
a.m[ptr] = struct{}{}
a.mux.Unlock()
}
func (a *cgoAllocMap) IsEmpty() bool {
a.mux.RLock()
isEmpty := len(a.m) == 0
a.mux.RUnlock()
return isEmpty
}
func (a *cgoAllocMap) Borrow(b *cgoAllocMap) {
if b == nil || b.IsEmpty() {
return
}
b.mux.Lock()
a.mux.Lock()
for ptr := range b.m {
if a.m == nil {
a.m = make(map[unsafe.Pointer]struct{})
}
a.m[ptr] = struct{}{}
delete(b.m, ptr)
}
a.mux.Unlock()
b.mux.Unlock()
}
func (a *cgoAllocMap) Free() {
a.mux.Lock()
for ptr := range a.m {
C.free(ptr)
delete(a.m, ptr)
}
a.mux.Unlock()
}
func (x *AssetManager) PassRef() *C.AAssetManager {
if x == nil {
x = (*AssetManager)(allocAssetManagerMemory(1))
}
return (*C.AAssetManager)(unsafe.Pointer(x))
}
func (x *AssetDir) Ref() *C.AAssetDir {
if x == nil {
return nil
}
return (*C.AAssetDir)(unsafe.Pointer(x))
}
func (x *AssetDir) Free() {
if x != nil {
C.free(unsafe.Pointer(x))
}
}
func NewAssetDirRef(ref unsafe.Pointer) *AssetDir {
return (*AssetDir)(ref)
}
func NewAssetDir() *AssetDir {
return (*AssetDir)(allocAssetDirMemory(1))
}
func allocAssetDirMemory(n int) unsafe.Pointer {
mem, err := C.calloc(C.size_t(n), (C.size_t)(sizeOfAssetDirValue))
if err != nil {
panic("memory alloc error: " + err.Error())
}
return mem
}
const sizeOfAssetDirValue = unsafe.Sizeof([1]C.AAssetDir{})
func (x *AssetDir) PassRef() *C.AAssetDir {
if x == nil {
x = (*AssetDir)(allocAssetDirMemory(1))
}
return (*C.AAssetDir)(unsafe.Pointer(x))
}
func (x *Asset) Ref() *C.AAsset {
if x == nil {
return nil
}
return (*C.AAsset)(unsafe.Pointer(x))
}
func (x *Asset) Free() {
if x != nil {
C.free(unsafe.Pointer(x))
}
}
func NewAssetRef(ref unsafe.Pointer) *Asset {
return (*Asset)(ref)
}
func NewAsset() *Asset {
return (*Asset)(allocAssetMemory(1))
}
func allocAssetMemory(n int) unsafe.Pointer {
mem, err := C.calloc(C.size_t(n), (C.size_t)(sizeOfAssetValue))
if err != nil {
panic("memory alloc error: " + err.Error())
}
return mem
}
const sizeOfAssetValue = unsafe.Sizeof([1]C.AAsset{})
func (x *Asset) PassRef() *C.AAsset {
if x == nil {
x = (*Asset)(allocAssetMemory(1))
}
return (*C.AAsset)(unsafe.Pointer(x))
}
func (x *JNINativeMethod) Ref() *C.JNINativeMethod {
if x == nil {
return nil
}
return (*C.JNINativeMethod)(unsafe.Pointer(x))
}
func (x *JNINativeMethod) Free() {
if x != nil {
C.free(unsafe.Pointer(x))
}
}
func NewJNINativeMethodRef(ref unsafe.Pointer) *JNINativeMethod {
return (*JNINativeMethod)(ref)
}
func NewJNINativeMethod() *JNINativeMethod {
return (*JNINativeMethod)(allocJNINativeMethodMemory(1))
}
func allocJNINativeMethodMemory(n int) unsafe.Pointer {
mem, err := C.calloc(C.size_t(n), (C.size_t)(sizeOfJNINativeMethodValue))
if err != nil {
panic("memory alloc error: " + err.Error())
}
return mem
}
const sizeOfJNINativeMethodValue = unsafe.Sizeof([1]C.JNINativeMethod{})
func (x *JNINativeMethod) PassRef() *C.JNINativeMethod {
if x == nil {
x = (*JNINativeMethod)(allocJNINativeMethodMemory(1))
}
return (*C.JNINativeMethod)(unsafe.Pointer(x))
}
func allocJavaVMAttachArgsMemory(n int) unsafe.Pointer {
mem, err := C.calloc(C.size_t(n), (C.size_t)(sizeOfJavaVMAttachArgsValue))
if err != nil {
panic("memory alloc error: " + err.Error())
}
return mem
}
const sizeOfJavaVMAttachArgsValue = unsafe.Sizeof([1]C.JavaVMAttachArgs{})
func unpackPCharString(str string) (*C.char, *cgoAllocMap) {
h := (*stringHeader)(unsafe.Pointer(&str))
return (*C.char)(unsafe.Pointer(h.Data)), cgoAllocsUnknown
}
type stringHeader struct {
Data uintptr
Len int
}
func packPCharString(p *C.char) (raw string) {
if p != nil && *p != 0 {
h := (*stringHeader)(unsafe.Pointer(&raw))
h.Data = uintptr(unsafe.Pointer(p))
for *p != 0 {
p = (*C.char)(unsafe.Pointer(uintptr(unsafe.Pointer(p)) + 1))
}
h.Len = int(uintptr(unsafe.Pointer(p)) - h.Data)
}
return
}
type RawString string
func (raw RawString) Copy() string {
if len(raw) == 0 {
return ""
}
h := (*stringHeader)(unsafe.Pointer(&raw))
return C.GoStringN((*C.char)(unsafe.Pointer(h.Data)), C.int(h.Len))
}
func (x *JavaVMAttachArgs) Ref() *C.JavaVMAttachArgs {
if x == nil {
return nil
}
return x.refab42f020
}
func (x *JavaVMAttachArgs) Free() {
if x != nil && x.allocsab42f020 != nil {
x.allocsab42f020.(*cgoAllocMap).Free()
x.refab42f020 = nil
}
}
func NewJavaVMAttachArgsRef(ref unsafe.Pointer) *JavaVMAttachArgs {
if ref == nil {
return nil
}
obj := new(JavaVMAttachArgs)
obj.refab42f020 = (*C.JavaVMAttachArgs)(unsafe.Pointer(ref))
return obj
}
func (x *JavaVMAttachArgs) PassRef() (*C.JavaVMAttachArgs, *cgoAllocMap) {
if x == nil {
return nil, nil
} else if x.refab42f020 != nil {
return x.refab42f020, nil
}
memab42f020 := allocJavaVMAttachArgsMemory(1)
refab42f020 := (*C.JavaVMAttachArgs)(memab42f020)
allocsab42f020 := new(cgoAllocMap)
allocsab42f020.Add(memab42f020)
var cversion_allocs *cgoAllocMap
refab42f020.version, cversion_allocs = (C.jint)(x.Version), cgoAllocsUnknown
allocsab42f020.Borrow(cversion_allocs)
var cname_allocs *cgoAllocMap
refab42f020.name, cname_allocs = unpackPCharString(x.Name)
allocsab42f020.Borrow(cname_allocs)
var cgroup_allocs *cgoAllocMap
refab42f020.group, cgroup_allocs = (C.jobject)(x.Group), cgoAllocsUnknown
allocsab42f020.Borrow(cgroup_allocs)
x.refab42f020 = refab42f020
x.allocsab42f020 = allocsab42f020
return refab42f020, allocsab42f020
}
func (x JavaVMAttachArgs) PassValue() (C.JavaVMAttachArgs, *cgoAllocMap) {
if x.refab42f020 != nil {
return *x.refab42f020, nil
}
ref, allocs := x.PassRef()
return *ref, allocs
}
func (x *JavaVMAttachArgs) Deref() {
if x.refab42f020 == nil {
return
}
x.Version = (Jint)(x.refab42f020.version)
x.Name = packPCharString(x.refab42f020.name)
x.Group = (Jobject)(x.refab42f020.group)
}
func (x *JavaVMOption) Ref() *C.JavaVMOption {
if x == nil {
return nil
}
return (*C.JavaVMOption)(unsafe.Pointer(x))
}
func (x *JavaVMOption) Free() {
if x != nil {
C.free(unsafe.Pointer(x))
}
}
func NewJavaVMOptionRef(ref unsafe.Pointer) *JavaVMOption {
return (*JavaVMOption)(ref)
}
func NewJavaVMOption() *JavaVMOption {
return (*JavaVMOption)(allocJavaVMOptionMemory(1))
}
func allocJavaVMOptionMemory(n int) unsafe.Pointer {
mem, err := C.calloc(C.size_t(n), (C.size_t)(sizeOfJavaVMOptionValue))
if err != nil {
panic("memory alloc error: " + err.Error())
}
return mem
}
const sizeOfJavaVMOptionValue = unsafe.Sizeof([1]C.JavaVMOption{})
func (x *JavaVMOption) PassRef() *C.JavaVMOption {
if x == nil {
x = (*JavaVMOption)(allocJavaVMOptionMemory(1))
}
return (*C.JavaVMOption)(unsafe.Pointer(x))
}
func (x *JavaVMInitArgs) Ref() *C.JavaVMInitArgs {
if x == nil {
return nil
}
return (*C.JavaVMInitArgs)(unsafe.Pointer(x))
}
func (x *JavaVMInitArgs) Free() {
if x != nil {
C.free(unsafe.Pointer(x))
}
}
func NewJavaVMInitArgsRef(ref unsafe.Pointer) *JavaVMInitArgs {
return (*JavaVMInitArgs)(ref)
}
func NewJavaVMInitArgs() *JavaVMInitArgs {
return (*JavaVMInitArgs)(allocJavaVMInitArgsMemory(1))
}
func allocJavaVMInitArgsMemory(n int) unsafe.Pointer {
mem, err := C.calloc(C.size_t(n), (C.size_t)(sizeOfJavaVMInitArgsValue))
if err != nil {
panic("memory alloc error: " + err.Error())
}
return mem
}
const sizeOfJavaVMInitArgsValue = unsafe.Sizeof([1]C.JavaVMInitArgs{})
func (x *JavaVMInitArgs) PassRef() *C.JavaVMInitArgs {
if x == nil {
x = (*JavaVMInitArgs)(allocJavaVMInitArgsMemory(1))
}
return (*C.JavaVMInitArgs)(unsafe.Pointer(x))
}
func (x *Configuration) Ref() *C.AConfiguration {
if x == nil {
return nil
}
return (*C.AConfiguration)(unsafe.Pointer(x))
}
func (x *Configuration) Free() {
if x != nil {
C.free(unsafe.Pointer(x))
}
}
func NewConfigurationRef(ref unsafe.Pointer) *Configuration {
return (*Configuration)(ref)
}
func NewConfiguration() *Configuration {
return (*Configuration)(allocConfigurationMemory(1))
}
func allocConfigurationMemory(n int) unsafe.Pointer {
mem, err := C.calloc(C.size_t(n), (C.size_t)(sizeOfConfigurationValue))
if err != nil {
panic("memory alloc error: " + err.Error())
}
return mem
}
const sizeOfConfigurationValue = unsafe.Sizeof([1]C.AConfiguration{})
func (x *Configuration) PassRef() *C.AConfiguration {
if x == nil {
x = (*Configuration)(allocConfigurationMemory(1))
}
return (*C.AConfiguration)(unsafe.Pointer(x))
}
func (x *Looper) Ref() *C.ALooper {
if x == nil {
return nil
}
return (*C.ALooper)(unsafe.Pointer(x))
} | MIT License |
spacemeshos/go-spacemesh | hare/messagevalidation.go | SyntacticallyValidateMessage | go | func (v *syntaxContextValidator) SyntacticallyValidateMessage(ctx context.Context, m *Msg) bool {
logger := v.WithContext(ctx)
if m == nil {
logger.Warning("syntax validation failed: m is nil")
return false
}
if m.PubKey == nil {
logger.Warning("syntax validation failed: missing public key")
return false
}
if m.InnerMsg == nil {
logger.With().Warning("syntax validation failed: inner message is nil",
log.String("sender_id", m.PubKey.ShortString()))
return false
}
claimedRound := m.InnerMsg.K % 4
switch m.InnerMsg.Type {
case pre:
return true
case status:
return claimedRound == statusRound
case proposal:
return claimedRound == proposalRound && v.validateSVP(ctx, m)
case commit:
return claimedRound == commitRound
case notify:
return v.validateCertificate(ctx, m.InnerMsg.Cert)
default:
logger.With().Error("unknown message type encountered during syntactic validation",
log.String("msg_type", m.InnerMsg.Type.String()))
return false
}
} | SyntacticallyValidateMessage the syntax of the provided message. | https://github.com/spacemeshos/go-spacemesh/blob/d4cbb8a6b64a0bc0ecadd6d3e47612839d1d9f23/hare/messagevalidation.go#L241-L277 | package hare
import (
"context"
"errors"
"fmt"
"time"
"github.com/spacemeshos/go-spacemesh/common/types"
"github.com/spacemeshos/go-spacemesh/log"
"github.com/spacemeshos/go-spacemesh/signing"
)
type messageValidator interface {
SyntacticallyValidateMessage(ctx context.Context, m *Msg) bool
ContextuallyValidateMessage(ctx context.Context, m *Msg, expectedK uint32) error
}
type identityProvider interface {
GetIdentity(edID string) (types.NodeID, error)
}
type eligibilityValidator struct {
oracle Rolacle
layersPerEpoch uint16
identityProvider identityProvider
maxExpActives int
expLeaders int
log.Log
}
func newEligibilityValidator(oracle Rolacle, layersPerEpoch uint16, idProvider identityProvider, maxExpActives, expLeaders int, logger log.Log) *eligibilityValidator {
return &eligibilityValidator{oracle, layersPerEpoch, idProvider, maxExpActives, expLeaders, logger}
}
func (ev *eligibilityValidator) validateRole(ctx context.Context, m *Msg) (bool, error) {
logger := ev.WithContext(ctx)
if m == nil {
logger.Error("eligibility validator: called with nil")
return false, errors.New("fatal: nil message")
}
if m.InnerMsg == nil {
logger.Error("eligibility validator: InnerMsg is nil")
return false, errors.New("fatal: nil inner message")
}
pub := m.PubKey
layer := m.InnerMsg.InstanceID
if layer.GetEpoch().IsGenesis() {
return true, nil
}
nID, err := ev.identityProvider.GetIdentity(pub.String())
if err != nil {
logger.With().Error("eligibility validator: GetIdentity failed (ignore if the safe layer is in genesis)",
log.Err(err),
log.String("sender_id", pub.ShortString()))
return false, fmt.Errorf("get identity: %w", err)
}
res, err := ev.oracle.Validate(ctx, layer, m.InnerMsg.K, expectedCommitteeSize(m.InnerMsg.K, ev.maxExpActives, ev.expLeaders), nID, m.InnerMsg.RoleProof, m.InnerMsg.EligibilityCount)
if err != nil {
logger.With().Error("eligibility validator: could not retrieve eligibility result",
log.Err(err),
log.String("sender_id", pub.ShortString()))
return false, fmt.Errorf("validate eligibility: %w", err)
}
if !res {
logger.With().Error("eligibility validator: sender is not eligible to participate",
log.String("sender_id", pub.ShortString()))
return false, nil
}
return true, nil
}
func (ev *eligibilityValidator) Validate(ctx context.Context, m *Msg) bool {
res, err := ev.validateRole(ctx, m)
if err != nil {
ev.WithContext(ctx).With().Error("error occurred while validating role",
log.Err(err),
log.String("sender_id", m.PubKey.ShortString()),
m.InnerMsg.InstanceID,
log.String("msg_type", m.InnerMsg.Type.String()))
return false
}
if !res {
ev.WithContext(ctx).With().Warning("validate message failed: role is invalid",
log.String("sender_id", m.PubKey.ShortString()),
m.InnerMsg.InstanceID,
log.String("msg_type", m.InnerMsg.Type.String()))
return false
}
return true
}
type roleValidator interface {
Validate(context.Context, *Msg) bool
}
type pubKeyGetter interface {
Track(*Msg)
PublicKey(*Message) *signing.PublicKey
}
type syntaxContextValidator struct {
signing Signer
threshold int
statusValidator func(m *Msg) bool
stateQuerier StateQuerier
layersPerEpoch uint16
roleValidator roleValidator
validMsgsTracker pubKeyGetter
log.Log
}
func newSyntaxContextValidator(sgr Signer, threshold int, validator func(m *Msg) bool, stateQuerier StateQuerier, layersPerEpoch uint16, ev roleValidator, validMsgsTracker pubKeyGetter, logger log.Log) *syntaxContextValidator {
return &syntaxContextValidator{sgr, threshold, validator, stateQuerier, layersPerEpoch, ev, validMsgsTracker, logger}
}
var (
errNilMsg = errors.New("nil message")
errNilInner = errors.New("nil inner message")
errEarlyMsg = errors.New("early message")
errInvalidIter = errors.New("incorrect iteration number")
errInvalidRound = errors.New("incorrect round")
errUnexpectedType = errors.New("unexpected message type")
)
func (v *syntaxContextValidator) ContextuallyValidateMessage(ctx context.Context, m *Msg, currentK uint32) error {
if m == nil {
return errNilMsg
}
if m.InnerMsg == nil {
return errNilInner
}
currentRound := currentK % 4
currentIteration := currentK / 4
msgIteration := m.InnerMsg.K / 4
sameIter := currentIteration == msgIteration
switch m.InnerMsg.Type {
case pre:
return nil
case notify:
if currentK == preRound && msgIteration != 0 {
return errInvalidIter
} else if currentK == preRound {
return errInvalidRound
}
if currentRound < commitRound && sameIter {
return errInvalidRound
}
if m.InnerMsg.K <= currentK {
return nil
}
if m.InnerMsg.K == currentK+1 && currentRound == commitRound {
return errEarlyMsg
}
return errInvalidIter
}
switch m.InnerMsg.Type {
case status:
if currentK == preRound && msgIteration != 0 {
return errInvalidIter
} else if currentK == preRound {
return errEarlyMsg
}
if currentRound == notifyRound && currentIteration+1 == msgIteration {
return errEarlyMsg
}
if currentRound == statusRound && sameIter {
return nil
}
if !sameIter {
return errInvalidIter
}
return errInvalidRound
case proposal:
if currentK == preRound && msgIteration != 0 {
return errInvalidIter
} else if currentK == preRound {
return errInvalidRound
}
if currentRound == statusRound && sameIter {
return errEarlyMsg
}
if (currentRound == proposalRound || currentRound == commitRound) && sameIter {
return nil
}
if !sameIter {
return errInvalidIter
}
return errInvalidRound
case commit:
if currentK == preRound && msgIteration != 0 {
return errInvalidIter
} else if currentK == preRound {
return errInvalidRound
}
if currentRound == proposalRound && sameIter {
return errEarlyMsg
}
if currentRound == commitRound && sameIter {
return nil
}
if !sameIter {
return errInvalidIter
}
return errInvalidRound
}
return errUnexpectedType
} | MIT License |
tikv/pd | server/handler.go | GetOperatorsOfKind | go | func (h *Handler) GetOperatorsOfKind(mask operator.OpKind) ([]*operator.Operator, error) {
ops, err := h.GetOperators()
if err != nil {
return nil, err
}
var results []*operator.Operator
for _, op := range ops {
if op.Kind()&mask != 0 {
results = append(results, op)
}
}
return results, nil
} | GetOperatorsOfKind returns the running operators of the kind. | https://github.com/tikv/pd/blob/35d07a131293acca3ad6d8c53fe5f204178c4ea1/server/handler.go#L412-L424 | package server
import (
"bytes"
"encoding/hex"
"fmt"
"net/http"
"path"
"strconv"
"strings"
"sync"
"time"
"github.com/pingcap/errors"
"github.com/pingcap/kvproto/pkg/metapb"
"github.com/pingcap/kvproto/pkg/pdpb"
"github.com/pingcap/log"
"github.com/tikv/pd/pkg/encryption"
"github.com/tikv/pd/pkg/errs"
"github.com/tikv/pd/server/cluster"
"github.com/tikv/pd/server/config"
"github.com/tikv/pd/server/core"
"github.com/tikv/pd/server/core/storelimit"
"github.com/tikv/pd/server/schedule"
"github.com/tikv/pd/server/schedule/operator"
"github.com/tikv/pd/server/schedule/opt"
"github.com/tikv/pd/server/schedule/placement"
"github.com/tikv/pd/server/schedulers"
"github.com/tikv/pd/server/statistics"
"github.com/tikv/pd/server/tso"
"go.uber.org/zap"
)
var (
SchedulerConfigHandlerPath = "/api/v1/scheduler-config"
ErrServerNotStarted = errors.New("The server has not been started")
ErrOperatorNotFound = errors.New("operator not found")
ErrAddOperator = errors.New("failed to add operator, maybe already have one")
ErrRegionNotAdjacent = errors.New("two regions are not adjacent")
ErrRegionNotFound = func(regionID uint64) error {
return errors.Errorf("region %v not found", regionID)
}
ErrRegionAbnormalPeer = func(regionID uint64) error {
return errors.Errorf("region %v has abnormal peer", regionID)
}
ErrStoreNotFound = func(storeID uint64) error {
return errors.Errorf("store %v not found", storeID)
}
ErrPluginNotFound = func(pluginPath string) error {
return errors.Errorf("plugin is not found: %s", pluginPath)
}
)
type Handler struct {
s *Server
opt *config.PersistOptions
pluginChMap map[string]chan string
pluginChMapLock sync.RWMutex
}
func newHandler(s *Server) *Handler {
return &Handler{s: s, opt: s.persistOptions, pluginChMap: make(map[string]chan string), pluginChMapLock: sync.RWMutex{}}
}
func (h *Handler) GetRaftCluster() (*cluster.RaftCluster, error) {
rc := h.s.GetRaftCluster()
if rc == nil {
return nil, errs.ErrNotBootstrapped.GenWithStackByArgs()
}
return rc, nil
}
func (h *Handler) GetOperatorController() (*schedule.OperatorController, error) {
rc := h.s.GetRaftCluster()
if rc == nil {
return nil, errs.ErrNotBootstrapped.GenWithStackByArgs()
}
return rc.GetOperatorController(), nil
}
func (h *Handler) IsSchedulerPaused(name string) (bool, error) {
rc, err := h.GetRaftCluster()
if err != nil {
return false, err
}
return rc.IsSchedulerPaused(name)
}
func (h *Handler) IsSchedulerDisabled(name string) (bool, error) {
rc, err := h.GetRaftCluster()
if err != nil {
return false, err
}
return rc.IsSchedulerDisabled(name)
}
func (h *Handler) IsSchedulerExisted(name string) (bool, error) {
rc, err := h.GetRaftCluster()
if err != nil {
return false, err
}
return rc.IsSchedulerExisted(name)
}
func (h *Handler) GetScheduleConfig() *config.ScheduleConfig {
return h.s.GetScheduleConfig()
}
func (h *Handler) GetSchedulers() ([]string, error) {
c, err := h.GetRaftCluster()
if err != nil {
return nil, err
}
return c.GetSchedulers(), nil
}
func (h *Handler) IsCheckerPaused(name string) (bool, error) {
rc, err := h.GetRaftCluster()
if err != nil {
return false, err
}
return rc.IsCheckerPaused(name)
}
func (h *Handler) GetStores() ([]*core.StoreInfo, error) {
rc := h.s.GetRaftCluster()
if rc == nil {
return nil, errs.ErrNotBootstrapped.GenWithStackByArgs()
}
storeMetas := rc.GetMetaStores()
stores := make([]*core.StoreInfo, 0, len(storeMetas))
for _, s := range storeMetas {
storeID := s.GetId()
store := rc.GetStore(storeID)
if store == nil {
return nil, ErrStoreNotFound(storeID)
}
stores = append(stores, store)
}
return stores, nil
}
func (h *Handler) GetHotWriteRegions() *statistics.StoreHotPeersInfos {
c, err := h.GetRaftCluster()
if err != nil {
return nil
}
return c.GetHotWriteRegions()
}
func (h *Handler) GetHotReadRegions() *statistics.StoreHotPeersInfos {
c, err := h.GetRaftCluster()
if err != nil {
return nil
}
return c.GetHotReadRegions()
}
func (h *Handler) GetStoresLoads() map[uint64][]float64 {
rc := h.s.GetRaftCluster()
if rc == nil {
return nil
}
return rc.GetStoresLoads()
}
func (h *Handler) AddScheduler(name string, args ...string) error {
c, err := h.GetRaftCluster()
if err != nil {
return err
}
s, err := schedule.CreateScheduler(name, c.GetOperatorController(), h.s.storage, schedule.ConfigSliceDecoder(name, args))
if err != nil {
return err
}
log.Info("create scheduler", zap.String("scheduler-name", s.GetName()), zap.Strings("scheduler-args", args))
if err = c.AddScheduler(s, args...); err != nil {
log.Error("can not add scheduler", zap.String("scheduler-name", s.GetName()), zap.Strings("scheduler-args", args), errs.ZapError(err))
} else if err = h.opt.Persist(c.GetStorage()); err != nil {
log.Error("can not persist scheduler config", errs.ZapError(err))
}
return err
}
func (h *Handler) RemoveScheduler(name string) error {
c, err := h.GetRaftCluster()
if err != nil {
return err
}
if err = c.RemoveScheduler(name); err != nil {
log.Error("can not remove scheduler", zap.String("scheduler-name", name), errs.ZapError(err))
}
return err
}
func (h *Handler) PauseOrResumeScheduler(name string, t int64) error {
c, err := h.GetRaftCluster()
if err != nil {
return err
}
if err = c.PauseOrResumeScheduler(name, t); err != nil {
if t == 0 {
log.Error("can not resume scheduler", zap.String("scheduler-name", name), errs.ZapError(err))
} else {
log.Error("can not pause scheduler", zap.String("scheduler-name", name), errs.ZapError(err))
}
}
return err
}
func (h *Handler) PauseOrResumeChecker(name string, t int64) error {
c, err := h.GetRaftCluster()
if err != nil {
return err
}
if err = c.PauseOrResumeChecker(name, t); err != nil {
if t == 0 {
log.Error("can not resume checker", zap.String("checker-name", name), errs.ZapError(err))
} else {
log.Error("can not pause checker", zap.String("checker-name", name), errs.ZapError(err))
}
}
return err
}
func (h *Handler) AddBalanceLeaderScheduler() error {
return h.AddScheduler(schedulers.BalanceLeaderType)
}
func (h *Handler) AddBalanceRegionScheduler() error {
return h.AddScheduler(schedulers.BalanceRegionType)
}
func (h *Handler) AddBalanceHotRegionScheduler() error {
return h.AddScheduler(schedulers.HotRegionType)
}
func (h *Handler) AddLabelScheduler() error {
return h.AddScheduler(schedulers.LabelType)
}
func (h *Handler) AddScatterRangeScheduler(args ...string) error {
return h.AddScheduler(schedulers.ScatterRangeType, args...)
}
func (h *Handler) AddGrantLeaderScheduler(storeID uint64) error {
return h.AddScheduler(schedulers.GrantLeaderType, strconv.FormatUint(storeID, 10))
}
func (h *Handler) AddEvictLeaderScheduler(storeID uint64) error {
return h.AddScheduler(schedulers.EvictLeaderType, strconv.FormatUint(storeID, 10))
}
func (h *Handler) AddShuffleLeaderScheduler() error {
return h.AddScheduler(schedulers.ShuffleLeaderType)
}
func (h *Handler) AddShuffleRegionScheduler() error {
return h.AddScheduler(schedulers.ShuffleRegionType)
}
func (h *Handler) AddShuffleHotRegionScheduler(limit uint64) error {
return h.AddScheduler(schedulers.ShuffleHotRegionType, strconv.FormatUint(limit, 10))
}
func (h *Handler) AddEvictSlowStoreScheduler() error {
return h.AddScheduler(schedulers.EvictSlowStoreType)
}
func (h *Handler) AddRandomMergeScheduler() error {
return h.AddScheduler(schedulers.RandomMergeType)
}
func (h *Handler) GetOperator(regionID uint64) (*operator.Operator, error) {
c, err := h.GetOperatorController()
if err != nil {
return nil, err
}
op := c.GetOperator(regionID)
if op == nil {
return nil, ErrOperatorNotFound
}
return op, nil
}
func (h *Handler) GetOperatorStatus(regionID uint64) (*schedule.OperatorWithStatus, error) {
c, err := h.GetOperatorController()
if err != nil {
return nil, err
}
op := c.GetOperatorStatus(regionID)
if op == nil {
return nil, ErrOperatorNotFound
}
return op, nil
}
func (h *Handler) RemoveOperator(regionID uint64) error {
c, err := h.GetOperatorController()
if err != nil {
return err
}
op := c.GetOperator(regionID)
if op == nil {
return ErrOperatorNotFound
}
_ = c.RemoveOperator(op)
return nil
}
func (h *Handler) GetOperators() ([]*operator.Operator, error) {
c, err := h.GetOperatorController()
if err != nil {
return nil, err
}
return c.GetOperators(), nil
}
func (h *Handler) GetWaitingOperators() ([]*operator.Operator, error) {
c, err := h.GetOperatorController()
if err != nil {
return nil, err
}
return c.GetWaitingOperators(), nil
}
func (h *Handler) GetAdminOperators() ([]*operator.Operator, error) {
return h.GetOperatorsOfKind(operator.OpAdmin)
}
func (h *Handler) GetLeaderOperators() ([]*operator.Operator, error) {
return h.GetOperatorsOfKind(operator.OpLeader)
}
func (h *Handler) GetRegionOperators() ([]*operator.Operator, error) {
return h.GetOperatorsOfKind(operator.OpRegion)
} | Apache License 2.0 |
google/cel-go | common/types/err.go | NoSuchOverloadErr | go | func NoSuchOverloadErr() ref.Val {
return celErrNoSuchOverload
} | NoSuchOverloadErr returns a new types.Err instance with a no such overload message. | https://github.com/google/cel-go/blob/8e5d9877f0ab106269dee64e5bf10c5315281830/common/types/err.go#L59-L61 | package types
import (
"errors"
"fmt"
"reflect"
"github.com/google/cel-go/common/types/ref"
)
type Err struct {
error
}
var (
ErrType = NewTypeValue("error")
errDivideByZero = errors.New("division by zero")
errModulusByZero = errors.New("modulus by zero")
errIntOverflow = errors.New("integer overflow")
errUintOverflow = errors.New("unsigned integer overflow")
errDurationOverflow = errors.New("duration overflow")
errTimestampOverflow = errors.New("timestamp overflow")
celErrTimestampOverflow = &Err{error: errTimestampOverflow}
celErrNoSuchOverload = NewErr("no such overload")
)
func NewErr(format string, args ...interface{}) ref.Val {
return &Err{fmt.Errorf(format, args...)}
} | Apache License 2.0 |
emer/emergent | emer/prjn.go | SendNameTry | go | func (pl *Prjns) SendNameTry(sender string) (Prjn, error) {
for _, pj := range *pl {
if pj.SendLay().Name() == sender {
return pj, nil
}
}
return nil, fmt.Errorf("sending layer: %v not found in list of projections", sender)
} | SendNameTry finds the projection with given send layer name.
returns error message if not found | https://github.com/emer/emergent/blob/f533e604942e6578f91de3eb5e439da14c954de8/emer/prjn.go#L220-L227 | package emer
import (
"fmt"
"io"
"github.com/emer/emergent/params"
"github.com/emer/emergent/prjn"
"github.com/emer/emergent/weights"
"github.com/goki/ki/kit"
)
type Prjn interface {
params.Styler
Init(prjn Prjn)
SendLay() Layer
RecvLay() Layer
Pattern() prjn.Pattern
SetPattern(pat prjn.Pattern) Prjn
Type() PrjnType
SetType(typ PrjnType) Prjn
PrjnTypeName() string
Connect(send, recv Layer, pat prjn.Pattern, typ PrjnType)
SetClass(cls string) Prjn
Label() string
IsOff() bool
SetOff(off bool)
SynVarNames() []string
SynVarProps() map[string]string
SynIdx(sidx, ridx int) int
SynVarIdx(varNm string) (int, error)
SynVarNum() int
SynVal1D(varIdx int, synIdx int) float32
SynVals(vals *[]float32, varNm string) error
SynVal(varNm string, sidx, ridx int) float32
SetSynVal(varNm string, sidx, ridx int, val float32) error
Defaults()
UpdateParams()
ApplyParams(pars *params.Sheet, setMsg bool) (bool, error)
NonDefaultParams() string
AllParams() string
WriteWtsJSON(w io.Writer, depth int)
ReadWtsJSON(r io.Reader) error
SetWts(pw *weights.Prjn) error
Build() error
}
type Prjns []Prjn
func (pl *Prjns) ElemLabel(idx int) string {
if len(*pl) == 0 {
return "(empty)"
}
if idx < 0 || idx >= len(*pl) {
return ""
}
pj := (*pl)[idx]
if kit.IfaceIsNil(pj) {
return "nil"
}
return pj.Name()
}
func (pl *Prjns) Add(p Prjn) {
(*pl) = append(*pl, p)
}
func (pl *Prjns) Send(send Layer) (Prjn, bool) {
for _, pj := range *pl {
if pj.SendLay() == send {
return pj, true
}
}
return nil, false
}
func (pl *Prjns) Recv(recv Layer) (Prjn, bool) {
for _, pj := range *pl {
if pj.RecvLay() == recv {
return pj, true
}
}
return nil, false
}
func (pl *Prjns) SendName(sender string) Prjn {
pj, _ := pl.SendNameTry(sender)
return pj
}
func (pl *Prjns) RecvName(recv string) Prjn {
pj, _ := pl.RecvNameTry(recv)
return pj
} | BSD 3-Clause New or Revised License |
itsabot/itsabot | shared/language/extract.go | ExtractEmails | go | func ExtractEmails(s string) ([]string, error) {
emails := regexEmail.FindAllString(s, -1)
if emails == nil {
return []string{}, ErrNotFound
}
return emails, nil
} | ExtractEmails from a user's message. | https://github.com/itsabot/itsabot/blob/48a5b1e70afca321d0c522922746b667c29a6070/shared/language/extract.go#L229-L235 | package language
import (
"encoding/xml"
"errors"
"io/ioutil"
"net/http"
"net/url"
"os"
"regexp"
"strconv"
"strings"
"github.com/itsabot/abot/core/log"
"github.com/itsabot/abot/shared/datatypes"
"github.com/itsabot/abot/shared/helpers/address"
"github.com/jmoiron/sqlx"
)
var regexCurrency = regexp.MustCompile(`\d+\.?\d*`)
var regexNum = regexp.MustCompile(`\d+`)
var regexNonWords = regexp.MustCompile(`[^\w\s]`)
var regexEmail = regexp.MustCompile(`\S+@\S+\.\w+`)
var ErrNotFound = errors.New("couldn't extract requested type from string")
func ExtractCurrency(s string) (int64, error) {
s = regexCurrency.FindString(s)
if len(s) == 0 {
return 0, ErrNotFound
}
val, err := strconv.ParseFloat(s, 64)
if err != nil {
return 0, err
}
log.Debug("found value", val)
return int64(val * 100), nil
}
func ExtractYesNo(s string) (bool, error) {
ss := strings.Fields(strings.ToLower(s))
for _, w := range ss {
w = strings.TrimRight(w, " .,;:!?'\"")
_, ok := yes[w]
if ok {
return true, nil
}
_, ok = no[w]
if ok {
return false, nil
}
}
return false, ErrNotFound
}
func ExtractAddress(db *sqlx.DB, u *dt.User, s string) (*dt.Address, bool, error) {
addr, err := address.Parse(s)
if err != nil {
return nil, false, err
}
type addr2S struct {
XMLName xml.Name `xml:"Address"`
ID string `xml:"ID,attr"`
FirmName string
Address1 string
Address2 string
City string
State string
Zip5 string
Zip4 string
}
addr2Stmp := addr2S{
ID: "0",
Address1: addr.Line2,
Address2: addr.Line1,
City: addr.City,
State: addr.State,
Zip5: addr.Zip5,
Zip4: addr.Zip4,
}
if len(addr.Zip) > 0 {
addr2Stmp.Zip5 = addr.Zip[:5]
}
if len(addr.Zip) > 5 {
addr2Stmp.Zip4 = addr.Zip[5:]
}
addrS := struct {
XMLName xml.Name `xml:"AddressValidateRequest"`
USPSUserID string `xml:"USERID,attr"`
Address addr2S
}{
USPSUserID: os.Getenv("USPS_USER_ID"),
Address: addr2Stmp,
}
xmlAddr, err := xml.Marshal(addrS)
if err != nil {
return nil, false, err
}
log.Debug(string(xmlAddr))
ul := "https://secure.shippingapis.com/ShippingAPI.dll?API=Verify&XML="
ul += url.QueryEscape(string(xmlAddr))
response, err := http.Get(ul)
if err != nil {
return nil, false, err
}
contents, err := ioutil.ReadAll(response.Body)
if err != nil {
return nil, false, err
}
if err = response.Body.Close(); err != nil {
return nil, false, err
}
resp := struct {
XMLName xml.Name `xml:"AddressValidateResponse"`
USPSUserID string `xml:"USERID,attr"`
Address addr2S
}{
USPSUserID: os.Getenv("USPS_USER_ID"),
Address: addr2Stmp,
}
if err = xml.Unmarshal(contents, &resp); err != nil {
log.Debug("USPS response", string(contents))
return nil, false, err
}
a := dt.Address{
Name: resp.Address.FirmName,
Line1: resp.Address.Address2,
Line2: resp.Address.Address1,
City: resp.Address.City,
State: resp.Address.State,
Zip5: resp.Address.Zip5,
Zip4: resp.Address.Zip4,
}
if len(resp.Address.Zip4) > 0 {
a.Zip = resp.Address.Zip5 + "-" + resp.Address.Zip4
} else {
a.Zip = resp.Address.Zip5
}
return &a, false, nil
}
func ExtractCount(s string) (int64, error) {
s = regexNum.FindString(s)
if len(s) == 0 {
return 0, ErrNotFound
}
val, err := strconv.ParseInt(s, 10, 64)
if err != nil {
return 0, err
}
return val, nil
}
func ExtractCities(db *sqlx.DB, in *dt.Msg) ([]dt.City, error) {
var args []interface{}
var start int
for i := range in.Stems {
switch in.Stems[i] {
case "at", "in", "on":
start = i
break
}
}
tmp := regexNonWords.ReplaceAllString(in.Sentence, "")
words := strings.Fields(strings.Title(tmp))
for i := start; i < len(words); i++ {
args = append(args, words[i])
}
bgs := bigrams(words, start)
for i := 0; i < len(bgs); i++ {
args = append(args, bgs[i])
}
cities := []dt.City{}
q := `SELECT name, countrycode FROM cities
WHERE countrycode='US' AND name IN (?)
ORDER BY LENGTH(name) DESC`
query, arguments, err := sqlx.In(q, args)
query = db.Rebind(query)
rows, err := db.Query(query, arguments...)
if err != nil {
return nil, err
}
defer func() {
if err = rows.Close(); err != nil {
log.Info("failed to close db rows.", err)
}
}()
for rows.Next() {
city := dt.City{}
if err = rows.Scan(&city.Name, &city.CountryCode); err != nil {
return nil, err
}
cities = append(cities, city)
}
if err = rows.Err(); err != nil {
return nil, err
}
if len(cities) == 0 {
return nil, ErrNotFound
}
return cities, nil
} | MIT License |
thethingsnetwork/lorawan-stack | pkg/ttnpb/search_services.pb.validate.go | ErrorName | go | func (e SearchClientsRequestValidationError) ErrorName() string {
return "SearchClientsRequestValidationError"
} | ErrorName returns error name. | https://github.com/thethingsnetwork/lorawan-stack/blob/228c615c0d55ce2eb21c750d644d9e9dd73d9f77/pkg/ttnpb/search_services.pb.validate.go#L396-L398 | package ttnpb
import (
"bytes"
"errors"
"fmt"
"net"
"net/mail"
"net/url"
"regexp"
"strings"
"time"
"unicode/utf8"
"github.com/gogo/protobuf/types"
)
var (
_ = bytes.MinRead
_ = errors.New("")
_ = fmt.Print
_ = utf8.UTFMax
_ = (*regexp.Regexp)(nil)
_ = (*strings.Reader)(nil)
_ = net.IPv4len
_ = time.Duration(0)
_ = (*url.URL)(nil)
_ = (*mail.Address)(nil)
_ = types.DynamicAny{}
)
var _search_services_uuidPattern = regexp.MustCompile("^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$")
func (m *SearchApplicationsRequest) ValidateFields(paths ...string) error {
if m == nil {
return nil
}
if len(paths) == 0 {
paths = SearchApplicationsRequestFieldPathsNested
}
for name, subs := range _processPaths(append(paths[:0:0], paths...)) {
_ = subs
switch name {
case "id_contains":
if utf8.RuneCountInString(m.GetIdContains()) > 50 {
return SearchApplicationsRequestValidationError{
field: "id_contains",
reason: "value length must be at most 50 runes",
}
}
case "name_contains":
if utf8.RuneCountInString(m.GetNameContains()) > 50 {
return SearchApplicationsRequestValidationError{
field: "name_contains",
reason: "value length must be at most 50 runes",
}
}
case "description_contains":
if utf8.RuneCountInString(m.GetDescriptionContains()) > 50 {
return SearchApplicationsRequestValidationError{
field: "description_contains",
reason: "value length must be at most 50 runes",
}
}
case "attributes_contain":
if len(m.GetAttributesContain()) > 10 {
return SearchApplicationsRequestValidationError{
field: "attributes_contain",
reason: "value must contain no more than 10 pair(s)",
}
}
for key, val := range m.GetAttributesContain() {
_ = val
if utf8.RuneCountInString(key) > 36 {
return SearchApplicationsRequestValidationError{
field: fmt.Sprintf("attributes_contain[%v]", key),
reason: "value length must be at most 36 runes",
}
}
if !_SearchApplicationsRequest_AttributesContain_Pattern.MatchString(key) {
return SearchApplicationsRequestValidationError{
field: fmt.Sprintf("attributes_contain[%v]", key),
reason: "value does not match regex pattern \"^[a-z0-9](?:[-]?[a-z0-9]){2,}$\"",
}
}
if utf8.RuneCountInString(val) > 50 {
return SearchApplicationsRequestValidationError{
field: fmt.Sprintf("attributes_contain[%v]", key),
reason: "value length must be at most 50 runes",
}
}
}
case "field_mask":
if v, ok := interface{}(m.GetFieldMask()).(interface{ ValidateFields(...string) error }); ok {
if err := v.ValidateFields(subs...); err != nil {
return SearchApplicationsRequestValidationError{
field: "field_mask",
reason: "embedded message failed validation",
cause: err,
}
}
}
case "order":
if _, ok := _SearchApplicationsRequest_Order_InLookup[m.GetOrder()]; !ok {
return SearchApplicationsRequestValidationError{
field: "order",
reason: "value must be in list [ application_id -application_id name -name created_at -created_at]",
}
}
case "limit":
if m.GetLimit() > 1000 {
return SearchApplicationsRequestValidationError{
field: "limit",
reason: "value must be less than or equal to 1000",
}
}
case "page":
case "deleted":
default:
return SearchApplicationsRequestValidationError{
field: name,
reason: "invalid field path",
}
}
}
return nil
}
type SearchApplicationsRequestValidationError struct {
field string
reason string
cause error
key bool
}
func (e SearchApplicationsRequestValidationError) Field() string { return e.field }
func (e SearchApplicationsRequestValidationError) Reason() string { return e.reason }
func (e SearchApplicationsRequestValidationError) Cause() error { return e.cause }
func (e SearchApplicationsRequestValidationError) Key() bool { return e.key }
func (e SearchApplicationsRequestValidationError) ErrorName() string {
return "SearchApplicationsRequestValidationError"
}
func (e SearchApplicationsRequestValidationError) Error() string {
cause := ""
if e.cause != nil {
cause = fmt.Sprintf(" | caused by: %v", e.cause)
}
key := ""
if e.key {
key = "key for "
}
return fmt.Sprintf(
"invalid %sSearchApplicationsRequest.%s: %s%s",
key,
e.field,
e.reason,
cause)
}
var _ error = SearchApplicationsRequestValidationError{}
var _ interface {
Field() string
Reason() string
Key() bool
Cause() error
ErrorName() string
} = SearchApplicationsRequestValidationError{}
var _SearchApplicationsRequest_AttributesContain_Pattern = regexp.MustCompile("^[a-z0-9](?:[-]?[a-z0-9]){2,}$")
var _SearchApplicationsRequest_Order_InLookup = map[string]struct{}{
"": {},
"application_id": {},
"-application_id": {},
"name": {},
"-name": {},
"created_at": {},
"-created_at": {},
}
func (m *SearchClientsRequest) ValidateFields(paths ...string) error {
if m == nil {
return nil
}
if len(paths) == 0 {
paths = SearchClientsRequestFieldPathsNested
}
for name, subs := range _processPaths(append(paths[:0:0], paths...)) {
_ = subs
switch name {
case "id_contains":
if utf8.RuneCountInString(m.GetIdContains()) > 50 {
return SearchClientsRequestValidationError{
field: "id_contains",
reason: "value length must be at most 50 runes",
}
}
case "name_contains":
if utf8.RuneCountInString(m.GetNameContains()) > 50 {
return SearchClientsRequestValidationError{
field: "name_contains",
reason: "value length must be at most 50 runes",
}
}
case "description_contains":
if utf8.RuneCountInString(m.GetDescriptionContains()) > 50 {
return SearchClientsRequestValidationError{
field: "description_contains",
reason: "value length must be at most 50 runes",
}
}
case "attributes_contain":
if len(m.GetAttributesContain()) > 10 {
return SearchClientsRequestValidationError{
field: "attributes_contain",
reason: "value must contain no more than 10 pair(s)",
}
}
for key, val := range m.GetAttributesContain() {
_ = val
if utf8.RuneCountInString(key) > 36 {
return SearchClientsRequestValidationError{
field: fmt.Sprintf("attributes_contain[%v]", key),
reason: "value length must be at most 36 runes",
}
}
if !_SearchClientsRequest_AttributesContain_Pattern.MatchString(key) {
return SearchClientsRequestValidationError{
field: fmt.Sprintf("attributes_contain[%v]", key),
reason: "value does not match regex pattern \"^[a-z0-9](?:[-]?[a-z0-9]){2,}$\"",
}
}
if utf8.RuneCountInString(val) > 50 {
return SearchClientsRequestValidationError{
field: fmt.Sprintf("attributes_contain[%v]", key),
reason: "value length must be at most 50 runes",
}
}
}
case "state":
_SearchClientsRequest_State_Unique := make(map[State]struct{}, len(m.GetState()))
for idx, item := range m.GetState() {
_, _ = idx, item
if _, exists := _SearchClientsRequest_State_Unique[item]; exists {
return SearchClientsRequestValidationError{
field: fmt.Sprintf("state[%v]", idx),
reason: "repeated value must contain unique items",
}
} else {
_SearchClientsRequest_State_Unique[item] = struct{}{}
}
if _, ok := State_name[int32(item)]; !ok {
return SearchClientsRequestValidationError{
field: fmt.Sprintf("state[%v]", idx),
reason: "value must be one of the defined enum values",
}
}
}
case "field_mask":
if v, ok := interface{}(m.GetFieldMask()).(interface{ ValidateFields(...string) error }); ok {
if err := v.ValidateFields(subs...); err != nil {
return SearchClientsRequestValidationError{
field: "field_mask",
reason: "embedded message failed validation",
cause: err,
}
}
}
case "order":
if _, ok := _SearchClientsRequest_Order_InLookup[m.GetOrder()]; !ok {
return SearchClientsRequestValidationError{
field: "order",
reason: "value must be in list [ client_id -client_id name -name created_at -created_at]",
}
}
case "limit":
if m.GetLimit() > 1000 {
return SearchClientsRequestValidationError{
field: "limit",
reason: "value must be less than or equal to 1000",
}
}
case "page":
case "deleted":
default:
return SearchClientsRequestValidationError{
field: name,
reason: "invalid field path",
}
}
}
return nil
}
type SearchClientsRequestValidationError struct {
field string
reason string
cause error
key bool
}
func (e SearchClientsRequestValidationError) Field() string { return e.field }
func (e SearchClientsRequestValidationError) Reason() string { return e.reason }
func (e SearchClientsRequestValidationError) Cause() error { return e.cause }
func (e SearchClientsRequestValidationError) Key() bool { return e.key } | Apache License 2.0 |
gonutz/d3d9 | surface_windows.go | GetPriority | go | func (obj *Surface) GetPriority() uint32 {
ret, _, _ := syscall.Syscall(
obj.vtbl.GetPriority,
1,
uintptr(unsafe.Pointer(obj)),
0,
0,
)
return uint32(ret)
} | GetPriority retrieves the priority for this resource. | https://github.com/gonutz/d3d9/blob/b9ca928c52bce58d7edb55a856de874c57130345/surface_windows.go#L171-L180 | package d3d9
import (
"syscall"
"unsafe"
)
type Surface struct {
vtbl *surfaceVtbl
}
type surfaceVtbl struct {
QueryInterface uintptr
AddRef uintptr
Release uintptr
GetDevice uintptr
SetPrivateData uintptr
GetPrivateData uintptr
FreePrivateData uintptr
SetPriority uintptr
GetPriority uintptr
PreLoad uintptr
GetType uintptr
GetContainer uintptr
GetDesc uintptr
LockRect uintptr
UnlockRect uintptr
GetDC uintptr
ReleaseDC uintptr
}
func (obj *Surface) AddRef() uint32 {
ret, _, _ := syscall.Syscall(
obj.vtbl.AddRef,
1,
uintptr(unsafe.Pointer(obj)),
0,
0,
)
return uint32(ret)
}
func (obj *Surface) Release() uint32 {
ret, _, _ := syscall.Syscall(
obj.vtbl.Release,
1,
uintptr(unsafe.Pointer(obj)),
0,
0,
)
return uint32(ret)
}
func (obj *Surface) GetDevice() (device *Device, err Error) {
ret, _, _ := syscall.Syscall(
obj.vtbl.GetDevice,
2,
uintptr(unsafe.Pointer(obj)),
uintptr(unsafe.Pointer(&device)),
0,
)
err = toErr(ret)
return
}
func (obj *Surface) SetPrivateData(
refguid GUID,
data uintptr,
sizeOfData uint32,
flags uint32,
) Error {
ret, _, _ := syscall.Syscall6(
obj.vtbl.SetPrivateData,
5,
uintptr(unsafe.Pointer(obj)),
uintptr(unsafe.Pointer(&refguid)),
data,
uintptr(sizeOfData),
uintptr(flags),
0,
)
return toErr(ret)
}
func (obj *Surface) SetPrivateDataBytes(
refguid GUID,
data []byte,
flags uint32,
) Error {
return obj.SetPrivateData(
refguid,
uintptr(unsafe.Pointer(&data[0])),
uint32(len(data)),
flags,
)
}
func (obj *Surface) GetPrivateData(refguid GUID) (data []byte, err Error) {
var sizeInBytes uint
ret, _, _ := syscall.Syscall6(
obj.vtbl.GetPrivateData,
4,
uintptr(unsafe.Pointer(obj)),
uintptr(unsafe.Pointer(&refguid)),
0,
uintptr(unsafe.Pointer(&sizeInBytes)),
0,
0,
)
if err := toErr(ret); err != nil {
return nil, err
}
data = make([]byte, sizeInBytes)
ret, _, _ = syscall.Syscall6(
obj.vtbl.GetPrivateData,
4,
uintptr(unsafe.Pointer(obj)),
uintptr(unsafe.Pointer(&refguid)),
uintptr(unsafe.Pointer(&data[0])),
uintptr(unsafe.Pointer(&sizeInBytes)),
0,
0,
)
return data, toErr(ret)
}
func (obj *Surface) FreePrivateData(refguid GUID) Error {
ret, _, _ := syscall.Syscall(
obj.vtbl.FreePrivateData,
2,
uintptr(unsafe.Pointer(obj)),
uintptr(unsafe.Pointer(&refguid)),
0,
)
return toErr(ret)
}
func (obj *Surface) SetPriority(priorityNew uint32) uint32 {
ret, _, _ := syscall.Syscall(
obj.vtbl.SetPriority,
2,
uintptr(unsafe.Pointer(obj)),
uintptr(priorityNew),
0,
)
return uint32(ret)
} | MIT License |
pingcap/tidb-tools | pkg/utils/printer.go | PrintInfo | go | func PrintInfo(app string) {
log.Info("Welcome to "+app,
zap.String("Release Version", Version),
zap.String("Git Commit Hash", GitHash),
zap.String("Git Branch", GitBranch),
zap.String("UTC Build Time", BuildTS),
zap.String("Go Version", runtime.Version()),
)
} | PrintInfo prints the app's basic information in log | https://github.com/pingcap/tidb-tools/blob/37a8bef2fa17ccb3bd0c0e3760cd962114aa4a7c/pkg/utils/printer.go#L44-L52 | package utils
import (
"fmt"
"runtime"
"github.com/pingcap/log"
"go.uber.org/zap"
)
var (
Version = "None"
BuildTS = "None"
GitHash = "None"
GitBranch = "None"
)
func GetRawInfo(app string) string {
info := ""
info += fmt.Sprintf("%s: %s\n", app, Version)
info += fmt.Sprintf("Git Commit Hash: %s\n", GitHash)
info += fmt.Sprintf("Git Branch: %s\n", GitBranch)
info += fmt.Sprintf("UTC Build Time: %s\n", BuildTS)
info += fmt.Sprintf("Go Version: %s\n", runtime.Version())
return info
} | Apache License 2.0 |
spkaeros/rscgo | pkg/game/world/mob.go | SetDirection | go | func (m *Mob) SetDirection(direction int) {
m.SetVar("direction", direction)
m.SetSpriteUpdated()
} | SetDirection Sets the mobs direction. | https://github.com/spkaeros/rscgo/blob/b6f29c32bdb16216c804e164b1935269beca129d/pkg/game/world/mob.go#L285-L288 | package world
import (
"math"
"math/rand"
"sync"
"time"
"github.com/spkaeros/rscgo/pkg/game/entity"
"github.com/spkaeros/rscgo/pkg/log"
"github.com/spkaeros/rscgo/pkg/isaac"
rscRand "github.com/spkaeros/rscgo/pkg/rand"
"github.com/spkaeros/rscgo/pkg/tasks"
)
type MobState = int
const (
StateIdle MobState = 0
StateChatting = 1 << iota
StateFighting
StateBanking
StateMenu
StateTrading
StateDueling
MSBatching
StateSleeping
StateChangingLooks
StateShopping
MSItemAction
StateAction
StateFightingDuel = StateDueling | StateFighting
StateChatChoosing = StateMenu | StateChatting
StateItemChoosing = StateMenu | MSItemAction
StateObjectChoosing = StateMenu | MSBatching
StatePanelActive = StateBanking | StateShopping | StateChangingLooks | StateSleeping | StateTrading | StateDueling
StateBusy = StatePanelActive | StateChatting | MSItemAction | MSBatching | StateAction
StateWaitEvent = StateMenu | StateChatting | MSItemAction | MSBatching
)
const (
SyncInit = 0
SyncSprite = 1 << iota
SyncMoved
SyncRemoved
SyncAppearance
SyncNeedsPosition = SyncRemoved | SyncMoved | SyncSprite
)
var mask = ^3
type mobSet []entity.MobileEntity
type MobList struct {
mobSet
sync.RWMutex
}
func NewMobList() *MobList {
return &MobList{mobSet: make(mobSet, 0, 255)}
}
func (l *MobList) Add(m entity.MobileEntity) int {
l.Lock()
defer l.Unlock()
l.mobSet = append(l.mobSet, m)
return len(l.mobSet)
}
func (l *MobList) Range(action func(entity.MobileEntity) bool) int {
l.RLock()
defer l.RUnlock()
for i, v := range l.mobSet {
if action(v) {
return i
}
}
return -1
}
func (l *MobList) Size() int {
l.RLock()
defer l.RUnlock()
return len(l.mobSet)
}
func (l *MobList) Contains(mob entity.MobileEntity) bool {
l.RLock()
defer l.RUnlock()
for _, v := range l.mobSet {
if v == mob {
return true
}
}
return false
}
func (l *MobList) Remove(m entity.MobileEntity) bool {
l.Lock()
defer l.Unlock()
for i, v := range l.mobSet {
if v == m {
if i >= len(l.mobSet) {
l.mobSet = l.mobSet[:i]
} else {
l.mobSet = append(l.mobSet[:i], l.mobSet[i+1:]...)
}
return true
}
}
return false
}
func (l *MobList) RangePlayers(action func(*Player) bool) int {
return l.Range(func(m entity.MobileEntity) bool {
if p := AsPlayer(m); p != nil {
return action(p)
}
return false
})
}
func (l *MobList) RangeNpcs(action func(*NPC) bool) int {
return l.Range(func(m entity.MobileEntity) bool {
if n := AsNpc(m); n != nil {
return action(n)
}
return false
})
}
func (l *MobList) Get(idx int) entity.MobileEntity {
l.RLock()
defer l.RUnlock()
for _, v := range l.mobSet {
if v.ServerIndex() == idx{
return v
}
}
return nil
}
type Mob struct {
SyncMask int
skills entity.SkillTable
path *Pathway
Prayers [15]bool
entity.Entity
*entity.AttributeList
sync.RWMutex
}
func (m *Mob) ExperienceReward() float64 {
meleeTotal := (m.Skills().Maximum(entity.StatStrength) + m.Skills().Maximum(entity.StatAttack) + m.Skills().Maximum(entity.StatDefense)) * 2.0
total := float64(m.Skills().Maximum(entity.StatHits) + meleeTotal)
return math.Floor(total/7.0) * 2.0 + 20.0
}
func (m *Mob) TargetMob() entity.MobileEntity {
return m.VarMob("targetMob")
}
func (m *Mob) TargetNpc() *NPC {
return AsNpc(m.TargetMob())
}
func (m *Mob) TargetPlayer() *Player {
return AsPlayer(m.TargetMob())
}
func (p *Player) IsPlayer() bool {
return true
}
func (p *Player) Type() entity.Type {
return entity.TypePlayer
}
func (p *Player) IsNpc() bool {
return false
}
func (n *NPC) Type() entity.Type {
return entity.TypeNpc
}
func (n *NPC) IsPlayer() bool {
return false
}
func (n *NPC) IsNpc() bool {
return true
}
func (m *Mob) Skulls() map[uint64]time.Time {
return nil
}
func (m *Mob) Busy() bool {
return m.State()&StateBusy != 0
}
func (m *Mob) BusyInput() bool {
filtered := m.State()&StateWaitEvent
return filtered&StateMenu != 0
}
func (m *Mob) IsFighting() bool {
return m.HasState(StateFighting)
}
func (m *Mob) FightTarget() entity.MobileEntity {
return m.VarMob("fightTarget")
}
func (m *Mob) SetFightTarget(m2 entity.MobileEntity) {
m.SetVar("fightTarget", m2)
}
func (m *Mob) FightRound() int {
return m.VarInt("fightRound", 0)
}
func (m *Mob) SetFightRound(i int) {
m.SetVar("fightRound", i)
}
func (m *Mob) LastRetreat() time.Time {
return m.VarTime("lastRetreat")
}
func (m *Mob) LastFight() time.Time {
return m.VarTime("lastFight")
}
func (m *Mob) UpdateLastRetreat() {
m.SetVar("lastRetreat", time.Now())
}
func (m *Mob) UpdateLastFight() {
m.SetVar("lastFight", time.Now())
}
func (m *Mob) Direction() int {
return m.VarInt("direction", North)
} | ISC License |
projectcalico/cni-plugin | pkg/k8s/k8s.go | ipAddrsResult | go | func ipAddrsResult(ipAddrs string, conf types.NetConf, args *skel.CmdArgs, logger *logrus.Entry) (*current.Result, error) {
logger.Infof("Parsing annotation \"cni.projectcalico.org/ipAddrs\":%s", ipAddrs)
ipList, err := validateAndExtractIPs(ipAddrs, "cni.projectcalico.org/ipAddrs", logger)
if err != nil {
return nil, err
}
result := current.Result{}
for _, ip := range ipList {
r, err := callIPAMWithIP(ip, conf, args, logger)
if err != nil {
return nil, fmt.Errorf("error getting IP from IPAM: %s", err)
}
result.IPs = append(result.IPs, r.IPs[0])
logger.Debugf("Adding IPv%s: %s to result", r.IPs[0].Version, ip.String())
}
return &result, nil
} | ipAddrsResult parses the ipAddrs annotation and calls the configured IPAM plugin for
each IP passed to it by setting the IP field in CNI_ARGS, and returns the result of calling the IPAM plugin.
Example annotation value string: "[\"10.0.0.1\", \"2001:db8::1\"]" | https://github.com/projectcalico/cni-plugin/blob/1e4e077b9bce26a4c8116b6359e200c7e95b85e3/pkg/k8s/k8s.go#L608-L635 | package k8s
import (
"context"
"encoding/json"
"errors"
"fmt"
"net"
"os"
"strings"
"time"
"github.com/containernetworking/cni/pkg/skel"
cnitypes "github.com/containernetworking/cni/pkg/types"
"github.com/containernetworking/cni/pkg/types/current"
"github.com/containernetworking/plugins/pkg/ipam"
"github.com/sirupsen/logrus"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/tools/clientcmd"
libapi "github.com/projectcalico/libcalico-go/lib/apis/v3"
k8sconversion "github.com/projectcalico/libcalico-go/lib/backend/k8s/conversion"
calicoclient "github.com/projectcalico/libcalico-go/lib/clientv3"
cerrors "github.com/projectcalico/libcalico-go/lib/errors"
cnet "github.com/projectcalico/libcalico-go/lib/net"
"github.com/projectcalico/libcalico-go/lib/options"
"github.com/projectcalico/cni-plugin/internal/pkg/utils"
"github.com/projectcalico/cni-plugin/internal/pkg/utils/cri"
"github.com/projectcalico/cni-plugin/pkg/dataplane"
"github.com/projectcalico/cni-plugin/pkg/types"
)
func CmdAddK8s(ctx context.Context, args *skel.CmdArgs, conf types.NetConf, epIDs utils.WEPIdentifiers, calicoClient calicoclient.Interface, endpoint *libapi.WorkloadEndpoint) (*current.Result, error) {
var err error
var result *current.Result
utils.ConfigureLogging(conf)
logger := logrus.WithFields(logrus.Fields{
"WorkloadEndpoint": epIDs.WEPName,
"ContainerID": epIDs.ContainerID,
"Pod": epIDs.Pod,
"Namespace": epIDs.Namespace,
})
d, err := dataplane.GetDataplane(conf, logger)
if err != nil {
return nil, err
}
logger.Info("Extracted identifiers for CmdAddK8s")
result, err = utils.CheckForSpuriousDockerAdd(args, conf, epIDs, endpoint, logger)
if result != nil || err != nil {
return result, err
}
client, err := NewK8sClient(conf, logger)
if err != nil {
return nil, err
}
logger.WithField("client", client).Debug("Created Kubernetes client")
var routes []*net.IPNet
if conf.IPAM.Type == "host-local" {
var stdinData map[string]interface{}
if err := json.Unmarshal(args.StdinData, &stdinData); err != nil {
return nil, err
}
var cachedPodCidr string
getRealPodCIDR := func() (string, error) {
if cachedPodCidr == "" {
var err error
cachedPodCidr, err = getPodCidr(client, conf, epIDs.Node)
if err != nil {
return "", err
}
}
return cachedPodCidr, nil
}
err = utils.ReplaceHostLocalIPAMPodCIDRs(logger, stdinData, getRealPodCIDR)
if err != nil {
return nil, err
}
args.StdinData, err = json.Marshal(stdinData)
if err != nil {
return nil, err
}
logger.Debug("Updated stdin data")
ipamData := stdinData["ipam"].(map[string]interface{})
untypedRoutes := ipamData["routes"]
hlRoutes, ok := untypedRoutes.([]interface{})
if untypedRoutes != nil && !ok {
return nil, fmt.Errorf(
"failed to parse host-local IPAM routes section; expecting list, not: %v", stdinData["ipam"])
}
for _, route := range hlRoutes {
route := route.(map[string]interface{})
untypedDst, ok := route["dst"]
if !ok {
logger.Debug("Ignoring host-ipam route with no dst")
continue
}
dst, ok := untypedDst.(string)
if !ok {
return nil, fmt.Errorf(
"invalid IPAM routes section; expecting 'dst' to be a string, not: %v", untypedDst)
}
_, cidr, err := net.ParseCIDR(dst)
if err != nil {
logger.WithError(err).WithField("routeDest", dst).Error(
"Failed to parse destination of host-local IPAM route in CNI configuration.")
return nil, err
}
routes = append(routes, cidr)
}
}
if len(routes) == 0 {
logger.Debug("No routes specified in CNI configuration, using defaults.")
routes = utils.DefaultRoutes
} else {
if conf.IncludeDefaultRoutes {
logger.Debug("Including Calico default routes in addition to routes from CNI config")
routes = append(utils.DefaultRoutes, routes...)
}
logger.WithField("routes", routes).Info("Using custom routes from CNI configuration.")
}
labels := make(map[string]string)
annot := make(map[string]string)
var ports []libapi.WorkloadEndpointPort
var profiles []string
var generateName string
var serviceAccount string
if conf.Policy.PolicyType == "k8s" {
annotNS, err := getK8sNSInfo(client, epIDs.Namespace)
if err != nil {
return nil, err
}
logger.WithField("NS Annotations", annotNS).Debug("Fetched K8s namespace annotations")
labels, annot, ports, profiles, generateName, serviceAccount, err = getK8sPodInfo(client, epIDs.Pod, epIDs.Namespace)
if err != nil {
return nil, err
}
logger.WithField("labels", labels).Debug("Fetched K8s labels")
logger.WithField("annotations", annot).Debug("Fetched K8s annotations")
logger.WithField("ports", ports).Debug("Fetched K8s ports")
logger.WithField("profiles", profiles).Debug("Generated profiles")
if conf.IPAM.Type == "calico-ipam" {
var v4pools, v6pools string
v4pools = annotNS["cni.projectcalico.org/ipv4pools"]
v6pools = annotNS["cni.projectcalico.org/ipv6pools"]
v4poolpod := annot["cni.projectcalico.org/ipv4pools"]
if len(v4poolpod) != 0 {
v4pools = v4poolpod
}
v6poolpod := annot["cni.projectcalico.org/ipv6pools"]
if len(v6poolpod) != 0 {
v6pools = v6poolpod
}
if len(v4pools) != 0 || len(v6pools) != 0 {
var stdinData map[string]interface{}
if err := json.Unmarshal(args.StdinData, &stdinData); err != nil {
return nil, err
}
var v4PoolSlice, v6PoolSlice []string
if len(v4pools) > 0 {
if err := json.Unmarshal([]byte(v4pools), &v4PoolSlice); err != nil {
logger.WithField("IPv4Pool", v4pools).Error("Error parsing IPv4 IPPools")
return nil, err
}
if _, ok := stdinData["ipam"].(map[string]interface{}); !ok {
return nil, errors.New("data on stdin was of unexpected type")
}
stdinData["ipam"].(map[string]interface{})["ipv4_pools"] = v4PoolSlice
logger.WithField("ipv4_pools", v4pools).Debug("Setting IPv4 Pools")
}
if len(v6pools) > 0 {
if err := json.Unmarshal([]byte(v6pools), &v6PoolSlice); err != nil {
logger.WithField("IPv6Pool", v6pools).Error("Error parsing IPv6 IPPools")
return nil, err
}
if _, ok := stdinData["ipam"].(map[string]interface{}); !ok {
return nil, errors.New("data on stdin was of unexpected type")
}
stdinData["ipam"].(map[string]interface{})["ipv6_pools"] = v6PoolSlice
logger.WithField("ipv6_pools", v6pools).Debug("Setting IPv6 Pools")
}
newData, err := json.Marshal(stdinData)
if err != nil {
logger.WithField("stdinData", stdinData).Error("Error Marshaling data")
return nil, err
}
args.StdinData = newData
logger.Debug("Updated stdin data")
}
}
}
ipAddrsNoIpam := annot["cni.projectcalico.org/ipAddrsNoIpam"]
ipAddrs := annot["cni.projectcalico.org/ipAddrs"]
switch {
case ipAddrs == "" && ipAddrsNoIpam == "":
result, err = utils.AddIPAM(conf, args, logger)
if err != nil {
return nil, err
}
case ipAddrs != "" && ipAddrsNoIpam != "":
e := fmt.Errorf("can't have both annotations: 'ipAddrs' and 'ipAddrsNoIpam' in use at the same time")
logger.Error(e)
return nil, e
case ipAddrsNoIpam != "":
if conf.IPAM.Type != "calico-ipam" {
e := fmt.Errorf("ipAddrsNoIpam is not compatible with configured IPAM: %s", conf.IPAM.Type)
logger.Error(e)
return nil, e
}
if !conf.FeatureControl.IPAddrsNoIpam {
e := fmt.Errorf("requested feature is not enabled: ip_addrs_no_ipam")
logger.Error(e)
return nil, e
}
overriddenResult, err := overrideIPAMResult(ipAddrsNoIpam, logger)
if err != nil {
return nil, err
}
logger.Debugf("Bypassing IPAM to set the result to: %+v", overriddenResult)
result, err = current.NewResultFromResult(overriddenResult)
if err != nil {
return nil, err
}
if len(result.IPs) == 0 {
return nil, errors.New("failed to build result")
}
case ipAddrs != "":
if conf.IPAM.Type != "calico-ipam" {
e := fmt.Errorf("ipAddrs is not compatible with configured IPAM: %s", conf.IPAM.Type)
logger.Error(e)
return nil, e
}
if endpoint != nil {
logger.Info("Endpoint already exists and ipAddrs is set. Release any old IPs")
if err := releaseIPAddrs(endpoint.Spec.IPNetworks, calicoClient, logger); err != nil {
return nil, fmt.Errorf("failed to release ipAddrs: %s", err)
}
}
result, err = ipAddrsResult(ipAddrs, conf, args, logger)
if err != nil {
return nil, err
}
logger.Debugf("IPAM result set to: %+v", result)
}
if endpoint == nil {
logger.Debug("Initializing new WorkloadEndpoint resource")
endpoint = libapi.NewWorkloadEndpoint()
}
endpoint.Name = epIDs.WEPName
endpoint.Namespace = epIDs.Namespace
endpoint.Labels = labels
endpoint.GenerateName = generateName
endpoint.Spec.Endpoint = epIDs.Endpoint
endpoint.Spec.Node = epIDs.Node
endpoint.Spec.Orchestrator = epIDs.Orchestrator
endpoint.Spec.Pod = epIDs.Pod
endpoint.Spec.Ports = ports
endpoint.Spec.IPNetworks = []string{}
endpoint.Spec.ServiceAccountName = serviceAccount
if conf.Policy.PolicyType == "k8s" {
endpoint.Spec.Profiles = profiles
} else {
endpoint.Spec.Profiles = []string{conf.Name}
}
if err = utils.PopulateEndpointNets(endpoint, result); err != nil {
utils.ReleaseIPAllocation(logger, conf, args)
return nil, err
}
logger.WithField("endpoint", endpoint).Info("Populated endpoint")
logger.Infof("Calico CNI using IPs: %s", endpoint.Spec.IPNetworks)
releaseIPAM := func() {
logger.WithField("endpointIPs", endpoint.Spec.IPNetworks).Info("Releasing IPAM allocation(s) after failure")
utils.ReleaseIPAllocation(logger, conf, args)
}
desiredVethName := k8sconversion.NewConverter().VethNameForWorkload(epIDs.Namespace, epIDs.Pod)
hostVethName, contVethMac, err := d.DoNetworking(
ctx, calicoClient, args, result, desiredVethName, routes, endpoint, annot)
if err != nil {
logger.WithError(err).Error("Error setting up networking")
releaseIPAM()
return nil, err
}
mac, err := net.ParseMAC(contVethMac)
if err != nil {
logger.WithError(err).WithField("mac", mac).Error("Error parsing container MAC")
releaseIPAM()
return nil, err
}
endpoint.Spec.MAC = mac.String()
endpoint.Spec.InterfaceName = hostVethName
endpoint.Spec.ContainerID = epIDs.ContainerID
logger.WithField("endpoint", endpoint).Info("Added Mac, interface name, and active container ID to endpoint")
if conf.Mode == "vxlan" {
_, subNet, _ := net.ParseCIDR(result.IPs[0].Address.String())
var err error
for attempts := 3; attempts > 0; attempts-- {
err = utils.EnsureVXLANTunnelAddr(ctx, calicoClient, epIDs.Node, subNet, conf.Name)
if err != nil {
logger.WithError(err).Warn("Failed to set node's VXLAN tunnel IP, node may not receive traffic. May retry...")
time.Sleep(1 * time.Second)
continue
}
break
}
if err != nil {
logger.WithError(err).Error("Failed to set node's VXLAN tunnel IP after retries, node may not receive traffic.")
}
}
floatingIPs := annot["cni.projectcalico.org/floatingIPs"]
if floatingIPs != "" {
if !conf.FeatureControl.FloatingIPs {
releaseIPAM()
return nil, fmt.Errorf("requested feature is not enabled: floating_ips")
}
ips, err := parseIPAddrs(floatingIPs, logger)
if err != nil {
releaseIPAM()
return nil, err
}
var podnetV4, podnetV6 net.IPNet
for _, ipNet := range result.IPs {
if ipNet.Address.IP.To4() != nil {
podnetV4 = ipNet.Address
netmask, _ := podnetV4.Mask.Size()
if netmask != 32 {
return nil, fmt.Errorf("PodIP %v is not a valid IPv4: Mask size is %d, not 32", ipNet, netmask)
}
} else {
podnetV6 = ipNet.Address
netmask, _ := podnetV6.Mask.Size()
if netmask != 128 {
return nil, fmt.Errorf("PodIP %v is not a valid IPv6: Mask size is %d, not 128", ipNet, netmask)
}
}
}
for _, ip := range ips {
if strings.Contains(ip, ":") {
endpoint.Spec.IPNATs = append(endpoint.Spec.IPNATs, libapi.IPNAT{
InternalIP: podnetV6.IP.String(),
ExternalIP: ip,
})
} else {
endpoint.Spec.IPNATs = append(endpoint.Spec.IPNATs, libapi.IPNAT{
InternalIP: podnetV4.IP.String(),
ExternalIP: ip,
})
}
}
logger.WithField("endpoint", endpoint).Info("Added floatingIPs to endpoint")
}
if _, err := utils.CreateOrUpdate(ctx, calicoClient, endpoint); err != nil {
logger.WithError(err).Error("Error creating/updating endpoint in datastore.")
releaseIPAM()
return nil, err
}
logger.Info("Wrote updated endpoint to datastore")
result.Interfaces = append(result.Interfaces, ¤t.Interface{
Name: endpoint.Spec.InterfaceName},
)
return result, nil
}
func CmdDelK8s(ctx context.Context, c calicoclient.Interface, epIDs utils.WEPIdentifiers, args *skel.CmdArgs, conf types.NetConf, logger *logrus.Entry) error {
d, err := dataplane.GetDataplane(conf, logger)
if err != nil {
return err
}
if cri.IsDockershimV1(args.Netns) {
err = utils.RegisterDeletedWep(args.ContainerID)
if err != nil {
logger.WithError(err).Warn("Failed to register pod deletion timestamp.")
return err
}
}
for attempts := 5; attempts >= 0; attempts-- {
wep, err := c.WorkloadEndpoints().Get(ctx, epIDs.Namespace, epIDs.WEPName, options.GetOptions{})
if err != nil {
if _, ok := err.(cerrors.ErrorResourceDoesNotExist); !ok {
return err
}
logger.WithField("WorkloadEndpoint", epIDs.WEPName).Warning("WorkloadEndpoint does not exist in the datastore, moving forward with the clean up")
} else if wep.Spec.ContainerID != "" && args.ContainerID != wep.Spec.ContainerID {
logger.WithField("WorkloadEndpoint", wep).Warning("CNI_CONTAINERID does not match WorkloadEndpoint ConainerID, don't delete WEP.")
} else if _, err = c.WorkloadEndpoints().Delete(
ctx,
wep.Namespace,
wep.Name,
options.DeleteOptions{
ResourceVersion: wep.ResourceVersion,
UID: &wep.UID,
},
); err != nil {
switch err := err.(type) {
case cerrors.ErrorResourceDoesNotExist:
logger.WithField("endpoint", wep).Info("Endpoint object does not exist, no need to clean up.")
case cerrors.ErrorResourceUpdateConflict:
if attempts == 0 {
logger.WithField("endpoint", wep).Warn("Endpoint was modified before it could be deleted. Giving up.")
return fmt.Errorf("error deleting endpoint: endpoint was modified before it could be deleted: %v", err)
}
logger.WithField("endpoint", wep).Info("Endpoint was modified before it could be deleted. Retrying...")
continue
case cerrors.ErrorOperationNotSupported:
logger.WithField("endpoint", wep).WithError(err).Warn("Deleting pod returned ErrorOperationNotSupported.")
default:
return err
}
}
break
}
logger.Info("Cleaning up netns")
err = d.CleanUpNamespace(args)
if err != nil {
return err
}
logger.Info("Releasing IP address(es)")
err = utils.DeleteIPAM(conf, args, logger)
if err != nil {
return err
}
logger.Info("Teardown processing complete.")
return nil
}
func releaseIPAddrs(ipAddrs []string, calico calicoclient.Interface, logger *logrus.Entry) error {
for _, ip := range ipAddrs {
log := logger.WithField("IP", ip)
log.Info("Releasing explicitly requested address")
cip, _, err := cnet.ParseCIDR(ip)
if err != nil {
return err
}
unallocated, err := calico.IPAM().ReleaseIPs(context.Background(), []cnet.IP{*cip})
if err != nil {
log.WithError(err).Error("Failed to release explicit IP")
return err
}
if len(unallocated) > 0 {
log.Warn("Asked to release address but it doesn't exist.")
} else {
log.Infof("Released explicit address: %s", ip)
}
}
return nil
} | Apache License 2.0 |
manifoldco/grafton | generated/connector/client/resource/resource_client.go | PutResourcesIDMeasures | go | func (a *Client) PutResourcesIDMeasures(params *PutResourcesIDMeasuresParams, authInfo runtime.ClientAuthInfoWriter) (*PutResourcesIDMeasuresNoContent, error) {
if params == nil {
params = NewPutResourcesIDMeasuresParams()
}
result, err := a.transport.Submit(&runtime.ClientOperation{
ID: "PutResourcesIDMeasures",
Method: "PUT",
PathPattern: "/resources/{id}/measures",
ProducesMediaTypes: []string{"application/json"},
ConsumesMediaTypes: []string{"application/json"},
Schemes: []string{"https"},
Params: params,
Reader: &PutResourcesIDMeasuresReader{formats: a.formats},
AuthInfo: authInfo,
Context: params.Context,
Client: params.HTTPClient,
})
if err != nil {
return nil, err
}
return result.(*PutResourcesIDMeasuresNoContent), nil
} | /*
PutResourcesIDMeasures bs e t a set how much a resource has used of its features
*BETA** A provider can call this endpoint to set how much a resource
has used of its features during a period of time. | https://github.com/manifoldco/grafton/blob/20c26bcbf0f5e42a2e9b19b698172c1ad85c7e03/generated/connector/client/resource/resource_client.go#L175-L199 | package resource
import (
"github.com/go-openapi/runtime"
strfmt "github.com/go-openapi/strfmt"
)
func New(transport runtime.ClientTransport, formats strfmt.Registry) *Client {
return &Client{transport: transport, formats: formats}
}
type Client struct {
transport runtime.ClientTransport
formats strfmt.Registry
}
func (a *Client) GetResourcesID(params *GetResourcesIDParams, authInfo runtime.ClientAuthInfoWriter) (*GetResourcesIDOK, error) {
if params == nil {
params = NewGetResourcesIDParams()
}
result, err := a.transport.Submit(&runtime.ClientOperation{
ID: "GetResourcesID",
Method: "GET",
PathPattern: "/resources/{id}",
ProducesMediaTypes: []string{"application/json"},
ConsumesMediaTypes: []string{"application/json"},
Schemes: []string{"https"},
Params: params,
Reader: &GetResourcesIDReader{formats: a.formats},
AuthInfo: authInfo,
Context: params.Context,
Client: params.HTTPClient,
})
if err != nil {
return nil, err
}
return result.(*GetResourcesIDOK), nil
}
func (a *Client) GetResourcesIDCredentials(params *GetResourcesIDCredentialsParams, authInfo runtime.ClientAuthInfoWriter) (*GetResourcesIDCredentialsOK, error) {
if params == nil {
params = NewGetResourcesIDCredentialsParams()
}
result, err := a.transport.Submit(&runtime.ClientOperation{
ID: "GetResourcesIDCredentials",
Method: "GET",
PathPattern: "/resources/{id}/credentials",
ProducesMediaTypes: []string{"application/json"},
ConsumesMediaTypes: []string{"application/json"},
Schemes: []string{"https"},
Params: params,
Reader: &GetResourcesIDCredentialsReader{formats: a.formats},
AuthInfo: authInfo,
Context: params.Context,
Client: params.HTTPClient,
})
if err != nil {
return nil, err
}
return result.(*GetResourcesIDCredentialsOK), nil
}
func (a *Client) GetResourcesIDMeasures(params *GetResourcesIDMeasuresParams, authInfo runtime.ClientAuthInfoWriter) (*GetResourcesIDMeasuresOK, error) {
if params == nil {
params = NewGetResourcesIDMeasuresParams()
}
result, err := a.transport.Submit(&runtime.ClientOperation{
ID: "GetResourcesIDMeasures",
Method: "GET",
PathPattern: "/resources/{id}/measures",
ProducesMediaTypes: []string{"application/json"},
ConsumesMediaTypes: []string{"application/json"},
Schemes: []string{"https"},
Params: params,
Reader: &GetResourcesIDMeasuresReader{formats: a.formats},
AuthInfo: authInfo,
Context: params.Context,
Client: params.HTTPClient,
})
if err != nil {
return nil, err
}
return result.(*GetResourcesIDMeasuresOK), nil
}
func (a *Client) GetResourcesIDUsers(params *GetResourcesIDUsersParams, authInfo runtime.ClientAuthInfoWriter) (*GetResourcesIDUsersOK, error) {
if params == nil {
params = NewGetResourcesIDUsersParams()
}
result, err := a.transport.Submit(&runtime.ClientOperation{
ID: "GetResourcesIDUsers",
Method: "GET",
PathPattern: "/resources/{id}/users",
ProducesMediaTypes: []string{"application/json"},
ConsumesMediaTypes: []string{"application/json"},
Schemes: []string{"https"},
Params: params,
Reader: &GetResourcesIDUsersReader{formats: a.formats},
AuthInfo: authInfo,
Context: params.Context,
Client: params.HTTPClient,
})
if err != nil {
return nil, err
}
return result.(*GetResourcesIDUsersOK), nil
} | BSD 3-Clause New or Revised License |
akualab/dsp | dsp.go | NewOneProc | go | func NewOneProc(f OneProcFunc) *OneProc {
return &OneProc{f: f}
} | NewOneProc creates a new Proc. | https://github.com/akualab/dsp/blob/a7203c702e9c905156667cd718b252cb203a2d32/dsp.go#L141-L143 | package dsp
import (
"bytes"
"errors"
"fmt"
"reflect"
"strings"
)
var ErrNoFunc = errors.New("no ProcFunc set")
var ErrOOB = errors.New("frame index out of bounds")
type Value interface {
}
type Processer interface {
}
type Framer interface {
Get(int) (Value, error)
}
type OneValuer interface {
Get() (Value, error)
}
type Inputter interface {
SetInputs(...Processer)
}
type Resetter interface {
Reset()
}
type ProcFunc func(int, ...Processer) (Value, error)
type Proc struct {
f ProcFunc
inputs []Processer
cache *cache
}
func NewProc(bufSize int, f ProcFunc) *Proc {
return &Proc{
f: f,
cache: newCache(bufSize),
}
}
func (bp *Proc) SetInputs(inputs ...Processer) {
bp.inputs = inputs
}
func (bp *Proc) Reset() {
bp.cache.clear()
}
func (bp *Proc) Get(idx int) (Value, error) {
if idx < 0 {
return nil, ErrOOB
}
val, ok := bp.cache.get(idx)
if ok {
return val, nil
}
if bp.f != nil {
v, e := bp.f(idx, bp.inputs...)
if e != nil {
return nil, e
}
bp.cache.set(idx, v)
return v, nil
}
return nil, ErrNoFunc
}
func (bp *Proc) SetCache(idx int, val Value) {
bp.cache.set(idx, val)
}
func (bp *Proc) GetCache(idx int) (Value, bool) {
val, ok := bp.cache.get(idx)
return val, ok
}
func (bp *Proc) ClearCache() {
bp.cache.clear()
}
func (bp *Proc) Inputs() []Processer {
return bp.inputs
}
func (bp *Proc) Framer(n int) Framer {
return bp.inputs[n].(Framer)
}
func (bp *Proc) OneValuer(n int) OneValuer {
return bp.inputs[n].(OneValuer)
}
type OneProcFunc func(...Processer) (Value, error)
type OneProc struct {
f OneProcFunc
inputs []Processer
cache Value
} | BSD 3-Clause New or Revised License |
haproxytech/dataplaneapi | operations/server_switching_rule/replace_server_switching_rule_responses.go | NewReplaceServerSwitchingRuleBadRequest | go | func NewReplaceServerSwitchingRuleBadRequest() *ReplaceServerSwitchingRuleBadRequest {
return &ReplaceServerSwitchingRuleBadRequest{}
} | NewReplaceServerSwitchingRuleBadRequest creates ReplaceServerSwitchingRuleBadRequest with default headers values | https://github.com/haproxytech/dataplaneapi/blob/b362aae0b04d0e330bd9dcfbf9f315b670de013b/operations/server_switching_rule/replace_server_switching_rule_responses.go#L161-L164 | package server_switching_rule
import (
"net/http"
"github.com/go-openapi/runtime"
"github.com/haproxytech/client-native/v2/models"
)
const ReplaceServerSwitchingRuleOKCode int = 200
type ReplaceServerSwitchingRuleOK struct {
Payload *models.ServerSwitchingRule `json:"body,omitempty"`
}
func NewReplaceServerSwitchingRuleOK() *ReplaceServerSwitchingRuleOK {
return &ReplaceServerSwitchingRuleOK{}
}
func (o *ReplaceServerSwitchingRuleOK) WithPayload(payload *models.ServerSwitchingRule) *ReplaceServerSwitchingRuleOK {
o.Payload = payload
return o
}
func (o *ReplaceServerSwitchingRuleOK) SetPayload(payload *models.ServerSwitchingRule) {
o.Payload = payload
}
func (o *ReplaceServerSwitchingRuleOK) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) {
rw.WriteHeader(200)
if o.Payload != nil {
payload := o.Payload
if err := producer.Produce(rw, payload); err != nil {
panic(err)
}
}
}
const ReplaceServerSwitchingRuleAcceptedCode int = 202
type ReplaceServerSwitchingRuleAccepted struct {
ReloadID string `json:"Reload-ID"`
Payload *models.ServerSwitchingRule `json:"body,omitempty"`
}
func NewReplaceServerSwitchingRuleAccepted() *ReplaceServerSwitchingRuleAccepted {
return &ReplaceServerSwitchingRuleAccepted{}
}
func (o *ReplaceServerSwitchingRuleAccepted) WithReloadID(reloadID string) *ReplaceServerSwitchingRuleAccepted {
o.ReloadID = reloadID
return o
}
func (o *ReplaceServerSwitchingRuleAccepted) SetReloadID(reloadID string) {
o.ReloadID = reloadID
}
func (o *ReplaceServerSwitchingRuleAccepted) WithPayload(payload *models.ServerSwitchingRule) *ReplaceServerSwitchingRuleAccepted {
o.Payload = payload
return o
}
func (o *ReplaceServerSwitchingRuleAccepted) SetPayload(payload *models.ServerSwitchingRule) {
o.Payload = payload
}
func (o *ReplaceServerSwitchingRuleAccepted) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) {
reloadID := o.ReloadID
if reloadID != "" {
rw.Header().Set("Reload-ID", reloadID)
}
rw.WriteHeader(202)
if o.Payload != nil {
payload := o.Payload
if err := producer.Produce(rw, payload); err != nil {
panic(err)
}
}
}
const ReplaceServerSwitchingRuleBadRequestCode int = 400
type ReplaceServerSwitchingRuleBadRequest struct {
ConfigurationVersion string `json:"Configuration-Version"`
Payload *models.Error `json:"body,omitempty"`
} | Apache License 2.0 |
containerum/mail | vendor/gopkg.in/mailgun/mailgun-go.v1/messages.go | SetTrackingOpens | go | func (m *Message) SetTrackingOpens(trackingOpens bool) {
m.trackingOpens = trackingOpens
m.trackingOpensSet = true
} | Refer to the Mailgun documentation for more information. | https://github.com/containerum/mail/blob/c16ffee9f00455ee855a02eef269372b22d99a7c/vendor/gopkg.in/mailgun/mailgun-go.v1/messages.go#L408-L411 | package mailgun
import (
"encoding/json"
"errors"
"io"
"time"
)
const MaxNumberOfRecipients = 1000
type Message struct {
to []string
tags []string
campaigns []string
dkim bool
deliveryTime *time.Time
attachments []string
readerAttachments []ReaderAttachment
inlines []string
readerInlines []ReaderAttachment
testMode bool
tracking bool
trackingClicks bool
trackingOpens bool
headers map[string]string
variables map[string]string
recipientVariables map[string]map[string]interface{}
dkimSet bool
trackingSet bool
trackingClicksSet bool
trackingOpensSet bool
specific features
mg Mailgun
}
type ReaderAttachment struct {
Filename string
ReadCloser io.ReadCloser
}
type StoredMessage struct {
Recipients string `json:"recipients"`
Sender string `json:"sender"`
From string `json:"from"`
Subject string `json:"subject"`
BodyPlain string `json:"body-plain"`
StrippedText string `json:"stripped-text"`
StrippedSignature string `json:"stripped-signature"`
BodyHtml string `json:"body-html"`
StrippedHtml string `json:"stripped-html"`
Attachments []StoredAttachment `json:"attachments"`
MessageUrl string `json:"message-url"`
ContentIDMap map[string]struct {
Url string `json:"url"`
ContentType string `json:"content-type"`
Name string `json:"name"`
Size int64 `json:"size"`
} `json:"content-id-map"`
MessageHeaders [][]string `json:"message-headers"`
}
type StoredAttachment struct {
Size int `json:"size"`
Url string `json:"url"`
Name string `json:"name"`
ContentType string `json:"content-type"`
}
type StoredMessageRaw struct {
Recipients string `json:"recipients"`
Sender string `json:"sender"`
From string `json:"from"`
Subject string `json:"subject"`
BodyMime string `json:"body-mime"`
}
type plainMessage struct {
from string
cc []string
bcc []string
subject string
text string
html string
}
type mimeMessage struct {
body io.ReadCloser
}
type sendMessageResponse struct {
Message string `json:"message"`
Id string `json:"id"`
}
type features interface {
addCC(string)
addBCC(string)
setHtml(string)
addValues(*formDataPayload)
isValid() bool
endpoint() string
recipientCount() int
}
func NewMessage(from string, subject string, text string, to ...string) *Message {
return &Message{
specific: &plainMessage{
from: from,
subject: subject,
text: text,
},
to: to,
}
}
func (mg *MailgunImpl) NewMessage(from, subject, text string, to ...string) *Message {
return &Message{
specific: &plainMessage{
from: from,
subject: subject,
text: text,
},
to: to,
mg: mg,
}
}
func NewMIMEMessage(body io.ReadCloser, to ...string) *Message {
return &Message{
specific: &mimeMessage{
body: body,
},
to: to,
}
}
func (mg *MailgunImpl) NewMIMEMessage(body io.ReadCloser, to ...string) *Message {
return &Message{
specific: &mimeMessage{
body: body,
},
to: to,
mg: mg,
}
}
func (m *Message) AddReaderAttachment(filename string, readCloser io.ReadCloser) {
ra := ReaderAttachment{Filename: filename, ReadCloser: readCloser}
m.readerAttachments = append(m.readerAttachments, ra)
}
func (m *Message) AddAttachment(attachment string) {
m.attachments = append(m.attachments, attachment)
}
func (m *Message) AddReaderInline(filename string, readCloser io.ReadCloser) {
ra := ReaderAttachment{Filename: filename, ReadCloser: readCloser}
m.readerInlines = append(m.readerInlines, ra)
}
func (m *Message) AddInline(inline string) {
m.inlines = append(m.inlines, inline)
}
func (m *Message) AddRecipient(recipient string) error {
return m.AddRecipientAndVariables(recipient, nil)
}
func (m *Message) AddRecipientAndVariables(r string, vars map[string]interface{}) error {
if m.RecipientCount() >= MaxNumberOfRecipients {
_, _, err := m.send()
if err != nil {
return err
}
m.to = make([]string, len(m.to))
m.recipientVariables = make(map[string]map[string]interface{}, len(m.recipientVariables))
}
m.to = append(m.to, r)
if vars != nil {
if m.recipientVariables == nil {
m.recipientVariables = make(map[string]map[string]interface{})
}
m.recipientVariables[r] = vars
}
return nil
}
func (m *Message) RecipientCount() int {
return len(m.to) + m.specific.recipientCount()
}
func (pm *plainMessage) recipientCount() int {
return len(pm.bcc) + len(pm.cc)
}
func (mm *mimeMessage) recipientCount() int {
return 10
}
func (m *Message) send() (string, string, error) {
return m.mg.Send(m)
}
func (m *Message) SetReplyTo(recipient string) {
m.AddHeader("Reply-To", recipient)
}
func (m *Message) AddCC(recipient string) {
m.specific.addCC(recipient)
}
func (pm *plainMessage) addCC(r string) {
pm.cc = append(pm.cc, r)
}
func (mm *mimeMessage) addCC(_ string) {}
func (m *Message) AddBCC(recipient string) {
m.specific.addBCC(recipient)
}
func (pm *plainMessage) addBCC(r string) {
pm.bcc = append(pm.bcc, r)
}
func (mm *mimeMessage) addBCC(_ string) {}
func (m *Message) SetHtml(html string) {
m.specific.setHtml(html)
}
func (pm *plainMessage) setHtml(h string) {
pm.html = h
}
func (mm *mimeMessage) setHtml(_ string) {}
func (m *Message) AddTag(tag string) {
m.tags = append(m.tags, tag)
}
func (m *Message) AddCampaign(campaign string) {
m.campaigns = append(m.campaigns, campaign)
}
func (m *Message) SetDKIM(dkim bool) {
m.dkim = dkim
m.dkimSet = true
}
func (m *Message) EnableTestMode() {
m.testMode = true
}
func (m *Message) SetDeliveryTime(dt time.Time) {
pdt := new(time.Time)
*pdt = dt
m.deliveryTime = pdt
}
func (m *Message) SetTracking(tracking bool) {
m.tracking = tracking
m.trackingSet = true
}
func (m *Message) SetTrackingClicks(trackingClicks bool) {
m.trackingClicks = trackingClicks
m.trackingClicksSet = true
} | Apache License 2.0 |
kubearmor/kubearmor | pkg/KubeArmorHostPolicy/api/security.kubearmor.com/v1/groupversion_info.go | addKnownTypes | go | func addKnownTypes(scheme *runtime.Scheme) error {
scheme.AddKnownTypes(SchemeGroupVersion,
&KubeArmorHostPolicy{},
&KubeArmorHostPolicyList{},
)
metav1.AddToGroupVersion(scheme, SchemeGroupVersion)
return nil
} | Adds the list of known types to Scheme. | https://github.com/kubearmor/kubearmor/blob/d1a983c5f8e3c57bb7a2ecd4b23ccb8357bdabc6/pkg/KubeArmorHostPolicy/api/security.kubearmor.com/v1/groupversion_info.go#L34-L41 | package v1
import (
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
)
var SchemeGroupVersion = schema.GroupVersion{Group: "security.kubearmor.com", Version: "v1"}
func Kind(kind string) schema.GroupKind {
return SchemeGroupVersion.WithKind(kind).GroupKind()
}
func Resource(resource string) schema.GroupResource {
return SchemeGroupVersion.WithResource(resource).GroupResource()
}
var (
SchemeBuilder = runtime.NewSchemeBuilder(addKnownTypes)
AddToScheme = SchemeBuilder.AddToScheme
) | Apache License 2.0 |
brutella/dnssd | mdns.go | isUnicastQuestion | go | func isUnicastQuestion(q dns.Question) bool {
return q.Qclass&(1<<15) != 0
} | Returns true if q requires unicast responses. | https://github.com/brutella/dnssd/blob/665cf86dce8e8a8b4c6164e2ac038d6b667dc80b/mdns.go#L463-L471 | package dnssd
import (
"context"
"fmt"
"net"
"github.com/brutella/dnssd/log"
"github.com/miekg/dns"
"golang.org/x/net/ipv4"
"golang.org/x/net/ipv6"
)
var (
IPv4LinkLocalMulticast = net.ParseIP("224.0.0.251")
IPv6LinkLocalMulticast = net.ParseIP("ff02::fb")
AddrIPv4LinkLocalMulticast = &net.UDPAddr{
IP: IPv4LinkLocalMulticast,
Port: 5353,
}
AddrIPv6LinkLocalMulticast = &net.UDPAddr{
IP: IPv6LinkLocalMulticast,
Port: 5353,
}
TTLDefault uint32 = 75 * 60
TTLHostname uint32 = 120
)
type Query struct {
msg *dns.Msg
iface *net.Interface
}
func (q Query) IfaceName() string {
if q.iface != nil {
return q.iface.Name
}
return "?"
}
type Response struct {
msg *dns.Msg
addr *net.UDPAddr
iface *net.Interface
}
type Request struct {
msg *dns.Msg
from *net.UDPAddr
iface *net.Interface
}
func (r Request) String() string {
return fmt.Sprintf("%s@%s\n%v", r.from.IP, r.IfaceName(), r.msg)
}
func (r Request) IfaceName() string {
if r.iface != nil {
return r.iface.Name
}
return "?"
}
type MDNSConn interface {
SendQuery(q *Query) error
SendResponse(resp *Response) error
Read(ctx context.Context) <-chan *Request
Drain(ctx context.Context)
Close()
}
type mdnsConn struct {
ipv4 *ipv4.PacketConn
ipv6 *ipv6.PacketConn
ch chan *Request
}
func NewMDNSConn() (MDNSConn, error) {
return newMDNSConn()
}
func (c *mdnsConn) SendQuery(q *Query) error {
return c.sendQuery(q.msg, q.iface)
}
func (c *mdnsConn) SendResponse(resp *Response) error {
if resp.addr != nil {
return c.sendResponseTo(resp.msg, resp.iface, resp.addr)
}
return c.sendResponse(resp.msg, resp.iface)
}
func (c *mdnsConn) Read(ctx context.Context) <-chan *Request {
return c.read(ctx)
}
func (c *mdnsConn) Drain(ctx context.Context) {
log.Debug.Println("Draining connection")
for {
select {
case req := <-c.Read(ctx):
log.Debug.Println("Ignoring msg from", req.from.IP)
break
default:
return
}
}
}
func (c *mdnsConn) Close() {
c.close()
}
func newMDNSConn() (*mdnsConn, error) {
var errs []error
var connIPv4 *ipv4.PacketConn
var connIPv6 *ipv6.PacketConn
if conn, err := net.ListenUDP("udp4", AddrIPv4LinkLocalMulticast); err != nil {
errs = append(errs, err)
} else {
connIPv4 = ipv4.NewPacketConn(conn)
if err := connIPv4.SetControlMessage(ipv4.FlagInterface, true); err != nil {
log.Debug.Printf("IPv4 interface socket opt: %v", err)
}
connIPv4.SetMulticastLoopback(true)
for _, iface := range multicastInterfaces() {
if err := connIPv4.JoinGroup(iface, &net.UDPAddr{IP: IPv4LinkLocalMulticast}); err != nil {
log.Debug.Printf("Failed joining IPv4 %v: %v", iface.Name, err)
} else {
log.Debug.Printf("Joined IPv4 %v", iface.Name)
}
}
}
if conn, err := net.ListenUDP("udp6", AddrIPv6LinkLocalMulticast); err != nil {
errs = append(errs, err)
} else {
connIPv6 = ipv6.NewPacketConn(conn)
if err := connIPv6.SetControlMessage(ipv6.FlagInterface, true); err != nil {
log.Debug.Printf("IPv6 interface socket opt: %v", err)
}
connIPv6.SetMulticastLoopback(true)
for _, iface := range multicastInterfaces() {
if err := connIPv6.JoinGroup(iface, &net.UDPAddr{IP: IPv6LinkLocalMulticast}); err != nil {
log.Debug.Printf("Failed joining IPv6 %v: %v", iface.Name, err)
} else {
log.Debug.Printf("Joined IPv6 %v", iface.Name)
}
}
}
if err := first(errs...); connIPv4 == nil && connIPv6 == nil {
return nil, fmt.Errorf("Failed setting up UDP server: %v", err)
}
return &mdnsConn{
ipv4: connIPv4,
ipv6: connIPv6,
ch: make(chan *Request),
}, nil
}
func (c *mdnsConn) close() {
if c.ipv4 != nil {
c.ipv4.Close()
}
if c.ipv6 != nil {
c.ipv6.Close()
}
}
func (c *mdnsConn) read(ctx context.Context) <-chan *Request {
c.readInto(ctx, c.ch)
return c.ch
}
func (c *mdnsConn) readInto(ctx context.Context, ch chan *Request) {
isDone := func(ctx context.Context) bool {
return ctx.Err() == context.Canceled
}
if c.ipv4 != nil {
go func() {
buf := make([]byte, 65536)
for {
if isDone(ctx) {
return
}
n, cm, from, err := c.ipv4.ReadFrom(buf)
if err != nil {
continue
}
udpAddr, ok := from.(*net.UDPAddr)
if !ok {
log.Info.Println("invalid source address")
continue
}
var iface *net.Interface
if cm != nil {
iface, err = net.InterfaceByIndex(cm.IfIndex)
if err != nil {
continue
}
}
if n > 0 {
m := new(dns.Msg)
if err := m.Unpack(buf); err == nil && !shouldIgnore(m) {
ch <- &Request{m, udpAddr, iface}
}
}
}
}()
}
if c.ipv6 != nil {
go func() {
buf := make([]byte, 65536)
for {
if isDone(ctx) {
return
}
n, cm, from, err := c.ipv6.ReadFrom(buf)
if err != nil {
continue
}
udpAddr, ok := from.(*net.UDPAddr)
if !ok {
log.Info.Println("invalid source address")
continue
}
var iface *net.Interface
if cm != nil {
iface, err = net.InterfaceByIndex(cm.IfIndex)
if err != nil {
continue
}
}
if n > 0 {
m := new(dns.Msg)
if err := m.Unpack(buf); err == nil && !shouldIgnore(m) {
ch <- &Request{m, udpAddr, iface}
}
}
}
}()
}
}
func (c *mdnsConn) sendQuery(m *dns.Msg, iface *net.Interface) error {
sanitizeQuery(m)
return c.writeMsg(m, iface)
}
func (c *mdnsConn) sendResponse(m *dns.Msg, iface *net.Interface) error {
sanitizeResponse(m)
return c.writeMsg(m, iface)
}
func (c *mdnsConn) sendResponseTo(m *dns.Msg, iface *net.Interface, addr *net.UDPAddr) error {
sanitizeResponse(m)
return c.writeMsgTo(m, iface, addr)
}
func (c *mdnsConn) writeMsg(m *dns.Msg, iface *net.Interface) error {
var err error
if c.ipv4 != nil {
err = c.writeMsgTo(m, iface, AddrIPv4LinkLocalMulticast)
}
if c.ipv6 != nil {
err = c.writeMsgTo(m, iface, AddrIPv6LinkLocalMulticast)
}
return err
}
func (c *mdnsConn) writeMsgTo(m *dns.Msg, iface *net.Interface, addr *net.UDPAddr) error {
sanitizeMsg(m)
if c.ipv4 != nil && addr.IP.To4() != nil {
if out, err := m.Pack(); err == nil {
var ctrl *ipv4.ControlMessage
if iface != nil {
ctrl = &ipv4.ControlMessage{
IfIndex: iface.Index,
}
}
if _, err = c.ipv4.WriteTo(out, ctrl, addr); err != nil {
return err
}
}
}
if c.ipv6 != nil && addr.IP.To4() == nil {
if out, err := m.Pack(); err == nil {
var ctrl *ipv6.ControlMessage
if iface != nil {
ctrl = &ipv6.ControlMessage{
IfIndex: iface.Index,
}
}
if _, err = c.ipv6.WriteTo(out, ctrl, addr); err != nil {
return err
}
}
}
return nil
}
func shouldIgnore(m *dns.Msg) bool {
if m.Opcode != 0 {
return true
}
if m.Rcode != 0 {
return true
}
return false
}
func sanitizeResponse(m *dns.Msg) {
if m.Question != nil && len(m.Question) > 0 {
log.Info.Println("Multicast DNS responses MUST NOT contain any questions in the Question Section. (RFC6762 6)")
m.Question = nil
}
if !m.Response {
log.Info.Println("In response messages the QR bit MUST be one (RFC6762 18.2)")
m.Response = true
}
if !m.Authoritative {
log.Info.Println("AA Bit bit MUST be set to one in response messages (RFC6762 18.4)")
m.Authoritative = true
}
if m.Truncated {
log.Info.Println("In multicast response messages, the TC bit MUST be zero on transmission. (RFC6762 18.5)")
m.Truncated = false
}
}
func sanitizeQuery(m *dns.Msg) {
if m.Response {
log.Info.Println("In query messages the QR bit MUST be zero (RFC6762 18.2)")
m.Response = false
}
if m.Authoritative {
log.Info.Println("AA Bit MUST be zero in query messages (RFC6762 18.4)")
m.Authoritative = false
}
}
func sanitizeMsg(m *dns.Msg) {
if m.Opcode != 0 {
log.Info.Println("In both multicast query and multicast response messages, the OPCODE MUST be zero on transmission (RFC6762 18.3)")
m.Opcode = 0
}
if m.RecursionDesired {
log.Info.Println("In both multicast query and multicast response messages, the Recursion Available bit MUST be zero on transmission. (RFC6762 18.7)")
m.RecursionDesired = false
}
if m.Zero {
log.Info.Println("In both query and response messages, the Zero bit MUST be zero on transmission (RFC6762 18.8)")
m.Zero = false
}
if m.AuthenticatedData {
log.Info.Println("In both multicast query and multicast response messages, the Authentic Data bit MUST be zero on transmission (RFC6762 18.9)")
m.AuthenticatedData = false
}
if m.CheckingDisabled {
log.Info.Println("In both multicast query and multicast response messages, the Checking Disabled bit MUST be zero on transmission (RFC6762 18.10)")
m.CheckingDisabled = false
}
if m.Rcode != 0 {
log.Info.Println("In both multicast query and multicast response messages, the Response Code MUST be zero on transmission. (RFC6762 18.11)")
m.Rcode = 0
}
}
func first(errs ...error) error {
for _, err := range errs {
if err != nil {
return err
}
}
return nil
}
func setAnswerCacheFlushBit(msg *dns.Msg) {
for _, a := range msg.Answer {
switch a.(type) {
case *dns.PTR:
continue
default:
a.Header().Class |= (1 << 15)
}
}
}
func setQuestionUnicast(q *dns.Question) {
q.Qclass |= (1 << 15)
} | MIT License |
dcos/dcos-log | vendor/github.com/sirupsen/logrus/logger.go | WithError | go | func (logger *Logger) WithError(err error) *Entry {
entry := logger.newEntry()
defer logger.releaseEntry(entry)
return entry.WithError(err)
} | Add an error as single field to the log entry. All it does is call
`WithError` for the given `error`. | https://github.com/dcos/dcos-log/blob/1ad4746b7359a126244748e32e6af95ca640e5e0/vendor/github.com/sirupsen/logrus/logger.go#L108-L112 | package logrus
import (
"io"
"os"
"sync"
)
type Logger struct {
Out io.Writer
Hooks LevelHooks
Formatter Formatter
Level Level
mu MutexWrap
entryPool sync.Pool
}
type MutexWrap struct {
lock sync.Mutex
disabled bool
}
func (mw *MutexWrap) Lock() {
if !mw.disabled {
mw.lock.Lock()
}
}
func (mw *MutexWrap) Unlock() {
if !mw.disabled {
mw.lock.Unlock()
}
}
func (mw *MutexWrap) Disable() {
mw.disabled = true
}
func New() *Logger {
return &Logger{
Out: os.Stderr,
Formatter: new(TextFormatter),
Hooks: make(LevelHooks),
Level: InfoLevel,
}
}
func (logger *Logger) newEntry() *Entry {
entry, ok := logger.entryPool.Get().(*Entry)
if ok {
return entry
}
return NewEntry(logger)
}
func (logger *Logger) releaseEntry(entry *Entry) {
logger.entryPool.Put(entry)
}
func (logger *Logger) WithField(key string, value interface{}) *Entry {
entry := logger.newEntry()
defer logger.releaseEntry(entry)
return entry.WithField(key, value)
}
func (logger *Logger) WithFields(fields Fields) *Entry {
entry := logger.newEntry()
defer logger.releaseEntry(entry)
return entry.WithFields(fields)
} | Apache License 2.0 |
hack4impact-upenn/transcribe4all | vendor/gopkg.in/kothar/go-backblaze.v0/files.go | DeleteFileVersion | go | func (b *Bucket) DeleteFileVersion(fileName, fileID string) (*FileStatus, error) {
request := &fileVersionRequest{
Name: fileName,
ID: fileID,
}
response := &FileStatus{}
if err := b.b2.apiRequest("b2_delete_file_version", request, response); err != nil {
return nil, err
}
return response, nil
} | DeleteFileVersion deletes one version of a file from B2.
If the version you delete is the latest version, and there are older
versions, then the most recent older version will become the current
version, and be the one that you'll get when downloading by name. See the
File Versions page for more details. | https://github.com/hack4impact-upenn/transcribe4all/blob/6397e43d6f325f10a5f15c8f9974edbec8500a31/vendor/gopkg.in/kothar/go-backblaze.v0/files.go#L331-L343 | package backblaze
import (
"bytes"
"crypto/sha1"
"encoding/hex"
"errors"
"fmt"
"io"
"io/ioutil"
"log"
"net/http"
"net/url"
"strconv"
"strings"
"github.com/pquerna/ffjson/ffjson"
)
func (b *Bucket) ListFileNames(startFileName string, maxFileCount int) (*ListFilesResponse, error) {
request := &listFilesRequest{
BucketID: b.ID,
StartFileName: startFileName,
MaxFileCount: maxFileCount,
}
response := &ListFilesResponse{}
if err := b.b2.apiRequest("b2_list_file_names", request, response); err != nil {
return nil, err
}
return response, nil
}
func (b *Bucket) UploadFile(name string, meta map[string]string, file io.Reader) (*File, error) {
hash := sha1.New()
var reader io.Reader
var contentLength int64
if r, ok := file.(io.ReadSeeker); ok {
written, err := io.Copy(hash, r)
if err != nil {
return nil, err
}
r.Seek(0, 0)
reader = r
contentLength = written
} else {
buffer := &bytes.Buffer{}
r := io.TeeReader(file, buffer)
written, err := io.Copy(hash, r)
if err != nil {
return nil, err
}
reader = buffer
contentLength = written
}
sha1Hash := hex.EncodeToString(hash.Sum(nil))
f, err := b.UploadHashedFile(name, meta, reader, sha1Hash, contentLength)
if b2err, ok := err.(*B2Error); ok {
if !b2err.IsFatal() && !b.b2.NoRetry {
f, err = b.UploadHashedFile(name, meta, reader, sha1Hash, contentLength)
}
}
return f, err
}
func (b *Bucket) UploadHashedFile(name string, meta map[string]string, file io.Reader, sha1Hash string, contentLength int64) (*File, error) {
uploadURL, auth, err := b.internalGetUploadURL()
if err != nil {
return nil, err
}
if b.b2.Debug {
fmt.Printf(" Upload: %s/%s\n", b.Name, name)
fmt.Printf(" SHA1: %s\n", sha1Hash)
fmt.Printf(" ContentLength: %d\n", contentLength)
}
req, err := http.NewRequest("POST", uploadURL.String(), file)
if err != nil {
return nil, err
}
req.Header.Add("Authorization", auth.AuthorizationToken)
req.ContentLength = contentLength
req.Header.Add("Content-Type", "b2/x-auto")
req.Header.Add("X-Bz-File-Name", url.QueryEscape(name))
req.Header.Add("X-Bz-Content-Sha1", sha1Hash)
if meta != nil {
for k, v := range meta {
req.Header.Add("X-Bz-Info-"+url.QueryEscape(k), url.QueryEscape(v))
}
}
resp, err := b.b2.httpClient.Do(req)
if err != nil {
auth.invalidate()
return nil, err
}
result := &File{}
if err := b.b2.parseResponse(resp, result, nil); err != nil {
auth.invalidate()
return nil, err
}
if sha1Hash != result.ContentSha1 {
return nil, errors.New("SHA1 of uploaded file does not match local hash")
}
return result, nil
}
func (b *Bucket) GetFileInfo(fileID string) (*File, error) {
request := &fileRequest{
ID: fileID,
}
response := &File{}
if err := b.b2.apiRequest("b2_get_file_info", request, response); err != nil {
return nil, err
}
return response, nil
}
func (c *B2) DownloadFileByID(fileID string) (*File, io.ReadCloser, error) {
request := &fileRequest{
ID: fileID,
}
requestBody, err := ffjson.Marshal(request)
if err != nil {
return nil, nil, err
}
f, body, err := c.tryDownloadFileByID(requestBody)
if b2err, ok := err.(*B2Error); ok {
if !b2err.IsFatal() && !c.NoRetry {
return c.tryDownloadFileByID(requestBody)
}
}
return f, body, err
}
func (c *B2) tryDownloadFileByID(requestBody []byte) (*File, io.ReadCloser, error) {
resp, auth, err := c.authPost("b2_download_file_by_id", bytes.NewReader(requestBody))
if err != nil {
return nil, nil, err
}
return c.downloadFile(resp, auth)
}
func (b *Bucket) FileURL(fileName string) (string, error) {
fileURL, _, err := b.internalFileURL(fileName)
return fileURL, err
}
func (b *Bucket) internalFileURL(fileName string) (string, *authorizationState, error) {
b.b2.mutex.Lock()
defer b.b2.mutex.Unlock()
if !b.b2.auth.isValid() {
if err := b.b2.internalAuthorizeAccount(); err != nil {
return "", nil, err
}
}
return b.b2.auth.DownloadURL + "/file/" + b.Name + "/" + fileName, b.b2.auth, nil
}
func (b *Bucket) DownloadFileByName(fileName string) (*File, io.ReadCloser, error) {
f, body, err := b.tryDownloadFileByName(fileName)
if b2err, ok := err.(*B2Error); ok {
if !b2err.IsFatal() && !b.b2.NoRetry {
return b.tryDownloadFileByName(fileName)
}
}
return f, body, err
}
func (b *Bucket) tryDownloadFileByName(fileName string) (*File, io.ReadCloser, error) {
fileURL, auth, err := b.internalFileURL(fileName)
if err != nil {
return nil, nil, err
}
req, err := http.NewRequest("GET", fileURL, nil)
if err != nil {
return nil, nil, err
}
req.Header.Add("Authorization", auth.AuthorizationToken)
resp, err := b.b2.httpClient.Do(req)
if err != nil {
return nil, nil, err
}
return b.b2.downloadFile(resp, auth)
}
func (c *B2) downloadFile(resp *http.Response, auth *authorizationState) (*File, io.ReadCloser, error) {
success := false
defer func() {
if !success {
resp.Body.Close()
}
}()
switch resp.StatusCode {
case 200:
case 401:
auth.invalidate()
return nil, nil, &B2Error{
Code: "UNAUTHORIZED",
Message: "The account ID is wrong, the account does not have B2 enabled, or the application key is not valid",
Status: resp.StatusCode,
}
default:
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, nil, err
}
if err := c.parseError(body); err != nil {
return nil, nil, err
}
return nil, nil, fmt.Errorf("Unrecognised status code: %d", resp.StatusCode)
}
name, err := url.QueryUnescape(resp.Header.Get("X-Bz-File-Name"))
if err != nil {
return nil, nil, err
}
file := &File{
ID: resp.Header.Get("X-Bz-File-Id"),
Name: name,
ContentSha1: resp.Header.Get("X-Bz-Content-Sha1"),
ContentType: resp.Header.Get("Content-Type"),
FileInfo: make(map[string]string),
}
size, err := strconv.ParseInt(resp.Header.Get("Content-Length"), 10, 64)
if err != nil {
return nil, nil, err
}
file.ContentLength = size
for k, v := range resp.Header {
if strings.HasPrefix(k, "X-Bz-Info-") {
key, err := url.QueryUnescape(k[len("X-Bz-Info-"):])
if err != nil {
key = k[len("X-Bz-Info-"):]
log.Printf("Unable to decode key: %q", key)
}
value, err := url.QueryUnescape(v[0])
if err != nil {
value = v[0]
log.Printf("Unable to decode value: %q", value)
}
file.FileInfo[key] = value
}
}
success = true
return file, resp.Body, nil
}
func (b *Bucket) ListFileVersions(startFileName, startFileID string, maxFileCount int) (*ListFileVersionsResponse, error) {
request := &listFileVersionsRequest{
BucketID: b.ID,
StartFileName: startFileName,
StartFileID: startFileID,
MaxFileCount: maxFileCount,
}
response := &ListFileVersionsResponse{}
if err := b.b2.apiRequest("b2_list_file_versions", request, response); err != nil {
return nil, err
}
return response, nil
} | MIT License |
cyberark/secretless-broker | internal/plugin/connectors/tcp/mssql/connector_test.go | newSingleUseConnectorWithOptions | go | func newSingleUseConnectorWithOptions(
options ...types.ConnectorOption,
) *SingleUseConnector {
args := &types.ConnectorOptions{}
for _, option := range options {
option(args)
}
return &SingleUseConnector{
ConnectorOptions: *args,
}
} | Test helpers
newSingleUseConnectorWithOptions creates a new SingleUseConnector, and allows
you to specify the newMSSQLConnector explicitly. Intended to be used in unit
tests only. | https://github.com/cyberark/secretless-broker/blob/47d06d4816c814b8729e26f345e717e86570cd2b/internal/plugin/connectors/tcp/mssql/connector_test.go#L171-L184 | package mssql
import (
"errors"
"io"
"net"
"testing"
errorspkg "github.com/pkg/errors"
"github.com/stretchr/testify/assert"
"github.com/cyberark/secretless-broker/internal/plugin/connectors/tcp/mssql/mock"
"github.com/cyberark/secretless-broker/internal/plugin/connectors/tcp/mssql/types"
pluginconnector "github.com/cyberark/secretless-broker/pkg/secretless/plugin/connector"
mssql "github.com/denisenkom/go-mssqldb"
)
func TestSingleUseConnector_Connect(t *testing.T) {
t.Run("singleUseConnector.driver#Connect success", func(t *testing.T) {
expectedBackendConn := mock.DefaultMSSQLConnectorCtor.BackendConn
connector := newSingleUseConnectorWithOptions(
mock.DefaultConnectorOptions,
)
actualBackendConn, err := runDefaultTestConnect(connector)
assert.Nil(t, err)
if err != nil {
return
}
assert.Equal(t, expectedBackendConn, actualBackendConn)
})
t.Run("singleUseConnector.driver#Connect fail", func(t *testing.T) {
var methodFailsExpectedErr = errors.New("failed to complete connection")
customCtor := mock.DefaultMSSQLConnectorCtor
customCtor.Err = methodFailsExpectedErr
methodFails(t, methodFailsExpectedErr, mock.CustomNewMSSQLConnectorOption(customCtor))
})
t.Run("singleUseConnector#ReadPreLoginRequest fail", func(t *testing.T) {
var methodFailsExpectedErr = errors.New("failed to read prelogin request from client")
methodFails(t, methodFailsExpectedErr, func(connectorOptions *types.ConnectorOptions) {
connectorOptions.ReadPreloginRequest = func(
io.ReadWriteCloser,
) (map[uint8][]byte, error) {
return nil, methodFailsExpectedErr
}
})
})
t.Run("singleUseConnector#WritePreloginResponse succeeds", func(t *testing.T) {
fakePreLoginResponse := map[uint8][]byte{
mssql.PreloginVERSION: {0, 0, 0, 0, 0, 0},
mssql.PreloginENCRYPTION: {mssql.EncryptOn},
mssql.PreloginINSTOPT: {0},
mssql.PreloginTHREADID: {0, 0, 0, 0},
mssql.PreloginMARS: {0},
}
expectedPreLoginResponse := map[uint8][]byte{
mssql.PreloginVERSION: {0, 0, 0, 0, 0, 0},
mssql.PreloginENCRYPTION: {mssql.EncryptNotSup},
mssql.PreloginINSTOPT: {0},
mssql.PreloginTHREADID: {0, 0, 0, 0},
mssql.PreloginMARS: {0},
}
var actualPreLoginResponse map[uint8][]byte
var actualClient io.ReadWriteCloser
customCtor := mock.DefaultMSSQLConnectorCtor
customCtor.ServerPreloginResponse = fakePreLoginResponse
connector := newSingleUseConnectorWithOptions(
mock.DefaultConnectorOptions,
mock.CustomNewMSSQLConnectorOption(customCtor),
func(connectorOptions *types.ConnectorOptions) {
connectorOptions.WritePreloginResponse = func(
w io.ReadWriteCloser,
fields map[uint8][]byte,
) error {
actualClient = w
actualPreLoginResponse = fields
return nil
}
},
)
_, _ = runDefaultTestConnect(connector)
expectedClient := connector.clientConn
assert.Equal(t, actualPreLoginResponse, expectedPreLoginResponse)
assert.Equal(t, expectedClient, actualClient)
})
t.Run("singleUseConnector#WritePreloginResponse fails", func(t *testing.T) {
var methodFailsExpectedErr = errors.New("failed to write prelogin response to client")
methodFails(t, methodFailsExpectedErr, func(connectorOptions *types.ConnectorOptions) {
connectorOptions.WritePreloginResponse = func(
io.ReadWriteCloser,
map[uint8][]byte,
) error {
return methodFailsExpectedErr
}
})
})
t.Run("singleUseConnector#ReadLoginRequest succeeds", func(t *testing.T) {
expectedLoginRequest := &mssql.LoginRequest{}
expectedLoginRequest.Database = "test-database"
expectedLoginRequest.AppName = "test-app-name"
var actualLoginRequest *mssql.LoginRequest
var actualClient io.ReadWriteCloser
customCtor := mock.DefaultMSSQLConnectorCtor
customCtor.ClientLoginRequestPtr = &actualLoginRequest
connector := newSingleUseConnectorWithOptions(
mock.DefaultConnectorOptions,
mock.CustomNewMSSQLConnectorOption(customCtor),
func(connectorOptions *types.ConnectorOptions) {
connectorOptions.ReadLoginRequest = func(r io.ReadWriteCloser) (*mssql.LoginRequest, error) {
actualClient = r
return expectedLoginRequest, nil
}
},
)
_, _ = runDefaultTestConnect(connector)
expectedClient := connector.clientConn
assert.Equal(t, actualLoginRequest, expectedLoginRequest)
assert.Equal(t, expectedClient, actualClient)
})
t.Run("singleUseConnector#ReadLoginRequest fail", func(t *testing.T) {
var methodFailsExpectedErr = errors.New("failed to handle login from client")
methodFails(t, methodFailsExpectedErr, func(connectorOptions *types.ConnectorOptions) {
connectorOptions.ReadLoginRequest = func(
r io.ReadWriteCloser,
) (request *mssql.LoginRequest, e error) {
return nil, methodFailsExpectedErr
}
})
})
} | Apache License 2.0 |
crowdstrike/gofalcon | falcon/client/falcon_complete_dashboard/aggregate_escalations_parameters.go | SetTimeout | go | func (o *AggregateEscalationsParams) SetTimeout(timeout time.Duration) {
o.timeout = timeout
} | SetTimeout adds the timeout to the aggregate escalations params | https://github.com/crowdstrike/gofalcon/blob/c1e03b54363d20c149ede3409aa9b1dd3d64194c/falcon/client/falcon_complete_dashboard/aggregate_escalations_parameters.go#L94-L96 | package falcon_complete_dashboard
import (
"context"
"net/http"
"time"
"github.com/go-openapi/errors"
"github.com/go-openapi/runtime"
cr "github.com/go-openapi/runtime/client"
"github.com/go-openapi/strfmt"
"github.com/crowdstrike/gofalcon/falcon/models"
)
func NewAggregateEscalationsParams() *AggregateEscalationsParams {
return &AggregateEscalationsParams{
timeout: cr.DefaultTimeout,
}
}
func NewAggregateEscalationsParamsWithTimeout(timeout time.Duration) *AggregateEscalationsParams {
return &AggregateEscalationsParams{
timeout: timeout,
}
}
func NewAggregateEscalationsParamsWithContext(ctx context.Context) *AggregateEscalationsParams {
return &AggregateEscalationsParams{
Context: ctx,
}
}
func NewAggregateEscalationsParamsWithHTTPClient(client *http.Client) *AggregateEscalationsParams {
return &AggregateEscalationsParams{
HTTPClient: client,
}
}
type AggregateEscalationsParams struct {
Body []*models.MsaAggregateQueryRequest
timeout time.Duration
Context context.Context
HTTPClient *http.Client
}
func (o *AggregateEscalationsParams) WithDefaults() *AggregateEscalationsParams {
o.SetDefaults()
return o
}
func (o *AggregateEscalationsParams) SetDefaults() {
}
func (o *AggregateEscalationsParams) WithTimeout(timeout time.Duration) *AggregateEscalationsParams {
o.SetTimeout(timeout)
return o
} | MIT License |
go-fed/activity | streams/impl/activitystreams/type_read/gen_type_activitystreams_read.go | GetActivityStreamsMediaType | go | func (this ActivityStreamsRead) GetActivityStreamsMediaType() vocab.ActivityStreamsMediaTypeProperty {
return this.ActivityStreamsMediaType
} | GetActivityStreamsMediaType returns the "mediaType" property if it exists, and
nil otherwise. | https://github.com/go-fed/activity/blob/d866ba75dd0ff3ddd3a72b132b7cc16e01f6e006/streams/impl/activitystreams/type_read/gen_type_activitystreams_read.go#L580-L582 | package typeread
import (
"fmt"
vocab "github.com/go-fed/activity/streams/vocab"
"strings"
)
type ActivityStreamsRead struct {
ActivityStreamsActor vocab.ActivityStreamsActorProperty
ActivityStreamsAltitude vocab.ActivityStreamsAltitudeProperty
ActivityStreamsAttachment vocab.ActivityStreamsAttachmentProperty
ActivityStreamsAttributedTo vocab.ActivityStreamsAttributedToProperty
ActivityStreamsAudience vocab.ActivityStreamsAudienceProperty
ActivityStreamsBcc vocab.ActivityStreamsBccProperty
ActivityStreamsBto vocab.ActivityStreamsBtoProperty
ActivityStreamsCc vocab.ActivityStreamsCcProperty
ActivityStreamsContent vocab.ActivityStreamsContentProperty
ActivityStreamsContext vocab.ActivityStreamsContextProperty
ActivityStreamsDuration vocab.ActivityStreamsDurationProperty
ActivityStreamsEndTime vocab.ActivityStreamsEndTimeProperty
ActivityStreamsGenerator vocab.ActivityStreamsGeneratorProperty
ActivityStreamsIcon vocab.ActivityStreamsIconProperty
JSONLDId vocab.JSONLDIdProperty
ActivityStreamsImage vocab.ActivityStreamsImageProperty
ActivityStreamsInReplyTo vocab.ActivityStreamsInReplyToProperty
ActivityStreamsInstrument vocab.ActivityStreamsInstrumentProperty
ActivityStreamsLikes vocab.ActivityStreamsLikesProperty
ActivityStreamsLocation vocab.ActivityStreamsLocationProperty
ActivityStreamsMediaType vocab.ActivityStreamsMediaTypeProperty
ActivityStreamsName vocab.ActivityStreamsNameProperty
ActivityStreamsObject vocab.ActivityStreamsObjectProperty
ActivityStreamsOrigin vocab.ActivityStreamsOriginProperty
ActivityStreamsPreview vocab.ActivityStreamsPreviewProperty
ActivityStreamsPublished vocab.ActivityStreamsPublishedProperty
ActivityStreamsReplies vocab.ActivityStreamsRepliesProperty
ActivityStreamsResult vocab.ActivityStreamsResultProperty
ActivityStreamsShares vocab.ActivityStreamsSharesProperty
ActivityStreamsSource vocab.ActivityStreamsSourceProperty
ActivityStreamsStartTime vocab.ActivityStreamsStartTimeProperty
ActivityStreamsSummary vocab.ActivityStreamsSummaryProperty
ActivityStreamsTag vocab.ActivityStreamsTagProperty
ActivityStreamsTarget vocab.ActivityStreamsTargetProperty
ForgeFedTeam vocab.ForgeFedTeamProperty
ForgeFedTicketsTrackedBy vocab.ForgeFedTicketsTrackedByProperty
ActivityStreamsTo vocab.ActivityStreamsToProperty
ForgeFedTracksTicketsFor vocab.ForgeFedTracksTicketsForProperty
JSONLDType vocab.JSONLDTypeProperty
ActivityStreamsUpdated vocab.ActivityStreamsUpdatedProperty
ActivityStreamsUrl vocab.ActivityStreamsUrlProperty
alias string
unknown map[string]interface{}
}
func ActivityStreamsReadExtends(other vocab.Type) bool {
extensions := []string{"Activity", "Object"}
for _, ext := range extensions {
if ext == other.GetTypeName() {
return true
}
}
return false
}
func DeserializeRead(m map[string]interface{}, aliasMap map[string]string) (*ActivityStreamsRead, error) {
alias := ""
aliasPrefix := ""
if a, ok := aliasMap["https://www.w3.org/ns/activitystreams"]; ok {
alias = a
aliasPrefix = a + ":"
}
this := &ActivityStreamsRead{
alias: alias,
unknown: make(map[string]interface{}),
}
if typeValue, ok := m["type"]; !ok {
return nil, fmt.Errorf("no \"type\" property in map")
} else if typeString, ok := typeValue.(string); ok {
typeName := strings.TrimPrefix(typeString, aliasPrefix)
if typeName != "Read" {
return nil, fmt.Errorf("\"type\" property is not of %q type: %s", "Read", typeName)
}
} else if arrType, ok := typeValue.([]interface{}); ok {
found := false
for _, elemVal := range arrType {
if typeString, ok := elemVal.(string); ok && strings.TrimPrefix(typeString, aliasPrefix) == "Read" {
found = true
break
}
}
if !found {
return nil, fmt.Errorf("could not find a \"type\" property of value %q", "Read")
}
} else {
return nil, fmt.Errorf("\"type\" property is unrecognized type: %T", typeValue)
}
if p, err := mgr.DeserializeActorPropertyActivityStreams()(m, aliasMap); err != nil {
return nil, err
} else if p != nil {
this.ActivityStreamsActor = p
}
if p, err := mgr.DeserializeAltitudePropertyActivityStreams()(m, aliasMap); err != nil {
return nil, err
} else if p != nil {
this.ActivityStreamsAltitude = p
}
if p, err := mgr.DeserializeAttachmentPropertyActivityStreams()(m, aliasMap); err != nil {
return nil, err
} else if p != nil {
this.ActivityStreamsAttachment = p
}
if p, err := mgr.DeserializeAttributedToPropertyActivityStreams()(m, aliasMap); err != nil {
return nil, err
} else if p != nil {
this.ActivityStreamsAttributedTo = p
}
if p, err := mgr.DeserializeAudiencePropertyActivityStreams()(m, aliasMap); err != nil {
return nil, err
} else if p != nil {
this.ActivityStreamsAudience = p
}
if p, err := mgr.DeserializeBccPropertyActivityStreams()(m, aliasMap); err != nil {
return nil, err
} else if p != nil {
this.ActivityStreamsBcc = p
}
if p, err := mgr.DeserializeBtoPropertyActivityStreams()(m, aliasMap); err != nil {
return nil, err
} else if p != nil {
this.ActivityStreamsBto = p
}
if p, err := mgr.DeserializeCcPropertyActivityStreams()(m, aliasMap); err != nil {
return nil, err
} else if p != nil {
this.ActivityStreamsCc = p
}
if p, err := mgr.DeserializeContentPropertyActivityStreams()(m, aliasMap); err != nil {
return nil, err
} else if p != nil {
this.ActivityStreamsContent = p
}
if p, err := mgr.DeserializeContextPropertyActivityStreams()(m, aliasMap); err != nil {
return nil, err
} else if p != nil {
this.ActivityStreamsContext = p
}
if p, err := mgr.DeserializeDurationPropertyActivityStreams()(m, aliasMap); err != nil {
return nil, err
} else if p != nil {
this.ActivityStreamsDuration = p
}
if p, err := mgr.DeserializeEndTimePropertyActivityStreams()(m, aliasMap); err != nil {
return nil, err
} else if p != nil {
this.ActivityStreamsEndTime = p
}
if p, err := mgr.DeserializeGeneratorPropertyActivityStreams()(m, aliasMap); err != nil {
return nil, err
} else if p != nil {
this.ActivityStreamsGenerator = p
}
if p, err := mgr.DeserializeIconPropertyActivityStreams()(m, aliasMap); err != nil {
return nil, err
} else if p != nil {
this.ActivityStreamsIcon = p
}
if p, err := mgr.DeserializeIdPropertyJSONLD()(m, aliasMap); err != nil {
return nil, err
} else if p != nil {
this.JSONLDId = p
}
if p, err := mgr.DeserializeImagePropertyActivityStreams()(m, aliasMap); err != nil {
return nil, err
} else if p != nil {
this.ActivityStreamsImage = p
}
if p, err := mgr.DeserializeInReplyToPropertyActivityStreams()(m, aliasMap); err != nil {
return nil, err
} else if p != nil {
this.ActivityStreamsInReplyTo = p
}
if p, err := mgr.DeserializeInstrumentPropertyActivityStreams()(m, aliasMap); err != nil {
return nil, err
} else if p != nil {
this.ActivityStreamsInstrument = p
}
if p, err := mgr.DeserializeLikesPropertyActivityStreams()(m, aliasMap); err != nil {
return nil, err
} else if p != nil {
this.ActivityStreamsLikes = p
}
if p, err := mgr.DeserializeLocationPropertyActivityStreams()(m, aliasMap); err != nil {
return nil, err
} else if p != nil {
this.ActivityStreamsLocation = p
}
if p, err := mgr.DeserializeMediaTypePropertyActivityStreams()(m, aliasMap); err != nil {
return nil, err
} else if p != nil {
this.ActivityStreamsMediaType = p
}
if p, err := mgr.DeserializeNamePropertyActivityStreams()(m, aliasMap); err != nil {
return nil, err
} else if p != nil {
this.ActivityStreamsName = p
}
if p, err := mgr.DeserializeObjectPropertyActivityStreams()(m, aliasMap); err != nil {
return nil, err
} else if p != nil {
this.ActivityStreamsObject = p
}
if p, err := mgr.DeserializeOriginPropertyActivityStreams()(m, aliasMap); err != nil {
return nil, err
} else if p != nil {
this.ActivityStreamsOrigin = p
}
if p, err := mgr.DeserializePreviewPropertyActivityStreams()(m, aliasMap); err != nil {
return nil, err
} else if p != nil {
this.ActivityStreamsPreview = p
}
if p, err := mgr.DeserializePublishedPropertyActivityStreams()(m, aliasMap); err != nil {
return nil, err
} else if p != nil {
this.ActivityStreamsPublished = p
}
if p, err := mgr.DeserializeRepliesPropertyActivityStreams()(m, aliasMap); err != nil {
return nil, err
} else if p != nil {
this.ActivityStreamsReplies = p
}
if p, err := mgr.DeserializeResultPropertyActivityStreams()(m, aliasMap); err != nil {
return nil, err
} else if p != nil {
this.ActivityStreamsResult = p
}
if p, err := mgr.DeserializeSharesPropertyActivityStreams()(m, aliasMap); err != nil {
return nil, err
} else if p != nil {
this.ActivityStreamsShares = p
}
if p, err := mgr.DeserializeSourcePropertyActivityStreams()(m, aliasMap); err != nil {
return nil, err
} else if p != nil {
this.ActivityStreamsSource = p
}
if p, err := mgr.DeserializeStartTimePropertyActivityStreams()(m, aliasMap); err != nil {
return nil, err
} else if p != nil {
this.ActivityStreamsStartTime = p
}
if p, err := mgr.DeserializeSummaryPropertyActivityStreams()(m, aliasMap); err != nil {
return nil, err
} else if p != nil {
this.ActivityStreamsSummary = p
}
if p, err := mgr.DeserializeTagPropertyActivityStreams()(m, aliasMap); err != nil {
return nil, err
} else if p != nil {
this.ActivityStreamsTag = p
}
if p, err := mgr.DeserializeTargetPropertyActivityStreams()(m, aliasMap); err != nil {
return nil, err
} else if p != nil {
this.ActivityStreamsTarget = p
}
if p, err := mgr.DeserializeTeamPropertyForgeFed()(m, aliasMap); err != nil {
return nil, err
} else if p != nil {
this.ForgeFedTeam = p
}
if p, err := mgr.DeserializeTicketsTrackedByPropertyForgeFed()(m, aliasMap); err != nil {
return nil, err
} else if p != nil {
this.ForgeFedTicketsTrackedBy = p
}
if p, err := mgr.DeserializeToPropertyActivityStreams()(m, aliasMap); err != nil {
return nil, err
} else if p != nil {
this.ActivityStreamsTo = p
}
if p, err := mgr.DeserializeTracksTicketsForPropertyForgeFed()(m, aliasMap); err != nil {
return nil, err
} else if p != nil {
this.ForgeFedTracksTicketsFor = p
}
if p, err := mgr.DeserializeTypePropertyJSONLD()(m, aliasMap); err != nil {
return nil, err
} else if p != nil {
this.JSONLDType = p
}
if p, err := mgr.DeserializeUpdatedPropertyActivityStreams()(m, aliasMap); err != nil {
return nil, err
} else if p != nil {
this.ActivityStreamsUpdated = p
}
if p, err := mgr.DeserializeUrlPropertyActivityStreams()(m, aliasMap); err != nil {
return nil, err
} else if p != nil {
this.ActivityStreamsUrl = p
}
for k, v := range m {
if k == "actor" {
continue
} else if k == "altitude" {
continue
} else if k == "attachment" {
continue
} else if k == "attributedTo" {
continue
} else if k == "audience" {
continue
} else if k == "bcc" {
continue
} else if k == "bto" {
continue
} else if k == "cc" {
continue
} else if k == "content" {
continue
} else if k == "contentMap" {
continue
} else if k == "context" {
continue
} else if k == "duration" {
continue
} else if k == "endTime" {
continue
} else if k == "generator" {
continue
} else if k == "icon" {
continue
} else if k == "id" {
continue
} else if k == "image" {
continue
} else if k == "inReplyTo" {
continue
} else if k == "instrument" {
continue
} else if k == "likes" {
continue
} else if k == "location" {
continue
} else if k == "mediaType" {
continue
} else if k == "name" {
continue
} else if k == "nameMap" {
continue
} else if k == "object" {
continue
} else if k == "origin" {
continue
} else if k == "preview" {
continue
} else if k == "published" {
continue
} else if k == "replies" {
continue
} else if k == "result" {
continue
} else if k == "shares" {
continue
} else if k == "source" {
continue
} else if k == "startTime" {
continue
} else if k == "summary" {
continue
} else if k == "summaryMap" {
continue
} else if k == "tag" {
continue
} else if k == "target" {
continue
} else if k == "team" {
continue
} else if k == "ticketsTrackedBy" {
continue
} else if k == "to" {
continue
} else if k == "tracksTicketsFor" {
continue
} else if k == "type" {
continue
} else if k == "updated" {
continue
} else if k == "url" {
continue
}
this.unknown[k] = v
}
return this, nil
}
func IsOrExtendsRead(other vocab.Type) bool {
if other.GetTypeName() == "Read" {
return true
}
return ReadIsExtendedBy(other)
}
func NewActivityStreamsRead() *ActivityStreamsRead {
typeProp := typePropertyConstructor()
typeProp.AppendXMLSchemaString("Read")
return &ActivityStreamsRead{
JSONLDType: typeProp,
alias: "",
unknown: make(map[string]interface{}),
}
}
func ReadIsDisjointWith(other vocab.Type) bool {
disjointWith := []string{"Link", "Mention"}
for _, disjoint := range disjointWith {
if disjoint == other.GetTypeName() {
return true
}
}
return false
}
func ReadIsExtendedBy(other vocab.Type) bool {
return false
}
func (this ActivityStreamsRead) GetActivityStreamsActor() vocab.ActivityStreamsActorProperty {
return this.ActivityStreamsActor
}
func (this ActivityStreamsRead) GetActivityStreamsAltitude() vocab.ActivityStreamsAltitudeProperty {
return this.ActivityStreamsAltitude
}
func (this ActivityStreamsRead) GetActivityStreamsAttachment() vocab.ActivityStreamsAttachmentProperty {
return this.ActivityStreamsAttachment
}
func (this ActivityStreamsRead) GetActivityStreamsAttributedTo() vocab.ActivityStreamsAttributedToProperty {
return this.ActivityStreamsAttributedTo
}
func (this ActivityStreamsRead) GetActivityStreamsAudience() vocab.ActivityStreamsAudienceProperty {
return this.ActivityStreamsAudience
}
func (this ActivityStreamsRead) GetActivityStreamsBcc() vocab.ActivityStreamsBccProperty {
return this.ActivityStreamsBcc
}
func (this ActivityStreamsRead) GetActivityStreamsBto() vocab.ActivityStreamsBtoProperty {
return this.ActivityStreamsBto
}
func (this ActivityStreamsRead) GetActivityStreamsCc() vocab.ActivityStreamsCcProperty {
return this.ActivityStreamsCc
}
func (this ActivityStreamsRead) GetActivityStreamsContent() vocab.ActivityStreamsContentProperty {
return this.ActivityStreamsContent
}
func (this ActivityStreamsRead) GetActivityStreamsContext() vocab.ActivityStreamsContextProperty {
return this.ActivityStreamsContext
}
func (this ActivityStreamsRead) GetActivityStreamsDuration() vocab.ActivityStreamsDurationProperty {
return this.ActivityStreamsDuration
}
func (this ActivityStreamsRead) GetActivityStreamsEndTime() vocab.ActivityStreamsEndTimeProperty {
return this.ActivityStreamsEndTime
}
func (this ActivityStreamsRead) GetActivityStreamsGenerator() vocab.ActivityStreamsGeneratorProperty {
return this.ActivityStreamsGenerator
}
func (this ActivityStreamsRead) GetActivityStreamsIcon() vocab.ActivityStreamsIconProperty {
return this.ActivityStreamsIcon
}
func (this ActivityStreamsRead) GetActivityStreamsImage() vocab.ActivityStreamsImageProperty {
return this.ActivityStreamsImage
}
func (this ActivityStreamsRead) GetActivityStreamsInReplyTo() vocab.ActivityStreamsInReplyToProperty {
return this.ActivityStreamsInReplyTo
}
func (this ActivityStreamsRead) GetActivityStreamsInstrument() vocab.ActivityStreamsInstrumentProperty {
return this.ActivityStreamsInstrument
}
func (this ActivityStreamsRead) GetActivityStreamsLikes() vocab.ActivityStreamsLikesProperty {
return this.ActivityStreamsLikes
}
func (this ActivityStreamsRead) GetActivityStreamsLocation() vocab.ActivityStreamsLocationProperty {
return this.ActivityStreamsLocation
} | BSD 3-Clause New or Revised License |
consensys/gnark | internal/backend/compiled/term.go | Unpack | go | func (t Term) Unpack() (coeffID, variableID int, variableVisiblity Visibility) {
coeffID = t.CoeffID()
variableID = t.VariableID()
variableVisiblity = t.VariableVisibility()
return
} | Unpack returns coeffID, variableID and visibility | https://github.com/consensys/gnark/blob/3a403e7107e6836ea1d35c0818d76f730f5ec976/internal/backend/compiled/term.go#L88-L93 | package compiled
import (
"math/big"
"strconv"
"strings"
)
type Term uint64
const (
CoeffIdZero = 0
CoeffIdOne = 1
CoeffIdTwo = 2
CoeffIdMinusOne = 3
)
const (
_ uint64 = 0b000
variablePublic uint64 = 0b001
variableSecret uint64 = 0b010
variableInternal uint64 = 0b011
variableVirtual uint64 = 0b100
)
const (
nbBitsVariableID = 29
nbBitsCoeffID = 30
nbBitsDelimitor = 1
nbBitsFutureUse = 1
nbBitsVariableVisibility = 3
)
const TermDelimitor Term = Term(maskDelimitor)
const (
shiftVariableID = 0
shiftCoeffID = nbBitsVariableID
shiftDelimitor = shiftCoeffID + nbBitsCoeffID
shiftFutureUse = shiftDelimitor + nbBitsDelimitor
shiftVariableVisibility = shiftFutureUse + nbBitsFutureUse
)
const (
maskVariableID = uint64((1 << nbBitsVariableID) - 1)
maskCoeffID = uint64((1<<nbBitsCoeffID)-1) << shiftCoeffID
maskDelimitor = uint64((1<<nbBitsDelimitor)-1) << shiftDelimitor
maskFutureUse = uint64((1<<nbBitsFutureUse)-1) << shiftFutureUse
maskVariableVisibility = uint64((1<<nbBitsVariableVisibility)-1) << shiftVariableVisibility
)
func Pack(variableID, coeffID int, variableVisiblity Visibility) Term {
var t Term
t.SetVariableID(variableID)
t.SetCoeffID(coeffID)
t.SetVariableVisibility(variableVisiblity)
return t
} | Apache License 2.0 |
kyverno/kyverno | pkg/client/clientset/versioned/typed/kyverno/v1/clusterpolicy.go | newClusterPolicies | go | func newClusterPolicies(c *KyvernoV1Client) *clusterPolicies {
return &clusterPolicies{
client: c.RESTClient(),
}
} | newClusterPolicies returns a ClusterPolicies | https://github.com/kyverno/kyverno/blob/63f5c09297d0cbf292a74d2e2913d3ed4ec92328/pkg/client/clientset/versioned/typed/kyverno/v1/clusterpolicy.go#L59-L63 | package v1
import (
"context"
"time"
v1 "github.com/kyverno/kyverno/pkg/api/kyverno/v1"
scheme "github.com/kyverno/kyverno/pkg/client/clientset/versioned/scheme"
metav1 "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 ClusterPoliciesGetter interface {
ClusterPolicies() ClusterPolicyInterface
}
type ClusterPolicyInterface interface {
Create(ctx context.Context, clusterPolicy *v1.ClusterPolicy, opts metav1.CreateOptions) (*v1.ClusterPolicy, error)
Update(ctx context.Context, clusterPolicy *v1.ClusterPolicy, opts metav1.UpdateOptions) (*v1.ClusterPolicy, error)
UpdateStatus(ctx context.Context, clusterPolicy *v1.ClusterPolicy, opts metav1.UpdateOptions) (*v1.ClusterPolicy, 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.ClusterPolicy, error)
List(ctx context.Context, opts metav1.ListOptions) (*v1.ClusterPolicyList, 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.ClusterPolicy, err error)
ClusterPolicyExpansion
}
type clusterPolicies struct {
client rest.Interface
} | Apache License 2.0 |
aws/amazon-ecs-cni-plugins | plugins/ipam/ipstore/ipstore.go | Update | go | func (manager *IPManager) Update(key string, value string) error {
return manager.client.Put(key, []byte(value), nil)
} | Update updates the value of existed key in the db | https://github.com/aws/amazon-ecs-cni-plugins/blob/55b2ae77ee0bf22321b14f2d4ebbcc04f77322e1/plugins/ipam/ipstore/ipstore.go#L224-L226 | package ipstore
import (
"math/big"
"net"
"time"
"github.com/docker/libkv/store"
"github.com/docker/libkv/store/boltdb"
"github.com/pkg/errors"
)
const (
MaxMask = 30
IPPrefix = "1"
)
type IPManager struct {
client store.Store
subnet net.IPNet
lastKnownIP net.IP
}
type Config struct {
DB string
PersistConnection bool
Bucket string
ConnectionTimeout time.Duration
}
type IPAllocator interface {
GetAvailableIP(string) (string, error)
Get(string) (string, error)
Assign(string, string) error
Update(string, string) error
Release(string) error
ReleaseByID(string) (string, error)
Exists(string) (bool, error)
SetLastKnownIP(net.IP)
Close()
}
func NewIPAllocator(options *Config, subnet net.IPNet) (IPAllocator, error) {
config := &store.Config{
PersistConnection: options.PersistConnection,
ConnectionTimeout: options.ConnectionTimeout,
Bucket: options.Bucket,
}
client, err := boltdb.New([]string{options.DB}, config)
if err != nil {
return nil, err
}
return &IPManager{
client: client,
subnet: subnet,
lastKnownIP: subnet.IP.Mask(subnet.Mask),
}, nil
}
func (manager *IPManager) SetLastKnownIP(ip net.IP) {
manager.lastKnownIP = ip
}
func (manager *IPManager) GetAvailableIP(id string) (string, error) {
var err error
nextIP := manager.lastKnownIP
for {
nextIP, err = NextIP(nextIP, manager.subnet)
if err != nil {
return "", err
}
err = manager.Assign(nextIP.String(), id)
if err != nil && err != store.ErrKeyExists {
return "", errors.Wrapf(err, "ipstore get ip: failed to assign ip in ipam")
} else if err == store.ErrKeyExists {
} else {
manager.lastKnownIP = nextIP
return nextIP.String(), nil
}
if nextIP.Equal(manager.lastKnownIP) {
return "", errors.New("getAvailableIP ipstore: failed to find available ip addresses in the subnet")
}
}
}
func (manager *IPManager) Get(ip string) (string, error) {
kvPair, err := manager.client.Get(ip)
if err != nil && err != store.ErrKeyNotFound {
return "", errors.Wrapf(err, "get ipstore: failed to get %v from db", kvPair)
}
if err == store.ErrKeyNotFound {
return "", nil
}
return string(kvPair.Value), nil
}
func (manager *IPManager) Assign(ip string, id string) error {
ok, err := manager.Exists(ip)
if err != nil {
return errors.Wrapf(err, "assign ipstore: query the db failed, err: %v", err)
}
if ok {
return store.ErrKeyExists
}
if id != "" {
ok, err := manager.UniqueID(id)
if err != nil {
return errors.Wrapf(err, "assign ipstore: check id unique failed, id: %s", id)
}
if !ok {
return errors.Errorf("assign ipstore: id already exists, id: %s", id)
}
}
err = manager.client.Put(ip, []byte(id), nil)
if err != nil {
return errors.Wrapf(err, "assign ipstore: failed to put the key/value into the db: %s -> %s", ip, id)
}
manager.lastKnownIP = net.ParseIP(ip)
return nil
}
func (manager *IPManager) Release(ip string) error {
ok, err := manager.Exists(ip)
if err != nil {
return errors.Wrap(err, "release ipstore: failed to query the db")
}
if !ok {
return errors.Errorf("release ipstore: ip does not existed in the db: %s", ip)
}
err = manager.client.Delete(ip)
if err != nil {
return errors.Wrap(err, "release ipstore: failed to delete the key in the db")
}
manager.lastKnownIP = net.ParseIP(ip)
return nil
}
func (manager *IPManager) ReleaseByID(id string) (string, error) {
kvPairs, err := manager.client.List(IPPrefix)
if err == store.ErrKeyNotFound {
return "", errors.Errorf("release ipstore: no ip associated with the id: %s", id)
}
if err != nil {
return "", errors.Wrapf(err, "release ipstore: failed to list the key-value pairs in db")
}
var ipDeleted string
for _, kvPair := range kvPairs {
if string(kvPair.Value) == id {
err = manager.Release(kvPair.Key)
if err != nil {
return "", err
}
ipDeleted = kvPair.Key
return ipDeleted, nil
}
}
return "", errors.Errorf("release ipstore: no ip address associated with the given id: %s", id)
}
func (manager *IPManager) UniqueID(id string) (bool, error) {
kvPairs, err := manager.client.List(IPPrefix)
if err == store.ErrKeyNotFound {
return true, nil
}
if err != nil {
return false, errors.Wrapf(err, "ipstore: failed to list the key-value pairs in db")
}
for _, kvPair := range kvPairs {
if string(kvPair.Value) == id {
return false, errors.Errorf("ipstore: id already exists")
}
}
return true, nil
} | Apache License 2.0 |
crowdstrike/gofalcon | falcon/client/firewall_management/query_events_parameters.go | WithDefaults | go | func (o *QueryEventsParams) WithDefaults() *QueryEventsParams {
o.SetDefaults()
return o
} | WithDefaults hydrates default values in the query events params (not the query body).
All values with no default are reset to their zero value. | https://github.com/crowdstrike/gofalcon/blob/c1e03b54363d20c149ede3409aa9b1dd3d64194c/falcon/client/firewall_management/query_events_parameters.go#L107-L110 | package firewall_management
import (
"context"
"net/http"
"time"
"github.com/go-openapi/errors"
"github.com/go-openapi/runtime"
cr "github.com/go-openapi/runtime/client"
"github.com/go-openapi/strfmt"
"github.com/go-openapi/swag"
)
func NewQueryEventsParams() *QueryEventsParams {
return &QueryEventsParams{
timeout: cr.DefaultTimeout,
}
}
func NewQueryEventsParamsWithTimeout(timeout time.Duration) *QueryEventsParams {
return &QueryEventsParams{
timeout: timeout,
}
}
func NewQueryEventsParamsWithContext(ctx context.Context) *QueryEventsParams {
return &QueryEventsParams{
Context: ctx,
}
}
func NewQueryEventsParamsWithHTTPClient(client *http.Client) *QueryEventsParams {
return &QueryEventsParams{
HTTPClient: client,
}
}
type QueryEventsParams struct {
After *string
Filter *string
Limit *int64
Offset *string
Q *string
Sort *string
timeout time.Duration
Context context.Context
HTTPClient *http.Client
} | MIT License |
wealdtech/chaind | services/chaindb/postgresql/tx.go | hasTx | go | func (s *Service) hasTx(ctx context.Context) bool {
if ctx == nil {
return false
}
_, ok := ctx.Value(&Tx{}).(pgx.Tx)
return ok
} | hasTx returns true if the context has a transaction. | https://github.com/wealdtech/chaind/blob/958336cb16e6a28d3266b97fe195031b6bfabc08/services/chaindb/postgresql/tx.go#L51-L57 | package postgresql
import (
"context"
"github.com/jackc/pgx/v4"
"github.com/pkg/errors"
)
var (
ErrNoTransaction = errors.New("no transaction for action")
)
type Tx struct{}
func (s *Service) BeginTx(ctx context.Context) (context.Context, context.CancelFunc, error) {
ctx, cancel := context.WithCancel(ctx)
tx, err := s.pool.Begin(ctx)
if err != nil {
cancel()
return nil, nil, errors.Wrap(err, "failed to begin transaction")
}
ctx = context.WithValue(ctx, &Tx{}, tx)
return ctx, func() {
if err := tx.Rollback(ctx); err != nil {
log.Warn().Err(err).Msg("Failed to rollback transaction")
}
cancel()
}, nil
} | Apache License 2.0 |
kube-node/nodeset | pkg/client/clientset/versioned/typed/nodeset/v1alpha1/nodeset_client.go | NewForConfigOrDie | go | func NewForConfigOrDie(c *rest.Config) *NodesetV1alpha1Client {
client, err := NewForConfig(c)
if err != nil {
panic(err)
}
return client
} | NewForConfigOrDie creates a new NodesetV1alpha1Client for the given config and
panics if there is an error in the config. | https://github.com/kube-node/nodeset/blob/6a55101a96e59a3fd67bf011061df017dcc2c22b/pkg/client/clientset/versioned/typed/nodeset/v1alpha1/nodeset_client.go#L60-L66 | package v1alpha1
import (
"github.com/kube-node/nodeset/pkg/client/clientset/versioned/scheme"
v1alpha1 "github.com/kube-node/nodeset/pkg/nodeset/v1alpha1"
serializer "k8s.io/apimachinery/pkg/runtime/serializer"
rest "k8s.io/client-go/rest"
)
type NodesetV1alpha1Interface interface {
RESTClient() rest.Interface
NodeClassesGetter
NodeSetsGetter
}
type NodesetV1alpha1Client struct {
restClient rest.Interface
}
func (c *NodesetV1alpha1Client) NodeClasses() NodeClassInterface {
return newNodeClasses(c)
}
func (c *NodesetV1alpha1Client) NodeSets() NodeSetInterface {
return newNodeSets(c)
}
func NewForConfig(c *rest.Config) (*NodesetV1alpha1Client, error) {
config := *c
if err := setConfigDefaults(&config); err != nil {
return nil, err
}
client, err := rest.RESTClientFor(&config)
if err != nil {
return nil, err
}
return &NodesetV1alpha1Client{client}, nil
} | Apache License 2.0 |
vrecan/fluxdash | vendor/github.com/influxdata/influxdb/models/points.go | scanMeasurement | go | func scanMeasurement(buf []byte, i int) (int, int, error) {
if buf[i] == ',' {
return -1, i, fmt.Errorf("missing measurement")
}
for {
i++
if i >= len(buf) {
return -1, i, fmt.Errorf("missing fields")
}
if buf[i-1] == '\\' {
continue
}
if buf[i] == ',' {
return tagKeyState, i + 1, nil
}
if buf[i] == ' ' {
return fieldsState, i, nil
}
}
} | scanMeasurement examines the measurement part of a Point, returning
the next state to move to, and the current location in the buffer. | https://github.com/vrecan/fluxdash/blob/a321ef9f35303502cf61ae57e6189f88c10c1060/vendor/github.com/influxdata/influxdb/models/points.go#L359-L390 | package models
import (
"bytes"
"encoding/binary"
"errors"
"fmt"
"hash/fnv"
"math"
"sort"
"strconv"
"strings"
"time"
"github.com/influxdata/influxdb/pkg/escape"
)
var (
measurementEscapeCodes = map[byte][]byte{
',': []byte(`\,`),
' ': []byte(`\ `),
}
tagEscapeCodes = map[byte][]byte{
',': []byte(`\,`),
' ': []byte(`\ `),
'=': []byte(`\=`),
}
ErrPointMustHaveAField = errors.New("point without fields is unsupported")
)
type Point interface {
Name() string
SetName(string)
Tags() Tags
AddTag(key, value string)
SetTags(tags Tags)
Fields() Fields
Time() time.Time
SetTime(t time.Time)
UnixNano() int64
HashID() uint64
Key() []byte
Data() []byte
SetData(buf []byte)
String() string
MarshalBinary() ([]byte, error)
PrecisionString(precision string) string
RoundedString(d time.Duration) string
}
type Points []Point
func (a Points) Len() int { return len(a) }
func (a Points) Less(i, j int) bool { return a[i].Time().Before(a[j].Time()) }
func (a Points) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
type point struct {
time time.Time
key []byte
fields []byte
ts []byte
data []byte
cachedFields map[string]interface{}
cachedName string
}
const (
maxInt64Digits = 19
minInt64Digits = 20
maxFloat64Digits = 25
minFloat64Digits = 27
)
func ParsePoints(buf []byte) ([]Point, error) {
return ParsePointsWithPrecision(buf, time.Now().UTC(), "n")
}
func ParsePointsString(buf string) ([]Point, error) {
return ParsePoints([]byte(buf))
}
func ParseKey(buf string) (string, Tags, error) {
_, keyBuf, err := scanKey([]byte(buf), 0)
tags := parseTags([]byte(buf))
return string(keyBuf), tags, err
}
func ParsePointsWithPrecision(buf []byte, defaultTime time.Time, precision string) ([]Point, error) {
points := []Point{}
var (
pos int
block []byte
failed []string
)
for {
pos, block = scanLine(buf, pos)
pos++
if len(block) == 0 {
break
}
start := skipWhitespace(block, 0)
if start >= len(block) {
continue
}
if block[start] == '#' {
continue
}
if block[len(block)-1] == '\n' {
block = block[:len(block)-1]
}
pt, err := parsePoint(block[start:len(block)], defaultTime, precision)
if err != nil {
failed = append(failed, fmt.Sprintf("unable to parse '%s': %v", string(block[start:len(block)]), err))
} else {
points = append(points, pt)
}
if pos >= len(buf) {
break
}
}
if len(failed) > 0 {
return points, fmt.Errorf("%s", strings.Join(failed, "\n"))
}
return points, nil
}
func parsePoint(buf []byte, defaultTime time.Time, precision string) (Point, error) {
pos, key, err := scanKey(buf, 0)
if err != nil {
return nil, err
}
if len(key) == 0 {
return nil, fmt.Errorf("missing measurement")
}
pos, fields, err := scanFields(buf, pos)
if err != nil {
return nil, err
}
if len(fields) == 0 {
return nil, fmt.Errorf("missing fields")
}
pos, ts, err := scanTime(buf, pos)
if err != nil {
return nil, err
}
pt := &point{
key: key,
fields: fields,
ts: ts,
}
if len(ts) == 0 {
pt.time = defaultTime
pt.SetPrecision(precision)
} else {
ts, err := strconv.ParseInt(string(ts), 10, 64)
if err != nil {
return nil, err
}
pt.time, err = SafeCalcTime(ts, precision)
if err != nil {
return nil, err
}
}
return pt, nil
}
func GetPrecisionMultiplier(precision string) int64 {
d := time.Nanosecond
switch precision {
case "u":
d = time.Microsecond
case "ms":
d = time.Millisecond
case "s":
d = time.Second
case "m":
d = time.Minute
case "h":
d = time.Hour
}
return int64(d)
}
func scanKey(buf []byte, i int) (int, []byte, error) {
start := skipWhitespace(buf, i)
i = start
sorted := true
indices := make([]int, 100)
commas := 0
state, i, err := scanMeasurement(buf, i)
if err != nil {
return i, buf[start:i], err
}
if state == tagKeyState {
i, commas, indices, err = scanTags(buf, i, indices)
if err != nil {
return i, buf[start:i], err
}
}
for j := 0; j < commas/2; j++ {
_, left := scanTo(buf[indices[j]:indices[j+1]-1], 0, '=')
_, right := scanTo(buf[indices[commas-j-1]:indices[commas-j]-1], 0, '=')
if bytes.Equal(left, right) {
return i, buf[start:i], fmt.Errorf("duplicate tags")
}
if bytes.Compare(left, right) > 0 {
sorted = false
}
}
if !sorted && commas > 0 {
measurement := buf[start : indices[0]-1]
indices := indices[:commas]
insertionSort(0, commas, buf, indices)
b := make([]byte, len(buf[start:i]))
pos := copy(b, measurement)
for _, i := range indices {
b[pos] = ','
pos++
_, v := scanToSpaceOr(buf, i, ',')
pos += copy(b[pos:], v)
}
return i, b, nil
}
return i, buf[start:i], nil
}
const (
tagKeyState = iota
tagValueState
fieldsState
) | MIT License |
tibcosoftware/tgdb-client | api/go/src/tgdb/impl/exceptionimpl.go | GetErrorCode | go | func (e *IOException) GetErrorCode() string {
return e.ErrorCode
} | ///////////////////////////////////////////////////////////////
Implement functions from Interface ==> TGError
/////////////////////////////////////////////////////////////// | https://github.com/tibcosoftware/tgdb-client/blob/90c1b2017c9aafad0a26cebace406744acf48e10/api/go/src/tgdb/impl/exceptionimpl.go#L834-L836 | package impl
import (
"fmt"
"tgdb"
)
const (
TGErrorBadVerb = iota
TGErrorInvalidMessageLength
TGErrorBadMagic
TGErrorProtocolNotSupported
TGErrorBadAuthentication
TGErrorIOException
TGErrorConnectionTimeout
TGErrorGeneralException
TGErrorRetryIOException
TGErrorChannelDisconnected
TGErrorSecurityException
TGErrorTransactionException
TGErrorTypeCoercionNotSupported
TGErrorTypeNotSupported
TGErrorVersionMismatchException
TGErrorInvalidErrorCode
TGSuccess
TGQryError
TGQryProviderNotInitialized
TGQryParsingError
TGQryStepNotSupported
TGQryStepNotAllowed
TGQryStepArgMissing
TGQryStepArgNotSupported
TGQryStepMissing
TGQryNotDefined
TGQryAttrDescNotFound
TGQryEdgeTypeNotFound
TGQryNodeTypeNotFound
TGQryInternalDataMismatchError
TGQryStepSignatureNotSupported
TGQryInvalidDataType
)
const (
TGQueryInvalid = iota + 8100
TGQueryProviderNotInitialized
TGQueryParsingError
TGQueryStepNotSupported
TGQueryStepNotAllowed
TGQueryStepArgMissing
TGQueryStepArgNotSupported
TGQueryStepMissing
TGQueryNotDefined
TGQueryAttrDescNotFound
TGQueryEdgeTypeNotFound
TGQueryNodeTypeNotFound
TGQueryInternalDataMismatchError
TGQueryStepSignatureNotSupported
TGQueryInvalidDataType
TGQueryErrorCodeEndMarker
)
type TGDBError struct {
ErrorCode string
ErrorType int
ErrorMsg string
ErrorDetails string
ErrorServerErrorCode int
}
func (e *TGDBError) GetErrorCode() string {
return e.ErrorCode
}
func (e *TGDBError) GetErrorType() int {
return e.ErrorType
}
func (e *TGDBError) GetErrorMsg() string {
return e.ErrorMsg
}
func (e *TGDBError) GetErrorDetails() string {
return e.ErrorDetails
}
func (e *TGDBError) GetServerErrorCode() int {
return e.ErrorServerErrorCode
}
var PreDefinedErrors = map[int]TGDBError{
TGErrorBadVerb: {ErrorCode: "TGErrorBadVerb", ErrorType: TGErrorBadVerb, ErrorMsg: "", ErrorDetails: "", ErrorServerErrorCode:-1},
TGErrorInvalidMessageLength: {ErrorCode: "TGErrorInvalidMessageLength", ErrorType: TGErrorInvalidMessageLength, ErrorMsg: "", ErrorDetails: "", ErrorServerErrorCode:-1},
TGErrorBadMagic: {ErrorCode: "TGErrorBadMagic", ErrorType: TGErrorBadMagic, ErrorMsg: "", ErrorDetails: "", ErrorServerErrorCode:-1},
TGErrorProtocolNotSupported: {ErrorCode: "TGErrorProtocolNotSupported", ErrorType: TGErrorProtocolNotSupported, ErrorMsg: "", ErrorDetails: "", ErrorServerErrorCode:-1},
TGErrorBadAuthentication: {ErrorCode: "TGErrorBadAuthentication", ErrorType: TGErrorBadAuthentication, ErrorMsg: "", ErrorDetails: "", ErrorServerErrorCode:-1},
TGErrorIOException: {ErrorCode: "TGErrorIOException", ErrorType: TGErrorIOException, ErrorMsg: "", ErrorDetails: "", ErrorServerErrorCode:-1},
TGErrorConnectionTimeout: {ErrorCode: "TGErrorConnectionTimeout", ErrorType: TGErrorConnectionTimeout, ErrorMsg: "", ErrorDetails: "", ErrorServerErrorCode:-1},
TGErrorGeneralException: {ErrorCode: "TGErrorGeneralException", ErrorType: TGErrorGeneralException, ErrorMsg: "", ErrorDetails: "", ErrorServerErrorCode:-1},
TGErrorRetryIOException: {ErrorCode: "TGErrorRetryIOException", ErrorType: TGErrorRetryIOException, ErrorMsg: "", ErrorDetails: "", ErrorServerErrorCode:-1},
TGErrorChannelDisconnected: {ErrorCode: "TGErrorChannelDisconnected", ErrorType: TGErrorChannelDisconnected, ErrorMsg: "", ErrorDetails: "", ErrorServerErrorCode:-1},
TGErrorSecurityException: {ErrorCode: "TGErrorSecurityException", ErrorType: TGErrorSecurityException, ErrorMsg: "", ErrorDetails: "", ErrorServerErrorCode:-1},
TGErrorTransactionException: {ErrorCode: "TGErrorTransactionException", ErrorType: TGErrorTransactionException, ErrorMsg: "", ErrorDetails: "", ErrorServerErrorCode:-1},
TGErrorTypeCoercionNotSupported: {ErrorCode: "TGErrorTypeCoercionNotSupported", ErrorType: TGErrorTypeCoercionNotSupported, ErrorMsg: "", ErrorDetails: "", ErrorServerErrorCode:-1},
TGErrorTypeNotSupported: {ErrorCode: "TGErrorTypeNotSupported", ErrorType: TGErrorTypeNotSupported, ErrorMsg: "", ErrorDetails: "", ErrorServerErrorCode:-1},
TGErrorVersionMismatchException: {ErrorCode: "TGErrorVersionMismatchException", ErrorType: TGErrorVersionMismatchException, ErrorMsg: "", ErrorDetails: "", ErrorServerErrorCode:-1},
TGErrorInvalidErrorCode: {ErrorCode: "TGErrorInvalidErrorCode", ErrorType: TGErrorInvalidErrorCode, ErrorMsg: "", ErrorDetails: "", ErrorServerErrorCode:-1},
TGSuccess: {ErrorCode: "TGSuccess", ErrorType: TGSuccess, ErrorMsg: "", ErrorDetails: "", ErrorServerErrorCode:-1},
}
func DefaultTGDBError() *TGDBError {
newTGDBError := TGDBError{ErrorCode: "", ErrorType: TGSuccess, ErrorMsg: "", ErrorDetails: "", ErrorServerErrorCode:-1}
return &newTGDBError
}
func NewTGDBError(eCode string, eType int, eMsg, eDetails string) *TGDBError {
newTGDBError := DefaultTGDBError()
newTGDBError.ErrorCode = eCode
newTGDBError.ErrorType = eType
newTGDBError.ErrorMsg = eMsg
newTGDBError.ErrorDetails = eDetails
return newTGDBError
}
func NewTGDBErrorWithServerErrorCode(eCode string, eType int, eMsg, eDetails string, eServerErrorCode int) *TGDBError {
newTGDBError := NewTGDBError(eCode, eType, eMsg, eDetails)
newTGDBError.ErrorServerErrorCode = eServerErrorCode
return newTGDBError
}
func GetPreDefinedErrors(code string) *TGDBError {
for _, tgError := range PreDefinedErrors {
if tgError.ErrorCode == code {
return &tgError
}
}
invalid := PreDefinedErrors[TGErrorInvalidErrorCode]
return &invalid
}
func (e *TGDBError) Error() string {
errMsg := fmt.Sprintf("ErrorCode: %s, ErrorType: %d, ErrorMessage: %s, ErrorDetails: %s", e.ErrorCode, e.ErrorType, e.ErrorMsg, e.ErrorDetails)
return errMsg
}
func CreateExceptionByType(excpTypeId int) tgdb.TGError {
inputExcpTypeId := excpTypeId
switch inputExcpTypeId {
case TGSuccess:
return DefaultTGSuccess()
case TGErrorBadAuthentication:
return DefaultTGBadAuthentication()
case TGErrorBadMagic:
return DefaultTGBadMagic()
case TGErrorBadVerb:
return DefaultTGBadVerb()
case TGErrorChannelDisconnected:
return DefaultTGChannelDisconnected()
case TGErrorConnectionTimeout:
return DefaultTGConnectionTimeout()
case TGErrorGeneralException:
return DefaultTGGeneralException()
case TGErrorInvalidMessageLength:
return DefaultTGInvalidMessageLength()
case TGErrorIOException:
return DefaultTGIOException()
case TGErrorProtocolNotSupported:
return DefaultTGProtocolNotSupported()
case TGErrorRetryIOException:
return DefaultTGRetryIOException()
case TGErrorSecurityException:
return DefaultTGSecurityException()
case TGErrorTransactionException:
return DefaultTGTransactionException()
case TGErrorTypeCoercionNotSupported:
return DefaultTGTypeCoercionNotSupported()
case TGErrorTypeNotSupported:
return DefaultTGTypeNotSupported()
case TGErrorVersionMismatchException:
return DefaultTGVersionMismatchException()
case TGErrorInvalidErrorCode:
fallthrough
default:
return GetPreDefinedErrors("TGErrorInvalidErrorCode")
}
return nil
}
func GetErrorByType(excpTypeId int, errorCode, errorMsg, errorDetails string) tgdb.TGError {
inputExcpTypeId := excpTypeId
switch inputExcpTypeId {
case TGSuccess:
return NewTGSuccess(errorCode, excpTypeId, errorMsg, errorDetails)
case TGErrorBadAuthentication:
return NewTGBadAuthentication(errorCode, excpTypeId, errorMsg, errorDetails)
case TGErrorBadMagic:
return NewTGBadMagic(errorCode, excpTypeId, errorMsg, errorDetails)
case TGErrorBadVerb:
return NewTGBadVerb(errorCode, excpTypeId, errorMsg, errorDetails)
case TGErrorChannelDisconnected:
return NewTGChannelDisconnected(errorCode, excpTypeId, errorMsg, errorDetails)
case TGErrorConnectionTimeout:
return NewTGConnectionTimeout(errorCode, excpTypeId, errorMsg, errorDetails)
case TGErrorGeneralException:
return NewTGGeneralException(errorCode, excpTypeId, errorMsg, errorDetails)
case TGErrorInvalidMessageLength:
return NewTGInvalidMessageLength(errorCode, excpTypeId, errorMsg, errorDetails)
case TGErrorIOException:
return NewTGIOException(errorCode, excpTypeId, errorMsg, errorDetails)
case TGErrorProtocolNotSupported:
return NewTGProtocolNotSupported(errorCode, excpTypeId, errorMsg, errorDetails)
case TGErrorRetryIOException:
return NewTGRetryIOException(errorCode, excpTypeId, errorMsg, errorDetails)
case TGErrorSecurityException:
return NewTGSecurityException(errorCode, excpTypeId, errorMsg, errorDetails)
case TGErrorTransactionException:
return NewTGTransactionException(errorCode, excpTypeId, errorMsg, errorDetails)
case TGErrorTypeCoercionNotSupported:
return NewTGTypeCoercionNotSupported(errorCode, excpTypeId, errorMsg, errorDetails)
case TGErrorTypeNotSupported:
return NewTGTypeNotSupported(errorCode, excpTypeId, errorMsg, errorDetails)
case TGErrorVersionMismatchException:
return NewTGVersionMismatchException(errorCode, excpTypeId, errorMsg, errorDetails)
case TGErrorInvalidErrorCode:
fallthrough
default:
return GetPreDefinedErrors("TGErrorInvalidErrorCode")
}
return nil
}
func GetErrorDetails(excpTypeId int) string {
tgDbError := CreateExceptionByType(excpTypeId)
if tgDbError != nil {
return tgDbError.GetErrorDetails()
}
return tgDbError.GetErrorDetails()
}
func Error(excpTypeId int) string {
tgDbError := CreateExceptionByType(excpTypeId)
if tgDbError != nil {
return tgDbError.Error()
}
return tgDbError.Error()
}
type Success struct {
*TGDBError
}
func DefaultTGSuccess() *Success {
newException := Success{
TGDBError: DefaultTGDBError(),
}
newException.ErrorType = TGSuccess
return &newException
}
func NewTGSuccess(eCode string, eType int, eMsg, eDetails string) *Success {
newException := DefaultTGSuccess()
newException.ErrorCode = eCode
newException.ErrorType = eType
newException.ErrorMsg = eMsg
newException.ErrorDetails = eDetails
return newException
}
func NewTGSuccessWithMsg(msg string) *Success {
newException := DefaultTGSuccess()
newException.ErrorMsg = msg
return newException
}
func (e *Success) GetErrorCode() string {
return e.ErrorCode
}
func (e *Success) GetErrorType() int {
return e.ErrorType
}
func (e *Success) GetErrorMsg() string {
return e.ErrorMsg
}
func (e *Success) GetErrorDetails() string {
return e.ErrorDetails
}
func (e *Success) Error() string {
errMsg := fmt.Sprintf("ErrorCode: %s, ErrorType: %d, ErrorMessage: %s, ErrorDetails: %s", e.ErrorCode, e.ErrorType, e.ErrorMsg, e.ErrorDetails)
return errMsg
}
type BadAuthentication struct {
*TGDBError
realm string
}
func DefaultTGBadAuthentication() *BadAuthentication {
newException := BadAuthentication{
TGDBError: DefaultTGDBError(),
}
newException.ErrorType = TGErrorBadAuthentication
newException.realm = ""
return &newException
}
func NewTGBadAuthentication(eCode string, eType int, eMsg, eDetails string) *BadAuthentication {
newException := DefaultTGBadAuthentication()
newException.ErrorCode = eCode
newException.ErrorType = eType
newException.ErrorMsg = eMsg
newException.ErrorDetails = eDetails
return newException
}
func NewTGBadAuthenticationWithMsg(msg string) *BadAuthentication {
newException := DefaultTGBadAuthentication()
newException.ErrorMsg = msg
return newException
}
func NewTGBadAuthenticationWithRealm(eCode string, eType int, eMsg, eDetails string, realm string) *BadAuthentication {
newException := NewTGBadAuthentication(eCode, eType, eMsg, eDetails)
newException.realm = realm
return newException
}
func (e *BadAuthentication) GetRealm() string {
return e.realm
}
func (e *BadAuthentication) SetRealm(realmStr string) {
e.realm = realmStr
}
func (e *BadAuthentication) GetErrorCode() string {
return e.ErrorCode
}
func (e *BadAuthentication) GetErrorType() int {
return e.ErrorType
}
func (e *BadAuthentication) GetErrorMsg() string {
return e.ErrorMsg
}
func (e *BadAuthentication) GetErrorDetails() string {
return e.ErrorDetails
}
func (e *BadAuthentication) Error() string {
errMsg := fmt.Sprintf("realm: %s, ErrorCode: %s, ErrorType: %d, ErrorMessage: %s, ErrorDetails: %s", e.realm, e.ErrorCode, e.ErrorType, e.ErrorMsg, e.ErrorDetails)
return errMsg
}
type BadMagic struct {
*TGDBError
}
func DefaultTGBadMagic() *BadMagic {
newException := BadMagic{
TGDBError: DefaultTGDBError(),
}
newException.ErrorType = TGErrorBadMagic
return &newException
}
func NewTGBadMagic(eCode string, eType int, eMsg, eDetails string) *BadMagic {
newException := DefaultTGBadMagic()
newException.ErrorCode = eCode
newException.ErrorType = eType
newException.ErrorMsg = eMsg
newException.ErrorDetails = eDetails
return newException
}
func NewTGBadMagicWithMsg(msg string) *BadMagic {
newException := DefaultTGBadMagic()
newException.ErrorMsg = msg
return newException
}
func (e *BadMagic) GetErrorCode() string {
return e.ErrorCode
}
func (e *BadMagic) GetErrorType() int {
return e.ErrorType
}
func (e *BadMagic) GetErrorMsg() string {
return e.ErrorMsg
}
func (e *BadMagic) GetErrorDetails() string {
return e.ErrorDetails
}
func (e *BadMagic) Error() string {
errMsg := fmt.Sprintf("ErrorCode: %s, ErrorType: %d, ErrorMessage: %s, ErrorDetails: %s", e.ErrorCode, e.ErrorType, e.ErrorMsg, e.ErrorDetails)
return errMsg
}
type BadVerb struct {
*TGDBError
}
func DefaultTGBadVerb() *BadVerb {
newException := BadVerb{
TGDBError: DefaultTGDBError(),
}
newException.ErrorType = TGErrorBadVerb
return &newException
}
func NewTGBadVerb(eCode string, eType int, eMsg, eDetails string) *BadVerb {
newException := DefaultTGBadVerb()
newException.ErrorCode = eCode
newException.ErrorType = eType
newException.ErrorMsg = eMsg
newException.ErrorDetails = eDetails
return newException
}
func NewTGBadVerbWithMsg(msg string) *BadVerb {
newException := DefaultTGBadVerb()
newException.ErrorMsg = msg
return newException
}
func (e *BadVerb) GetErrorCode() string {
return e.ErrorCode
}
func (e *BadVerb) GetErrorType() int {
return e.ErrorType
}
func (e *BadVerb) GetErrorMsg() string {
return e.ErrorMsg
}
func (e *BadVerb) GetErrorDetails() string {
return e.ErrorDetails
}
func (e *BadVerb) Error() string {
errMsg := fmt.Sprintf("ErrorCode: %s, ErrorType: %d, ErrorMessage: %s, ErrorDetails: %s", e.ErrorCode, e.ErrorType, e.ErrorMsg, e.ErrorDetails)
return errMsg
}
type ChannelDisconnected struct {
*TGDBError
}
func DefaultTGChannelDisconnected() *ChannelDisconnected {
newException := ChannelDisconnected{
TGDBError: DefaultTGDBError(),
}
newException.ErrorType = TGErrorChannelDisconnected
return &newException
}
func NewTGChannelDisconnected(eCode string, eType int, eMsg, eDetails string) *ChannelDisconnected {
newException := DefaultTGChannelDisconnected()
newException.ErrorCode = eCode
newException.ErrorType = eType
newException.ErrorMsg = eMsg
newException.ErrorDetails = eDetails
return newException
}
func NewTGChannelDisconnectedWithMsg(msg string) *ChannelDisconnected {
newException := DefaultTGChannelDisconnected()
newException.ErrorMsg = msg
return newException
}
func (e *ChannelDisconnected) GetErrorCode() string {
return e.ErrorCode
}
func (e *ChannelDisconnected) GetErrorType() int {
return e.ErrorType
}
func (e *ChannelDisconnected) GetErrorMsg() string {
return e.ErrorMsg
}
func (e *ChannelDisconnected) GetErrorDetails() string {
return e.ErrorDetails
}
func (e *ChannelDisconnected) Error() string {
errMsg := fmt.Sprintf("ErrorCode: %s, ErrorType: %d, ErrorMessage: %s, ErrorDetails: %s", e.ErrorCode, e.ErrorType, e.ErrorMsg, e.ErrorDetails)
return errMsg
}
type ConnectionTimeout struct {
*TGDBError
}
func DefaultTGConnectionTimeout() *ConnectionTimeout {
newException := ConnectionTimeout{
TGDBError: DefaultTGDBError(),
}
newException.ErrorType = TGErrorConnectionTimeout
return &newException
}
func NewTGConnectionTimeout(eCode string, eType int, eMsg, eDetails string) *ConnectionTimeout {
newException := DefaultTGConnectionTimeout()
newException.ErrorCode = eCode
newException.ErrorType = eType
newException.ErrorMsg = eMsg
newException.ErrorDetails = eDetails
return newException
}
func NewTGConnectionTimeoutWithMsg(msg string) *ConnectionTimeout {
newException := DefaultTGConnectionTimeout()
newException.ErrorMsg = msg
return newException
}
func (e *ConnectionTimeout) GetErrorCode() string {
return e.ErrorCode
}
func (e *ConnectionTimeout) GetErrorType() int {
return e.ErrorType
}
func (e *ConnectionTimeout) GetErrorMsg() string {
return e.ErrorMsg
}
func (e *ConnectionTimeout) GetErrorDetails() string {
return e.ErrorDetails
}
func (e *ConnectionTimeout) Error() string {
errMsg := fmt.Sprintf("ErrorCode: %s, ErrorType: %d, ErrorMessage: %s, ErrorDetails: %s", e.ErrorCode, e.ErrorType, e.ErrorMsg, e.ErrorDetails)
return errMsg
}
type GeneralException struct {
*TGDBError
}
func DefaultTGGeneralException() *GeneralException {
newException := GeneralException{
TGDBError: DefaultTGDBError(),
}
newException.ErrorType = TGErrorGeneralException
return &newException
}
func NewTGGeneralException(eCode string, eType int, eMsg, eDetails string) *GeneralException {
newException := DefaultTGGeneralException()
newException.ErrorCode = eCode
newException.ErrorType = eType
newException.ErrorMsg = eMsg
newException.ErrorDetails = eDetails
return newException
}
func NewTGGeneralExceptionWithMsg(msg string) *GeneralException {
newException := DefaultTGGeneralException()
newException.ErrorMsg = msg
return newException
}
func (e *GeneralException) GetErrorCode() string {
return e.ErrorCode
}
func (e *GeneralException) GetErrorType() int {
return e.ErrorType
}
func (e *GeneralException) GetErrorMsg() string {
return e.ErrorMsg
}
func (e *GeneralException) GetErrorDetails() string {
return e.ErrorDetails
}
func (e *GeneralException) Error() string {
errMsg := fmt.Sprintf("ErrorCode: %s, ErrorType: %d, ErrorMessage: %s, ErrorDetails: %s", e.ErrorCode, e.ErrorType, e.ErrorMsg, e.ErrorDetails)
return errMsg
}
type InvalidMessageLength struct {
*TGDBError
}
func DefaultTGInvalidMessageLength() *InvalidMessageLength {
newException := InvalidMessageLength{
TGDBError: DefaultTGDBError(),
}
newException.ErrorType = TGErrorInvalidMessageLength
return &newException
}
func NewTGInvalidMessageLength(eCode string, eType int, eMsg, eDetails string) *InvalidMessageLength {
newException := DefaultTGInvalidMessageLength()
newException.ErrorCode = eCode
newException.ErrorType = eType
newException.ErrorMsg = eMsg
newException.ErrorDetails = eDetails
return newException
}
func NewTGInvalidMessageLengthWithMsg(msg string) *InvalidMessageLength {
newException := DefaultTGInvalidMessageLength()
newException.ErrorMsg = msg
return newException
}
func (e *InvalidMessageLength) GetErrorCode() string {
return e.ErrorCode
}
func (e *InvalidMessageLength) GetErrorType() int {
return e.ErrorType
}
func (e *InvalidMessageLength) GetErrorMsg() string {
return e.ErrorMsg
}
func (e *InvalidMessageLength) GetErrorDetails() string {
return e.ErrorDetails
}
func (e *InvalidMessageLength) Error() string {
errMsg := fmt.Sprintf("ErrorCode: %s, ErrorType: %d, ErrorMessage: %s, ErrorDetails: %s", e.ErrorCode, e.ErrorType, e.ErrorMsg, e.ErrorDetails)
return errMsg
}
type IOException struct {
*TGDBError
}
func DefaultTGIOException() *IOException {
newException := IOException{
TGDBError: DefaultTGDBError(),
}
newException.ErrorType = TGErrorIOException
return &newException
}
func NewTGIOException(eCode string, eType int, eMsg, eDetails string) *IOException {
newException := DefaultTGIOException()
newException.ErrorCode = eCode
newException.ErrorType = eType
newException.ErrorMsg = eMsg
newException.ErrorDetails = eDetails
return newException
}
func NewTGIOExceptionWithMsg(msg string) *IOException {
newException := DefaultTGIOException()
newException.ErrorMsg = msg
return newException
} | Apache License 2.0 |
remind101/kinesumer | vendor/github.com/aws/aws-sdk-go/aws/credentials/static_provider.go | NewStaticCredentials | go | func NewStaticCredentials(id, secret, token string) *Credentials {
return NewCredentials(&StaticProvider{Value: Value{
AccessKeyID: id,
SecretAccessKey: secret,
SessionToken: token,
}})
} | NewStaticCredentials returns a pointer to a new Credentials object
wrapping a static credentials value provider. | https://github.com/remind101/kinesumer/blob/2d4f00f055ea7b474c72f181ed4578af370c5376/vendor/github.com/aws/aws-sdk-go/aws/credentials/static_provider.go#L25-L31 | package credentials
import (
"github.com/aws/aws-sdk-go/aws/awserr"
)
const StaticProviderName = "StaticProvider"
var (
ErrStaticCredentialsEmpty = awserr.New("EmptyStaticCreds", "static credentials are empty", nil)
)
type StaticProvider struct {
Value
} | MIT License |
joincivil/civil-events-crawler | pkg/model/event.go | LogTopics | go | func (e *Event) LogTopics() []common.Hash {
return e.logPayload.Topics
} | LogTopics returns the list of topics provided by the contract | https://github.com/joincivil/civil-events-crawler/blob/2646333a7115aa7731cd64b8e65045faa3100ac9/pkg/model/event.go#L274-L276 | package model
import (
"fmt"
"math/big"
"reflect"
"strconv"
"strings"
log "github.com/golang/glog"
"github.com/pkg/errors"
specs "github.com/joincivil/civil-events-crawler/pkg/contractspecs"
"github.com/ethereum/go-ethereum/accounts/abi"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/crypto"
"github.com/ethereum/go-ethereum/rlp"
"github.com/fatih/structs"
)
const (
Filterer RetrievalMethod = iota
Watcher
)
type RetrievalMethod int
func ReturnEventFromABI(_abi abi.ABI, eventType string) (abi.Event, error) {
event, ok := _abi.Events[eventType]
if !ok {
event, ok = _abi.Events[fmt.Sprintf("_%s", eventType)]
if !ok {
return abi.Event{}, errors.Errorf("no event type %v in contract", eventType)
}
}
return event, nil
}
func NewEventFromContractEvent(eventType string, contractName string, contractAddress common.Address,
eventData interface{}, timestamp int64, retrievalMethod RetrievalMethod) (*Event, error) {
event := &Event{}
payload := NewEventPayload(eventData)
logPayload, err := extractRawFieldFromEvent(payload)
if err != nil {
return event, err
}
eventPayload, err := extractFieldsFromEvent(payload, eventData, eventType, contractName)
if err != nil {
return event, err
}
event, err = NewEvent(eventType, contractName, contractAddress, timestamp, retrievalMethod, eventPayload, logPayload)
return event, err
}
func NewEvent(eventType string, contractName string, contractAddress common.Address, timestamp int64,
retrievalMethod RetrievalMethod, eventPayload map[string]interface{}, logPayload *types.Log) (*Event, error) {
event := &Event{}
event.eventType = eventType
event.contractName = contractName
event.contractAddress = contractAddress
event.eventPayload = eventPayload
event.logPayload = logPayload
event.timestamp = timestamp
event.retrievalMethod = retrievalMethod
event.eventHash = event.hashEvent()
return event, nil
}
type Event struct {
eventHash string
eventType string
contractAddress common.Address
contractName string
timestamp int64
retrievalMethod RetrievalMethod
eventPayload map[string]interface{}
logPayload *types.Log
}
func extractFieldsFromEvent(payload *EventPayload, eventData interface{}, eventType string, contractName string) (map[string]interface{}, error) {
eventPayload := make(map[string]interface{}, len(payload.data.Fields()))
_abi, err := AbiJSON(contractName)
if err != nil {
return eventPayload, err
}
abiEvent, err := ReturnEventFromABI(_abi, eventType)
if err != nil {
return eventPayload, err
}
for _, input := range abiEvent.Inputs {
eventFieldName := strings.Title(input.Name)
eventField, ok := payload.Value(eventFieldName)
if !ok {
return eventPayload, errors.New("can't get event name in event")
}
switch input.Type.String() {
case "address":
addressVal, ok := eventField.Address()
if !ok {
return eventPayload, errors.New("could not convert to common.address type")
}
eventPayload[eventFieldName] = addressVal
case "uint256":
bigintVal, ok := eventField.BigInt()
if !ok {
return eventPayload, errors.New("could not convert to big.int")
}
eventPayload[eventFieldName] = bigintVal
case "string":
stringVal, ok := eventField.String()
if !ok {
return eventPayload, errors.New("could not convert to string")
}
eventPayload[eventFieldName] = stringVal
case "bytes32":
bytesVal, ok := eventField.Bytes32()
if !ok {
return eventPayload, errors.New("Could not convert to bytes32")
}
eventPayload[eventFieldName] = bytesVal
default:
return eventPayload, errors.Errorf("unsupported type encountered when parsing %v field for %v event %v",
input.Type.String(), contractName, eventType)
}
}
return eventPayload, nil
}
func AbiJSON(contractName string) (abi.ABI, error) {
contractType, ok := specs.NameToContractTypes.GetFromContractName(contractName)
if !ok {
return abi.ABI{}, errors.New("contract name does not exist")
}
contractSpecs, ok := specs.ContractTypeToSpecs.Get(contractType)
if !ok {
return abi.ABI{}, errors.New("invalid contract type")
}
_abi, err := abi.JSON(strings.NewReader(contractSpecs.AbiStr()))
if err != nil {
return abi.ABI{}, errors.New("cannot parse abi string")
}
return _abi, nil
}
func extractRawFieldFromEvent(payload *EventPayload) (*types.Log, error) {
rawPayload, ok := payload.Value("Raw")
if !ok {
return &types.Log{}, errors.New("can't get raw value for event")
}
logPayload, ok := rawPayload.Log()
if !ok {
return &types.Log{}, errors.New("can't get log field of raw value for event")
}
return logPayload, nil
}
func (e *Event) hashEvent() string {
logIndex := int(e.logPayload.Index)
txHash := e.logPayload.TxHash.Hex()
eventBytes, err := rlp.EncodeToBytes([]interface{}{
e.contractAddress.Hex(),
e.eventType,
strconv.Itoa(logIndex),
txHash,
})
if err != nil {
log.Errorf("Error encoding to bytes: err: %v", err)
return ""
}
h := crypto.Keccak256Hash(eventBytes)
return h.Hex()
}
func (e *Event) Hash() string {
return e.eventHash
}
func (e *Event) EventType() string {
return e.eventType
}
func (e *Event) ContractAddress() common.Address {
return e.contractAddress
}
func (e *Event) Timestamp() int64 {
return e.timestamp
}
func (e *Event) SetTimestamp(ts int64) {
e.timestamp = ts
}
func (e *Event) RetrievalMethod() RetrievalMethod {
return e.retrievalMethod
}
func (e *Event) EventPayload() map[string]interface{} {
return e.eventPayload
}
func (e *Event) ContractName() string {
return e.contractName
}
func (e *Event) LogPayload() *types.Log {
logPayloadCopy := &types.Log{
Address: e.logPayload.Address,
Topics: e.logPayload.Topics,
Data: e.logPayload.Data,
BlockNumber: e.logPayload.BlockNumber,
TxHash: e.logPayload.TxHash,
TxIndex: e.logPayload.TxIndex,
BlockHash: e.logPayload.BlockHash,
Index: e.logPayload.Index,
Removed: e.logPayload.Removed}
return logPayloadCopy
} | Apache License 2.0 |
nabeken/aws-go-sqs | queue/queue.go | ReceiveMessage | go | func (q *Queue) ReceiveMessage(opts ...option.ReceiveMessageInput) ([]*sqs.Message, error) {
req := &sqs.ReceiveMessageInput{
QueueUrl: q.URL,
}
for _, f := range opts {
f(req)
}
resp, err := q.SQS.ReceiveMessage(req)
if err != nil {
return nil, err
}
return resp.Messages, nil
} | ReceiveMessage receives messages from SQS queue.
opts are used to change parameters for a request. | https://github.com/nabeken/aws-go-sqs/blob/6435fa427c185fad9c66bdebf3965d07a29a7411/queue/queue.go#L178-L192 | package queue
import (
"fmt"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/sqs"
"github.com/aws/aws-sdk-go/service/sqs/sqsiface"
multierror "github.com/hashicorp/go-multierror"
"github.com/nabeken/aws-go-sqs/v3/queue/option"
)
type Queue struct {
SQS sqsiface.SQSAPI
URL *string
}
func New(s sqsiface.SQSAPI, name string) (*Queue, error) {
u, err := GetQueueURL(s, name)
if err != nil {
return nil, err
}
return &Queue{
SQS: s,
URL: u,
}, nil
}
func MustNew(s sqsiface.SQSAPI, name string) *Queue {
q, err := New(s, name)
if err != nil {
panic(err)
}
return q
}
func (q *Queue) ChangeMessageVisibility(receiptHandle *string, visibilityTimeout int64) error {
req := &sqs.ChangeMessageVisibilityInput{
ReceiptHandle: receiptHandle,
VisibilityTimeout: aws.Int64(visibilityTimeout),
QueueUrl: q.URL,
}
_, err := q.SQS.ChangeMessageVisibility(req)
return err
}
type BatchChangeMessageVisibility struct {
ReceiptHandle *string
VisibilityTimeout int64
}
func (q *Queue) ChangeMessageVisibilityBatch(opts ...BatchChangeMessageVisibility) error {
entries := make([]*sqs.ChangeMessageVisibilityBatchRequestEntry, len(opts))
id2index := make(map[string]int)
for i, b := range opts {
id := aws.String(fmt.Sprintf("msg-%d", i))
entries[i] = &sqs.ChangeMessageVisibilityBatchRequestEntry{
Id: id,
ReceiptHandle: b.ReceiptHandle,
VisibilityTimeout: aws.Int64(b.VisibilityTimeout),
}
id2index[*id] = i
}
req := &sqs.ChangeMessageVisibilityBatchInput{
Entries: entries,
QueueUrl: q.URL,
}
resp, err := q.SQS.ChangeMessageVisibilityBatch(req)
if err != nil {
return err
}
return NewBatchError(id2index, resp.Failed)
}
func (q *Queue) SendMessage(body string, opts ...option.SendMessageInput) (*sqs.SendMessageOutput, error) {
req := &sqs.SendMessageInput{
MessageBody: aws.String(body),
QueueUrl: q.URL,
}
for _, f := range opts {
f(req)
}
return q.SQS.SendMessage(req)
}
type BatchMessage struct {
Body string
Options []option.SendMessageInput
}
type BatchError struct {
Index int
Code string
Message string
SenderFault bool
}
func NewBatchError(id2index map[string]int, errors []*sqs.BatchResultErrorEntry) error {
var result error
for _, entry := range errors {
err := &BatchError{
Index: id2index[*entry.Id],
Code: *entry.Code,
Message: *entry.Message,
SenderFault: *entry.SenderFault,
}
result = multierror.Append(result, err)
}
return result
}
func (e *BatchError) Error() string {
return fmt.Sprintf("sqs: index: %d, code: %s, is_sender_fault: %v: message: %s",
e.Index,
e.Code,
e.SenderFault,
e.Message,
)
}
func IsBatchError(err error) (errors []*BatchError, ok bool) {
merr, mok := err.(*multierror.Error)
if !mok {
return nil, false
}
for _, e := range merr.Errors {
berr, ok := e.(*BatchError)
if ok {
errors = append(errors, berr)
}
}
return errors, len(errors) > 0
}
func (q *Queue) SendMessageBatch(messages ...BatchMessage) error {
entries, id2index := BuildBatchRequestEntry(messages...)
req := &sqs.SendMessageBatchInput{
Entries: entries,
QueueUrl: q.URL,
}
resp, err := q.SQS.SendMessageBatch(req)
if err != nil {
return err
}
return NewBatchError(id2index, resp.Failed)
} | MIT License |
zorkian/marshal | marshal/claim.go | PrintState | go | func (c *claim) PrintState() {
c.lock.RLock()
defer c.lock.RUnlock()
state := "----"
cl := c.marshal.GetPartitionClaim(c.topic, c.partID)
if cl.Claimed() {
if c.Terminated() {
state = "CL+T"
} else {
state = "CLMD"
}
} else if c.Terminated() {
state = "TERM"
}
ct := 0
for _, st := range c.tracking {
if st {
ct++
}
}
now := time.Now().Unix()
log.Infof(" * %2d [%s]: offsets %d <= %d <= %d | %d",
c.partID, state, c.offsets.Earliest, c.offsets.Current,
c.offsets.Latest, c.offsets.Committed)
log.Infof(" BC %d | LHB %d (%d) | OM %d | CB %d",
c.beatCounter, c.lastHeartbeat, now-c.lastHeartbeat,
c.outstandingMessages, c.cyclesBehind)
log.Infof(" TRACK COMMITTED %d | TRACK OUTSTANDING %d",
ct, len(c.tracking)-ct)
log.Infof(" PV %0.2f | CV %0.2f",
c.PartitionVelocity(), c.ConsumerVelocity())
} | PrintState outputs the status of the consumer. | https://github.com/zorkian/marshal/blob/80cc6d177592b5293d300b1e180c16d2237d4cfd/marshal/claim.go#L670-L707 | package marshal
import (
"fmt"
"math/rand"
"sort"
"sync"
"sync/atomic"
"time"
"github.com/zorkian/kafka"
"github.com/zorkian/kafka/proto"
"github.com/jpillora/backoff"
)
type int64slice []int64
func (a int64slice) Len() int { return len(a) }
func (a int64slice) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
func (a int64slice) Less(i, j int) bool { return a[i] < a[j] }
type claim struct {
topic string
partID int
lock *sync.RWMutex
messagesLock *sync.Mutex
offsets PartitionOffsets
marshal *Marshaler
consumer *Consumer
rand *rand.Rand
terminated *int32
beatCounter int32
lastHeartbeat int64
lastMessageTime time.Time
options ConsumerOptions
kafkaConsumer kafka.Consumer
messages chan *Message
stopChan chan struct{}
doneChan chan struct{}
tracking map[int64]bool
outstandingMessages int
cyclesBehind int
offsetCurrentHistory [10]int64
offsetLatestHistory [10]int64
}
func newClaim(topic string, partID int, marshal *Marshaler, consumer *Consumer,
messages chan *Message, options ConsumerOptions) *claim {
offsets, err := marshal.GetPartitionOffsets(topic, partID)
if err != nil {
log.Errorf("[%s:%d] failed to get offsets: %s", topic, partID, err)
return nil
}
log.Debugf("[%s:%d] consumer offsets: early = %d, cur/comm = %d/%d, late = %d",
topic, partID, offsets.Earliest, offsets.Current, offsets.Committed, offsets.Latest)
if offsets.Current > 0 {
} else if offsets.Committed > 0 {
log.Infof("[%s:%d] no Marshal offset found, using committed offset %d",
topic, partID, offsets.Committed)
offsets.Current = offsets.Committed
} else {
log.Infof("[%s:%d] no Marshal or committed offset found, using earliest offset %d",
topic, partID, offsets.Earliest)
offsets.Current = offsets.Earliest
}
obj := &claim{
lock: &sync.RWMutex{},
messagesLock: &sync.Mutex{},
stopChan: make(chan struct{}),
doneChan: make(chan struct{}),
marshal: marshal,
consumer: consumer,
topic: topic,
partID: partID,
terminated: new(int32),
offsets: offsets,
messages: messages,
options: options,
tracking: make(map[int64]bool),
rand: rand.New(rand.NewSource(time.Now().UnixNano())),
lastMessageTime: time.Now(),
}
log.Infof("[%s:%d] consumer attempting to claim", topic, partID)
if !marshal.ClaimPartition(topic, partID) {
log.Infof("[%s:%d] consumer failed to claim", topic, partID)
return nil
}
obj.setup()
return obj
}
func (c *claim) setup() {
c.lock.Lock()
defer c.lock.Unlock()
if c.offsets.Current < c.offsets.Earliest {
log.Warningf("[%s:%d] consumer fast-forwarding from %d to %d",
c.topic, c.partID, c.offsets.Current, c.offsets.Earliest)
c.offsets.Current = c.offsets.Earliest
}
err := c.marshal.Heartbeat(c.topic, c.partID, c.offsets.Current)
if err != nil {
log.Errorf("[%s:%d] consumer failed to heartbeat: %s", c.topic, c.partID, err)
go c.Release()
return
}
c.lastHeartbeat = time.Now().Unix()
consumerConf := kafka.NewConsumerConf(c.topic, int32(c.partID))
consumerConf.StartOffset = c.offsets.Current
consumerConf.MaxFetchSize = c.marshal.cluster.options.MaxMessageSize
consumerConf.RequestTimeout = c.marshal.cluster.options.ConsumeRequestTimeout
consumerConf.RetryLimit = 0
kafkaConsumer, err := c.marshal.cluster.broker.Consumer(consumerConf)
if err != nil {
log.Errorf("[%s:%d] consumer failed to create Kafka Consumer: %s",
c.topic, c.partID, err)
go c.Release()
return
}
c.kafkaConsumer = kafkaConsumer
go c.messagePump()
log.Infof("[%s:%d] consumer %s claimed at offset %d (is %d behind)",
c.topic, c.partID, c.marshal.clientID, c.offsets.Current, c.offsets.Latest-c.offsets.Current)
}
func (c *claim) Commit(offset int64) error {
if c.Terminated() {
return fmt.Errorf("[%s:%d] is no longer claimed; can't commit offset %d",
c.topic, c.partID, offset)
}
c.lock.Lock()
defer c.lock.Unlock()
_, ok := c.tracking[offset]
if !ok {
return fmt.Errorf("[%s:%d] committing offset %d but we've never seen it",
c.topic, c.partID, offset)
}
c.tracking[offset] = true
c.outstandingMessages--
return nil
}
func (c *claim) Terminated() bool {
return atomic.LoadInt32(c.terminated) == 1
}
func (c *claim) GetCurrentLag() int64 {
c.lock.RLock()
defer c.lock.RUnlock()
if c.offsets.Current < c.offsets.Latest {
return c.offsets.Latest - c.offsets.Current
}
return 0
}
func (c *claim) Flush() error {
if c.Terminated() {
return nil
}
didAdvance, currentOffset := c.updateCurrentOffsets()
if !didAdvance {
return nil
}
if err := c.marshal.Heartbeat(c.topic, c.partID, currentOffset); err != nil {
go c.Release()
return fmt.Errorf("[%s:%d] failed to flush, releasing: %s", c.topic, c.partID, err)
}
return nil
}
func (c *claim) Release() bool {
return c.teardown(true)
}
func (c *claim) Terminate() bool {
return c.teardown(false)
}
func (c *claim) teardown(releasePartition bool) bool {
if !atomic.CompareAndSwapInt32(c.terminated, 0, 1) {
<-c.doneChan
return false
}
close(c.stopChan)
c.messagesLock.Lock()
defer c.messagesLock.Unlock()
_, currentOffset := c.updateCurrentOffsets()
if c.consumer != nil {
go c.consumer.claimTerminated(c, releasePartition)
}
var err error
if releasePartition {
log.Infof("[%s:%d] releasing partition claim", c.topic, c.partID)
err = c.marshal.ReleasePartition(c.topic, c.partID, currentOffset)
} else {
err = c.marshal.Heartbeat(c.topic, c.partID, currentOffset)
}
<-c.doneChan
if err != nil {
log.Errorf("[%s:%d] failed to release: %s", c.topic, c.partID, err)
return false
}
return true
}
func (c *claim) messagePump() {
defer close(c.doneChan)
retry := &backoff.Backoff{Min: 10 * time.Millisecond, Max: 1 * time.Second, Jitter: true}
for !c.Terminated() {
msg, err := c.kafkaConsumer.Consume()
if err == proto.ErrOffsetOutOfRange {
log.Warningf("[%s:%d] error consuming: out of range, abandoning partition",
c.topic, c.partID)
go c.Release()
return
} else if err == kafka.ErrNoData {
time.Sleep(retry.Duration())
continue
} else if err != nil {
log.Errorf("[%s:%d] error consuming: %s", c.topic, c.partID, err)
time.Sleep(1 * time.Second)
continue
}
retry.Reset()
c.lock.Lock()
c.lastMessageTime = time.Now()
c.tracking[msg.Offset] = false
c.outstandingMessages++
if msg.Offset < c.offsets.Current {
log.Errorf("[%s:%d] just consumed offset %d earlier than current %d",
c.topic, c.partID, msg.Offset, c.offsets.Current)
}
c.lock.Unlock()
c.messagesLock.Lock()
if !c.Terminated() {
tmp := Message(*msg)
select {
case c.messages <- &tmp:
case <-c.stopChan:
}
}
c.messagesLock.Unlock()
}
log.Debugf("[%s:%d] no longer claimed, pump exiting", c.topic, c.partID)
}
func (c *claim) heartbeat() bool {
if c.Terminated() {
return false
}
c.lock.Lock()
defer c.lock.Unlock()
err := c.marshal.Heartbeat(c.topic, c.partID, c.offsets.Current)
if err != nil {
log.Errorf("[%s:%d] failed to heartbeat, releasing: %s", c.topic, c.partID, err)
go c.Release()
}
log.Infof("[%s:%d] heartbeat: Current offset is %d, partition offset range is %d..%d.",
c.topic, c.partID, c.offsets.Current, c.offsets.Earliest, c.offsets.Latest)
log.Infof("[%s:%d] heartbeat: There are %d messages in queue and %d messages outstanding.",
c.topic, c.partID, len(c.messages), c.outstandingMessages)
c.lastHeartbeat = time.Now().Unix()
return true
}
func (c *claim) updateCurrentOffsets() (bool, int64) {
c.lock.Lock()
defer c.lock.Unlock()
offsets := make(int64slice, 0, len(c.tracking))
for key := range c.tracking {
offsets = append(offsets, key)
}
sort.Sort(offsets)
didAdvance := false
for _, offset := range offsets {
if !c.tracking[offset] {
break
}
didAdvance = true
if offset+1 <= c.offsets.Current {
log.Errorf("[%s:%d] rewinding current offset from %d to %d",
c.topic, c.partID, c.offsets.Current, offset+1)
}
c.offsets.Current = offset + 1
delete(c.tracking, offset)
}
if len(c.tracking) > c.marshal.cluster.options.MaxMessageQueue {
log.Errorf("[%s:%d] has %d uncommitted offsets. You must call Commit.",
c.topic, c.partID, len(c.tracking))
}
return didAdvance, c.offsets.Current
}
func (c *claim) heartbeatExpired() bool {
c.lock.RLock()
defer c.lock.RUnlock()
return c.lastHeartbeat < time.Now().Unix()-HeartbeatInterval
}
func (c *claim) healthCheck() bool {
if c.Terminated() {
return false
}
consumerVelocity := c.ConsumerVelocity()
partitionVelocity := c.PartitionVelocity()
if c.heartbeatExpired() {
log.Warningf("[%s:%d] consumer unhealthy by heartbeat test, releasing",
c.topic, c.partID)
go c.Release()
return false
}
if c.marshal.cluster.IsGroupPaused(c.marshal.GroupID()) {
log.Infof("[%s:%d] consumer group %s is paused, claim releasing",
c.topic, c.partID, c.marshal.GroupID())
go c.Release()
return false
}
c.lock.Lock()
defer c.lock.Unlock()
if time.Now().After(c.lastMessageTime.Add(HeartbeatInterval * time.Second)) {
if c.options.ReleaseClaimsIfBehind && consumerVelocity == 0 && (partitionVelocity > 0 || c.offsets.Latest > c.offsets.Current) {
log.Warningf("[%s:%d] no messages received for %d seconds with CV=%0.2f PV=%0.2f, releasing",
c.topic, c.partID, HeartbeatInterval, consumerVelocity, partitionVelocity)
go c.Release()
return false
} else {
log.Infof("[%s:%d] no messages received for %d seconds with CV=%0.2f PV=%0.2f",
c.topic, c.partID, HeartbeatInterval, consumerVelocity, partitionVelocity)
}
}
if c.options.ClaimEntireTopic || !c.options.ReleaseClaimsIfBehind {
return true
}
testOffset := c.offsets.Current + int64(consumerVelocity*2)
if testOffset >= c.offsets.Latest {
c.cyclesBehind = 0
return true
}
if partitionVelocity < consumerVelocity {
log.Infof("[%s:%d] consumer catching up: consume ∆ %0.2f >= produce ∆ %0.2f",
c.topic, c.partID, consumerVelocity, partitionVelocity)
c.cyclesBehind = 0
return true
}
c.cyclesBehind++
if c.cyclesBehind >= 3 {
log.Warningf("[%s:%d] consumer unhealthy for too long, releasing",
c.topic, c.partID)
go c.Release()
return false
}
log.Warningf("[%s:%d] consumer too slow: consume ∆ %0.2f < produce ∆ %0.2f (warning #%d)",
c.topic, c.partID, consumerVelocity, partitionVelocity, c.cyclesBehind)
return true
}
func (c *claim) healthCheckLoop() {
time.Sleep(<-c.marshal.cluster.jitters)
for !c.Terminated() {
for !c.heartbeatExpired() {
if err := c.updateOffsets(); err != nil {
log.Errorf("[%s:%d] health check loop failed to update offsets: %s",
c.topic, c.partID, err)
time.Sleep(1 * time.Second)
continue
}
break
}
if c.healthCheck() {
go c.heartbeat()
}
time.Sleep(<-c.marshal.cluster.jitters)
}
log.Infof("[%s:%d] health check loop exiting, claim terminated",
c.topic, c.partID)
}
func average(vals []int64) float64 {
min, max, ct := int64(0), int64(0), int64(0)
for _, val := range vals {
if val <= 0 {
continue
}
if min == 0 || val < min {
min = val
}
if max == 0 || val > max {
max = val
}
ct++
}
if min == max || ct < 2 {
return 0
}
return float64(max-min) / float64(ct-1)
}
func (c *claim) ConsumerVelocity() float64 {
c.lock.RLock()
defer c.lock.RUnlock()
return average(c.offsetCurrentHistory[0:])
}
func (c *claim) PartitionVelocity() float64 {
c.lock.RLock()
defer c.lock.RUnlock()
return average(c.offsetLatestHistory[0:])
}
func (c *claim) updateOffsets() error {
c.updateCurrentOffsets()
offsets, err := c.marshal.GetPartitionOffsets(c.topic, c.partID)
if err != nil {
log.Errorf("[%s:%d] failed to get offsets: %s", c.topic, c.partID, err)
return err
}
c.lock.Lock()
defer c.lock.Unlock()
c.offsets.Earliest = offsets.Earliest
c.offsets.Latest = offsets.Latest
c.offsetLatestHistory[c.beatCounter] = offsets.Latest
c.offsetCurrentHistory[c.beatCounter] = c.offsets.Current
c.beatCounter = (c.beatCounter + 1) % 10
return nil
}
func (c *claim) numTrackingOffsets() int {
c.lock.RLock()
defer c.lock.RUnlock()
return len(c.tracking)
} | BSD 3-Clause New or Revised License |
ent/contrib | entproto/internal/entprototest/ent/messagewithoptionals/where.go | UUIDOptionalLTE | go | func UUIDOptionalLTE(v uuid.UUID) predicate.MessageWithOptionals {
return predicate.MessageWithOptionals(func(s *sql.Selector) {
s.Where(sql.LTE(s.C(FieldUUIDOptional), v))
})
} | UUIDOptionalLTE applies the LTE predicate on the "uuid_optional" field. | https://github.com/ent/contrib/blob/2f98d3a15e7dfcc96aa696a5aceb0c8b1249f9e4/entproto/internal/entprototest/ent/messagewithoptionals/where.go#L735-L739 | package messagewithoptionals
import (
"time"
"entgo.io/contrib/entproto/internal/entprototest/ent/predicate"
"entgo.io/ent/dialect/sql"
"github.com/google/uuid"
)
func ID(id int) predicate.MessageWithOptionals {
return predicate.MessageWithOptionals(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldID), id))
})
}
func IDEQ(id int) predicate.MessageWithOptionals {
return predicate.MessageWithOptionals(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldID), id))
})
}
func IDNEQ(id int) predicate.MessageWithOptionals {
return predicate.MessageWithOptionals(func(s *sql.Selector) {
s.Where(sql.NEQ(s.C(FieldID), id))
})
}
func IDIn(ids ...int) predicate.MessageWithOptionals {
return predicate.MessageWithOptionals(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 ...int) predicate.MessageWithOptionals {
return predicate.MessageWithOptionals(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 int) predicate.MessageWithOptionals {
return predicate.MessageWithOptionals(func(s *sql.Selector) {
s.Where(sql.GT(s.C(FieldID), id))
})
}
func IDGTE(id int) predicate.MessageWithOptionals {
return predicate.MessageWithOptionals(func(s *sql.Selector) {
s.Where(sql.GTE(s.C(FieldID), id))
})
}
func IDLT(id int) predicate.MessageWithOptionals {
return predicate.MessageWithOptionals(func(s *sql.Selector) {
s.Where(sql.LT(s.C(FieldID), id))
})
}
func IDLTE(id int) predicate.MessageWithOptionals {
return predicate.MessageWithOptionals(func(s *sql.Selector) {
s.Where(sql.LTE(s.C(FieldID), id))
})
}
func StrOptional(v string) predicate.MessageWithOptionals {
return predicate.MessageWithOptionals(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldStrOptional), v))
})
}
func IntOptional(v int8) predicate.MessageWithOptionals {
return predicate.MessageWithOptionals(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldIntOptional), v))
})
}
func UintOptional(v uint8) predicate.MessageWithOptionals {
return predicate.MessageWithOptionals(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldUintOptional), v))
})
}
func FloatOptional(v float32) predicate.MessageWithOptionals {
return predicate.MessageWithOptionals(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldFloatOptional), v))
})
}
func BoolOptional(v bool) predicate.MessageWithOptionals {
return predicate.MessageWithOptionals(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldBoolOptional), v))
})
}
func BytesOptional(v []byte) predicate.MessageWithOptionals {
return predicate.MessageWithOptionals(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldBytesOptional), v))
})
}
func UUIDOptional(v uuid.UUID) predicate.MessageWithOptionals {
return predicate.MessageWithOptionals(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldUUIDOptional), v))
})
}
func TimeOptional(v time.Time) predicate.MessageWithOptionals {
return predicate.MessageWithOptionals(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldTimeOptional), v))
})
}
func StrOptionalEQ(v string) predicate.MessageWithOptionals {
return predicate.MessageWithOptionals(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldStrOptional), v))
})
}
func StrOptionalNEQ(v string) predicate.MessageWithOptionals {
return predicate.MessageWithOptionals(func(s *sql.Selector) {
s.Where(sql.NEQ(s.C(FieldStrOptional), v))
})
}
func StrOptionalIn(vs ...string) predicate.MessageWithOptionals {
v := make([]interface{}, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.MessageWithOptionals(func(s *sql.Selector) {
if len(v) == 0 {
s.Where(sql.False())
return
}
s.Where(sql.In(s.C(FieldStrOptional), v...))
})
}
func StrOptionalNotIn(vs ...string) predicate.MessageWithOptionals {
v := make([]interface{}, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.MessageWithOptionals(func(s *sql.Selector) {
if len(v) == 0 {
s.Where(sql.False())
return
}
s.Where(sql.NotIn(s.C(FieldStrOptional), v...))
})
}
func StrOptionalGT(v string) predicate.MessageWithOptionals {
return predicate.MessageWithOptionals(func(s *sql.Selector) {
s.Where(sql.GT(s.C(FieldStrOptional), v))
})
}
func StrOptionalGTE(v string) predicate.MessageWithOptionals {
return predicate.MessageWithOptionals(func(s *sql.Selector) {
s.Where(sql.GTE(s.C(FieldStrOptional), v))
})
}
func StrOptionalLT(v string) predicate.MessageWithOptionals {
return predicate.MessageWithOptionals(func(s *sql.Selector) {
s.Where(sql.LT(s.C(FieldStrOptional), v))
})
}
func StrOptionalLTE(v string) predicate.MessageWithOptionals {
return predicate.MessageWithOptionals(func(s *sql.Selector) {
s.Where(sql.LTE(s.C(FieldStrOptional), v))
})
}
func StrOptionalContains(v string) predicate.MessageWithOptionals {
return predicate.MessageWithOptionals(func(s *sql.Selector) {
s.Where(sql.Contains(s.C(FieldStrOptional), v))
})
}
func StrOptionalHasPrefix(v string) predicate.MessageWithOptionals {
return predicate.MessageWithOptionals(func(s *sql.Selector) {
s.Where(sql.HasPrefix(s.C(FieldStrOptional), v))
})
}
func StrOptionalHasSuffix(v string) predicate.MessageWithOptionals {
return predicate.MessageWithOptionals(func(s *sql.Selector) {
s.Where(sql.HasSuffix(s.C(FieldStrOptional), v))
})
}
func StrOptionalIsNil() predicate.MessageWithOptionals {
return predicate.MessageWithOptionals(func(s *sql.Selector) {
s.Where(sql.IsNull(s.C(FieldStrOptional)))
})
}
func StrOptionalNotNil() predicate.MessageWithOptionals {
return predicate.MessageWithOptionals(func(s *sql.Selector) {
s.Where(sql.NotNull(s.C(FieldStrOptional)))
})
}
func StrOptionalEqualFold(v string) predicate.MessageWithOptionals {
return predicate.MessageWithOptionals(func(s *sql.Selector) {
s.Where(sql.EqualFold(s.C(FieldStrOptional), v))
})
}
func StrOptionalContainsFold(v string) predicate.MessageWithOptionals {
return predicate.MessageWithOptionals(func(s *sql.Selector) {
s.Where(sql.ContainsFold(s.C(FieldStrOptional), v))
})
}
func IntOptionalEQ(v int8) predicate.MessageWithOptionals {
return predicate.MessageWithOptionals(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldIntOptional), v))
})
}
func IntOptionalNEQ(v int8) predicate.MessageWithOptionals {
return predicate.MessageWithOptionals(func(s *sql.Selector) {
s.Where(sql.NEQ(s.C(FieldIntOptional), v))
})
}
func IntOptionalIn(vs ...int8) predicate.MessageWithOptionals {
v := make([]interface{}, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.MessageWithOptionals(func(s *sql.Selector) {
if len(v) == 0 {
s.Where(sql.False())
return
}
s.Where(sql.In(s.C(FieldIntOptional), v...))
})
}
func IntOptionalNotIn(vs ...int8) predicate.MessageWithOptionals {
v := make([]interface{}, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.MessageWithOptionals(func(s *sql.Selector) {
if len(v) == 0 {
s.Where(sql.False())
return
}
s.Where(sql.NotIn(s.C(FieldIntOptional), v...))
})
}
func IntOptionalGT(v int8) predicate.MessageWithOptionals {
return predicate.MessageWithOptionals(func(s *sql.Selector) {
s.Where(sql.GT(s.C(FieldIntOptional), v))
})
}
func IntOptionalGTE(v int8) predicate.MessageWithOptionals {
return predicate.MessageWithOptionals(func(s *sql.Selector) {
s.Where(sql.GTE(s.C(FieldIntOptional), v))
})
}
func IntOptionalLT(v int8) predicate.MessageWithOptionals {
return predicate.MessageWithOptionals(func(s *sql.Selector) {
s.Where(sql.LT(s.C(FieldIntOptional), v))
})
}
func IntOptionalLTE(v int8) predicate.MessageWithOptionals {
return predicate.MessageWithOptionals(func(s *sql.Selector) {
s.Where(sql.LTE(s.C(FieldIntOptional), v))
})
}
func IntOptionalIsNil() predicate.MessageWithOptionals {
return predicate.MessageWithOptionals(func(s *sql.Selector) {
s.Where(sql.IsNull(s.C(FieldIntOptional)))
})
}
func IntOptionalNotNil() predicate.MessageWithOptionals {
return predicate.MessageWithOptionals(func(s *sql.Selector) {
s.Where(sql.NotNull(s.C(FieldIntOptional)))
})
}
func UintOptionalEQ(v uint8) predicate.MessageWithOptionals {
return predicate.MessageWithOptionals(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldUintOptional), v))
})
}
func UintOptionalNEQ(v uint8) predicate.MessageWithOptionals {
return predicate.MessageWithOptionals(func(s *sql.Selector) {
s.Where(sql.NEQ(s.C(FieldUintOptional), v))
})
}
func UintOptionalIn(vs ...uint8) predicate.MessageWithOptionals {
v := make([]interface{}, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.MessageWithOptionals(func(s *sql.Selector) {
if len(v) == 0 {
s.Where(sql.False())
return
}
s.Where(sql.In(s.C(FieldUintOptional), v...))
})
}
func UintOptionalNotIn(vs ...uint8) predicate.MessageWithOptionals {
v := make([]interface{}, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.MessageWithOptionals(func(s *sql.Selector) {
if len(v) == 0 {
s.Where(sql.False())
return
}
s.Where(sql.NotIn(s.C(FieldUintOptional), v...))
})
}
func UintOptionalGT(v uint8) predicate.MessageWithOptionals {
return predicate.MessageWithOptionals(func(s *sql.Selector) {
s.Where(sql.GT(s.C(FieldUintOptional), v))
})
}
func UintOptionalGTE(v uint8) predicate.MessageWithOptionals {
return predicate.MessageWithOptionals(func(s *sql.Selector) {
s.Where(sql.GTE(s.C(FieldUintOptional), v))
})
}
func UintOptionalLT(v uint8) predicate.MessageWithOptionals {
return predicate.MessageWithOptionals(func(s *sql.Selector) {
s.Where(sql.LT(s.C(FieldUintOptional), v))
})
}
func UintOptionalLTE(v uint8) predicate.MessageWithOptionals {
return predicate.MessageWithOptionals(func(s *sql.Selector) {
s.Where(sql.LTE(s.C(FieldUintOptional), v))
})
}
func UintOptionalIsNil() predicate.MessageWithOptionals {
return predicate.MessageWithOptionals(func(s *sql.Selector) {
s.Where(sql.IsNull(s.C(FieldUintOptional)))
})
}
func UintOptionalNotNil() predicate.MessageWithOptionals {
return predicate.MessageWithOptionals(func(s *sql.Selector) {
s.Where(sql.NotNull(s.C(FieldUintOptional)))
})
}
func FloatOptionalEQ(v float32) predicate.MessageWithOptionals {
return predicate.MessageWithOptionals(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldFloatOptional), v))
})
}
func FloatOptionalNEQ(v float32) predicate.MessageWithOptionals {
return predicate.MessageWithOptionals(func(s *sql.Selector) {
s.Where(sql.NEQ(s.C(FieldFloatOptional), v))
})
}
func FloatOptionalIn(vs ...float32) predicate.MessageWithOptionals {
v := make([]interface{}, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.MessageWithOptionals(func(s *sql.Selector) {
if len(v) == 0 {
s.Where(sql.False())
return
}
s.Where(sql.In(s.C(FieldFloatOptional), v...))
})
}
func FloatOptionalNotIn(vs ...float32) predicate.MessageWithOptionals {
v := make([]interface{}, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.MessageWithOptionals(func(s *sql.Selector) {
if len(v) == 0 {
s.Where(sql.False())
return
}
s.Where(sql.NotIn(s.C(FieldFloatOptional), v...))
})
}
func FloatOptionalGT(v float32) predicate.MessageWithOptionals {
return predicate.MessageWithOptionals(func(s *sql.Selector) {
s.Where(sql.GT(s.C(FieldFloatOptional), v))
})
}
func FloatOptionalGTE(v float32) predicate.MessageWithOptionals {
return predicate.MessageWithOptionals(func(s *sql.Selector) {
s.Where(sql.GTE(s.C(FieldFloatOptional), v))
})
}
func FloatOptionalLT(v float32) predicate.MessageWithOptionals {
return predicate.MessageWithOptionals(func(s *sql.Selector) {
s.Where(sql.LT(s.C(FieldFloatOptional), v))
})
}
func FloatOptionalLTE(v float32) predicate.MessageWithOptionals {
return predicate.MessageWithOptionals(func(s *sql.Selector) {
s.Where(sql.LTE(s.C(FieldFloatOptional), v))
})
}
func FloatOptionalIsNil() predicate.MessageWithOptionals {
return predicate.MessageWithOptionals(func(s *sql.Selector) {
s.Where(sql.IsNull(s.C(FieldFloatOptional)))
})
}
func FloatOptionalNotNil() predicate.MessageWithOptionals {
return predicate.MessageWithOptionals(func(s *sql.Selector) {
s.Where(sql.NotNull(s.C(FieldFloatOptional)))
})
}
func BoolOptionalEQ(v bool) predicate.MessageWithOptionals {
return predicate.MessageWithOptionals(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldBoolOptional), v))
})
}
func BoolOptionalNEQ(v bool) predicate.MessageWithOptionals {
return predicate.MessageWithOptionals(func(s *sql.Selector) {
s.Where(sql.NEQ(s.C(FieldBoolOptional), v))
})
}
func BoolOptionalIsNil() predicate.MessageWithOptionals {
return predicate.MessageWithOptionals(func(s *sql.Selector) {
s.Where(sql.IsNull(s.C(FieldBoolOptional)))
})
}
func BoolOptionalNotNil() predicate.MessageWithOptionals {
return predicate.MessageWithOptionals(func(s *sql.Selector) {
s.Where(sql.NotNull(s.C(FieldBoolOptional)))
})
}
func BytesOptionalEQ(v []byte) predicate.MessageWithOptionals {
return predicate.MessageWithOptionals(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldBytesOptional), v))
})
}
func BytesOptionalNEQ(v []byte) predicate.MessageWithOptionals {
return predicate.MessageWithOptionals(func(s *sql.Selector) {
s.Where(sql.NEQ(s.C(FieldBytesOptional), v))
})
}
func BytesOptionalIn(vs ...[]byte) predicate.MessageWithOptionals {
v := make([]interface{}, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.MessageWithOptionals(func(s *sql.Selector) {
if len(v) == 0 {
s.Where(sql.False())
return
}
s.Where(sql.In(s.C(FieldBytesOptional), v...))
})
}
func BytesOptionalNotIn(vs ...[]byte) predicate.MessageWithOptionals {
v := make([]interface{}, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.MessageWithOptionals(func(s *sql.Selector) {
if len(v) == 0 {
s.Where(sql.False())
return
}
s.Where(sql.NotIn(s.C(FieldBytesOptional), v...))
})
}
func BytesOptionalGT(v []byte) predicate.MessageWithOptionals {
return predicate.MessageWithOptionals(func(s *sql.Selector) {
s.Where(sql.GT(s.C(FieldBytesOptional), v))
})
}
func BytesOptionalGTE(v []byte) predicate.MessageWithOptionals {
return predicate.MessageWithOptionals(func(s *sql.Selector) {
s.Where(sql.GTE(s.C(FieldBytesOptional), v))
})
}
func BytesOptionalLT(v []byte) predicate.MessageWithOptionals {
return predicate.MessageWithOptionals(func(s *sql.Selector) {
s.Where(sql.LT(s.C(FieldBytesOptional), v))
})
}
func BytesOptionalLTE(v []byte) predicate.MessageWithOptionals {
return predicate.MessageWithOptionals(func(s *sql.Selector) {
s.Where(sql.LTE(s.C(FieldBytesOptional), v))
})
}
func BytesOptionalIsNil() predicate.MessageWithOptionals {
return predicate.MessageWithOptionals(func(s *sql.Selector) {
s.Where(sql.IsNull(s.C(FieldBytesOptional)))
})
}
func BytesOptionalNotNil() predicate.MessageWithOptionals {
return predicate.MessageWithOptionals(func(s *sql.Selector) {
s.Where(sql.NotNull(s.C(FieldBytesOptional)))
})
}
func UUIDOptionalEQ(v uuid.UUID) predicate.MessageWithOptionals {
return predicate.MessageWithOptionals(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldUUIDOptional), v))
})
}
func UUIDOptionalNEQ(v uuid.UUID) predicate.MessageWithOptionals {
return predicate.MessageWithOptionals(func(s *sql.Selector) {
s.Where(sql.NEQ(s.C(FieldUUIDOptional), v))
})
}
func UUIDOptionalIn(vs ...uuid.UUID) predicate.MessageWithOptionals {
v := make([]interface{}, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.MessageWithOptionals(func(s *sql.Selector) {
if len(v) == 0 {
s.Where(sql.False())
return
}
s.Where(sql.In(s.C(FieldUUIDOptional), v...))
})
}
func UUIDOptionalNotIn(vs ...uuid.UUID) predicate.MessageWithOptionals {
v := make([]interface{}, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.MessageWithOptionals(func(s *sql.Selector) {
if len(v) == 0 {
s.Where(sql.False())
return
}
s.Where(sql.NotIn(s.C(FieldUUIDOptional), v...))
})
}
func UUIDOptionalGT(v uuid.UUID) predicate.MessageWithOptionals {
return predicate.MessageWithOptionals(func(s *sql.Selector) {
s.Where(sql.GT(s.C(FieldUUIDOptional), v))
})
}
func UUIDOptionalGTE(v uuid.UUID) predicate.MessageWithOptionals {
return predicate.MessageWithOptionals(func(s *sql.Selector) {
s.Where(sql.GTE(s.C(FieldUUIDOptional), v))
})
}
func UUIDOptionalLT(v uuid.UUID) predicate.MessageWithOptionals {
return predicate.MessageWithOptionals(func(s *sql.Selector) {
s.Where(sql.LT(s.C(FieldUUIDOptional), v))
})
} | Apache License 2.0 |
kubernetes-csi/csi-lib-utils | vendor/k8s.io/client-go/applyconfigurations/autoscaling/v2beta2/horizontalpodautoscalerstatus.go | WithCurrentMetrics | go | func (b *HorizontalPodAutoscalerStatusApplyConfiguration) WithCurrentMetrics(values ...*MetricStatusApplyConfiguration) *HorizontalPodAutoscalerStatusApplyConfiguration {
for i := range values {
if values[i] == nil {
panic("nil value passed to WithCurrentMetrics")
}
b.CurrentMetrics = append(b.CurrentMetrics, *values[i])
}
return b
} | WithCurrentMetrics adds the given value to the CurrentMetrics 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 CurrentMetrics field. | https://github.com/kubernetes-csi/csi-lib-utils/blob/a2ccb594bb74b61a0655d3431c6365a6a567c7af/vendor/k8s.io/client-go/applyconfigurations/autoscaling/v2beta2/horizontalpodautoscalerstatus.go#L77-L85 | package v2beta2
import (
v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
type HorizontalPodAutoscalerStatusApplyConfiguration struct {
ObservedGeneration *int64 `json:"observedGeneration,omitempty"`
LastScaleTime *v1.Time `json:"lastScaleTime,omitempty"`
CurrentReplicas *int32 `json:"currentReplicas,omitempty"`
DesiredReplicas *int32 `json:"desiredReplicas,omitempty"`
CurrentMetrics []MetricStatusApplyConfiguration `json:"currentMetrics,omitempty"`
Conditions []HorizontalPodAutoscalerConditionApplyConfiguration `json:"conditions,omitempty"`
}
func HorizontalPodAutoscalerStatus() *HorizontalPodAutoscalerStatusApplyConfiguration {
return &HorizontalPodAutoscalerStatusApplyConfiguration{}
}
func (b *HorizontalPodAutoscalerStatusApplyConfiguration) WithObservedGeneration(value int64) *HorizontalPodAutoscalerStatusApplyConfiguration {
b.ObservedGeneration = &value
return b
}
func (b *HorizontalPodAutoscalerStatusApplyConfiguration) WithLastScaleTime(value v1.Time) *HorizontalPodAutoscalerStatusApplyConfiguration {
b.LastScaleTime = &value
return b
}
func (b *HorizontalPodAutoscalerStatusApplyConfiguration) WithCurrentReplicas(value int32) *HorizontalPodAutoscalerStatusApplyConfiguration {
b.CurrentReplicas = &value
return b
}
func (b *HorizontalPodAutoscalerStatusApplyConfiguration) WithDesiredReplicas(value int32) *HorizontalPodAutoscalerStatusApplyConfiguration {
b.DesiredReplicas = &value
return b
} | Apache License 2.0 |
kubeflow/katib | pkg/controller.v1beta1/util/unstructured.go | ConvertObjectToUnstructured | go | func ConvertObjectToUnstructured(in interface{}) (*unstructured.Unstructured, error) {
out := &unstructured.Unstructured{}
var err error
out.Object, err = runtime.DefaultUnstructuredConverter.ToUnstructured(&in)
if err != nil {
logUnstructured.Error(err, "Convert Object to Unstructured failed")
return nil, err
}
return out, nil
} | ConvertObjectToUnstructured returns Unstructured from Kubernetes Object value | https://github.com/kubeflow/katib/blob/195db292374dcf3b39b55dcb3fcd14b3a55d5942/pkg/controller.v1beta1/util/unstructured.go#L62-L73 | package util
import (
"bytes"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/runtime"
k8syaml "k8s.io/apimachinery/pkg/util/yaml"
logf "sigs.k8s.io/controller-runtime/pkg/log"
)
const (
bufferSize = 1024
)
var (
logUnstructured = logf.Log.WithName("util-unstructured")
)
func ConvertUnstructuredToString(in *unstructured.Unstructured) (string, error) {
inByte, err := in.MarshalJSON()
if err != nil {
logUnstructured.Error(err, "MarshalJSON failed")
return "", err
}
return string(inByte), nil
}
func ConvertStringToUnstructured(in string) (*unstructured.Unstructured, error) {
inBytes := bytes.NewBufferString(in)
out := &unstructured.Unstructured{}
err := k8syaml.NewYAMLOrJSONDecoder(inBytes, bufferSize).Decode(out)
if err != nil {
logUnstructured.Error(err, "Decode Unstructured to String failed")
return nil, err
}
return out, nil
} | Apache License 2.0 |
yofu/dxf | object/dictionary.go | IsObject | go | func (d *Dictionary) IsObject() bool {
return true
} | IsObject is for Object interface. | https://github.com/yofu/dxf/blob/5a6d1e83f16c3cf5526505a4f07ddf8c70755e5e/object/dictionary.go#L18-L20 | package object
import (
"fmt"
"sort"
"github.com/yofu/dxf/format"
"github.com/yofu/dxf/handle"
)
type Dictionary struct {
handle int
item map[string]handle.Handler
} | MIT License |
tellor-io/telliot | pkg/contracts/balancer/balancer.go | MAXWEIGHT | go | func (_BConst *BConstCallerSession) MAXWEIGHT() (*big.Int, error) {
return _BConst.Contract.MAXWEIGHT(&_BConst.CallOpts)
} | MAXWEIGHT is a free data retrieval call binding the contract method 0xe4a28a52.
Solidity: function MAX_WEIGHT() view returns(uint256) | https://github.com/tellor-io/telliot/blob/3219b50d08623436b9bb8424dc16e625ee006c59/pkg/contracts/balancer/balancer.go#L928-L930 | package balancer
import (
"math/big"
"strings"
ethereum "github.com/ethereum/go-ethereum"
"github.com/ethereum/go-ethereum/accounts/abi"
"github.com/ethereum/go-ethereum/accounts/abi/bind"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/event"
)
var (
_ = big.NewInt
_ = strings.NewReader
_ = ethereum.NotFound
_ = bind.Bind
_ = common.Big1
_ = types.BloomLookup
_ = event.NewSubscription
)
const BBronzeABI = "[{\"constant\":true,\"inputs\":[],\"name\":\"getColor\",\"outputs\":[{\"internalType\":\"bytes32\",\"name\":\"\",\"type\":\"bytes32\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"}]"
var BBronzeFuncSigs = map[string]string{
"9a86139b": "getColor()",
}
var BBronzeBin = "0x6080604052348015600f57600080fd5b5060878061001e6000396000f3fe6080604052348015600f57600080fd5b506004361060285760003560e01c80639a86139b14602d575b600080fd5b60336045565b60408051918252519081900360200190f35b6542524f4e5a4560d01b9056fea265627a7a72315820d3d552b78e7b2e77e5322e2b4f9dd135223e46ccfe5175ad6ad1064b13640ce664736f6c634300050c0032"
func DeployBBronze(auth *bind.TransactOpts, backend bind.ContractBackend) (common.Address, *types.Transaction, *BBronze, error) {
parsed, err := abi.JSON(strings.NewReader(BBronzeABI))
if err != nil {
return common.Address{}, nil, nil, err
}
address, tx, contract, err := bind.DeployContract(auth, parsed, common.FromHex(BBronzeBin), backend)
if err != nil {
return common.Address{}, nil, nil, err
}
return address, tx, &BBronze{BBronzeCaller: BBronzeCaller{contract: contract}, BBronzeTransactor: BBronzeTransactor{contract: contract}, BBronzeFilterer: BBronzeFilterer{contract: contract}}, nil
}
type BBronze struct {
BBronzeCaller
BBronzeTransactor
BBronzeFilterer
}
type BBronzeCaller struct {
contract *bind.BoundContract
}
type BBronzeTransactor struct {
contract *bind.BoundContract
}
type BBronzeFilterer struct {
contract *bind.BoundContract
}
type BBronzeSession struct {
Contract *BBronze
CallOpts bind.CallOpts
TransactOpts bind.TransactOpts
}
type BBronzeCallerSession struct {
Contract *BBronzeCaller
CallOpts bind.CallOpts
}
type BBronzeTransactorSession struct {
Contract *BBronzeTransactor
TransactOpts bind.TransactOpts
}
type BBronzeRaw struct {
Contract *BBronze
}
type BBronzeCallerRaw struct {
Contract *BBronzeCaller
}
type BBronzeTransactorRaw struct {
Contract *BBronzeTransactor
}
func NewBBronze(address common.Address, backend bind.ContractBackend) (*BBronze, error) {
contract, err := bindBBronze(address, backend, backend, backend)
if err != nil {
return nil, err
}
return &BBronze{BBronzeCaller: BBronzeCaller{contract: contract}, BBronzeTransactor: BBronzeTransactor{contract: contract}, BBronzeFilterer: BBronzeFilterer{contract: contract}}, nil
}
func NewBBronzeCaller(address common.Address, caller bind.ContractCaller) (*BBronzeCaller, error) {
contract, err := bindBBronze(address, caller, nil, nil)
if err != nil {
return nil, err
}
return &BBronzeCaller{contract: contract}, nil
}
func NewBBronzeTransactor(address common.Address, transactor bind.ContractTransactor) (*BBronzeTransactor, error) {
contract, err := bindBBronze(address, nil, transactor, nil)
if err != nil {
return nil, err
}
return &BBronzeTransactor{contract: contract}, nil
}
func NewBBronzeFilterer(address common.Address, filterer bind.ContractFilterer) (*BBronzeFilterer, error) {
contract, err := bindBBronze(address, nil, nil, filterer)
if err != nil {
return nil, err
}
return &BBronzeFilterer{contract: contract}, nil
}
func bindBBronze(address common.Address, caller bind.ContractCaller, transactor bind.ContractTransactor, filterer bind.ContractFilterer) (*bind.BoundContract, error) {
parsed, err := abi.JSON(strings.NewReader(BBronzeABI))
if err != nil {
return nil, err
}
return bind.NewBoundContract(address, parsed, caller, transactor, filterer), nil
}
func (_BBronze *BBronzeRaw) Call(opts *bind.CallOpts, result *[]interface{}, method string, params ...interface{}) error {
return _BBronze.Contract.BBronzeCaller.contract.Call(opts, result, method, params...)
}
func (_BBronze *BBronzeRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) {
return _BBronze.Contract.BBronzeTransactor.contract.Transfer(opts)
}
func (_BBronze *BBronzeRaw) Transact(opts *bind.TransactOpts, method string, params ...interface{}) (*types.Transaction, error) {
return _BBronze.Contract.BBronzeTransactor.contract.Transact(opts, method, params...)
}
func (_BBronze *BBronzeCallerRaw) Call(opts *bind.CallOpts, result *[]interface{}, method string, params ...interface{}) error {
return _BBronze.Contract.contract.Call(opts, result, method, params...)
}
func (_BBronze *BBronzeTransactorRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) {
return _BBronze.Contract.contract.Transfer(opts)
}
func (_BBronze *BBronzeTransactorRaw) Transact(opts *bind.TransactOpts, method string, params ...interface{}) (*types.Transaction, error) {
return _BBronze.Contract.contract.Transact(opts, method, params...)
}
func (_BBronze *BBronzeCaller) GetColor(opts *bind.CallOpts) ([32]byte, error) {
var out []interface{}
err := _BBronze.contract.Call(opts, &out, "getColor")
if err != nil {
return *new([32]byte), err
}
out0 := *abi.ConvertType(out[0], new([32]byte)).(*[32]byte)
return out0, err
}
func (_BBronze *BBronzeSession) GetColor() ([32]byte, error) {
return _BBronze.Contract.GetColor(&_BBronze.CallOpts)
}
func (_BBronze *BBronzeCallerSession) GetColor() ([32]byte, error) {
return _BBronze.Contract.GetColor(&_BBronze.CallOpts)
}
const BColorABI = "[{\"constant\":true,\"inputs\":[],\"name\":\"getColor\",\"outputs\":[{\"internalType\":\"bytes32\",\"name\":\"\",\"type\":\"bytes32\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"}]"
var BColorFuncSigs = map[string]string{
"9a86139b": "getColor()",
}
type BColor struct {
BColorCaller
BColorTransactor
BColorFilterer
}
type BColorCaller struct {
contract *bind.BoundContract
}
type BColorTransactor struct {
contract *bind.BoundContract
}
type BColorFilterer struct {
contract *bind.BoundContract
}
type BColorSession struct {
Contract *BColor
CallOpts bind.CallOpts
TransactOpts bind.TransactOpts
}
type BColorCallerSession struct {
Contract *BColorCaller
CallOpts bind.CallOpts
}
type BColorTransactorSession struct {
Contract *BColorTransactor
TransactOpts bind.TransactOpts
}
type BColorRaw struct {
Contract *BColor
}
type BColorCallerRaw struct {
Contract *BColorCaller
}
type BColorTransactorRaw struct {
Contract *BColorTransactor
}
func NewBColor(address common.Address, backend bind.ContractBackend) (*BColor, error) {
contract, err := bindBColor(address, backend, backend, backend)
if err != nil {
return nil, err
}
return &BColor{BColorCaller: BColorCaller{contract: contract}, BColorTransactor: BColorTransactor{contract: contract}, BColorFilterer: BColorFilterer{contract: contract}}, nil
}
func NewBColorCaller(address common.Address, caller bind.ContractCaller) (*BColorCaller, error) {
contract, err := bindBColor(address, caller, nil, nil)
if err != nil {
return nil, err
}
return &BColorCaller{contract: contract}, nil
}
func NewBColorTransactor(address common.Address, transactor bind.ContractTransactor) (*BColorTransactor, error) {
contract, err := bindBColor(address, nil, transactor, nil)
if err != nil {
return nil, err
}
return &BColorTransactor{contract: contract}, nil
}
func NewBColorFilterer(address common.Address, filterer bind.ContractFilterer) (*BColorFilterer, error) {
contract, err := bindBColor(address, nil, nil, filterer)
if err != nil {
return nil, err
}
return &BColorFilterer{contract: contract}, nil
}
func bindBColor(address common.Address, caller bind.ContractCaller, transactor bind.ContractTransactor, filterer bind.ContractFilterer) (*bind.BoundContract, error) {
parsed, err := abi.JSON(strings.NewReader(BColorABI))
if err != nil {
return nil, err
}
return bind.NewBoundContract(address, parsed, caller, transactor, filterer), nil
}
func (_BColor *BColorRaw) Call(opts *bind.CallOpts, result *[]interface{}, method string, params ...interface{}) error {
return _BColor.Contract.BColorCaller.contract.Call(opts, result, method, params...)
}
func (_BColor *BColorRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) {
return _BColor.Contract.BColorTransactor.contract.Transfer(opts)
}
func (_BColor *BColorRaw) Transact(opts *bind.TransactOpts, method string, params ...interface{}) (*types.Transaction, error) {
return _BColor.Contract.BColorTransactor.contract.Transact(opts, method, params...)
}
func (_BColor *BColorCallerRaw) Call(opts *bind.CallOpts, result *[]interface{}, method string, params ...interface{}) error {
return _BColor.Contract.contract.Call(opts, result, method, params...)
}
func (_BColor *BColorTransactorRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) {
return _BColor.Contract.contract.Transfer(opts)
}
func (_BColor *BColorTransactorRaw) Transact(opts *bind.TransactOpts, method string, params ...interface{}) (*types.Transaction, error) {
return _BColor.Contract.contract.Transact(opts, method, params...)
}
func (_BColor *BColorCaller) GetColor(opts *bind.CallOpts) ([32]byte, error) {
var out []interface{}
err := _BColor.contract.Call(opts, &out, "getColor")
if err != nil {
return *new([32]byte), err
}
out0 := *abi.ConvertType(out[0], new([32]byte)).(*[32]byte)
return out0, err
}
func (_BColor *BColorSession) GetColor() ([32]byte, error) {
return _BColor.Contract.GetColor(&_BColor.CallOpts)
}
func (_BColor *BColorCallerSession) GetColor() ([32]byte, error) {
return _BColor.Contract.GetColor(&_BColor.CallOpts)
}
const BConstABI = "[{\"constant\":true,\"inputs\":[],\"name\":\"BONE\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"BPOW_PRECISION\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"EXIT_FEE\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"INIT_POOL_SUPPLY\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"MAX_BOUND_TOKENS\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"MAX_BPOW_BASE\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"MAX_FEE\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"MAX_IN_RATIO\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"MAX_OUT_RATIO\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"MAX_TOTAL_WEIGHT\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"MAX_WEIGHT\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"MIN_BALANCE\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"MIN_BOUND_TOKENS\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"MIN_BPOW_BASE\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"MIN_FEE\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"MIN_WEIGHT\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"getColor\",\"outputs\":[{\"internalType\":\"bytes32\",\"name\":\"\",\"type\":\"bytes32\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"}]"
var BConstFuncSigs = map[string]string{
"c36596a6": "BONE()",
"189d00ca": "BPOW_PRECISION()",
"c6580d12": "EXIT_FEE()",
"9381cd2b": "INIT_POOL_SUPPLY()",
"b0e0d136": "MAX_BOUND_TOKENS()",
"bc694ea2": "MAX_BPOW_BASE()",
"bc063e1a": "MAX_FEE()",
"ec093021": "MAX_IN_RATIO()",
"992e2a92": "MAX_OUT_RATIO()",
"09a3bbe4": "MAX_TOTAL_WEIGHT()",
"e4a28a52": "MAX_WEIGHT()",
"867378c5": "MIN_BALANCE()",
"b7b800a4": "MIN_BOUND_TOKENS()",
"ba019dab": "MIN_BPOW_BASE()",
"76c7a3c7": "MIN_FEE()",
"218b5382": "MIN_WEIGHT()",
"9a86139b": "getColor()",
}
var BConstBin = "0x608060405234801561001057600080fd5b50610288806100206000396000f3fe608060405234801561001057600080fd5b506004361061010b5760003560e01c8063b0e0d136116100a2578063bc694ea211610071578063bc694ea214610182578063c36596a614610132578063c6580d121461018a578063e4a28a5214610110578063ec093021146101925761010b565b8063b0e0d13614610162578063b7b800a41461016a578063ba019dab14610172578063bc063e1a1461017a5761010b565b8063867378c5116100de578063867378c5146101425780639381cd2b1461014a578063992e2a92146101525780639a86139b1461015a5761010b565b806309a3bbe414610110578063189d00ca1461012a578063218b53821461013257806376c7a3c71461013a575b600080fd5b61011861019a565b60408051918252519081900360200190f35b6101186101a7565b6101186101bb565b6101186101c7565b6101186101d9565b6101186101ed565b6101186101fa565b610118610206565b610118610213565b610118610218565b61011861021d565b610118610222565b610118610232565b61011861023e565b610118610243565b6802b5e3af16b188000081565b6402540be400670de0b6b3a76400005b0481565b670de0b6b3a764000081565b620f4240670de0b6b3a76400006101b7565b64e8d4a51000670de0b6b3a76400006101b7565b68056bc75e2d6310000081565b6704a03ce68d21555681565b6542524f4e5a4560d01b90565b600881565b600281565b600181565b600a670de0b6b3a76400006101b7565b671bc16d674ec7ffff81565b600081565b6002670de0b6b3a76400006101b756fea265627a7a72315820d8f7793b5addb822085cc966647b0a04694550078347c0ab51edcb365ea7e17b64736f6c634300050c0032"
func DeployBConst(auth *bind.TransactOpts, backend bind.ContractBackend) (common.Address, *types.Transaction, *BConst, error) {
parsed, err := abi.JSON(strings.NewReader(BConstABI))
if err != nil {
return common.Address{}, nil, nil, err
}
address, tx, contract, err := bind.DeployContract(auth, parsed, common.FromHex(BConstBin), backend)
if err != nil {
return common.Address{}, nil, nil, err
}
return address, tx, &BConst{BConstCaller: BConstCaller{contract: contract}, BConstTransactor: BConstTransactor{contract: contract}, BConstFilterer: BConstFilterer{contract: contract}}, nil
}
type BConst struct {
BConstCaller
BConstTransactor
BConstFilterer
}
type BConstCaller struct {
contract *bind.BoundContract
}
type BConstTransactor struct {
contract *bind.BoundContract
}
type BConstFilterer struct {
contract *bind.BoundContract
}
type BConstSession struct {
Contract *BConst
CallOpts bind.CallOpts
TransactOpts bind.TransactOpts
}
type BConstCallerSession struct {
Contract *BConstCaller
CallOpts bind.CallOpts
}
type BConstTransactorSession struct {
Contract *BConstTransactor
TransactOpts bind.TransactOpts
}
type BConstRaw struct {
Contract *BConst
}
type BConstCallerRaw struct {
Contract *BConstCaller
}
type BConstTransactorRaw struct {
Contract *BConstTransactor
}
func NewBConst(address common.Address, backend bind.ContractBackend) (*BConst, error) {
contract, err := bindBConst(address, backend, backend, backend)
if err != nil {
return nil, err
}
return &BConst{BConstCaller: BConstCaller{contract: contract}, BConstTransactor: BConstTransactor{contract: contract}, BConstFilterer: BConstFilterer{contract: contract}}, nil
}
func NewBConstCaller(address common.Address, caller bind.ContractCaller) (*BConstCaller, error) {
contract, err := bindBConst(address, caller, nil, nil)
if err != nil {
return nil, err
}
return &BConstCaller{contract: contract}, nil
}
func NewBConstTransactor(address common.Address, transactor bind.ContractTransactor) (*BConstTransactor, error) {
contract, err := bindBConst(address, nil, transactor, nil)
if err != nil {
return nil, err
}
return &BConstTransactor{contract: contract}, nil
}
func NewBConstFilterer(address common.Address, filterer bind.ContractFilterer) (*BConstFilterer, error) {
contract, err := bindBConst(address, nil, nil, filterer)
if err != nil {
return nil, err
}
return &BConstFilterer{contract: contract}, nil
}
func bindBConst(address common.Address, caller bind.ContractCaller, transactor bind.ContractTransactor, filterer bind.ContractFilterer) (*bind.BoundContract, error) {
parsed, err := abi.JSON(strings.NewReader(BConstABI))
if err != nil {
return nil, err
}
return bind.NewBoundContract(address, parsed, caller, transactor, filterer), nil
}
func (_BConst *BConstRaw) Call(opts *bind.CallOpts, result *[]interface{}, method string, params ...interface{}) error {
return _BConst.Contract.BConstCaller.contract.Call(opts, result, method, params...)
}
func (_BConst *BConstRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) {
return _BConst.Contract.BConstTransactor.contract.Transfer(opts)
}
func (_BConst *BConstRaw) Transact(opts *bind.TransactOpts, method string, params ...interface{}) (*types.Transaction, error) {
return _BConst.Contract.BConstTransactor.contract.Transact(opts, method, params...)
}
func (_BConst *BConstCallerRaw) Call(opts *bind.CallOpts, result *[]interface{}, method string, params ...interface{}) error {
return _BConst.Contract.contract.Call(opts, result, method, params...)
}
func (_BConst *BConstTransactorRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) {
return _BConst.Contract.contract.Transfer(opts)
}
func (_BConst *BConstTransactorRaw) Transact(opts *bind.TransactOpts, method string, params ...interface{}) (*types.Transaction, error) {
return _BConst.Contract.contract.Transact(opts, method, params...)
}
func (_BConst *BConstCaller) BONE(opts *bind.CallOpts) (*big.Int, error) {
var out []interface{}
err := _BConst.contract.Call(opts, &out, "BONE")
if err != nil {
return *new(*big.Int), err
}
out0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int)
return out0, err
}
func (_BConst *BConstSession) BONE() (*big.Int, error) {
return _BConst.Contract.BONE(&_BConst.CallOpts)
}
func (_BConst *BConstCallerSession) BONE() (*big.Int, error) {
return _BConst.Contract.BONE(&_BConst.CallOpts)
}
func (_BConst *BConstCaller) BPOWPRECISION(opts *bind.CallOpts) (*big.Int, error) {
var out []interface{}
err := _BConst.contract.Call(opts, &out, "BPOW_PRECISION")
if err != nil {
return *new(*big.Int), err
}
out0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int)
return out0, err
}
func (_BConst *BConstSession) BPOWPRECISION() (*big.Int, error) {
return _BConst.Contract.BPOWPRECISION(&_BConst.CallOpts)
}
func (_BConst *BConstCallerSession) BPOWPRECISION() (*big.Int, error) {
return _BConst.Contract.BPOWPRECISION(&_BConst.CallOpts)
}
func (_BConst *BConstCaller) EXITFEE(opts *bind.CallOpts) (*big.Int, error) {
var out []interface{}
err := _BConst.contract.Call(opts, &out, "EXIT_FEE")
if err != nil {
return *new(*big.Int), err
}
out0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int)
return out0, err
}
func (_BConst *BConstSession) EXITFEE() (*big.Int, error) {
return _BConst.Contract.EXITFEE(&_BConst.CallOpts)
}
func (_BConst *BConstCallerSession) EXITFEE() (*big.Int, error) {
return _BConst.Contract.EXITFEE(&_BConst.CallOpts)
}
func (_BConst *BConstCaller) INITPOOLSUPPLY(opts *bind.CallOpts) (*big.Int, error) {
var out []interface{}
err := _BConst.contract.Call(opts, &out, "INIT_POOL_SUPPLY")
if err != nil {
return *new(*big.Int), err
}
out0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int)
return out0, err
}
func (_BConst *BConstSession) INITPOOLSUPPLY() (*big.Int, error) {
return _BConst.Contract.INITPOOLSUPPLY(&_BConst.CallOpts)
}
func (_BConst *BConstCallerSession) INITPOOLSUPPLY() (*big.Int, error) {
return _BConst.Contract.INITPOOLSUPPLY(&_BConst.CallOpts)
}
func (_BConst *BConstCaller) MAXBOUNDTOKENS(opts *bind.CallOpts) (*big.Int, error) {
var out []interface{}
err := _BConst.contract.Call(opts, &out, "MAX_BOUND_TOKENS")
if err != nil {
return *new(*big.Int), err
}
out0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int)
return out0, err
}
func (_BConst *BConstSession) MAXBOUNDTOKENS() (*big.Int, error) {
return _BConst.Contract.MAXBOUNDTOKENS(&_BConst.CallOpts)
}
func (_BConst *BConstCallerSession) MAXBOUNDTOKENS() (*big.Int, error) {
return _BConst.Contract.MAXBOUNDTOKENS(&_BConst.CallOpts)
}
func (_BConst *BConstCaller) MAXBPOWBASE(opts *bind.CallOpts) (*big.Int, error) {
var out []interface{}
err := _BConst.contract.Call(opts, &out, "MAX_BPOW_BASE")
if err != nil {
return *new(*big.Int), err
}
out0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int)
return out0, err
}
func (_BConst *BConstSession) MAXBPOWBASE() (*big.Int, error) {
return _BConst.Contract.MAXBPOWBASE(&_BConst.CallOpts)
}
func (_BConst *BConstCallerSession) MAXBPOWBASE() (*big.Int, error) {
return _BConst.Contract.MAXBPOWBASE(&_BConst.CallOpts)
}
func (_BConst *BConstCaller) MAXFEE(opts *bind.CallOpts) (*big.Int, error) {
var out []interface{}
err := _BConst.contract.Call(opts, &out, "MAX_FEE")
if err != nil {
return *new(*big.Int), err
}
out0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int)
return out0, err
}
func (_BConst *BConstSession) MAXFEE() (*big.Int, error) {
return _BConst.Contract.MAXFEE(&_BConst.CallOpts)
}
func (_BConst *BConstCallerSession) MAXFEE() (*big.Int, error) {
return _BConst.Contract.MAXFEE(&_BConst.CallOpts)
}
func (_BConst *BConstCaller) MAXINRATIO(opts *bind.CallOpts) (*big.Int, error) {
var out []interface{}
err := _BConst.contract.Call(opts, &out, "MAX_IN_RATIO")
if err != nil {
return *new(*big.Int), err
}
out0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int)
return out0, err
}
func (_BConst *BConstSession) MAXINRATIO() (*big.Int, error) {
return _BConst.Contract.MAXINRATIO(&_BConst.CallOpts)
}
func (_BConst *BConstCallerSession) MAXINRATIO() (*big.Int, error) {
return _BConst.Contract.MAXINRATIO(&_BConst.CallOpts)
}
func (_BConst *BConstCaller) MAXOUTRATIO(opts *bind.CallOpts) (*big.Int, error) {
var out []interface{}
err := _BConst.contract.Call(opts, &out, "MAX_OUT_RATIO")
if err != nil {
return *new(*big.Int), err
}
out0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int)
return out0, err
}
func (_BConst *BConstSession) MAXOUTRATIO() (*big.Int, error) {
return _BConst.Contract.MAXOUTRATIO(&_BConst.CallOpts)
}
func (_BConst *BConstCallerSession) MAXOUTRATIO() (*big.Int, error) {
return _BConst.Contract.MAXOUTRATIO(&_BConst.CallOpts)
}
func (_BConst *BConstCaller) MAXTOTALWEIGHT(opts *bind.CallOpts) (*big.Int, error) {
var out []interface{}
err := _BConst.contract.Call(opts, &out, "MAX_TOTAL_WEIGHT")
if err != nil {
return *new(*big.Int), err
}
out0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int)
return out0, err
}
func (_BConst *BConstSession) MAXTOTALWEIGHT() (*big.Int, error) {
return _BConst.Contract.MAXTOTALWEIGHT(&_BConst.CallOpts)
}
func (_BConst *BConstCallerSession) MAXTOTALWEIGHT() (*big.Int, error) {
return _BConst.Contract.MAXTOTALWEIGHT(&_BConst.CallOpts)
}
func (_BConst *BConstCaller) MAXWEIGHT(opts *bind.CallOpts) (*big.Int, error) {
var out []interface{}
err := _BConst.contract.Call(opts, &out, "MAX_WEIGHT")
if err != nil {
return *new(*big.Int), err
}
out0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int)
return out0, err
}
func (_BConst *BConstSession) MAXWEIGHT() (*big.Int, error) {
return _BConst.Contract.MAXWEIGHT(&_BConst.CallOpts)
} | MIT License |
leberkleber/simple-jwt-provider | internal/storage_moq_test.go | CreateToken | go | func (mock *StorageMock) CreateToken(t *storage.Token) error {
if mock.CreateTokenFunc == nil {
panic("StorageMock.CreateTokenFunc: method is nil but Storage.CreateToken was just called")
}
callInfo := struct {
T *storage.Token
}{
T: t,
}
mock.lockCreateToken.Lock()
mock.calls.CreateToken = append(mock.calls.CreateToken, callInfo)
mock.lockCreateToken.Unlock()
return mock.CreateTokenFunc(t)
} | CreateToken calls CreateTokenFunc. | https://github.com/leberkleber/simple-jwt-provider/blob/58e0de8f99b86df84a9f94c6c2d9d13e00d1124d/internal/storage_moq_test.go#L120-L133 | package internal
import (
"github.com/leberKleber/simple-jwt-provider/internal/storage"
"sync"
)
var _ Storage = &StorageMock{}
type StorageMock struct {
CreateTokenFunc func(t *storage.Token) error
CreateUserFunc func(user storage.User) error
DeleteTokenFunc func(id uint) error
DeleteUserFunc func(email string) error
TokensByEMailAndTokenFunc func(email string, token string) ([]storage.Token, error)
UpdateUserFunc func(user storage.User) error
UserFunc func(email string) (storage.User, error)
calls struct {
CreateToken []struct {
T *storage.Token
}
CreateUser []struct {
User storage.User
}
DeleteToken []struct {
ID uint
}
DeleteUser []struct {
Email string
}
TokensByEMailAndToken []struct {
Email string
Token string
}
UpdateUser []struct {
User storage.User
}
User []struct {
Email string
}
}
lockCreateToken sync.RWMutex
lockCreateUser sync.RWMutex
lockDeleteToken sync.RWMutex
lockDeleteUser sync.RWMutex
lockTokensByEMailAndToken sync.RWMutex
lockUpdateUser sync.RWMutex
lockUser sync.RWMutex
} | MIT License |
keybase/search | vendor/github.com/keybase/client/go/logger/output_windows.go | setConsoleTextAttribute | go | func setConsoleTextAttribute(handle uintptr, attribute WORD) error {
r1, r2, err := setConsoleTextAttributeProc.Call(handle, uintptr(attribute), 0)
use(attribute)
return checkError(r1, r2, err)
} | setConsoleTextAttribute sets the attributes of characters written to the
console screen buffer by the WriteFile or WriteConsole function.
See http://msdn.microsoft.com/en-us/library/windows/desktop/ms686047(v=vs.85).aspx. | https://github.com/keybase/search/blob/1fd911fa01213f084011d7bf29f375bca4536176/vendor/github.com/keybase/client/go/logger/output_windows.go#L219-L223 | package logger
import (
"bytes"
"fmt"
"io"
"os"
"sync"
"syscall"
"golang.org/x/sys/windows"
)
var (
kernel32DLL = windows.NewLazySystemDLL("kernel32.dll")
setConsoleTextAttributeProc = kernel32DLL.NewProc("SetConsoleTextAttribute")
stdOutMutex sync.Mutex
stdErrMutex sync.Mutex
)
type WORD uint16
const (
fgBlack WORD = 0x0000
fgBlue WORD = 0x0001
fgGreen WORD = 0x0002
fgCyan WORD = 0x0003
fgRed WORD = 0x0004
fgMagenta WORD = 0x0005
fgYellow WORD = 0x0006
fgWhite WORD = 0x0007
fgIntensity WORD = 0x0008
fgMask WORD = 0x000F
bgBlack WORD = 0x0000
bgBlue WORD = 0x0010
bgGreen WORD = 0x0020
bgCyan WORD = 0x0030
bgRed WORD = 0x0040
bgMagenta WORD = 0x0050
bgYellow WORD = 0x0060
bgWhite WORD = 0x0070
bgIntensity WORD = 0x0080
bgMask WORD = 0x00F0
)
var codesWin = map[byte]WORD{
0: fgWhite | bgBlack,
1: fgIntensity,
22: fgWhite,
39: fgWhite,
49: fgWhite,
30: fgBlack,
31: fgRed,
32: fgGreen,
33: fgYellow,
34: fgBlue,
35: fgMagenta,
36: fgCyan,
37: fgWhite,
90: fgWhite,
40: bgBlack,
41: bgRed,
42: bgGreen,
43: bgYellow,
44: bgBlue,
45: bgMagenta,
46: bgCyan,
47: bgWhite,
}
func OutputWriterFromFile(out *os.File) io.Writer {
return &ColorWriter{w: out, fd: out.Fd(), mutex: &stdOutMutex, lastFgColor: fgWhite}
}
func OutputWriter() io.Writer {
return OutputWriterFromFile(os.Stdout)
}
func ErrorWriter() io.Writer {
return &ColorWriter{w: os.Stderr, fd: os.Stderr.Fd(), mutex: &stdErrMutex, lastFgColor: fgWhite}
}
type ColorWriter struct {
w io.Writer
fd uintptr
mutex *sync.Mutex
lastFgColor WORD
bold bool
}
func (cw *ColorWriter) Fd() uintptr {
return cw.fd
}
func (cw *ColorWriter) Write(p []byte) (n int, err error) {
cw.mutex.Lock()
defer cw.mutex.Unlock()
var totalWritten = len(p)
ctlStart := []byte{0x1b, '['}
for nextIndex := 0; len(p) > 0; {
nextIndex = bytes.Index(p, ctlStart)
if nextIndex == -1 {
nextIndex = len(p)
}
cw.w.Write(p[0:nextIndex])
if nextIndex+2 < len(p) {
nextIndex += 2
}
p = p[nextIndex:]
if len(p) > 0 {
if '0' <= p[0] && p[0] <= '9' {
p = cw.parseColorControl(p)
} else {
p = cw.parseControlCode(p)
}
}
}
return totalWritten, nil
}
func (cw *ColorWriter) parseColorControl(p []byte) []byte {
var controlIndex int
controlCode := p[controlIndex] - '0'
controlIndex++
for i := 0; controlIndex < len(p) && p[controlIndex] != 'm' && i < 4; i++ {
if '0' <= p[controlIndex] && p[controlIndex] <= '9' {
controlCode *= 10
controlCode += p[controlIndex] - '0'
}
controlIndex++
}
if code, ok := codesWin[controlCode]; ok {
if controlCode == 1 {
cw.bold = true
} else if controlCode == 0 || controlCode == 22 || controlCode == 39 {
code = fgWhite
cw.bold = false
}
if code >= fgBlue && code <= fgWhite {
cw.lastFgColor = code
} else {
code = cw.lastFgColor
}
if cw.bold {
code = code | fgIntensity
}
setConsoleTextAttribute(cw.fd, code)
}
if controlIndex+1 <= len(p) {
controlIndex += 1
}
return p[controlIndex:]
}
func (cw *ColorWriter) parseControlCode(p []byte) []byte {
if p[0] == 'D' {
cw.w.Write([]byte(fmt.Sprintf("\b")))
}
return p[1:]
} | BSD 3-Clause New or Revised License |
redspread/spread | vendor/k8s.io/kubernetes/pkg/client/cache/reflector.go | Run | go | func (r *Reflector) Run() {
go wait.Until(func() { r.ListAndWatch(wait.NeverStop) }, r.period, wait.NeverStop)
} | Run starts a watch and handles watch events. Will restart the watch if it is closed.
Run starts a goroutine and returns immediately. | https://github.com/redspread/spread/blob/382198ac9350d771facc76f4242ab76ca774acb9/vendor/k8s.io/kubernetes/pkg/client/cache/reflector.go#L159-L161 | package cache
import (
"errors"
"fmt"
"io"
"math/rand"
"net"
"net/url"
"reflect"
goruntime "runtime"
"strings"
"sync"
"syscall"
"time"
"github.com/golang/glog"
"k8s.io/kubernetes/pkg/api"
apierrs "k8s.io/kubernetes/pkg/api/errors"
"k8s.io/kubernetes/pkg/api/meta"
"k8s.io/kubernetes/pkg/runtime"
utilruntime "k8s.io/kubernetes/pkg/util/runtime"
"k8s.io/kubernetes/pkg/util/wait"
"k8s.io/kubernetes/pkg/watch"
)
type ListerWatcher interface {
List(options api.ListOptions) (runtime.Object, error)
Watch(options api.ListOptions) (watch.Interface, error)
}
type Reflector struct {
name string
expectedType reflect.Type
store Store
listerWatcher ListerWatcher
period time.Duration
resyncPeriod time.Duration
now func() time.Time
nextResync time.Time
lastSyncResourceVersion string
lastSyncResourceVersionMutex sync.RWMutex
}
var (
minWatchTimeout = 5 * time.Minute
forceResyncThreshold = 3 * time.Second
timeoutThreshold = 1 * time.Second
)
func NewNamespaceKeyedIndexerAndReflector(lw ListerWatcher, expectedType interface{}, resyncPeriod time.Duration) (indexer Indexer, reflector *Reflector) {
indexer = NewIndexer(MetaNamespaceKeyFunc, Indexers{"namespace": MetaNamespaceIndexFunc})
reflector = NewReflector(lw, expectedType, indexer, resyncPeriod)
return indexer, reflector
}
func NewReflector(lw ListerWatcher, expectedType interface{}, store Store, resyncPeriod time.Duration) *Reflector {
return NewNamedReflector(getDefaultReflectorName(internalPackages...), lw, expectedType, store, resyncPeriod)
}
func NewNamedReflector(name string, lw ListerWatcher, expectedType interface{}, store Store, resyncPeriod time.Duration) *Reflector {
r := &Reflector{
name: name,
listerWatcher: lw,
store: store,
expectedType: reflect.TypeOf(expectedType),
period: time.Second,
resyncPeriod: resyncPeriod,
now: time.Now,
}
return r
}
var internalPackages = []string{"kubernetes/pkg/client/cache/", "kubernetes/pkg/controller/framework/"}
func getDefaultReflectorName(ignoredPackages ...string) string {
name := "????"
outer:
for i := 1; i < 10; i++ {
_, file, line, ok := goruntime.Caller(i)
if !ok {
break
}
for _, ignoredPackage := range ignoredPackages {
if strings.Contains(file, ignoredPackage) {
continue outer
}
}
pkgLocation := strings.LastIndex(file, "/pkg/")
if pkgLocation >= 0 {
file = file[pkgLocation+1:]
}
name = fmt.Sprintf("%s:%d", file, line)
break
}
return name
} | Apache License 2.0 |
graveyard/gearcmd | baseworker/mock/mock.go | Warnings | go | func (m *Job) Warnings() [][]byte {
return m.GearmanWarnings
} | Warnings returns the array of jobs warnings | https://github.com/graveyard/gearcmd/blob/22734283e1b0edda348ed6a7b7a1da085706db4a/baseworker/mock/mock.go#L50-L52 | package mock
import "bytes"
type Job struct {
Payload, Name, GearmanHandle, ID string
GearmanErr error
GearmanWarnings [][]byte
DataBuffer bytes.Buffer
Numerator, Denominator int
}
func CreateMockJob(payload string) *Job {
return &Job{Payload: payload}
}
func (m Job) Data() []byte {
return []byte(m.Payload)
}
func (m Job) OutData() []byte {
return m.DataBuffer.Bytes()
}
func (m Job) Fn() string {
return m.Name
}
func (m Job) Err() error {
return m.GearmanErr
}
func (m Job) Handle() string {
return m.GearmanHandle
}
func (m Job) UniqueId() string {
return m.ID
} | Apache License 2.0 |
gnboorse/centipede | variable.go | EvaluateDomainRemovals | go | func (variables *Variables) EvaluateDomainRemovals(domainRemovals DomainRemovals) {
for _, removal := range domainRemovals {
modifiedVariable := variables.Find(removal.VariableName)
if modifiedVariable.Empty {
modifiedVariable.Domain = modifiedVariable.Domain.Remove(removal.Value)
}
}
} | EvaluateDomainRemovals remove values from domain based on DomainRemovals in propagation | https://github.com/gnboorse/centipede/blob/4f8c1c49293851d3ba71a867106b11a93f5e184e/variable.go#L158-L168 | package centipede
import "fmt"
type VariableName string
type VariableNames []VariableName
func (varnames *VariableNames) Contains(varname VariableName) bool {
for _, item := range *varnames {
if item == varname {
return true
}
}
return false
}
type Variable struct {
Name VariableName
Value interface{}
Domain Domain
Empty bool
}
func NewVariable(name VariableName, domain Domain) Variable {
return Variable{name, 0, domain, true}
}
func (variable *Variable) SetValue(value interface{}) {
variable.Value = value
variable.Empty = false
}
func (variable *Variable) Unset() {
variable.Empty = true
variable.Value = nil
}
func (variable *Variable) SetDomain(domain Domain) {
variable.Domain = domain
}
type Variables []Variable
func (variables *Variables) SetValue(name VariableName, value interface{}) {
foundIndex := -1
for index, variable := range *variables {
if variable.Name == name {
foundIndex = index
}
}
if !(foundIndex >= 0) {
panic(fmt.Sprintf("Variable not found by name %v in variables %v", name, variables))
} else {
(*variables)[foundIndex].Value = value
(*variables)[foundIndex].Empty = false
}
}
func (variables *Variables) Unset(name VariableName) {
foundIndex := -1
for index, variable := range *variables {
if variable.Name == name {
foundIndex = index
}
}
if !(foundIndex >= 0) {
panic(fmt.Sprintf("Variable not found by name %v in variables %v", name, variables))
} else {
(*variables)[foundIndex].Value = nil
(*variables)[foundIndex].Empty = true
}
}
func (variables *Variables) SetDomain(name VariableName, domain Domain) {
foundIndex := -1
for index, variable := range *variables {
if variable.Name == name {
foundIndex = index
}
}
if !(foundIndex >= 0) {
panic(fmt.Sprintf("Variable not found by name %v in variables %v", name, variables))
} else {
(*variables)[foundIndex].Domain = domain
}
}
func (variables *Variables) Find(name VariableName) *Variable {
for i := 0; i < len(*variables); i++ {
if (*variables)[i].Name == name {
return &(*variables)[i]
}
}
panic(fmt.Sprintf("Variable not found by name %v in variables %v", name, variables))
}
func (variables *Variables) Contains(name VariableName) bool {
for _, variable := range *variables {
if variable.Name == name {
return true
}
}
return false
}
func (variables *Variables) Unassigned() int {
count := 0
for _, variable := range *variables {
if variable.Empty {
count++
}
}
return count
}
func (variables *Variables) Complete() bool {
return variables.Unassigned() == 0
} | Apache License 2.0 |
sdslabs/gctl | cmd/testmocks/mock_dbsApi.go | EXPECT | go | func (m *MockDbsAPIService) EXPECT() *MockDbsAPIServiceMockRecorder {
return m.recorder
} | EXPECT returns an object that allows the caller to indicate expected use | https://github.com/sdslabs/gctl/blob/c5d95e6c05aae0f28afcb9ca7f2c94e7a851586d/cmd/testmocks/mock_dbsApi.go#L34-L36 | package testmocks
import (
context "context"
gomock "github.com/golang/mock/gomock"
openapi "github.com/sdslabs/gctl/client"
http "net/http"
reflect "reflect"
)
type MockDbsAPIService struct {
ctrl *gomock.Controller
recorder *MockDbsAPIServiceMockRecorder
}
type MockDbsAPIServiceMockRecorder struct {
mock *MockDbsAPIService
}
func NewMockDbsAPIService(ctrl *gomock.Controller) *MockDbsAPIService {
mock := &MockDbsAPIService{ctrl: ctrl}
mock.recorder = &MockDbsAPIServiceMockRecorder{mock}
return mock
} | MIT License |
newrelic/nri-kubernetes | src/prometheus/metric.go | valid | go | func (f *MetricFamily) valid() bool {
return f.Name != "" && f.Type != "" && len(f.Metrics) > 0
} | valid validates that all the attributes were filled. | https://github.com/newrelic/nri-kubernetes/blob/2bd966fad87176a64f5601a8c55b6bd341bac2da/src/prometheus/metric.go#L64-L66 | package prometheus
import (
"fmt"
"strconv"
model "github.com/prometheus/client_model/go"
)
type Value interface {
fmt.Stringer
}
type noValueType string
func (v noValueType) String() string {
return string(v)
}
const EmptyValue noValueType = "no_value"
type Labels map[string]string
func (l Labels) AreIn(p []*model.LabelPair) bool {
var votes int
for name, value := range l {
for _, pl := range p {
if pl.GetName() == name && pl.GetValue() == value {
votes++
}
}
}
return votes == len(l)
}
func (l Labels) Has(name string) bool {
if _, ok := l[name]; ok {
return true
}
return false
}
type Metric struct {
Labels Labels
Value Value
}
type MetricFamily struct {
Name string
Type string
Metrics []Metric
} | Apache License 2.0 |
viafintech/cronlocker | vendor/golang.org/x/sys/unix/syscall_darwin.go | Listxattr | go | func Listxattr(path string, dest []byte) (sz int, err error) {
return listxattr(path, xattrPointer(dest), len(dest), 0)
} | sys listxattr(path string, dest *byte, size int, options int) (sz int, err error) | https://github.com/viafintech/cronlocker/blob/2ac4d6fe6e05a9b41f3fb54bb138340d876080c8/vendor/golang.org/x/sys/unix/syscall_darwin.go#L270-L272 | package unix
import (
"errors"
"syscall"
"unsafe"
)
const ImplementsGetwd = true
func Getwd() (string, error) {
buf := make([]byte, 2048)
attrs, err := getAttrList(".", attrList{CommonAttr: attrCmnFullpath}, buf, 0)
if err == nil && len(attrs) == 1 && len(attrs[0]) >= 2 {
wd := string(attrs[0])
if wd[0] == '/' && wd[len(wd)-1] == 0 {
return wd[:len(wd)-1], nil
}
}
return "", ENOTSUP
}
type SockaddrDatalink struct {
Len uint8
Family uint8
Index uint16
Type uint8
Nlen uint8
Alen uint8
Slen uint8
Data [12]int8
raw RawSockaddrDatalink
}
func nametomib(name string) (mib []_C_int, err error) {
const siz = unsafe.Sizeof(mib[0])
var buf [CTL_MAXNAME + 2]_C_int
n := uintptr(CTL_MAXNAME) * siz
p := (*byte)(unsafe.Pointer(&buf[0]))
bytes, err := ByteSliceFromString(name)
if err != nil {
return nil, err
}
if err = sysctl([]_C_int{0, 3}, p, &n, &bytes[0], uintptr(len(name))); err != nil {
return nil, err
}
return buf[0 : n/siz], nil
}
func direntIno(buf []byte) (uint64, bool) {
return readInt(buf, unsafe.Offsetof(Dirent{}.Ino), unsafe.Sizeof(Dirent{}.Ino))
}
func direntReclen(buf []byte) (uint64, bool) {
return readInt(buf, unsafe.Offsetof(Dirent{}.Reclen), unsafe.Sizeof(Dirent{}.Reclen))
}
func direntNamlen(buf []byte) (uint64, bool) {
return readInt(buf, unsafe.Offsetof(Dirent{}.Namlen), unsafe.Sizeof(Dirent{}.Namlen))
}
func PtraceAttach(pid int) (err error) { return ptrace(PT_ATTACH, pid, 0, 0) }
func PtraceDetach(pid int) (err error) { return ptrace(PT_DETACH, pid, 0, 0) }
const (
attrBitMapCount = 5
attrCmnFullpath = 0x08000000
)
type attrList struct {
bitmapCount uint16
_ uint16
CommonAttr uint32
VolAttr uint32
DirAttr uint32
FileAttr uint32
Forkattr uint32
}
func getAttrList(path string, attrList attrList, attrBuf []byte, options uint) (attrs [][]byte, err error) {
if len(attrBuf) < 4 {
return nil, errors.New("attrBuf too small")
}
attrList.bitmapCount = attrBitMapCount
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return nil, err
}
if err := getattrlist(_p0, unsafe.Pointer(&attrList), unsafe.Pointer(&attrBuf[0]), uintptr(len(attrBuf)), int(options)); err != nil {
return nil, err
}
size := *(*uint32)(unsafe.Pointer(&attrBuf[0]))
dat := attrBuf
if int(size) < len(attrBuf) {
dat = dat[:size]
}
dat = dat[4:]
for i := uint32(0); int(i) < len(dat); {
header := dat[i:]
if len(header) < 8 {
return attrs, errors.New("truncated attribute header")
}
datOff := *(*int32)(unsafe.Pointer(&header[0]))
attrLen := *(*uint32)(unsafe.Pointer(&header[4]))
if datOff < 0 || uint32(datOff)+attrLen > uint32(len(dat)) {
return attrs, errors.New("truncated results; attrBuf too small")
}
end := uint32(datOff) + attrLen
attrs = append(attrs, dat[datOff:end])
i = end
if r := i % 4; r != 0 {
i += (4 - r)
}
}
return
}
func Pipe(p []int) (err error) {
if len(p) != 2 {
return EINVAL
}
p[0], p[1], err = pipe()
return
}
func Getfsstat(buf []Statfs_t, flags int) (n int, err error) {
var _p0 unsafe.Pointer
var bufsize uintptr
if len(buf) > 0 {
_p0 = unsafe.Pointer(&buf[0])
bufsize = unsafe.Sizeof(Statfs_t{}) * uintptr(len(buf))
}
return getfsstat(_p0, bufsize, flags)
}
func xattrPointer(dest []byte) *byte {
var destp *byte
if len(dest) > 0 {
destp = &dest[0]
}
return destp
}
func Getxattr(path string, attr string, dest []byte) (sz int, err error) {
return getxattr(path, attr, xattrPointer(dest), len(dest), 0, 0)
}
func Lgetxattr(link string, attr string, dest []byte) (sz int, err error) {
return getxattr(link, attr, xattrPointer(dest), len(dest), 0, XATTR_NOFOLLOW)
}
func Fgetxattr(fd int, attr string, dest []byte) (sz int, err error) {
return fgetxattr(fd, attr, xattrPointer(dest), len(dest), 0, 0)
}
func Setxattr(path string, attr string, data []byte, flags int) (err error) {
return setxattr(path, attr, xattrPointer(data), len(data), 0, flags)
}
func Lsetxattr(link string, attr string, data []byte, flags int) (err error) {
return setxattr(link, attr, xattrPointer(data), len(data), 0, flags|XATTR_NOFOLLOW)
}
func Fsetxattr(fd int, attr string, data []byte, flags int) (err error) {
return fsetxattr(fd, attr, xattrPointer(data), len(data), 0, 0)
}
func Removexattr(path string, attr string) (err error) {
return removexattr(path, attr, 0)
}
func Lremovexattr(link string, attr string) (err error) {
return removexattr(link, attr, XATTR_NOFOLLOW)
}
func Fremovexattr(fd int, attr string) (err error) {
return fremovexattr(fd, attr, 0)
} | MIT License |
u-root/cpu | vendor/github.com/vishvananda/netlink/link_linux.go | LinkSetXdpFd | go | func LinkSetXdpFd(link Link, fd int) error {
return LinkSetXdpFdWithFlags(link, fd, 0)
} | LinkSetXdpFd adds a bpf function to the driver. The fd must be a bpf
program loaded with bpf(type=BPF_PROG_TYPE_XDP) | https://github.com/u-root/cpu/blob/0a371c3a086dec78994eb7bf1fb9885f15ead2ec/vendor/github.com/vishvananda/netlink/link_linux.go#L840-L842 | package netlink
import (
"bytes"
"encoding/binary"
"fmt"
"io/ioutil"
"net"
"os"
"strconv"
"strings"
"syscall"
"unsafe"
"github.com/vishvananda/netlink/nl"
"github.com/vishvananda/netns"
"golang.org/x/sys/unix"
)
const (
SizeofLinkStats32 = 0x5c
SizeofLinkStats64 = 0xb8
)
const (
TUNTAP_MODE_TUN TuntapMode = unix.IFF_TUN
TUNTAP_MODE_TAP TuntapMode = unix.IFF_TAP
TUNTAP_DEFAULTS TuntapFlag = unix.IFF_TUN_EXCL | unix.IFF_ONE_QUEUE
TUNTAP_VNET_HDR TuntapFlag = unix.IFF_VNET_HDR
TUNTAP_TUN_EXCL TuntapFlag = unix.IFF_TUN_EXCL
TUNTAP_NO_PI TuntapFlag = unix.IFF_NO_PI
TUNTAP_ONE_QUEUE TuntapFlag = unix.IFF_ONE_QUEUE
TUNTAP_MULTI_QUEUE TuntapFlag = unix.IFF_MULTI_QUEUE
TUNTAP_MULTI_QUEUE_DEFAULTS TuntapFlag = TUNTAP_MULTI_QUEUE | TUNTAP_NO_PI
)
const (
VF_LINK_STATE_AUTO uint32 = 0
VF_LINK_STATE_ENABLE uint32 = 1
VF_LINK_STATE_DISABLE uint32 = 2
)
var lookupByDump = false
var macvlanModes = [...]uint32{
0,
nl.MACVLAN_MODE_PRIVATE,
nl.MACVLAN_MODE_VEPA,
nl.MACVLAN_MODE_BRIDGE,
nl.MACVLAN_MODE_PASSTHRU,
nl.MACVLAN_MODE_SOURCE,
}
func ensureIndex(link *LinkAttrs) {
if link != nil && link.Index == 0 {
newlink, _ := LinkByName(link.Name)
if newlink != nil {
link.Index = newlink.Attrs().Index
}
}
}
func (h *Handle) ensureIndex(link *LinkAttrs) {
if link != nil && link.Index == 0 {
newlink, _ := h.LinkByName(link.Name)
if newlink != nil {
link.Index = newlink.Attrs().Index
}
}
}
func (h *Handle) LinkSetARPOff(link Link) error {
base := link.Attrs()
h.ensureIndex(base)
req := h.newNetlinkRequest(unix.RTM_SETLINK, unix.NLM_F_ACK)
msg := nl.NewIfInfomsg(unix.AF_UNSPEC)
msg.Change |= unix.IFF_NOARP
msg.Flags |= unix.IFF_NOARP
msg.Index = int32(base.Index)
req.AddData(msg)
_, err := req.Execute(unix.NETLINK_ROUTE, 0)
return err
}
func LinkSetARPOff(link Link) error {
return pkgHandle.LinkSetARPOff(link)
}
func (h *Handle) LinkSetARPOn(link Link) error {
base := link.Attrs()
h.ensureIndex(base)
req := h.newNetlinkRequest(unix.RTM_SETLINK, unix.NLM_F_ACK)
msg := nl.NewIfInfomsg(unix.AF_UNSPEC)
msg.Change |= unix.IFF_NOARP
msg.Flags &= ^uint32(unix.IFF_NOARP)
msg.Index = int32(base.Index)
req.AddData(msg)
_, err := req.Execute(unix.NETLINK_ROUTE, 0)
return err
}
func LinkSetARPOn(link Link) error {
return pkgHandle.LinkSetARPOn(link)
}
func (h *Handle) SetPromiscOn(link Link) error {
base := link.Attrs()
h.ensureIndex(base)
req := h.newNetlinkRequest(unix.RTM_SETLINK, unix.NLM_F_ACK)
msg := nl.NewIfInfomsg(unix.AF_UNSPEC)
msg.Change = unix.IFF_PROMISC
msg.Flags = unix.IFF_PROMISC
msg.Index = int32(base.Index)
req.AddData(msg)
_, err := req.Execute(unix.NETLINK_ROUTE, 0)
return err
}
func LinkSetAllmulticastOn(link Link) error {
return pkgHandle.LinkSetAllmulticastOn(link)
}
func (h *Handle) LinkSetAllmulticastOn(link Link) error {
base := link.Attrs()
h.ensureIndex(base)
req := h.newNetlinkRequest(unix.RTM_NEWLINK, unix.NLM_F_ACK)
msg := nl.NewIfInfomsg(unix.AF_UNSPEC)
msg.Change = unix.IFF_ALLMULTI
msg.Flags = unix.IFF_ALLMULTI
msg.Index = int32(base.Index)
req.AddData(msg)
_, err := req.Execute(unix.NETLINK_ROUTE, 0)
return err
}
func LinkSetAllmulticastOff(link Link) error {
return pkgHandle.LinkSetAllmulticastOff(link)
}
func (h *Handle) LinkSetAllmulticastOff(link Link) error {
base := link.Attrs()
h.ensureIndex(base)
req := h.newNetlinkRequest(unix.RTM_NEWLINK, unix.NLM_F_ACK)
msg := nl.NewIfInfomsg(unix.AF_UNSPEC)
msg.Change = unix.IFF_ALLMULTI
msg.Index = int32(base.Index)
req.AddData(msg)
_, err := req.Execute(unix.NETLINK_ROUTE, 0)
return err
}
func MacvlanMACAddrAdd(link Link, addr net.HardwareAddr) error {
return pkgHandle.MacvlanMACAddrAdd(link, addr)
}
func (h *Handle) MacvlanMACAddrAdd(link Link, addr net.HardwareAddr) error {
return h.macvlanMACAddrChange(link, []net.HardwareAddr{addr}, nl.MACVLAN_MACADDR_ADD)
}
func MacvlanMACAddrDel(link Link, addr net.HardwareAddr) error {
return pkgHandle.MacvlanMACAddrDel(link, addr)
}
func (h *Handle) MacvlanMACAddrDel(link Link, addr net.HardwareAddr) error {
return h.macvlanMACAddrChange(link, []net.HardwareAddr{addr}, nl.MACVLAN_MACADDR_DEL)
}
func MacvlanMACAddrFlush(link Link) error {
return pkgHandle.MacvlanMACAddrFlush(link)
}
func (h *Handle) MacvlanMACAddrFlush(link Link) error {
return h.macvlanMACAddrChange(link, nil, nl.MACVLAN_MACADDR_FLUSH)
}
func MacvlanMACAddrSet(link Link, addrs []net.HardwareAddr) error {
return pkgHandle.MacvlanMACAddrSet(link, addrs)
}
func (h *Handle) MacvlanMACAddrSet(link Link, addrs []net.HardwareAddr) error {
return h.macvlanMACAddrChange(link, addrs, nl.MACVLAN_MACADDR_SET)
}
func (h *Handle) macvlanMACAddrChange(link Link, addrs []net.HardwareAddr, mode uint32) error {
base := link.Attrs()
h.ensureIndex(base)
req := h.newNetlinkRequest(unix.RTM_NEWLINK, unix.NLM_F_ACK)
msg := nl.NewIfInfomsg(unix.AF_UNSPEC)
msg.Index = int32(base.Index)
req.AddData(msg)
linkInfo := nl.NewRtAttr(unix.IFLA_LINKINFO, nil)
linkInfo.AddRtAttr(nl.IFLA_INFO_KIND, nl.NonZeroTerminated(link.Type()))
inner := linkInfo.AddRtAttr(nl.IFLA_INFO_DATA, nil)
b := make([]byte, 4)
native.PutUint32(b, mode)
inner.AddRtAttr(nl.IFLA_MACVLAN_MACADDR_MODE, b)
switch mode {
case nl.MACVLAN_MACADDR_ADD, nl.MACVLAN_MACADDR_DEL:
if len(addrs) == 1 {
inner.AddRtAttr(nl.IFLA_MACVLAN_MACADDR, []byte(addrs[0]))
}
case nl.MACVLAN_MACADDR_SET:
mad := inner.AddRtAttr(nl.IFLA_MACVLAN_MACADDR_DATA, nil)
for _, addr := range addrs {
mad.AddRtAttr(nl.IFLA_MACVLAN_MACADDR, []byte(addr))
}
}
req.AddData(linkInfo)
_, err := req.Execute(unix.NETLINK_ROUTE, 0)
return err
}
func BridgeSetMcastSnoop(link Link, on bool) error {
return pkgHandle.BridgeSetMcastSnoop(link, on)
}
func (h *Handle) BridgeSetMcastSnoop(link Link, on bool) error {
bridge := link.(*Bridge)
bridge.MulticastSnooping = &on
return h.linkModify(bridge, unix.NLM_F_ACK)
}
func BridgeSetVlanFiltering(link Link, on bool) error {
return pkgHandle.BridgeSetVlanFiltering(link, on)
}
func (h *Handle) BridgeSetVlanFiltering(link Link, on bool) error {
bridge := link.(*Bridge)
bridge.VlanFiltering = &on
return h.linkModify(bridge, unix.NLM_F_ACK)
}
func SetPromiscOn(link Link) error {
return pkgHandle.SetPromiscOn(link)
}
func (h *Handle) SetPromiscOff(link Link) error {
base := link.Attrs()
h.ensureIndex(base)
req := h.newNetlinkRequest(unix.RTM_SETLINK, unix.NLM_F_ACK)
msg := nl.NewIfInfomsg(unix.AF_UNSPEC)
msg.Change = unix.IFF_PROMISC
msg.Index = int32(base.Index)
req.AddData(msg)
_, err := req.Execute(unix.NETLINK_ROUTE, 0)
return err
}
func SetPromiscOff(link Link) error {
return pkgHandle.SetPromiscOff(link)
}
func LinkSetUp(link Link) error {
return pkgHandle.LinkSetUp(link)
}
func (h *Handle) LinkSetUp(link Link) error {
base := link.Attrs()
h.ensureIndex(base)
req := h.newNetlinkRequest(unix.RTM_NEWLINK, unix.NLM_F_ACK)
msg := nl.NewIfInfomsg(unix.AF_UNSPEC)
msg.Change = unix.IFF_UP
msg.Flags = unix.IFF_UP
msg.Index = int32(base.Index)
req.AddData(msg)
_, err := req.Execute(unix.NETLINK_ROUTE, 0)
return err
}
func LinkSetDown(link Link) error {
return pkgHandle.LinkSetDown(link)
}
func (h *Handle) LinkSetDown(link Link) error {
base := link.Attrs()
h.ensureIndex(base)
req := h.newNetlinkRequest(unix.RTM_NEWLINK, unix.NLM_F_ACK)
msg := nl.NewIfInfomsg(unix.AF_UNSPEC)
msg.Change = unix.IFF_UP
msg.Index = int32(base.Index)
req.AddData(msg)
_, err := req.Execute(unix.NETLINK_ROUTE, 0)
return err
}
func LinkSetMTU(link Link, mtu int) error {
return pkgHandle.LinkSetMTU(link, mtu)
}
func (h *Handle) LinkSetMTU(link Link, mtu int) error {
base := link.Attrs()
h.ensureIndex(base)
req := h.newNetlinkRequest(unix.RTM_SETLINK, unix.NLM_F_ACK)
msg := nl.NewIfInfomsg(unix.AF_UNSPEC)
msg.Index = int32(base.Index)
req.AddData(msg)
b := make([]byte, 4)
native.PutUint32(b, uint32(mtu))
data := nl.NewRtAttr(unix.IFLA_MTU, b)
req.AddData(data)
_, err := req.Execute(unix.NETLINK_ROUTE, 0)
return err
}
func LinkSetName(link Link, name string) error {
return pkgHandle.LinkSetName(link, name)
}
func (h *Handle) LinkSetName(link Link, name string) error {
base := link.Attrs()
h.ensureIndex(base)
req := h.newNetlinkRequest(unix.RTM_SETLINK, unix.NLM_F_ACK)
msg := nl.NewIfInfomsg(unix.AF_UNSPEC)
msg.Index = int32(base.Index)
req.AddData(msg)
data := nl.NewRtAttr(unix.IFLA_IFNAME, []byte(name))
req.AddData(data)
_, err := req.Execute(unix.NETLINK_ROUTE, 0)
return err
}
func LinkSetAlias(link Link, name string) error {
return pkgHandle.LinkSetAlias(link, name)
}
func (h *Handle) LinkSetAlias(link Link, name string) error {
base := link.Attrs()
h.ensureIndex(base)
req := h.newNetlinkRequest(unix.RTM_SETLINK, unix.NLM_F_ACK)
msg := nl.NewIfInfomsg(unix.AF_UNSPEC)
msg.Index = int32(base.Index)
req.AddData(msg)
data := nl.NewRtAttr(unix.IFLA_IFALIAS, []byte(name))
req.AddData(data)
_, err := req.Execute(unix.NETLINK_ROUTE, 0)
return err
}
func LinkSetHardwareAddr(link Link, hwaddr net.HardwareAddr) error {
return pkgHandle.LinkSetHardwareAddr(link, hwaddr)
}
func (h *Handle) LinkSetHardwareAddr(link Link, hwaddr net.HardwareAddr) error {
base := link.Attrs()
h.ensureIndex(base)
req := h.newNetlinkRequest(unix.RTM_SETLINK, unix.NLM_F_ACK)
msg := nl.NewIfInfomsg(unix.AF_UNSPEC)
msg.Index = int32(base.Index)
req.AddData(msg)
data := nl.NewRtAttr(unix.IFLA_ADDRESS, []byte(hwaddr))
req.AddData(data)
_, err := req.Execute(unix.NETLINK_ROUTE, 0)
return err
}
func LinkSetVfHardwareAddr(link Link, vf int, hwaddr net.HardwareAddr) error {
return pkgHandle.LinkSetVfHardwareAddr(link, vf, hwaddr)
}
func (h *Handle) LinkSetVfHardwareAddr(link Link, vf int, hwaddr net.HardwareAddr) error {
base := link.Attrs()
h.ensureIndex(base)
req := h.newNetlinkRequest(unix.RTM_SETLINK, unix.NLM_F_ACK)
msg := nl.NewIfInfomsg(unix.AF_UNSPEC)
msg.Index = int32(base.Index)
req.AddData(msg)
data := nl.NewRtAttr(unix.IFLA_VFINFO_LIST, nil)
info := data.AddRtAttr(nl.IFLA_VF_INFO, nil)
vfmsg := nl.VfMac{
Vf: uint32(vf),
}
copy(vfmsg.Mac[:], []byte(hwaddr))
info.AddRtAttr(nl.IFLA_VF_MAC, vfmsg.Serialize())
req.AddData(data)
_, err := req.Execute(unix.NETLINK_ROUTE, 0)
return err
}
func LinkSetVfVlan(link Link, vf, vlan int) error {
return pkgHandle.LinkSetVfVlan(link, vf, vlan)
}
func (h *Handle) LinkSetVfVlan(link Link, vf, vlan int) error {
base := link.Attrs()
h.ensureIndex(base)
req := h.newNetlinkRequest(unix.RTM_SETLINK, unix.NLM_F_ACK)
msg := nl.NewIfInfomsg(unix.AF_UNSPEC)
msg.Index = int32(base.Index)
req.AddData(msg)
data := nl.NewRtAttr(unix.IFLA_VFINFO_LIST, nil)
info := data.AddRtAttr(nl.IFLA_VF_INFO, nil)
vfmsg := nl.VfVlan{
Vf: uint32(vf),
Vlan: uint32(vlan),
}
info.AddRtAttr(nl.IFLA_VF_VLAN, vfmsg.Serialize())
req.AddData(data)
_, err := req.Execute(unix.NETLINK_ROUTE, 0)
return err
}
func LinkSetVfVlanQos(link Link, vf, vlan, qos int) error {
return pkgHandle.LinkSetVfVlanQos(link, vf, vlan, qos)
}
func (h *Handle) LinkSetVfVlanQos(link Link, vf, vlan, qos int) error {
base := link.Attrs()
h.ensureIndex(base)
req := h.newNetlinkRequest(unix.RTM_SETLINK, unix.NLM_F_ACK)
msg := nl.NewIfInfomsg(unix.AF_UNSPEC)
msg.Index = int32(base.Index)
req.AddData(msg)
data := nl.NewRtAttr(unix.IFLA_VFINFO_LIST, nil)
info := nl.NewRtAttrChild(data, nl.IFLA_VF_INFO, nil)
vfmsg := nl.VfVlan{
Vf: uint32(vf),
Vlan: uint32(vlan),
Qos: uint32(qos),
}
nl.NewRtAttrChild(info, nl.IFLA_VF_VLAN, vfmsg.Serialize())
req.AddData(data)
_, err := req.Execute(unix.NETLINK_ROUTE, 0)
return err
}
func LinkSetVfTxRate(link Link, vf, rate int) error {
return pkgHandle.LinkSetVfTxRate(link, vf, rate)
}
func (h *Handle) LinkSetVfTxRate(link Link, vf, rate int) error {
base := link.Attrs()
h.ensureIndex(base)
req := h.newNetlinkRequest(unix.RTM_SETLINK, unix.NLM_F_ACK)
msg := nl.NewIfInfomsg(unix.AF_UNSPEC)
msg.Index = int32(base.Index)
req.AddData(msg)
data := nl.NewRtAttr(unix.IFLA_VFINFO_LIST, nil)
info := data.AddRtAttr(nl.IFLA_VF_INFO, nil)
vfmsg := nl.VfTxRate{
Vf: uint32(vf),
Rate: uint32(rate),
}
info.AddRtAttr(nl.IFLA_VF_TX_RATE, vfmsg.Serialize())
req.AddData(data)
_, err := req.Execute(unix.NETLINK_ROUTE, 0)
return err
}
func LinkSetVfRate(link Link, vf, minRate, maxRate int) error {
return pkgHandle.LinkSetVfRate(link, vf, minRate, maxRate)
}
func (h *Handle) LinkSetVfRate(link Link, vf, minRate, maxRate int) error {
base := link.Attrs()
h.ensureIndex(base)
req := h.newNetlinkRequest(unix.RTM_SETLINK, unix.NLM_F_ACK)
msg := nl.NewIfInfomsg(unix.AF_UNSPEC)
msg.Index = int32(base.Index)
req.AddData(msg)
data := nl.NewRtAttr(unix.IFLA_VFINFO_LIST, nil)
info := data.AddRtAttr(nl.IFLA_VF_INFO, nil)
vfmsg := nl.VfRate{
Vf: uint32(vf),
MinTxRate: uint32(minRate),
MaxTxRate: uint32(maxRate),
}
info.AddRtAttr(nl.IFLA_VF_RATE, vfmsg.Serialize())
req.AddData(data)
_, err := req.Execute(unix.NETLINK_ROUTE, 0)
return err
}
func LinkSetVfState(link Link, vf int, state uint32) error {
return pkgHandle.LinkSetVfState(link, vf, state)
}
func (h *Handle) LinkSetVfState(link Link, vf int, state uint32) error {
base := link.Attrs()
h.ensureIndex(base)
req := h.newNetlinkRequest(unix.RTM_SETLINK, unix.NLM_F_ACK)
msg := nl.NewIfInfomsg(unix.AF_UNSPEC)
msg.Index = int32(base.Index)
req.AddData(msg)
data := nl.NewRtAttr(unix.IFLA_VFINFO_LIST, nil)
info := data.AddRtAttr(nl.IFLA_VF_INFO, nil)
vfmsg := nl.VfLinkState{
Vf: uint32(vf),
LinkState: state,
}
info.AddRtAttr(nl.IFLA_VF_LINK_STATE, vfmsg.Serialize())
req.AddData(data)
_, err := req.Execute(unix.NETLINK_ROUTE, 0)
return err
}
func LinkSetVfSpoofchk(link Link, vf int, check bool) error {
return pkgHandle.LinkSetVfSpoofchk(link, vf, check)
}
func (h *Handle) LinkSetVfSpoofchk(link Link, vf int, check bool) error {
var setting uint32
base := link.Attrs()
h.ensureIndex(base)
req := h.newNetlinkRequest(unix.RTM_SETLINK, unix.NLM_F_ACK)
msg := nl.NewIfInfomsg(unix.AF_UNSPEC)
msg.Index = int32(base.Index)
req.AddData(msg)
data := nl.NewRtAttr(unix.IFLA_VFINFO_LIST, nil)
info := data.AddRtAttr(nl.IFLA_VF_INFO, nil)
if check {
setting = 1
}
vfmsg := nl.VfSpoofchk{
Vf: uint32(vf),
Setting: setting,
}
info.AddRtAttr(nl.IFLA_VF_SPOOFCHK, vfmsg.Serialize())
req.AddData(data)
_, err := req.Execute(unix.NETLINK_ROUTE, 0)
return err
}
func LinkSetVfTrust(link Link, vf int, state bool) error {
return pkgHandle.LinkSetVfTrust(link, vf, state)
}
func (h *Handle) LinkSetVfTrust(link Link, vf int, state bool) error {
var setting uint32
base := link.Attrs()
h.ensureIndex(base)
req := h.newNetlinkRequest(unix.RTM_SETLINK, unix.NLM_F_ACK)
msg := nl.NewIfInfomsg(unix.AF_UNSPEC)
msg.Index = int32(base.Index)
req.AddData(msg)
data := nl.NewRtAttr(unix.IFLA_VFINFO_LIST, nil)
info := data.AddRtAttr(nl.IFLA_VF_INFO, nil)
if state {
setting = 1
}
vfmsg := nl.VfTrust{
Vf: uint32(vf),
Setting: setting,
}
info.AddRtAttr(nl.IFLA_VF_TRUST, vfmsg.Serialize())
req.AddData(data)
_, err := req.Execute(unix.NETLINK_ROUTE, 0)
return err
}
func LinkSetVfNodeGUID(link Link, vf int, nodeguid net.HardwareAddr) error {
return pkgHandle.LinkSetVfGUID(link, vf, nodeguid, nl.IFLA_VF_IB_NODE_GUID)
}
func LinkSetVfPortGUID(link Link, vf int, portguid net.HardwareAddr) error {
return pkgHandle.LinkSetVfGUID(link, vf, portguid, nl.IFLA_VF_IB_PORT_GUID)
}
func (h *Handle) LinkSetVfGUID(link Link, vf int, vfGuid net.HardwareAddr, guidType int) error {
var err error
var guid uint64
buf := bytes.NewBuffer(vfGuid)
err = binary.Read(buf, binary.BigEndian, &guid)
if err != nil {
return err
}
base := link.Attrs()
h.ensureIndex(base)
req := h.newNetlinkRequest(unix.RTM_SETLINK, unix.NLM_F_ACK)
msg := nl.NewIfInfomsg(unix.AF_UNSPEC)
msg.Index = int32(base.Index)
req.AddData(msg)
data := nl.NewRtAttr(unix.IFLA_VFINFO_LIST, nil)
info := data.AddRtAttr(nl.IFLA_VF_INFO, nil)
vfmsg := nl.VfGUID{
Vf: uint32(vf),
GUID: guid,
}
info.AddRtAttr(guidType, vfmsg.Serialize())
req.AddData(data)
_, err = req.Execute(unix.NETLINK_ROUTE, 0)
return err
}
func LinkSetMaster(link Link, master Link) error {
return pkgHandle.LinkSetMaster(link, master)
}
func (h *Handle) LinkSetMaster(link Link, master Link) error {
index := 0
if master != nil {
masterBase := master.Attrs()
h.ensureIndex(masterBase)
index = masterBase.Index
}
if index <= 0 {
return fmt.Errorf("Device does not exist")
}
return h.LinkSetMasterByIndex(link, index)
}
func LinkSetNoMaster(link Link) error {
return pkgHandle.LinkSetNoMaster(link)
}
func (h *Handle) LinkSetNoMaster(link Link) error {
return h.LinkSetMasterByIndex(link, 0)
}
func LinkSetMasterByIndex(link Link, masterIndex int) error {
return pkgHandle.LinkSetMasterByIndex(link, masterIndex)
}
func (h *Handle) LinkSetMasterByIndex(link Link, masterIndex int) error {
base := link.Attrs()
h.ensureIndex(base)
req := h.newNetlinkRequest(unix.RTM_SETLINK, unix.NLM_F_ACK)
msg := nl.NewIfInfomsg(unix.AF_UNSPEC)
msg.Index = int32(base.Index)
req.AddData(msg)
b := make([]byte, 4)
native.PutUint32(b, uint32(masterIndex))
data := nl.NewRtAttr(unix.IFLA_MASTER, b)
req.AddData(data)
_, err := req.Execute(unix.NETLINK_ROUTE, 0)
return err
}
func LinkSetNsPid(link Link, nspid int) error {
return pkgHandle.LinkSetNsPid(link, nspid)
}
func (h *Handle) LinkSetNsPid(link Link, nspid int) error {
base := link.Attrs()
h.ensureIndex(base)
req := h.newNetlinkRequest(unix.RTM_SETLINK, unix.NLM_F_ACK)
msg := nl.NewIfInfomsg(unix.AF_UNSPEC)
msg.Index = int32(base.Index)
req.AddData(msg)
b := make([]byte, 4)
native.PutUint32(b, uint32(nspid))
data := nl.NewRtAttr(unix.IFLA_NET_NS_PID, b)
req.AddData(data)
_, err := req.Execute(unix.NETLINK_ROUTE, 0)
return err
}
func LinkSetNsFd(link Link, fd int) error {
return pkgHandle.LinkSetNsFd(link, fd)
}
func (h *Handle) LinkSetNsFd(link Link, fd int) error {
base := link.Attrs()
h.ensureIndex(base)
req := h.newNetlinkRequest(unix.RTM_SETLINK, unix.NLM_F_ACK)
msg := nl.NewIfInfomsg(unix.AF_UNSPEC)
msg.Index = int32(base.Index)
req.AddData(msg)
b := make([]byte, 4)
native.PutUint32(b, uint32(fd))
data := nl.NewRtAttr(unix.IFLA_NET_NS_FD, b)
req.AddData(data)
_, err := req.Execute(unix.NETLINK_ROUTE, 0)
return err
} | BSD 3-Clause New or Revised License |
go-xweb/xweb | action.go | IsWebsocket | go | func (c *Action) IsWebsocket() bool {
return c.Header("Upgrade") == "websocket"
} | IsSecure returns boolean of this request is in webSocket. | https://github.com/go-xweb/xweb/blob/92575454ff292294a51a4d535b2a87b5cbe47d71/action.go#L134-L136 | package xweb
import (
"bytes"
"compress/flate"
"compress/gzip"
"crypto/hmac"
"crypto/md5"
"crypto/sha1"
"encoding/base64"
"encoding/hex"
"encoding/json"
"encoding/xml"
"errors"
"fmt"
"html/template"
"io"
"io/ioutil"
"mime"
"mime/multipart"
"net/http"
"net/url"
"os"
"path"
"reflect"
"strconv"
"strings"
"time"
"github.com/go-xweb/httpsession"
"github.com/go-xweb/log"
"github.com/go-xweb/uuid"
)
type ActionOption struct {
AutoMapForm bool
CheckXsrf bool
}
type Action struct {
Request *http.Request
App *App
Option *ActionOption
http.ResponseWriter
C reflect.Value
session *httpsession.Session
T T
f T
RootTemplate *template.Template
RequestBody []byte
StatusCode int
}
type Mapper struct {
}
type T map[string]interface{}
func XsrfName() string {
return XSRF_TAG
}
func (c *Action) Protocol() string {
return c.Request.Proto
}
func (c *Action) Uri() string {
return c.Request.RequestURI
}
func (c *Action) Url() string {
return c.Request.URL.String()
}
func (c *Action) Site() string {
return c.Scheme() + "://" + c.Domain()
}
func (c *Action) Scheme() string {
if c.Request.URL.Scheme != "" {
return c.Request.URL.Scheme
} else if c.Request.TLS == nil {
return "http"
} else {
return "https"
}
}
func (c *Action) Domain() string {
return c.Host()
}
func (c *Action) Host() string {
if c.Request.Host != "" {
hostParts := strings.Split(c.Request.Host, ":")
if len(hostParts) > 0 {
return hostParts[0]
}
return c.Request.Host
}
return "localhost"
}
func (c *Action) Is(method string) bool {
return c.Method() == method
}
func (c *Action) IsAjax() bool {
return c.Header("X-Requested-With") == "XMLHttpRequest"
}
func (c *Action) IsSecure() bool {
return c.Scheme() == "https"
} | MIT License |
eleboucher/coalibot | vendor/github.com/slack-go/slack/admin.go | SetRestrictedContext | go | func (api *Client) SetRestrictedContext(ctx context.Context, teamName, uid string, channelIds ...string) error {
values := url.Values{
"user": {uid},
"token": {api.token},
"set_active": {"true"},
"_attempts": {"1"},
"channels": {strings.Join(channelIds, ",")},
}
err := api.adminRequest(ctx, "setRestricted", teamName, values)
if err != nil {
return fmt.Errorf("failed to restrict account: %s", err)
}
return nil
} | SetRestrictedContext converts a user into a restricted account with a custom context | https://github.com/eleboucher/coalibot/blob/9a7977782486fd32dc439b7675739389aa00332d/vendor/github.com/slack-go/slack/admin.go#L192-L207 | package slack
import (
"context"
"fmt"
"net/url"
"strings"
)
func (api *Client) adminRequest(ctx context.Context, method string, teamName string, values url.Values) error {
resp := &SlackResponse{}
err := parseAdminResponse(ctx, api.httpclient, method, teamName, values, resp, api)
if err != nil {
return err
}
return resp.Err()
}
func (api *Client) DisableUser(teamName string, uid string) error {
return api.DisableUserContext(context.Background(), teamName, uid)
}
func (api *Client) DisableUserContext(ctx context.Context, teamName string, uid string) error {
values := url.Values{
"user": {uid},
"token": {api.token},
"set_active": {"true"},
"_attempts": {"1"},
}
if err := api.adminRequest(ctx, "setInactive", teamName, values); err != nil {
return fmt.Errorf("failed to disable user with id '%s': %s", uid, err)
}
return nil
}
func (api *Client) InviteGuest(teamName, channel, firstName, lastName, emailAddress string) error {
return api.InviteGuestContext(context.Background(), teamName, channel, firstName, lastName, emailAddress)
}
func (api *Client) InviteGuestContext(ctx context.Context, teamName, channel, firstName, lastName, emailAddress string) error {
values := url.Values{
"email": {emailAddress},
"channels": {channel},
"first_name": {firstName},
"last_name": {lastName},
"ultra_restricted": {"1"},
"token": {api.token},
"resend": {"true"},
"set_active": {"true"},
"_attempts": {"1"},
}
err := api.adminRequest(ctx, "invite", teamName, values)
if err != nil {
return fmt.Errorf("Failed to invite single-channel guest: %s", err)
}
return nil
}
func (api *Client) InviteRestricted(teamName, channel, firstName, lastName, emailAddress string) error {
return api.InviteRestrictedContext(context.Background(), teamName, channel, firstName, lastName, emailAddress)
}
func (api *Client) InviteRestrictedContext(ctx context.Context, teamName, channel, firstName, lastName, emailAddress string) error {
values := url.Values{
"email": {emailAddress},
"channels": {channel},
"first_name": {firstName},
"last_name": {lastName},
"restricted": {"1"},
"token": {api.token},
"resend": {"true"},
"set_active": {"true"},
"_attempts": {"1"},
}
err := api.adminRequest(ctx, "invite", teamName, values)
if err != nil {
return fmt.Errorf("Failed to restricted account: %s", err)
}
return nil
}
func (api *Client) InviteToTeam(teamName, firstName, lastName, emailAddress string) error {
return api.InviteToTeamContext(context.Background(), teamName, firstName, lastName, emailAddress)
}
func (api *Client) InviteToTeamContext(ctx context.Context, teamName, firstName, lastName, emailAddress string) error {
values := url.Values{
"email": {emailAddress},
"first_name": {firstName},
"last_name": {lastName},
"token": {api.token},
"set_active": {"true"},
"_attempts": {"1"},
}
err := api.adminRequest(ctx, "invite", teamName, values)
if err != nil {
return fmt.Errorf("Failed to invite to team: %s", err)
}
return nil
}
func (api *Client) SetRegular(teamName, user string) error {
return api.SetRegularContext(context.Background(), teamName, user)
}
func (api *Client) SetRegularContext(ctx context.Context, teamName, user string) error {
values := url.Values{
"user": {user},
"token": {api.token},
"set_active": {"true"},
"_attempts": {"1"},
}
err := api.adminRequest(ctx, "setRegular", teamName, values)
if err != nil {
return fmt.Errorf("Failed to change the user (%s) to a regular user: %s", user, err)
}
return nil
}
func (api *Client) SendSSOBindingEmail(teamName, user string) error {
return api.SendSSOBindingEmailContext(context.Background(), teamName, user)
}
func (api *Client) SendSSOBindingEmailContext(ctx context.Context, teamName, user string) error {
values := url.Values{
"user": {user},
"token": {api.token},
"set_active": {"true"},
"_attempts": {"1"},
}
err := api.adminRequest(ctx, "sendSSOBind", teamName, values)
if err != nil {
return fmt.Errorf("Failed to send SSO binding email for user (%s): %s", user, err)
}
return nil
}
func (api *Client) SetUltraRestricted(teamName, uid, channel string) error {
return api.SetUltraRestrictedContext(context.Background(), teamName, uid, channel)
}
func (api *Client) SetUltraRestrictedContext(ctx context.Context, teamName, uid, channel string) error {
values := url.Values{
"user": {uid},
"channel": {channel},
"token": {api.token},
"set_active": {"true"},
"_attempts": {"1"},
}
err := api.adminRequest(ctx, "setUltraRestricted", teamName, values)
if err != nil {
return fmt.Errorf("Failed to ultra-restrict account: %s", err)
}
return nil
}
func (api *Client) SetRestricted(teamName, uid string, channelIds ...string) error {
return api.SetRestrictedContext(context.Background(), teamName, uid, channelIds...)
} | MIT License |
cloudflare/unsee | internal/mapper/v04/silences.go | QueryArgs | go | func (m SilenceMapper) QueryArgs() string {
return fmt.Sprintf("limit=%d", math.MaxInt32)
} | QueryArgs for HTTP requests send to the Alertmanager API endpoint | https://github.com/cloudflare/unsee/blob/4c306c05f4d63d390ac946f71a000454c0f7742b/internal/mapper/v04/silences.go#L58-L62 | package v04
import (
"encoding/json"
"errors"
"fmt"
"io"
"math"
"strconv"
"time"
"github.com/blang/semver"
"github.com/cloudflare/unsee/internal/mapper"
"github.com/cloudflare/unsee/internal/models"
"github.com/cloudflare/unsee/internal/uri"
)
type silence struct {
ID int `json:"id"`
Matchers []struct {
Name string `json:"name"`
Value string `json:"value"`
IsRegex bool `json:"isRegex"`
} `json:"matchers"`
StartsAt time.Time `json:"startsAt"`
EndsAt time.Time `json:"endsAt"`
CreatedAt time.Time `json:"createdAt"`
CreatedBy string `json:"createdBy"`
Comment string `json:"comment"`
}
type silenceAPISchema struct {
Status string `json:"status"`
Data struct {
Silences []silence `json:"silences"`
TotalSilences int `json:"totalSilences"`
} `json:"data"`
Error string `json:"error"`
}
type SilenceMapper struct {
mapper.SilenceMapper
}
func (m SilenceMapper) AbsoluteURL(baseURI string) (string, error) {
return uri.JoinURL(baseURI, "api/v1/silences")
} | Apache License 2.0 |
open-telemetry/opentelemetry-go-contrib | instrumentation/github.com/Shopify/sarama/otelsarama/example/consumer/consumer.go | ConsumeClaim | go | func (consumer *Consumer) ConsumeClaim(session sarama.ConsumerGroupSession, claim sarama.ConsumerGroupClaim) error {
for message := range claim.Messages() {
printMessage(message)
session.MarkMessage(message, "")
}
return nil
} | ConsumeClaim must start a consumer loop of ConsumerGroupClaim's Messages(). | https://github.com/open-telemetry/opentelemetry-go-contrib/blob/aed1d9d92cc38f74f5a523a9d3b632855f991f4f/instrumentation/github.com/Shopify/sarama/otelsarama/example/consumer/consumer.go#L113-L124 | package main
import (
"context"
"flag"
"log"
"os"
"strings"
"time"
"github.com/Shopify/sarama"
"go.opentelemetry.io/otel"
semconv "go.opentelemetry.io/otel/semconv/v1.4.0"
"go.opentelemetry.io/otel/trace"
"go.opentelemetry.io/contrib/instrumentation/github.com/Shopify/sarama/otelsarama"
"go.opentelemetry.io/contrib/instrumentation/github.com/Shopify/sarama/otelsarama/example"
)
var (
brokers = flag.String("brokers", os.Getenv("KAFKA_PEERS"), "The Kafka brokers to connect to, as a comma separated list")
)
func main() {
tp := example.InitTracer()
defer func() {
if err := tp.Shutdown(context.Background()); err != nil {
log.Printf("Error shutting down tracer provider: %v", err)
}
}()
flag.Parse()
if *brokers == "" {
flag.PrintDefaults()
os.Exit(1)
}
brokerList := strings.Split(*brokers, ",")
log.Printf("Kafka brokers: %s", strings.Join(brokerList, ", "))
startConsumerGroup(brokerList)
select {}
}
func startConsumerGroup(brokerList []string) {
consumerGroupHandler := Consumer{}
handler := otelsarama.WrapConsumerGroupHandler(&consumerGroupHandler)
config := sarama.NewConfig()
config.Version = sarama.V2_5_0_0
config.Consumer.Offsets.Initial = sarama.OffsetOldest
consumerGroup, err := sarama.NewConsumerGroup(brokerList, "example", config)
if err != nil {
log.Fatalln("Failed to start sarama consumer group:", err)
}
err = consumerGroup.Consume(context.Background(), []string{example.KafkaTopic}, handler)
if err != nil {
log.Fatalln("Failed to consume via handler:", err)
}
}
func printMessage(msg *sarama.ConsumerMessage) {
ctx := otel.GetTextMapPropagator().Extract(context.Background(), otelsarama.NewConsumerMessageCarrier(msg))
tr := otel.Tracer("consumer")
_, span := tr.Start(ctx, "consume message", trace.WithAttributes(
semconv.MessagingOperationProcess,
))
defer span.End()
time.Sleep(1 * time.Second)
log.Println("Successful to read message: ", string(msg.Value))
}
type Consumer struct {
}
func (consumer *Consumer) Setup(sarama.ConsumerGroupSession) error {
return nil
}
func (consumer *Consumer) Cleanup(sarama.ConsumerGroupSession) error {
return nil
} | Apache License 2.0 |
mcuadros/go-candyjs | examples/demo/main.go | main | go | func main() {
script := os.Args[1]
ctx := candyjs.NewContext()
ctx.PevalFile(script)
} | go:generate candyjs import net
go:generate candyjs import net/http
go:generate candyjs import io/ioutil | https://github.com/mcuadros/go-candyjs/blob/d703dfa5153a4276b8a4783d985793595228073d/examples/demo/main.go#L12-L16 | package main
import (
"os"
"github.com/mcuadros/go-candyjs"
) | MIT License |
kubearmor/kubearmor | pkg/KubeArmorPolicy/api/security.kubearmor.com/v1/zz_generated.deepcopy.go | DeepCopyInto | go | func (in *SelectorType) DeepCopyInto(out *SelectorType) {
*out = *in
if in.MatchLabels != nil {
in, out := &in.MatchLabels, &out.MatchLabels
*out = make(map[string]string, len(*in))
for key, val := range *in {
(*out)[key] = val
}
}
} | DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. | https://github.com/kubearmor/kubearmor/blob/d1a983c5f8e3c57bb7a2ecd4b23ccb8357bdabc6/pkg/KubeArmorPolicy/api/security.kubearmor.com/v1/zz_generated.deepcopy.go#L504-L513 | package v1
import (
"k8s.io/apimachinery/pkg/runtime"
)
func (in *CapabilitiesType) DeepCopyInto(out *CapabilitiesType) {
*out = *in
if in.MatchCapabilities != nil {
in, out := &in.MatchCapabilities, &out.MatchCapabilities
*out = make([]MatchCapabilitiesType, len(*in))
for i := range *in {
(*in)[i].DeepCopyInto(&(*out)[i])
}
}
if in.Tags != nil {
in, out := &in.Tags, &out.Tags
*out = make([]string, len(*in))
copy(*out, *in)
}
}
func (in *CapabilitiesType) DeepCopy() *CapabilitiesType {
if in == nil {
return nil
}
out := new(CapabilitiesType)
in.DeepCopyInto(out)
return out
}
func (in *FileDirectoryType) DeepCopyInto(out *FileDirectoryType) {
*out = *in
if in.FromSource != nil {
in, out := &in.FromSource, &out.FromSource
*out = make([]MatchSourceType, len(*in))
copy(*out, *in)
}
if in.Tags != nil {
in, out := &in.Tags, &out.Tags
*out = make([]string, len(*in))
copy(*out, *in)
}
}
func (in *FileDirectoryType) DeepCopy() *FileDirectoryType {
if in == nil {
return nil
}
out := new(FileDirectoryType)
in.DeepCopyInto(out)
return out
}
func (in *FilePathType) DeepCopyInto(out *FilePathType) {
*out = *in
if in.FromSource != nil {
in, out := &in.FromSource, &out.FromSource
*out = make([]MatchSourceType, len(*in))
copy(*out, *in)
}
if in.Tags != nil {
in, out := &in.Tags, &out.Tags
*out = make([]string, len(*in))
copy(*out, *in)
}
}
func (in *FilePathType) DeepCopy() *FilePathType {
if in == nil {
return nil
}
out := new(FilePathType)
in.DeepCopyInto(out)
return out
}
func (in *FilePatternType) DeepCopyInto(out *FilePatternType) {
*out = *in
if in.Tags != nil {
in, out := &in.Tags, &out.Tags
*out = make([]string, len(*in))
copy(*out, *in)
}
}
func (in *FilePatternType) DeepCopy() *FilePatternType {
if in == nil {
return nil
}
out := new(FilePatternType)
in.DeepCopyInto(out)
return out
}
func (in *FileType) DeepCopyInto(out *FileType) {
*out = *in
if in.MatchPaths != nil {
in, out := &in.MatchPaths, &out.MatchPaths
*out = make([]FilePathType, len(*in))
for i := range *in {
(*in)[i].DeepCopyInto(&(*out)[i])
}
}
if in.MatchDirectories != nil {
in, out := &in.MatchDirectories, &out.MatchDirectories
*out = make([]FileDirectoryType, len(*in))
for i := range *in {
(*in)[i].DeepCopyInto(&(*out)[i])
}
}
if in.MatchPatterns != nil {
in, out := &in.MatchPatterns, &out.MatchPatterns
*out = make([]FilePatternType, len(*in))
for i := range *in {
(*in)[i].DeepCopyInto(&(*out)[i])
}
}
if in.Tags != nil {
in, out := &in.Tags, &out.Tags
*out = make([]string, len(*in))
copy(*out, *in)
}
}
func (in *FileType) DeepCopy() *FileType {
if in == nil {
return nil
}
out := new(FileType)
in.DeepCopyInto(out)
return out
}
func (in *KubeArmorPolicy) DeepCopyInto(out *KubeArmorPolicy) {
*out = *in
out.TypeMeta = in.TypeMeta
in.ObjectMeta.DeepCopyInto(&out.ObjectMeta)
in.Spec.DeepCopyInto(&out.Spec)
out.Status = in.Status
}
func (in *KubeArmorPolicy) DeepCopy() *KubeArmorPolicy {
if in == nil {
return nil
}
out := new(KubeArmorPolicy)
in.DeepCopyInto(out)
return out
}
func (in *KubeArmorPolicy) DeepCopyObject() runtime.Object {
if c := in.DeepCopy(); c != nil {
return c
}
return nil
}
func (in *KubeArmorPolicyList) DeepCopyInto(out *KubeArmorPolicyList) {
*out = *in
out.TypeMeta = in.TypeMeta
in.ListMeta.DeepCopyInto(&out.ListMeta)
if in.Items != nil {
in, out := &in.Items, &out.Items
*out = make([]KubeArmorPolicy, len(*in))
for i := range *in {
(*in)[i].DeepCopyInto(&(*out)[i])
}
}
}
func (in *KubeArmorPolicyList) DeepCopy() *KubeArmorPolicyList {
if in == nil {
return nil
}
out := new(KubeArmorPolicyList)
in.DeepCopyInto(out)
return out
}
func (in *KubeArmorPolicyList) DeepCopyObject() runtime.Object {
if c := in.DeepCopy(); c != nil {
return c
}
return nil
}
func (in *KubeArmorPolicySpec) DeepCopyInto(out *KubeArmorPolicySpec) {
*out = *in
in.Selector.DeepCopyInto(&out.Selector)
in.Process.DeepCopyInto(&out.Process)
in.File.DeepCopyInto(&out.File)
in.Network.DeepCopyInto(&out.Network)
in.Capabilities.DeepCopyInto(&out.Capabilities)
in.SELinux.DeepCopyInto(&out.SELinux)
if in.Tags != nil {
in, out := &in.Tags, &out.Tags
*out = make([]string, len(*in))
copy(*out, *in)
}
}
func (in *KubeArmorPolicySpec) DeepCopy() *KubeArmorPolicySpec {
if in == nil {
return nil
}
out := new(KubeArmorPolicySpec)
in.DeepCopyInto(out)
return out
}
func (in *KubeArmorPolicyStatus) DeepCopyInto(out *KubeArmorPolicyStatus) {
*out = *in
}
func (in *KubeArmorPolicyStatus) DeepCopy() *KubeArmorPolicyStatus {
if in == nil {
return nil
}
out := new(KubeArmorPolicyStatus)
in.DeepCopyInto(out)
return out
}
func (in *MatchCapabilitiesType) DeepCopyInto(out *MatchCapabilitiesType) {
*out = *in
if in.FromSource != nil {
in, out := &in.FromSource, &out.FromSource
*out = make([]MatchSourceType, len(*in))
copy(*out, *in)
}
if in.Tags != nil {
in, out := &in.Tags, &out.Tags
*out = make([]string, len(*in))
copy(*out, *in)
}
}
func (in *MatchCapabilitiesType) DeepCopy() *MatchCapabilitiesType {
if in == nil {
return nil
}
out := new(MatchCapabilitiesType)
in.DeepCopyInto(out)
return out
}
func (in *MatchNetworkProtocolType) DeepCopyInto(out *MatchNetworkProtocolType) {
*out = *in
if in.FromSource != nil {
in, out := &in.FromSource, &out.FromSource
*out = make([]MatchSourceType, len(*in))
copy(*out, *in)
}
if in.Tags != nil {
in, out := &in.Tags, &out.Tags
*out = make([]string, len(*in))
copy(*out, *in)
}
}
func (in *MatchNetworkProtocolType) DeepCopy() *MatchNetworkProtocolType {
if in == nil {
return nil
}
out := new(MatchNetworkProtocolType)
in.DeepCopyInto(out)
return out
}
func (in *MatchSourceType) DeepCopyInto(out *MatchSourceType) {
*out = *in
}
func (in *MatchSourceType) DeepCopy() *MatchSourceType {
if in == nil {
return nil
}
out := new(MatchSourceType)
in.DeepCopyInto(out)
return out
}
func (in *MatchVolumeMountType) DeepCopyInto(out *MatchVolumeMountType) {
*out = *in
if in.Tags != nil {
in, out := &in.Tags, &out.Tags
*out = make([]string, len(*in))
copy(*out, *in)
}
}
func (in *MatchVolumeMountType) DeepCopy() *MatchVolumeMountType {
if in == nil {
return nil
}
out := new(MatchVolumeMountType)
in.DeepCopyInto(out)
return out
}
func (in *NetworkType) DeepCopyInto(out *NetworkType) {
*out = *in
if in.MatchProtocols != nil {
in, out := &in.MatchProtocols, &out.MatchProtocols
*out = make([]MatchNetworkProtocolType, len(*in))
for i := range *in {
(*in)[i].DeepCopyInto(&(*out)[i])
}
}
if in.Tags != nil {
in, out := &in.Tags, &out.Tags
*out = make([]string, len(*in))
copy(*out, *in)
}
}
func (in *NetworkType) DeepCopy() *NetworkType {
if in == nil {
return nil
}
out := new(NetworkType)
in.DeepCopyInto(out)
return out
}
func (in *ProcessDirectoryType) DeepCopyInto(out *ProcessDirectoryType) {
*out = *in
if in.FromSource != nil {
in, out := &in.FromSource, &out.FromSource
*out = make([]MatchSourceType, len(*in))
copy(*out, *in)
}
if in.Tags != nil {
in, out := &in.Tags, &out.Tags
*out = make([]string, len(*in))
copy(*out, *in)
}
}
func (in *ProcessDirectoryType) DeepCopy() *ProcessDirectoryType {
if in == nil {
return nil
}
out := new(ProcessDirectoryType)
in.DeepCopyInto(out)
return out
}
func (in *ProcessPathType) DeepCopyInto(out *ProcessPathType) {
*out = *in
if in.FromSource != nil {
in, out := &in.FromSource, &out.FromSource
*out = make([]MatchSourceType, len(*in))
copy(*out, *in)
}
if in.Tags != nil {
in, out := &in.Tags, &out.Tags
*out = make([]string, len(*in))
copy(*out, *in)
}
}
func (in *ProcessPathType) DeepCopy() *ProcessPathType {
if in == nil {
return nil
}
out := new(ProcessPathType)
in.DeepCopyInto(out)
return out
}
func (in *ProcessPatternType) DeepCopyInto(out *ProcessPatternType) {
*out = *in
if in.Tags != nil {
in, out := &in.Tags, &out.Tags
*out = make([]string, len(*in))
copy(*out, *in)
}
}
func (in *ProcessPatternType) DeepCopy() *ProcessPatternType {
if in == nil {
return nil
}
out := new(ProcessPatternType)
in.DeepCopyInto(out)
return out
}
func (in *ProcessType) DeepCopyInto(out *ProcessType) {
*out = *in
if in.MatchPaths != nil {
in, out := &in.MatchPaths, &out.MatchPaths
*out = make([]ProcessPathType, len(*in))
for i := range *in {
(*in)[i].DeepCopyInto(&(*out)[i])
}
}
if in.MatchDirectories != nil {
in, out := &in.MatchDirectories, &out.MatchDirectories
*out = make([]ProcessDirectoryType, len(*in))
for i := range *in {
(*in)[i].DeepCopyInto(&(*out)[i])
}
}
if in.MatchPatterns != nil {
in, out := &in.MatchPatterns, &out.MatchPatterns
*out = make([]ProcessPatternType, len(*in))
for i := range *in {
(*in)[i].DeepCopyInto(&(*out)[i])
}
}
if in.Tags != nil {
in, out := &in.Tags, &out.Tags
*out = make([]string, len(*in))
copy(*out, *in)
}
}
func (in *ProcessType) DeepCopy() *ProcessType {
if in == nil {
return nil
}
out := new(ProcessType)
in.DeepCopyInto(out)
return out
}
func (in *SELinuxType) DeepCopyInto(out *SELinuxType) {
*out = *in
if in.MatchVolumeMounts != nil {
in, out := &in.MatchVolumeMounts, &out.MatchVolumeMounts
*out = make([]MatchVolumeMountType, len(*in))
for i := range *in {
(*in)[i].DeepCopyInto(&(*out)[i])
}
}
if in.Tags != nil {
in, out := &in.Tags, &out.Tags
*out = make([]string, len(*in))
copy(*out, *in)
}
}
func (in *SELinuxType) DeepCopy() *SELinuxType {
if in == nil {
return nil
}
out := new(SELinuxType)
in.DeepCopyInto(out)
return out
} | Apache License 2.0 |
ent/contrib | entproto/internal/entprototest/ent/client.go | CreateBulk | go | func (c *DuplicateNumberMessageClient) CreateBulk(builders ...*DuplicateNumberMessageCreate) *DuplicateNumberMessageCreateBulk {
return &DuplicateNumberMessageCreateBulk{config: c.config, builders: builders}
} | CreateBulk returns a builder for creating a bulk of DuplicateNumberMessage entities. | https://github.com/ent/contrib/blob/2f98d3a15e7dfcc96aa696a5aceb0c8b1249f9e4/entproto/internal/entprototest/ent/client.go#L588-L590 | package ent
import (
"context"
"fmt"
"log"
"entgo.io/contrib/entproto/internal/entprototest/ent/migrate"
"github.com/google/uuid"
"entgo.io/contrib/entproto/internal/entprototest/ent/blogpost"
"entgo.io/contrib/entproto/internal/entprototest/ent/category"
"entgo.io/contrib/entproto/internal/entprototest/ent/dependsonskipped"
"entgo.io/contrib/entproto/internal/entprototest/ent/duplicatenumbermessage"
"entgo.io/contrib/entproto/internal/entprototest/ent/explicitskippedmessage"
"entgo.io/contrib/entproto/internal/entprototest/ent/image"
"entgo.io/contrib/entproto/internal/entprototest/ent/implicitskippedmessage"
"entgo.io/contrib/entproto/internal/entprototest/ent/invalidfieldmessage"
"entgo.io/contrib/entproto/internal/entprototest/ent/messagewithenum"
"entgo.io/contrib/entproto/internal/entprototest/ent/messagewithfieldone"
"entgo.io/contrib/entproto/internal/entprototest/ent/messagewithid"
"entgo.io/contrib/entproto/internal/entprototest/ent/messagewithoptionals"
"entgo.io/contrib/entproto/internal/entprototest/ent/messagewithpackagename"
"entgo.io/contrib/entproto/internal/entprototest/ent/portal"
"entgo.io/contrib/entproto/internal/entprototest/ent/user"
"entgo.io/contrib/entproto/internal/entprototest/ent/validmessage"
"entgo.io/ent/dialect"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
)
type Client struct {
config
Schema *migrate.Schema
BlogPost *BlogPostClient
Category *CategoryClient
DependsOnSkipped *DependsOnSkippedClient
DuplicateNumberMessage *DuplicateNumberMessageClient
ExplicitSkippedMessage *ExplicitSkippedMessageClient
Image *ImageClient
ImplicitSkippedMessage *ImplicitSkippedMessageClient
InvalidFieldMessage *InvalidFieldMessageClient
MessageWithEnum *MessageWithEnumClient
MessageWithFieldOne *MessageWithFieldOneClient
MessageWithID *MessageWithIDClient
MessageWithOptionals *MessageWithOptionalsClient
MessageWithPackageName *MessageWithPackageNameClient
Portal *PortalClient
User *UserClient
ValidMessage *ValidMessageClient
}
func NewClient(opts ...Option) *Client {
cfg := config{log: log.Println, hooks: &hooks{}}
cfg.options(opts...)
client := &Client{config: cfg}
client.init()
return client
}
func (c *Client) init() {
c.Schema = migrate.NewSchema(c.driver)
c.BlogPost = NewBlogPostClient(c.config)
c.Category = NewCategoryClient(c.config)
c.DependsOnSkipped = NewDependsOnSkippedClient(c.config)
c.DuplicateNumberMessage = NewDuplicateNumberMessageClient(c.config)
c.ExplicitSkippedMessage = NewExplicitSkippedMessageClient(c.config)
c.Image = NewImageClient(c.config)
c.ImplicitSkippedMessage = NewImplicitSkippedMessageClient(c.config)
c.InvalidFieldMessage = NewInvalidFieldMessageClient(c.config)
c.MessageWithEnum = NewMessageWithEnumClient(c.config)
c.MessageWithFieldOne = NewMessageWithFieldOneClient(c.config)
c.MessageWithID = NewMessageWithIDClient(c.config)
c.MessageWithOptionals = NewMessageWithOptionalsClient(c.config)
c.MessageWithPackageName = NewMessageWithPackageNameClient(c.config)
c.Portal = NewPortalClient(c.config)
c.User = NewUserClient(c.config)
c.ValidMessage = NewValidMessageClient(c.config)
}
func Open(driverName, dataSourceName string, options ...Option) (*Client, error) {
switch driverName {
case dialect.MySQL, dialect.Postgres, dialect.SQLite:
drv, err := sql.Open(driverName, dataSourceName)
if err != nil {
return nil, err
}
return NewClient(append(options, Driver(drv))...), nil
default:
return nil, fmt.Errorf("unsupported driver: %q", driverName)
}
}
func (c *Client) Tx(ctx context.Context) (*Tx, error) {
if _, ok := c.driver.(*txDriver); ok {
return nil, fmt.Errorf("ent: cannot start a transaction within a transaction")
}
tx, err := newTx(ctx, c.driver)
if err != nil {
return nil, fmt.Errorf("ent: starting a transaction: %w", err)
}
cfg := c.config
cfg.driver = tx
return &Tx{
ctx: ctx,
config: cfg,
BlogPost: NewBlogPostClient(cfg),
Category: NewCategoryClient(cfg),
DependsOnSkipped: NewDependsOnSkippedClient(cfg),
DuplicateNumberMessage: NewDuplicateNumberMessageClient(cfg),
ExplicitSkippedMessage: NewExplicitSkippedMessageClient(cfg),
Image: NewImageClient(cfg),
ImplicitSkippedMessage: NewImplicitSkippedMessageClient(cfg),
InvalidFieldMessage: NewInvalidFieldMessageClient(cfg),
MessageWithEnum: NewMessageWithEnumClient(cfg),
MessageWithFieldOne: NewMessageWithFieldOneClient(cfg),
MessageWithID: NewMessageWithIDClient(cfg),
MessageWithOptionals: NewMessageWithOptionalsClient(cfg),
MessageWithPackageName: NewMessageWithPackageNameClient(cfg),
Portal: NewPortalClient(cfg),
User: NewUserClient(cfg),
ValidMessage: NewValidMessageClient(cfg),
}, nil
}
func (c *Client) BeginTx(ctx context.Context, opts *sql.TxOptions) (*Tx, error) {
if _, ok := c.driver.(*txDriver); ok {
return nil, fmt.Errorf("ent: cannot start a transaction within a transaction")
}
tx, err := c.driver.(interface {
BeginTx(context.Context, *sql.TxOptions) (dialect.Tx, error)
}).BeginTx(ctx, opts)
if err != nil {
return nil, fmt.Errorf("ent: starting a transaction: %w", err)
}
cfg := c.config
cfg.driver = &txDriver{tx: tx, drv: c.driver}
return &Tx{
config: cfg,
BlogPost: NewBlogPostClient(cfg),
Category: NewCategoryClient(cfg),
DependsOnSkipped: NewDependsOnSkippedClient(cfg),
DuplicateNumberMessage: NewDuplicateNumberMessageClient(cfg),
ExplicitSkippedMessage: NewExplicitSkippedMessageClient(cfg),
Image: NewImageClient(cfg),
ImplicitSkippedMessage: NewImplicitSkippedMessageClient(cfg),
InvalidFieldMessage: NewInvalidFieldMessageClient(cfg),
MessageWithEnum: NewMessageWithEnumClient(cfg),
MessageWithFieldOne: NewMessageWithFieldOneClient(cfg),
MessageWithID: NewMessageWithIDClient(cfg),
MessageWithOptionals: NewMessageWithOptionalsClient(cfg),
MessageWithPackageName: NewMessageWithPackageNameClient(cfg),
Portal: NewPortalClient(cfg),
User: NewUserClient(cfg),
ValidMessage: NewValidMessageClient(cfg),
}, nil
}
func (c *Client) Debug() *Client {
if c.debug {
return c
}
cfg := c.config
cfg.driver = dialect.Debug(c.driver, c.log)
client := &Client{config: cfg}
client.init()
return client
}
func (c *Client) Close() error {
return c.driver.Close()
}
func (c *Client) Use(hooks ...Hook) {
c.BlogPost.Use(hooks...)
c.Category.Use(hooks...)
c.DependsOnSkipped.Use(hooks...)
c.DuplicateNumberMessage.Use(hooks...)
c.ExplicitSkippedMessage.Use(hooks...)
c.Image.Use(hooks...)
c.ImplicitSkippedMessage.Use(hooks...)
c.InvalidFieldMessage.Use(hooks...)
c.MessageWithEnum.Use(hooks...)
c.MessageWithFieldOne.Use(hooks...)
c.MessageWithID.Use(hooks...)
c.MessageWithOptionals.Use(hooks...)
c.MessageWithPackageName.Use(hooks...)
c.Portal.Use(hooks...)
c.User.Use(hooks...)
c.ValidMessage.Use(hooks...)
}
type BlogPostClient struct {
config
}
func NewBlogPostClient(c config) *BlogPostClient {
return &BlogPostClient{config: c}
}
func (c *BlogPostClient) Use(hooks ...Hook) {
c.hooks.BlogPost = append(c.hooks.BlogPost, hooks...)
}
func (c *BlogPostClient) Create() *BlogPostCreate {
mutation := newBlogPostMutation(c.config, OpCreate)
return &BlogPostCreate{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
func (c *BlogPostClient) CreateBulk(builders ...*BlogPostCreate) *BlogPostCreateBulk {
return &BlogPostCreateBulk{config: c.config, builders: builders}
}
func (c *BlogPostClient) Update() *BlogPostUpdate {
mutation := newBlogPostMutation(c.config, OpUpdate)
return &BlogPostUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
func (c *BlogPostClient) UpdateOne(bp *BlogPost) *BlogPostUpdateOne {
mutation := newBlogPostMutation(c.config, OpUpdateOne, withBlogPost(bp))
return &BlogPostUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
func (c *BlogPostClient) UpdateOneID(id int) *BlogPostUpdateOne {
mutation := newBlogPostMutation(c.config, OpUpdateOne, withBlogPostID(id))
return &BlogPostUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
func (c *BlogPostClient) Delete() *BlogPostDelete {
mutation := newBlogPostMutation(c.config, OpDelete)
return &BlogPostDelete{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
func (c *BlogPostClient) DeleteOne(bp *BlogPost) *BlogPostDeleteOne {
return c.DeleteOneID(bp.ID)
}
func (c *BlogPostClient) DeleteOneID(id int) *BlogPostDeleteOne {
builder := c.Delete().Where(blogpost.ID(id))
builder.mutation.id = &id
builder.mutation.op = OpDeleteOne
return &BlogPostDeleteOne{builder}
}
func (c *BlogPostClient) Query() *BlogPostQuery {
return &BlogPostQuery{
config: c.config,
}
}
func (c *BlogPostClient) Get(ctx context.Context, id int) (*BlogPost, error) {
return c.Query().Where(blogpost.ID(id)).Only(ctx)
}
func (c *BlogPostClient) GetX(ctx context.Context, id int) *BlogPost {
obj, err := c.Get(ctx, id)
if err != nil {
panic(err)
}
return obj
}
func (c *BlogPostClient) QueryAuthor(bp *BlogPost) *UserQuery {
query := &UserQuery{config: c.config}
query.path = func(ctx context.Context) (fromV *sql.Selector, _ error) {
id := bp.ID
step := sqlgraph.NewStep(
sqlgraph.From(blogpost.Table, blogpost.FieldID, id),
sqlgraph.To(user.Table, user.FieldID),
sqlgraph.Edge(sqlgraph.M2O, false, blogpost.AuthorTable, blogpost.AuthorColumn),
)
fromV = sqlgraph.Neighbors(bp.driver.Dialect(), step)
return fromV, nil
}
return query
}
func (c *BlogPostClient) QueryCategories(bp *BlogPost) *CategoryQuery {
query := &CategoryQuery{config: c.config}
query.path = func(ctx context.Context) (fromV *sql.Selector, _ error) {
id := bp.ID
step := sqlgraph.NewStep(
sqlgraph.From(blogpost.Table, blogpost.FieldID, id),
sqlgraph.To(category.Table, category.FieldID),
sqlgraph.Edge(sqlgraph.M2M, true, blogpost.CategoriesTable, blogpost.CategoriesPrimaryKey...),
)
fromV = sqlgraph.Neighbors(bp.driver.Dialect(), step)
return fromV, nil
}
return query
}
func (c *BlogPostClient) Hooks() []Hook {
return c.hooks.BlogPost
}
type CategoryClient struct {
config
}
func NewCategoryClient(c config) *CategoryClient {
return &CategoryClient{config: c}
}
func (c *CategoryClient) Use(hooks ...Hook) {
c.hooks.Category = append(c.hooks.Category, hooks...)
}
func (c *CategoryClient) Create() *CategoryCreate {
mutation := newCategoryMutation(c.config, OpCreate)
return &CategoryCreate{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
func (c *CategoryClient) CreateBulk(builders ...*CategoryCreate) *CategoryCreateBulk {
return &CategoryCreateBulk{config: c.config, builders: builders}
}
func (c *CategoryClient) Update() *CategoryUpdate {
mutation := newCategoryMutation(c.config, OpUpdate)
return &CategoryUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
func (c *CategoryClient) UpdateOne(ca *Category) *CategoryUpdateOne {
mutation := newCategoryMutation(c.config, OpUpdateOne, withCategory(ca))
return &CategoryUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
func (c *CategoryClient) UpdateOneID(id int) *CategoryUpdateOne {
mutation := newCategoryMutation(c.config, OpUpdateOne, withCategoryID(id))
return &CategoryUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
func (c *CategoryClient) Delete() *CategoryDelete {
mutation := newCategoryMutation(c.config, OpDelete)
return &CategoryDelete{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
func (c *CategoryClient) DeleteOne(ca *Category) *CategoryDeleteOne {
return c.DeleteOneID(ca.ID)
}
func (c *CategoryClient) DeleteOneID(id int) *CategoryDeleteOne {
builder := c.Delete().Where(category.ID(id))
builder.mutation.id = &id
builder.mutation.op = OpDeleteOne
return &CategoryDeleteOne{builder}
}
func (c *CategoryClient) Query() *CategoryQuery {
return &CategoryQuery{
config: c.config,
}
}
func (c *CategoryClient) Get(ctx context.Context, id int) (*Category, error) {
return c.Query().Where(category.ID(id)).Only(ctx)
}
func (c *CategoryClient) GetX(ctx context.Context, id int) *Category {
obj, err := c.Get(ctx, id)
if err != nil {
panic(err)
}
return obj
}
func (c *CategoryClient) QueryBlogPosts(ca *Category) *BlogPostQuery {
query := &BlogPostQuery{config: c.config}
query.path = func(ctx context.Context) (fromV *sql.Selector, _ error) {
id := ca.ID
step := sqlgraph.NewStep(
sqlgraph.From(category.Table, category.FieldID, id),
sqlgraph.To(blogpost.Table, blogpost.FieldID),
sqlgraph.Edge(sqlgraph.M2M, false, category.BlogPostsTable, category.BlogPostsPrimaryKey...),
)
fromV = sqlgraph.Neighbors(ca.driver.Dialect(), step)
return fromV, nil
}
return query
}
func (c *CategoryClient) Hooks() []Hook {
return c.hooks.Category
}
type DependsOnSkippedClient struct {
config
}
func NewDependsOnSkippedClient(c config) *DependsOnSkippedClient {
return &DependsOnSkippedClient{config: c}
}
func (c *DependsOnSkippedClient) Use(hooks ...Hook) {
c.hooks.DependsOnSkipped = append(c.hooks.DependsOnSkipped, hooks...)
}
func (c *DependsOnSkippedClient) Create() *DependsOnSkippedCreate {
mutation := newDependsOnSkippedMutation(c.config, OpCreate)
return &DependsOnSkippedCreate{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
func (c *DependsOnSkippedClient) CreateBulk(builders ...*DependsOnSkippedCreate) *DependsOnSkippedCreateBulk {
return &DependsOnSkippedCreateBulk{config: c.config, builders: builders}
}
func (c *DependsOnSkippedClient) Update() *DependsOnSkippedUpdate {
mutation := newDependsOnSkippedMutation(c.config, OpUpdate)
return &DependsOnSkippedUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
func (c *DependsOnSkippedClient) UpdateOne(dos *DependsOnSkipped) *DependsOnSkippedUpdateOne {
mutation := newDependsOnSkippedMutation(c.config, OpUpdateOne, withDependsOnSkipped(dos))
return &DependsOnSkippedUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
func (c *DependsOnSkippedClient) UpdateOneID(id int) *DependsOnSkippedUpdateOne {
mutation := newDependsOnSkippedMutation(c.config, OpUpdateOne, withDependsOnSkippedID(id))
return &DependsOnSkippedUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
func (c *DependsOnSkippedClient) Delete() *DependsOnSkippedDelete {
mutation := newDependsOnSkippedMutation(c.config, OpDelete)
return &DependsOnSkippedDelete{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
func (c *DependsOnSkippedClient) DeleteOne(dos *DependsOnSkipped) *DependsOnSkippedDeleteOne {
return c.DeleteOneID(dos.ID)
}
func (c *DependsOnSkippedClient) DeleteOneID(id int) *DependsOnSkippedDeleteOne {
builder := c.Delete().Where(dependsonskipped.ID(id))
builder.mutation.id = &id
builder.mutation.op = OpDeleteOne
return &DependsOnSkippedDeleteOne{builder}
}
func (c *DependsOnSkippedClient) Query() *DependsOnSkippedQuery {
return &DependsOnSkippedQuery{
config: c.config,
}
}
func (c *DependsOnSkippedClient) Get(ctx context.Context, id int) (*DependsOnSkipped, error) {
return c.Query().Where(dependsonskipped.ID(id)).Only(ctx)
}
func (c *DependsOnSkippedClient) GetX(ctx context.Context, id int) *DependsOnSkipped {
obj, err := c.Get(ctx, id)
if err != nil {
panic(err)
}
return obj
}
func (c *DependsOnSkippedClient) QuerySkipped(dos *DependsOnSkipped) *ImplicitSkippedMessageQuery {
query := &ImplicitSkippedMessageQuery{config: c.config}
query.path = func(ctx context.Context) (fromV *sql.Selector, _ error) {
id := dos.ID
step := sqlgraph.NewStep(
sqlgraph.From(dependsonskipped.Table, dependsonskipped.FieldID, id),
sqlgraph.To(implicitskippedmessage.Table, implicitskippedmessage.FieldID),
sqlgraph.Edge(sqlgraph.O2M, false, dependsonskipped.SkippedTable, dependsonskipped.SkippedColumn),
)
fromV = sqlgraph.Neighbors(dos.driver.Dialect(), step)
return fromV, nil
}
return query
}
func (c *DependsOnSkippedClient) Hooks() []Hook {
return c.hooks.DependsOnSkipped
}
type DuplicateNumberMessageClient struct {
config
}
func NewDuplicateNumberMessageClient(c config) *DuplicateNumberMessageClient {
return &DuplicateNumberMessageClient{config: c}
}
func (c *DuplicateNumberMessageClient) Use(hooks ...Hook) {
c.hooks.DuplicateNumberMessage = append(c.hooks.DuplicateNumberMessage, hooks...)
}
func (c *DuplicateNumberMessageClient) Create() *DuplicateNumberMessageCreate {
mutation := newDuplicateNumberMessageMutation(c.config, OpCreate)
return &DuplicateNumberMessageCreate{config: c.config, hooks: c.Hooks(), mutation: mutation}
} | Apache License 2.0 |
dahernan/gopherdiscovery | stringSet.go | NewStringSet | go | func NewStringSet() StringSet {
s := make(StringSet)
return s
} | NewStringSet creates and returns a reference to an empty set.
func NewStringSet(a ...string) StringSet {
s := make(StringSet)
for _, i := range a {
s.Add(i)
}
return s
}
NewStringSet creates and returns a reference to an empty set. | https://github.com/dahernan/gopherdiscovery/blob/119dd71d152e21d8d0630d006e461ff8a53a136e/stringSet.go#L20-L23 | package gopherdiscovery
type StringSet map[string]struct{} | Apache License 2.0 |
viafintech/cronlocker | vendor/golang.org/x/sys/unix/zsyscall_aix_ppc64.go | Fstatfs | go | func Fstatfs(fd int, buf *Statfs_t) (err error) {
_, e1 := callfstatfs(fd, uintptr(unsafe.Pointer(buf)))
if e1 != 0 {
err = errnoErr(e1)
}
return
} | THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT | https://github.com/viafintech/cronlocker/blob/2ac4d6fe6e05a9b41f3fb54bb138340d876080c8/vendor/golang.org/x/sys/unix/zsyscall_aix_ppc64.go#L831-L837 | package unix
import (
"unsafe"
)
func utimes(path string, times *[2]Timeval) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
_, e1 := callutimes(uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(times)))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
func utimensat(dirfd int, path string, times *[2]Timespec, flag int) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
_, e1 := callutimensat(dirfd, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(times)), flag)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
func getcwd(buf []byte) (err error) {
var _p0 *byte
if len(buf) > 0 {
_p0 = &buf[0]
}
_, e1 := callgetcwd(uintptr(unsafe.Pointer(_p0)), len(buf))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
func accept(s int, rsa *RawSockaddrAny, addrlen *_Socklen) (fd int, err error) {
r0, e1 := callaccept(s, uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen)))
fd = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
func getdirent(fd int, buf []byte) (n int, err error) {
var _p0 *byte
if len(buf) > 0 {
_p0 = &buf[0]
}
r0, e1 := callgetdirent(fd, uintptr(unsafe.Pointer(_p0)), len(buf))
n = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
func wait4(pid Pid_t, status *_C_int, options int, rusage *Rusage) (wpid Pid_t, err error) {
r0, e1 := callwait4(int(pid), uintptr(unsafe.Pointer(status)), options, uintptr(unsafe.Pointer(rusage)))
wpid = Pid_t(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
func ioctl(fd int, req uint, arg uintptr) (err error) {
_, e1 := callioctl(fd, int(req), arg)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
func FcntlInt(fd uintptr, cmd int, arg int) (r int, err error) {
r0, e1 := callfcntl(fd, cmd, uintptr(arg))
r = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
func FcntlFlock(fd uintptr, cmd int, lk *Flock_t) (err error) {
_, e1 := callfcntl(fd, cmd, uintptr(unsafe.Pointer(lk)))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
func fcntl(fd int, cmd int, arg int) (val int, err error) {
r0, e1 := callfcntl(uintptr(fd), cmd, uintptr(arg))
val = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
func Acct(path string) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
_, e1 := callacct(uintptr(unsafe.Pointer(_p0)))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
func Chdir(path string) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
_, e1 := callchdir(uintptr(unsafe.Pointer(_p0)))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
func Chroot(path string) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
_, e1 := callchroot(uintptr(unsafe.Pointer(_p0)))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
func Close(fd int) (err error) {
_, e1 := callclose(fd)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
func Dup(oldfd int) (fd int, err error) {
r0, e1 := calldup(oldfd)
fd = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
func Exit(code int) {
callexit(code)
return
}
func Faccessat(dirfd int, path string, mode uint32, flags int) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
_, e1 := callfaccessat(dirfd, uintptr(unsafe.Pointer(_p0)), mode, flags)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
func Fchdir(fd int) (err error) {
_, e1 := callfchdir(fd)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
func Fchmod(fd int, mode uint32) (err error) {
_, e1 := callfchmod(fd, mode)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
func Fchmodat(dirfd int, path string, mode uint32, flags int) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
_, e1 := callfchmodat(dirfd, uintptr(unsafe.Pointer(_p0)), mode, flags)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
func Fchownat(dirfd int, path string, uid int, gid int, flags int) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
_, e1 := callfchownat(dirfd, uintptr(unsafe.Pointer(_p0)), uid, gid, flags)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
func Fdatasync(fd int) (err error) {
_, e1 := callfdatasync(fd)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
func Fsync(fd int) (err error) {
_, e1 := callfsync(fd)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
func Getpgid(pid int) (pgid int, err error) {
r0, e1 := callgetpgid(pid)
pgid = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
func Getpgrp() (pid int) {
r0, _ := callgetpgrp()
pid = int(r0)
return
}
func Getpid() (pid int) {
r0, _ := callgetpid()
pid = int(r0)
return
}
func Getppid() (ppid int) {
r0, _ := callgetppid()
ppid = int(r0)
return
}
func Getpriority(which int, who int) (prio int, err error) {
r0, e1 := callgetpriority(which, who)
prio = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
func Getrusage(who int, rusage *Rusage) (err error) {
_, e1 := callgetrusage(who, uintptr(unsafe.Pointer(rusage)))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
func Getsid(pid int) (sid int, err error) {
r0, e1 := callgetsid(pid)
sid = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
func Kill(pid int, sig Signal) (err error) {
_, e1 := callkill(pid, int(sig))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
func Klogctl(typ int, buf []byte) (n int, err error) {
var _p0 *byte
if len(buf) > 0 {
_p0 = &buf[0]
}
r0, e1 := callsyslog(typ, uintptr(unsafe.Pointer(_p0)), len(buf))
n = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
func Mkdir(dirfd int, path string, mode uint32) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
_, e1 := callmkdir(dirfd, uintptr(unsafe.Pointer(_p0)), mode)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
func Mkdirat(dirfd int, path string, mode uint32) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
_, e1 := callmkdirat(dirfd, uintptr(unsafe.Pointer(_p0)), mode)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
func Mkfifo(path string, mode uint32) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
_, e1 := callmkfifo(uintptr(unsafe.Pointer(_p0)), mode)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
func Mknod(path string, mode uint32, dev int) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
_, e1 := callmknod(uintptr(unsafe.Pointer(_p0)), mode, dev)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
func Mknodat(dirfd int, path string, mode uint32, dev int) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
_, e1 := callmknodat(dirfd, uintptr(unsafe.Pointer(_p0)), mode, dev)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
func Nanosleep(time *Timespec, leftover *Timespec) (err error) {
_, e1 := callnanosleep(uintptr(unsafe.Pointer(time)), uintptr(unsafe.Pointer(leftover)))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
func Open(path string, mode int, perm uint32) (fd int, err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
r0, e1 := callopen64(uintptr(unsafe.Pointer(_p0)), mode, perm)
fd = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
func Openat(dirfd int, path string, flags int, mode uint32) (fd int, err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
r0, e1 := callopenat(dirfd, uintptr(unsafe.Pointer(_p0)), flags, mode)
fd = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
func read(fd int, p []byte) (n int, err error) {
var _p0 *byte
if len(p) > 0 {
_p0 = &p[0]
}
r0, e1 := callread(fd, uintptr(unsafe.Pointer(_p0)), len(p))
n = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
func Readlink(path string, buf []byte) (n int, err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
var _p1 *byte
if len(buf) > 0 {
_p1 = &buf[0]
}
r0, e1 := callreadlink(uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), len(buf))
n = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
func Renameat(olddirfd int, oldpath string, newdirfd int, newpath string) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(oldpath)
if err != nil {
return
}
var _p1 *byte
_p1, err = BytePtrFromString(newpath)
if err != nil {
return
}
_, e1 := callrenameat(olddirfd, uintptr(unsafe.Pointer(_p0)), newdirfd, uintptr(unsafe.Pointer(_p1)))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
func Setdomainname(p []byte) (err error) {
var _p0 *byte
if len(p) > 0 {
_p0 = &p[0]
}
_, e1 := callsetdomainname(uintptr(unsafe.Pointer(_p0)), len(p))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
func Sethostname(p []byte) (err error) {
var _p0 *byte
if len(p) > 0 {
_p0 = &p[0]
}
_, e1 := callsethostname(uintptr(unsafe.Pointer(_p0)), len(p))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
func Setpgid(pid int, pgid int) (err error) {
_, e1 := callsetpgid(pid, pgid)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
func Setsid() (pid int, err error) {
r0, e1 := callsetsid()
pid = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
func Settimeofday(tv *Timeval) (err error) {
_, e1 := callsettimeofday(uintptr(unsafe.Pointer(tv)))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
func Setuid(uid int) (err error) {
_, e1 := callsetuid(uid)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
func Setgid(uid int) (err error) {
_, e1 := callsetgid(uid)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
func Setpriority(which int, who int, prio int) (err error) {
_, e1 := callsetpriority(which, who, prio)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
func Statx(dirfd int, path string, flags int, mask int, stat *Statx_t) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
_, e1 := callstatx(dirfd, uintptr(unsafe.Pointer(_p0)), flags, mask, uintptr(unsafe.Pointer(stat)))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
func Sync() {
callsync()
return
}
func Times(tms *Tms) (ticks uintptr, err error) {
r0, e1 := calltimes(uintptr(unsafe.Pointer(tms)))
ticks = uintptr(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
func Umask(mask int) (oldmask int) {
r0, _ := callumask(mask)
oldmask = int(r0)
return
}
func Uname(buf *Utsname) (err error) {
_, e1 := calluname(uintptr(unsafe.Pointer(buf)))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
func Unlink(path string) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
_, e1 := callunlink(uintptr(unsafe.Pointer(_p0)))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
func Unlinkat(dirfd int, path string, flags int) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
_, e1 := callunlinkat(dirfd, uintptr(unsafe.Pointer(_p0)), flags)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
func Ustat(dev int, ubuf *Ustat_t) (err error) {
_, e1 := callustat(dev, uintptr(unsafe.Pointer(ubuf)))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
func write(fd int, p []byte) (n int, err error) {
var _p0 *byte
if len(p) > 0 {
_p0 = &p[0]
}
r0, e1 := callwrite(fd, uintptr(unsafe.Pointer(_p0)), len(p))
n = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
func readlen(fd int, p *byte, np int) (n int, err error) {
r0, e1 := callread(fd, uintptr(unsafe.Pointer(p)), np)
n = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
func writelen(fd int, p *byte, np int) (n int, err error) {
r0, e1 := callwrite(fd, uintptr(unsafe.Pointer(p)), np)
n = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
func Dup2(oldfd int, newfd int) (err error) {
_, e1 := calldup2(oldfd, newfd)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
func Fadvise(fd int, offset int64, length int64, advice int) (err error) {
_, e1 := callposix_fadvise64(fd, offset, length, advice)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
func Fchown(fd int, uid int, gid int) (err error) {
_, e1 := callfchown(fd, uid, gid)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
func fstat(fd int, stat *Stat_t) (err error) {
_, e1 := callfstat(fd, uintptr(unsafe.Pointer(stat)))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
func fstatat(dirfd int, path string, stat *Stat_t, flags int) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
_, e1 := callfstatat(dirfd, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), flags)
if e1 != 0 {
err = errnoErr(e1)
}
return
} | MIT License |
schwarzlichtbezirk/wpk | luawpk/luatag.go | NewTagBool | go | func NewTagBool(ls *lua.LState) int {
var val = ls.CheckBool(1)
PushTag(ls, &LuaTag{wpk.TagBool(val)})
return 1
} | NewTagBool constructs LuaTag by given boolean value. | https://github.com/schwarzlichtbezirk/wpk/blob/b9d153e9549b81863a5918dbdb11ce9482faf2c6/luawpk/luatag.go#L77-L81 | package luawpk
import (
"encoding/base64"
"encoding/hex"
"github.com/schwarzlichtbezirk/wpk"
lua "github.com/yuin/gopher-lua"
)
const TagMT = "tag"
type LuaTag struct {
wpk.Tag
}
func RegTag(ls *lua.LState) {
var mt = ls.NewTypeMetatable(TagMT)
ls.SetGlobal(TagMT, mt)
ls.SetField(mt, "newhex", ls.NewFunction(NewTagHex))
ls.SetField(mt, "newbase64", ls.NewFunction(NewTagBase64))
ls.SetField(mt, "newstring", ls.NewFunction(NewTagString))
ls.SetField(mt, "newbool", ls.NewFunction(NewTagBool))
ls.SetField(mt, "newuint16", ls.NewFunction(NewTagUint16))
ls.SetField(mt, "newuint32", ls.NewFunction(NewTagUint32))
ls.SetField(mt, "newuint64", ls.NewFunction(NewTagUint64))
ls.SetField(mt, "newnumber", ls.NewFunction(NewTagNumber))
ls.SetField(mt, "__index", ls.NewFunction(getterTag))
ls.SetField(mt, "__newindex", ls.NewFunction(setterTag))
ls.SetField(mt, "__tostring", ls.NewFunction(stringTag))
ls.SetField(mt, "__len", ls.NewFunction(lenTag))
for name, f := range methodsTag {
ls.SetField(mt, name, ls.NewFunction(f))
}
for i, p := range propertiesTag {
ls.SetField(mt, p.name, lua.LNumber(i))
}
}
func PushTag(ls *lua.LState, v *LuaTag) {
var ud = ls.NewUserData()
ud.Value = v
ls.SetMetatable(ud, ls.GetTypeMetatable(TagMT))
ls.Push(ud)
}
func NewTagHex(ls *lua.LState) int {
var val = ls.CheckString(1)
var ds, _ = hex.DecodeString(val)
PushTag(ls, &LuaTag{ds})
return 1
}
func NewTagBase64(ls *lua.LState) int {
var val = ls.CheckString(1)
var ds, _ = base64.StdEncoding.DecodeString(val)
PushTag(ls, &LuaTag{ds})
return 1
}
func NewTagString(ls *lua.LState) int {
var val = ls.CheckString(1)
PushTag(ls, &LuaTag{wpk.TagString(val)})
return 1
} | MIT License |
cloudfoundry-incubator/bosh-alicloud-cpi-release | src/bosh-alicloud-cpi/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/ecs/create_security_group.go | CreateSecurityGroup | go | func (client *Client) CreateSecurityGroup(request *CreateSecurityGroupRequest) (response *CreateSecurityGroupResponse, err error) {
response = CreateCreateSecurityGroupResponse()
err = client.DoAction(request, response)
return
} | CreateSecurityGroup invokes the ecs.CreateSecurityGroup API synchronously
api document: https://help.aliyun.com/api/ecs/createsecuritygroup.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/create_security_group.go#L25-L29 | package ecs
import (
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses"
) | Apache License 2.0 |
outbrain/orchestrator-agent | vendor/github.com/outbrain/golib/log/log.go | SetPrintStackTrace | go | func SetPrintStackTrace(shouldPrintStackTrace bool) {
printStackTrace = shouldPrintStackTrace
} | SetPrintStackTrace enables/disables dumping the stack upon error logging | https://github.com/outbrain/orchestrator-agent/blob/61af2a939779e19a13e2eb2bdd54e3cae28b6ae9/vendor/github.com/outbrain/golib/log/log.go#L93-L95 | package log
import (
"errors"
"fmt"
"log/syslog"
"os"
"runtime/debug"
"time"
)
type LogLevel int
func (this LogLevel) String() string {
switch this {
case FATAL:
return "FATAL"
case CRITICAL:
return "CRITICAL"
case ERROR:
return "ERROR"
case WARNING:
return "WARNING"
case NOTICE:
return "NOTICE"
case INFO:
return "INFO"
case DEBUG:
return "DEBUG"
}
return "unknown"
}
func LogLevelFromString(logLevelName string) (LogLevel, error) {
switch logLevelName {
case "FATAL":
return FATAL, nil
case "CRITICAL":
return CRITICAL, nil
case "ERROR":
return ERROR, nil
case "WARNING":
return WARNING, nil
case "NOTICE":
return NOTICE, nil
case "INFO":
return INFO, nil
case "DEBUG":
return DEBUG, nil
}
return 0, fmt.Errorf("Unknown LogLevel name: %+v", logLevelName)
}
const (
FATAL LogLevel = iota
CRITICAL
ERROR
WARNING
NOTICE
INFO
DEBUG
)
const TimeFormat = "2006-01-02 15:04:05"
var globalLogLevel LogLevel = DEBUG
var printStackTrace bool = false
var syslogLevel LogLevel = ERROR
var syslogWriter *syslog.Writer | Apache License 2.0 |
goccmack/godsp | ppeaks/ppeaks.go | Max | go | func (pks *Peaks) Max(fracOfMaxPersistence float64) int {
idxs := pks.GetIndices(fracOfMaxPersistence)
biggest, val := -1, math.Inf(-1)
for _, pk := range idxs {
if pks.seq[pk] > val {
biggest, val = pk, pks.seq[pk]
}
}
return biggest
} | /*
Max returns the index in the original time series `seq` of the peak with the
highest y-value. See GetIndices for fracOfMaxPersistence. | https://github.com/goccmack/godsp/blob/3fe9db9bddd990665cc098f3ddf7d148d987a4ec/ppeaks/ppeaks.go#L151-L160 | package ppeaks
import (
"math"
"sort"
"github.com/goccmack/godsp"
)
const none = -1
type Peak struct {
born, died, left, right int
}
func newPeak(startIdx int) *Peak {
return &Peak{
born: startIdx,
left: startIdx,
right: startIdx,
died: none,
}
}
type Peaks struct {
peaks []*Peak
seq []float64
}
func (p *Peak) getPersistence(seq []float64) float64 {
if p.died == none {
return math.Inf(1)
}
return seq[p.born] - seq[p.died]
}
func GetPeaksInt(seq []int) *Peaks {
seq1 := godsp.ToFloat(seq)
return GetPeaks(seq1)
}
func GetPeaks(seq []float64) *Peaks {
peaks := make([]*Peak, 0, 1024)
idxtopeak := make([]int, len(seq))
for i := range idxtopeak {
idxtopeak[i] = none
}
indices := godsp.Range(len(seq))
sort.SliceStable(indices, func(i, j int) bool { return seq[indices[i]] > seq[indices[j]] })
for _, idx := range indices {
lftdone := (idx > 0 && idxtopeak[idx-1] != none)
rgtdone := (idx < len(seq)-1 && idxtopeak[idx+1] != none)
il := none
if lftdone {
il = idxtopeak[idx-1]
}
ir := none
if rgtdone {
ir = idxtopeak[idx+1]
}
if !lftdone && !rgtdone {
peaks = append(peaks, newPeak(idx))
idxtopeak[idx] = len(peaks) - 1
}
if lftdone && !rgtdone {
peaks[il].right++
idxtopeak[idx] = il
}
if !lftdone && rgtdone {
peaks[ir].left--
idxtopeak[idx] = ir
}
if lftdone && rgtdone {
if seq[peaks[il].born] > seq[peaks[ir].born] {
peaks[ir].died = idx
peaks[il].right = peaks[ir].right
idxtopeak[peaks[il].right], idxtopeak[idx] = il, il
} else {
peaks[il].died = idx
peaks[ir].left = peaks[il].left
idxtopeak[peaks[ir].left], idxtopeak[idx] = ir, ir
}
}
}
sort.SliceStable(peaks, func(i, j int) bool { return peaks[i].born < peaks[j].born })
return &Peaks{
peaks: peaks,
seq: seq,
}
}
func (pks *Peaks) GetIndices(fracOfMaxPersistence float64) []int {
indices := make([]int, 0, len(pks.peaks))
_, maxPersistence := pks.MinMaxPersistence()
for _, pk := range pks.peaks {
if pk.getPersistence(pks.seq)/maxPersistence >= fracOfMaxPersistence {
indices = append(indices, pk.born)
}
}
return indices
} | Apache License 2.0 |
iotaledger/hive.go | crypto/bls/publickey.go | Base58 | go | func (p PublicKey) Base58() string {
return base58.Encode(p.Bytes())
} | Base58 returns a base58 encoded version of the PublicKey | https://github.com/iotaledger/hive.go/blob/2f217dcf2ad720495ce52a8830c432cdf36fcdbd/crypto/bls/publickey.go#L75-L77 | package bls
import (
"github.com/iotaledger/hive.go/marshalutil"
"github.com/mr-tron/base58"
"go.dedis.ch/kyber/v3"
"go.dedis.ch/kyber/v3/sign/bdn"
"golang.org/x/xerrors"
)
type PublicKey struct {
Point kyber.Point
}
func PublicKeyFromBytes(bytes []byte) (publicKey PublicKey, consumedBytes int, err error) {
marshalUtil := marshalutil.New(bytes)
if publicKey, err = PublicKeyFromMarshalUtil(marshalUtil); err != nil {
err = xerrors.Errorf("failed to parse PublicKey from MarshalUtil: %w", err)
}
consumedBytes = marshalUtil.ReadOffset()
return
}
func PublicKeyFromBase58EncodedString(base58String string) (publicKey PublicKey, err error) {
bytes, err := base58.Decode(base58String)
if err != nil {
err = xerrors.Errorf("error while decoding base58 encoded PublicKey (%v): %w", err, ErrBase58DecodeFailed)
return
}
if publicKey, _, err = PublicKeyFromBytes(bytes); err != nil {
err = xerrors.Errorf("failed to parse PublicKey from bytes: %w", err)
return
}
return
}
func PublicKeyFromMarshalUtil(marshalUtil *marshalutil.MarshalUtil) (publicKey PublicKey, err error) {
bytes, err := marshalUtil.ReadBytes(PublicKeySize)
if err != nil {
err = xerrors.Errorf("failed to read PublicKey bytes (%v): %w", err, ErrParseBytesFailed)
return
}
publicKey.Point = blsSuite.G2().Point()
if err = publicKey.Point.UnmarshalBinary(bytes); err != nil {
err = xerrors.Errorf("failed to unmarshal PublicKey (%v): %w", err, ErrParseBytesFailed)
return
}
return
}
func (p PublicKey) SignatureValid(data []byte, signature Signature) bool {
return bdn.Verify(blsSuite, p.Point, data, signature.Bytes()) == nil
}
func (p PublicKey) Bytes() []byte {
bytes, err := p.Point.MarshalBinary()
if err != nil {
panic(err)
}
return bytes
} | Apache License 2.0 |
mirantis/k8s-appcontroller | pkg/scheduler/flows_test.go | TestPassUndeclaredFlowParameter | go | func TestPassUndeclaredFlowParameter(t *testing.T) {
flow := mocks.MakeFlow("flow")
flow.Flow.Parameters = map[string]client.FlowParameter{
"arg1": mocks.MakeFlowParameter("p"),
}
c := mocks.NewClient(
mocks.MakeFlow("flow"),
mocks.MakeResourceDefinition("job/ready-1"),
mocks.MakeDependency("flow/flow", "job/ready-1", "flow=flow"),
)
_, err := New(c, nil, 0).BuildDependencyGraph(
interfaces.DependencyGraphOptions{
ReplicaCount: 1,
FlowName: "flow",
Args: map[string]string{
"arg2": "x",
}})
if err == nil {
t.Error("pass of undeclared argument should not succeed")
} else if err.Error() != "unexpected argument arg2" {
t.Errorf("unexpected error: %v", err)
}
_, err = New(c, nil, 0).BuildDependencyGraph(
interfaces.DependencyGraphOptions{
ReplicaCount: 1,
FlowName: "flow",
AllowUndeclaredArgs: true,
Args: map[string]string{
"arg2": "x",
}})
if err != nil {
t.Error("pass of undeclared argument should succeed if it was explicitly permited")
}
} | TestPassUndeclaredFlowParameter tests that by-default only declared flow arguments can be passed | https://github.com/mirantis/k8s-appcontroller/blob/437b0eb26b0734b222c8d104d9e6ddd8615286f3/pkg/scheduler/flows_test.go#L464-L501 | package scheduler
import (
"errors"
"strings"
"testing"
"github.com/Mirantis/k8s-AppController/pkg/client"
"github.com/Mirantis/k8s-AppController/pkg/interfaces"
"github.com/Mirantis/k8s-AppController/pkg/mocks"
"k8s.io/client-go/pkg/api"
api_v1 "k8s.io/client-go/pkg/api/v1"
batchapiv1 "k8s.io/client-go/pkg/apis/batch/v1"
"k8s.io/client-go/pkg/runtime"
k8stesting "k8s.io/client-go/testing"
)
func TestFlowResourcesIdentified(t *testing.T) {
c := mocks.NewClient(
mocks.MakeFlow("test"),
mocks.MakeResourceDefinition("job/1"),
mocks.MakeResourceDefinition("job/2"),
mocks.MakeResourceDefinition("job/3"),
mocks.MakeResourceDefinition("job/4"),
mocks.MakeDependency("flow/test", "job/1", "flow=test"),
mocks.MakeDependency("job/1", "job/2", "flow=test"),
mocks.MakeDependency("job/2", "job/3"),
)
depGraph, err := New(c, nil, 0).BuildDependencyGraph(
interfaces.DependencyGraphOptions{
FlowName: "test",
ReplicaCount: 1,
})
if err != nil {
t.Fatal(err)
}
graph := depGraph.(*dependencyGraph).graph
expectedLength := 2
if len(graph) != expectedLength {
t.Errorf("wrong length of a graph %d != %d", expectedLength, len(graph))
}
if _, found := graph["job/1"]; !found {
t.Error("job/1 is not in the graph")
}
if _, found := graph["job/2"]; !found {
t.Error("job/2 is not in the graph")
}
}
func TestTopLevelResourcesAssignedToDefaultFlow(t *testing.T) {
c := mocks.NewClient(
mocks.MakeFlow("test"),
mocks.MakeResourceDefinition("job/1"),
mocks.MakeResourceDefinition("job/2"),
mocks.MakeResourceDefinition("job/3"),
mocks.MakeResourceDefinition("job/4"),
mocks.MakeResourceDefinition("job/5"),
mocks.MakeDependency("flow/test", "job/1", "flow=test"),
mocks.MakeDependency("job/1", "job/2", "flow=test"),
mocks.MakeDependency("job/2", "job/3"),
mocks.MakeDependency("job/4", "job/5"),
)
depGraph, err := New(c, nil, 0).BuildDependencyGraph(
interfaces.DependencyGraphOptions{ReplicaCount: 1})
if err != nil {
t.Fatal(err)
}
graph := depGraph.(*dependencyGraph).graph
expectedLength := 2
if len(graph) != expectedLength {
t.Errorf("wrong length of a graph %d != %d", expectedLength, len(graph))
}
if _, found := graph["job/4"]; !found {
t.Error("job/4 is not in the graph")
}
if _, found := graph["job/5"]; !found {
t.Error("job/5 is not in the graph")
}
}
func TestTriggerFlowIndependently(t *testing.T) {
c := mocks.NewClient(
mocks.MakeFlow("flow1"),
mocks.MakeFlow("flow2"),
mocks.MakeResourceDefinition("job/ready-flow1-1"),
mocks.MakeResourceDefinition("job/ready-flow1-2"),
mocks.MakeResourceDefinition("job/ready-flow2-1"),
mocks.MakeResourceDefinition("job/ready-flow2-2"),
mocks.MakeDependency("flow/flow1", "job/ready-flow1-1", "flow=flow1"),
mocks.MakeDependency("job/ready-flow1-1", "flow/flow2", "flow=flow1"),
mocks.MakeDependency("flow/flow2", "job/ready-flow1-2", "flow=flow1"),
mocks.MakeDependency("flow/flow2", "job/ready-flow2-1", "flow=flow2"),
mocks.MakeDependency("job/ready-flow2-1", "job/ready-flow2-2", "flow=flow2"),
)
depGraph, err := New(c, nil, 0).BuildDependencyGraph(
interfaces.DependencyGraphOptions{ReplicaCount: 1, FlowName: "flow2"})
if err != nil {
t.Fatal(err)
}
jobs, err := c.Jobs().List(api_v1.ListOptions{})
if err != nil {
t.Fatal(err)
}
if len(jobs.Items) != 0 {
t.Fatal("Job list is not empty")
}
stopChan := make(chan struct{})
depGraph.Deploy(stopChan)
jobs, err = c.Jobs().List(api_v1.ListOptions{})
if err != nil {
t.Fatal(err)
}
jobNames := map[string]bool{
"ready-flow2-1": true,
"ready-flow2-2": true,
}
for _, job := range jobs.Items {
if !jobNames[job.Name] {
t.Error("found unexpected job", job.Name)
}
delete(jobNames, job.Name)
}
if len(jobNames) != 0 {
t.Errorf("not all jobs were created: %d jobs were not found", len(jobNames))
}
}
func TestUseNotExportedFlow(t *testing.T) {
flow := mocks.MakeFlow("test")
flow.Flow.Exported = false
c := mocks.NewClient(flow)
sched := New(c, nil, 0)
_, err := sched.BuildDependencyGraph(
interfaces.DependencyGraphOptions{ReplicaCount: 1, FlowName: "test", ExportedOnly: true})
if err == nil {
t.Error("not exported flows cannot be run if ExportedOnly is true")
} else if err.Error() != "flow test is not exported" {
t.Errorf("unexpected error: %v", err)
}
_, err = sched.BuildDependencyGraph(
interfaces.DependencyGraphOptions{ReplicaCount: 1, FlowName: "test"})
if err != nil {
t.Fatal(err)
}
}
func TestTriggerOneFlowFromAnother(t *testing.T) {
flow2 := mocks.MakeFlow("flow2")
flow2.Flow.Exported = false
c := mocks.NewClient(
mocks.MakeFlow("flow1"),
flow2,
mocks.MakeResourceDefinition("job/ready-flow1-1"),
mocks.MakeResourceDefinition("job/ready-flow1-2"),
mocks.MakeResourceDefinition("job/ready-flow2-1"),
mocks.MakeResourceDefinition("job/ready-flow2-2"),
mocks.MakeDependency("flow/flow1", "job/ready-flow1-1", "flow=flow1"),
mocks.MakeDependency("job/ready-flow1-1", "flow/flow2", "flow=flow1"),
mocks.MakeDependency("flow/flow2", "job/ready-flow1-2", "flow=flow1"),
mocks.MakeDependency("flow/flow2", "job/ready-flow2-1", "flow=flow2"),
mocks.MakeDependency("job/ready-flow2-1", "job/ready-flow2-2", "flow=flow2"),
)
depGraph, err := New(c, nil, 0).BuildDependencyGraph(
interfaces.DependencyGraphOptions{ReplicaCount: 1, FlowName: "flow1"})
if err != nil {
t.Fatal(err)
}
stopChan := make(chan struct{})
depGraph.Deploy(stopChan)
jobs, err := c.Jobs().List(api_v1.ListOptions{})
if err != nil {
t.Fatal(err)
}
jobNames := map[string]bool{
"ready-flow1-1": true,
"ready-flow1-2": true,
"ready-flow2-1": true,
"ready-flow2-2": true,
}
for _, job := range jobs.Items {
if !jobNames[job.Name] {
t.Error("found unexpected job", job.Name)
}
delete(jobNames, job.Name)
}
if len(jobNames) != 0 {
t.Errorf("not all jobs were created: %d jobs were not found", len(jobNames))
}
}
func TestParameterPassing(t *testing.T) {
dep := mocks.MakeDependency("job/ready-1", "job/ready-$arg1-$arg2")
dep.Args = map[string]string{
"arg1": "x",
"arg2": "y",
}
c := mocks.NewClient(
mocks.MakeResourceDefinition("job/ready-1"),
mocks.MakeResourceDefinition("job/ready-$arg1-$arg2"),
dep,
)
depGraph, err := New(c, nil, 0).BuildDependencyGraph(
interfaces.DependencyGraphOptions{ReplicaCount: 1})
if err != nil {
t.Fatal(err)
}
stopChan := make(chan struct{})
depGraph.Deploy(stopChan)
jobs, err := c.Jobs().List(api_v1.ListOptions{})
if err != nil {
t.Fatal(err)
}
jobNames := map[string]bool{
"ready-1": true,
"ready-x-y": true,
}
for _, job := range jobs.Items {
if !jobNames[job.Name] {
t.Error("found unexpected job", job.Name)
}
delete(jobNames, job.Name)
}
if len(jobNames) != 0 {
t.Errorf("not all jobs were created: %d jobs were not found", len(jobNames))
}
}
func TestMultipathParameterPassing(t *testing.T) {
dep1 := mocks.MakeDependency("job/ready-1", "job/ready-$arg")
dep1.Args = map[string]string{"arg": "x"}
dep2 := mocks.MakeDependency("job/ready-1", "job/ready-$arg")
dep2.Args = map[string]string{"arg": "y"}
c := mocks.NewClient(
mocks.MakeResourceDefinition("job/ready-1"),
mocks.MakeResourceDefinition("job/ready-$arg"),
dep1,
dep2,
)
depGraph, err := New(c, nil, 0).BuildDependencyGraph(
interfaces.DependencyGraphOptions{ReplicaCount: 1})
if err != nil {
t.Fatal(err)
}
stopChan := make(chan struct{})
depGraph.Deploy(stopChan)
jobs, err := c.Jobs().List(api_v1.ListOptions{})
if err != nil {
t.Fatal(err)
}
jobNames := map[string]bool{
"ready-1": true,
"ready-x": true,
"ready-y": true,
}
for _, job := range jobs.Items {
if !jobNames[job.Name] {
t.Error("found unexpected job", job.Name)
}
delete(jobNames, job.Name)
}
if len(jobNames) != 0 {
t.Errorf("not all jobs were created: %d jobs were not found", len(jobNames))
}
}
func TestParametrizedFlow(t *testing.T) {
flow := mocks.MakeFlow("flow")
flow.Flow.Parameters = map[string]client.FlowParameter{
"arg1": mocks.MakeFlowParameter("p"),
"arg2": mocks.MakeFlowParameter("q"),
}
c := mocks.NewClient(
flow,
mocks.MakeResourceDefinition("job/ready-$arg1-$arg2"),
mocks.MakeDependency("flow/flow", "job/ready-$arg1-$arg2", "flow=flow"),
)
depGraph, err := New(c, nil, 0).BuildDependencyGraph(
interfaces.DependencyGraphOptions{
ReplicaCount: 1,
FlowName: "flow",
Args: map[string]string{
"arg1": "x",
}})
if err != nil {
t.Fatal(err)
}
stopChan := make(chan struct{})
depGraph.Deploy(stopChan)
jobs, err := c.Jobs().List(api_v1.ListOptions{})
if err != nil {
t.Fatal(err)
}
expectedJobName := "ready-x-q"
if len(jobs.Items) != 1 {
t.Errorf("wrong number %d of jobs were created", len(jobs.Items))
} else if jobs.Items[0].Name != expectedJobName {
t.Errorf("expected job name: %s, found: %s", expectedJobName, jobs.Items[0].Name)
}
}
func TestAcNameParameter(t *testing.T) {
flow := mocks.MakeFlow("flow2")
flow.Flow.Parameters = map[string]client.FlowParameter{
"name": mocks.MakeFlowParameter(""),
}
dep := mocks.MakeDependency("flow/flow1", "flow/flow2", "flow=flow1")
dep.Args = map[string]string{"name": "$AC_NAME"}
c := mocks.NewClient(
mocks.MakeFlow("flow1"),
flow,
dep,
mocks.MakeResourceDefinition("job/ready-$name"),
mocks.MakeDependency("flow/flow2", "job/ready-$name", "flow=flow2"),
)
depGraph, err := New(c, nil, 0).BuildDependencyGraph(
interfaces.DependencyGraphOptions{
ReplicaCount: 1,
FlowName: "flow1",
})
if err != nil {
t.Fatal(err)
}
stopChan := make(chan struct{})
depGraph.Deploy(stopChan)
replicas, err := c.Replicas().List(api.ListOptions{})
if err != nil {
t.Fatal(err)
}
if len(replicas.Items) != 2 {
t.Fatalf("there should be 2 replicas - 1 for each flow. Found %d replicas", len(replicas.Items))
}
for _, replica := range replicas.Items {
if replica.FlowName == "flow1" {
acName := replica.ReplicaName()
jobName := "ready-" + acName
_, err := c.Jobs().Get(jobName)
if err != nil {
t.Error(err)
}
return
}
}
t.Error("no flow1 replica found")
}
func TestUseUndeclaredFlowParameter(t *testing.T) {
flow := mocks.MakeFlow("flow")
flow.Flow.Parameters = map[string]client.FlowParameter{
"arg1": mocks.MakeFlowParameter("p"),
}
c := mocks.NewClient(
flow,
mocks.MakeResourceDefinition("job/ready-$arg1-$arg2"),
mocks.MakeDependency("flow/flow", "job/ready-$arg1-$arg2", "flow=flow"),
)
depGraph, err := New(c, nil, 0).BuildDependencyGraph(
interfaces.DependencyGraphOptions{
ReplicaCount: 1,
FlowName: "flow",
})
if err != nil {
t.Fatal(err)
}
stopChan := make(chan struct{})
depGraph.Deploy(stopChan)
jobs, err := c.Jobs().List(api_v1.ListOptions{})
if err != nil {
t.Fatal(err)
}
expectedJobName := "ready-p-$arg2"
if len(jobs.Items) != 1 {
t.Errorf("wrong number %d of jobs were created", len(jobs.Items))
} else if jobs.Items[0].Name != expectedJobName {
t.Errorf("expected job name: %s, found: %s", expectedJobName, jobs.Items[0].Name)
}
} | Apache License 2.0 |
spoke-d/thermionic | internal/db/schema/schema_integration_test.go | TestSchemaDump | go | func TestSchemaDump(t *testing.T) {
schema, db := newSchemaAndDB(t)
schema.Add(updateCreateTable)
schema.Add(updateAddColumn)
_, err := schema.Ensure(db)
if err != nil {
t.Errorf("expected err to be nil: %v", err)
}
dump, err := schema.Dump(db)
if err != nil {
t.Errorf("expected err to be nil: %v", err)
}
_, db = newSchemaAndDB(t)
schema.Fresh(dump)
_, err = schema.Ensure(db)
if err != nil {
t.Errorf("expected err to be nil: %v", err)
}
tx, err := db.Begin()
if err != nil {
t.Errorf("expected err to be nil: %v", err)
}
versions, err := query.SelectIntegers(tx, "SELECT version FROM schema")
if err != nil {
t.Errorf("expected err to be nil: %v", err)
}
if expected, actual := []int{2}, versions; !reflect.DeepEqual(expected, actual) {
t.Errorf("expected: %v, actual: %v", expected, actual)
}
_, err = tx.Exec("SELECT id, name FROM test")
if err != nil {
t.Errorf("expected err to be nil: %v", err)
}
} | The SQL text returns by Dump() can be used to create the schema from
scratch, without applying each individual update. | https://github.com/spoke-d/thermionic/blob/d2438c51b10f8abb051b1d008e4a0067fd0537c6/internal/db/schema/schema_integration_test.go#L355-L396 | package schema_test
import (
"database/sql"
"reflect"
"testing"
"github.com/pkg/errors"
"github.com/spoke-d/thermionic/internal/db/database"
"github.com/spoke-d/thermionic/internal/db/query"
"github.com/spoke-d/thermionic/internal/db/schema"
"github.com/spoke-d/thermionic/internal/fsys"
)
func TestNewFromMap(t *testing.T) {
db := newDB(t)
fs := newFileSystem(t)
s := schema.New(fs, []schema.Update{
updateCreateTable,
updateInsertValue,
})
initial, err := s.Ensure(db)
if err != nil {
t.Errorf("expected err to be nil: %v", err)
}
if expected, actual := 0, initial; expected != actual {
t.Errorf("expected: %d, actual: %d", expected, actual)
}
}
func TestSchemaEnsure_VersionMostRecentThanExpected(t *testing.T) {
schema, db := newSchemaAndDB(t)
schema.Add(updateNoop)
_, err := schema.Ensure(db)
if err != nil {
t.Errorf("expected err to be nil: %v", err)
}
schema, _ = newSchemaAndDB(t)
_, err = schema.Ensure(db)
if err == nil {
t.Errorf("expected err not to be nil")
}
if expected, actual := "schema version '1' is more recent than expected '0'", errors.Cause(err).Error(); expected != actual {
t.Errorf("expected: %v, actual: %v", expected, actual)
}
}
func TestSchemaEnsure_FreshStatementError(t *testing.T) {
schema, db := newSchemaAndDB(t)
schema.Add(updateNoop)
schema.Fresh("garbage")
_, err := schema.Ensure(db)
if err == nil {
t.Errorf("expected err not to be nil")
}
if expected, actual := "cannot apply fresh schema: near \"garbage\": syntax error", err.Error(); expected != actual {
t.Errorf("expected: %v, actual: %v", expected, actual)
}
}
func TestSchemaEnsure_MissingVersion(t *testing.T) {
schema, db := newSchemaAndDB(t)
schema.Add(updateNoop)
_, err := schema.Ensure(db)
if err != nil {
t.Errorf("expected err to be nil: %v", err)
}
tx, err := db.Begin()
if err != nil {
t.Errorf("expected err to be nil: %v", err)
}
_, err = tx.Exec(`INSERT INTO schema (version, updated_at) VALUES (3, strftime("%s"))`)
if err != nil {
t.Errorf("expected err to be nil: %v", err)
}
if err := tx.Commit(); err != nil {
t.Errorf("expected err to be nil: %v", err)
}
schema.Add(updateNoop)
schema.Add(updateNoop)
_, err = schema.Ensure(db)
if err == nil {
t.Errorf("expected err to be nil: %v", err)
}
if expected, actual := "missing updates: 1 -> 3", err.Error(); expected != actual {
t.Errorf("expected: %v, actual: %v", expected, actual)
}
}
func TestSchemaEnsure_ZeroUpdates(t *testing.T) {
schema, db := newSchemaAndDB(t)
_, err := schema.Ensure(db)
if err != nil {
t.Errorf("expected err to be nil: %v", err)
}
tx, err := db.Begin()
if err != nil {
t.Errorf("expected err to be nil: %v", err)
}
versions, err := query.SelectIntegers(tx, "SELECT version FROM SCHEMA")
if err != nil {
t.Errorf("expected err to be nil: %v", err)
}
var want []int
if expected, actual := want, versions; !reflect.DeepEqual(expected, actual) {
t.Errorf("expected: %v, actual: %v", expected, actual)
}
}
func TestSchemaEnsure_ApplyAllUpdates(t *testing.T) {
schema, db := newSchemaAndDB(t)
schema.Add(updateCreateTable)
schema.Add(updateInsertValue)
initial, err := schema.Ensure(db)
if err != nil {
t.Errorf("expected err to be nil: %v", err)
}
if expected, actual := 0, initial; expected != actual {
t.Errorf("expected: %v, actual: %v", expected, actual)
}
tx, err := db.Begin()
if err != nil {
t.Errorf("expected err to be nil: %v", err)
}
versions, err := query.SelectIntegers(tx, "SELECT version FROM SCHEMA")
if err != nil {
t.Errorf("expected err to be nil: %v", err)
}
if expected, actual := []int{1, 2}, versions; !reflect.DeepEqual(expected, actual) {
t.Errorf("expected: %v, actual: %v", expected, actual)
}
ids, err := query.SelectIntegers(tx, "SELECT id FROM test")
if err != nil {
t.Errorf("expected err to be nil: %v", err)
}
if expected, actual := []int{1}, ids; !reflect.DeepEqual(expected, actual) {
t.Errorf("expected: %v, actual: %v", expected, actual)
}
}
func TestSchemaEnsure_ApplyAfterInitialDumpCreation(t *testing.T) {
schema, db := newSchemaAndDB(t)
schema.Add(updateCreateTable)
schema.Add(updateAddColumn)
_, err := schema.Ensure(db)
if err != nil {
t.Errorf("expected err to be nil: %v", err)
}
dump, err := schema.Dump(db)
if err != nil {
t.Errorf("expected err to be nil: %v", err)
}
_, db = newSchemaAndDB(t)
schema.Fresh(dump)
_, err = schema.Ensure(db)
if err != nil {
t.Errorf("expected err to be nil: %v", err)
}
schema.Add(updateNoop)
_, err = schema.Ensure(db)
if err != nil {
t.Errorf("expected err to be nil: %v", err)
}
tx, err := db.Begin()
if err != nil {
t.Errorf("expected err to be nil: %v", err)
}
versions, err := query.SelectIntegers(tx, "SELECT version FROM schema")
if err != nil {
t.Errorf("expected err to be nil: %v", err)
}
if expected, actual := []int{2, 3}, versions; !reflect.DeepEqual(expected, actual) {
t.Errorf("expected: %v, actual: %v", expected, actual)
}
}
func TestSchemaEnsure_OnlyApplyMissing(t *testing.T) {
schema, db := newSchemaAndDB(t)
schema.Add(updateCreateTable)
_, err := schema.Ensure(db)
if err != nil {
t.Errorf("expected err to be nil: %v", err)
}
schema.Add(updateInsertValue)
initial, err := schema.Ensure(db)
if err != nil {
t.Errorf("expected err to be nil: %v", err)
}
if expected, actual := 1, initial; expected != actual {
t.Errorf("expected: %v, actual: %v", expected, actual)
}
tx, err := db.Begin()
if err != nil {
t.Errorf("expected err to be nil: %v", err)
}
versions, err := query.SelectIntegers(tx, "SELECT version FROM SCHEMA")
if err != nil {
t.Errorf("expected err to be nil: %v", err)
}
if expected, actual := []int{1, 2}, versions; !reflect.DeepEqual(expected, actual) {
t.Errorf("expected: %v, actual: %v", expected, actual)
}
ids, err := query.SelectIntegers(tx, "SELECT id FROM test")
if err != nil {
t.Errorf("expected err to be nil: %v", err)
}
if expected, actual := []int{1}, ids; !reflect.DeepEqual(expected, actual) {
t.Errorf("expected: %v, actual: %v", expected, actual)
}
}
func TestSchemaEnsure_FailingUpdate(t *testing.T) {
schema, db := newSchemaAndDB(t)
schema.Add(updateCreateTable)
schema.Add(updateBoom)
_, err := schema.Ensure(db)
if expected, actual := "failed to apply update 1: boom", err.Error(); expected != actual {
t.Errorf("expected: %v, actual: %v", expected, actual)
}
tx, err := db.Begin()
if err != nil {
t.Errorf("expected err to be nil: %v", err)
}
tables, err := query.SelectStrings(tx, "SELECT name FROM sqlite_master WHERE type = 'table'")
if err != nil {
t.Errorf("expected err to be nil: %v", err)
}
if expected, actual := "schema", tables; contains(actual, expected) {
t.Errorf("expected: %v, actual: %v", expected, actual)
}
if expected, actual := "test", tables; contains(actual, expected) {
t.Errorf("expected: %v, actual: %v", expected, actual)
}
}
func TestSchemaEnsure_FailingHook(t *testing.T) {
schema, db := newSchemaAndDB(t)
schema.Add(updateCreateTable)
schema.Hook(func(int, database.Tx) error { return errors.Errorf("boom") })
_, err := schema.Ensure(db)
if expected, actual := "failed to execute hook (version 0): boom", err.Error(); expected != actual {
t.Errorf("expected: %v, actual: %v", expected, actual)
}
tx, err := db.Begin()
if err != nil {
t.Errorf("expected err to be nil: %v", err)
}
tables, err := query.SelectStrings(tx, "SELECT name FROM sqlite_master WHERE type = 'table'")
if err != nil {
t.Errorf("expected err to be nil: %v", err)
}
if expected, actual := "schema", tables; contains(actual, expected) {
t.Errorf("expected: %v, actual: %v", expected, actual)
}
if expected, actual := "test", tables; contains(actual, expected) {
t.Errorf("expected: %v, actual: %v", expected, actual)
}
}
func TestSchemaEnsure_CheckGracefulAbort(t *testing.T) {
check := func(current int, tx database.Tx) error {
_, err := tx.Exec("CREATE TABLE test (n INTEGER)")
if err != nil {
t.Errorf("expected err to be nil: %v", err)
}
return schema.ErrGracefulAbort
}
schema, db := newSchemaAndDB(t)
schema.Add(updateCreateTable)
schema.Check(check)
_, err := schema.Ensure(db)
if expected, actual := "schema check gracefully aborted", err.Error(); expected != actual {
t.Errorf("expected: %v, actual: %v", expected, actual)
}
tx, err := db.Begin()
if err != nil {
t.Errorf("expected err to be nil: %v", err)
}
ids, err := query.SelectIntegers(tx, "SELECT n FROM test")
if err != nil {
t.Errorf("expected err to be nil: %v", err)
}
var want []int
if expected, actual := want, ids; !reflect.DeepEqual(expected, actual) {
t.Errorf("expected: %v, actual: %v", expected, actual)
}
} | Apache License 2.0 |
eeonevision/anychaindb | vendor/github.com/go-kit/kit/metrics/prometheus/prometheus.go | Add | go | func (g *Gauge) Add(delta float64) {
g.gv.With(makeLabels(g.lvs...)).Add(delta)
} | Add is supported by Prometheus GaugeVecs. | https://github.com/eeonevision/anychaindb/blob/eae432a35f903d1b87b7aadda49899d5e3d4478d/vendor/github.com/go-kit/kit/metrics/prometheus/prometheus.go#L83-L85 | package prometheus
import (
"github.com/prometheus/client_golang/prometheus"
"github.com/go-kit/kit/metrics"
"github.com/go-kit/kit/metrics/internal/lv"
)
type Counter struct {
cv *prometheus.CounterVec
lvs lv.LabelValues
}
func NewCounterFrom(opts prometheus.CounterOpts, labelNames []string) *Counter {
cv := prometheus.NewCounterVec(opts, labelNames)
prometheus.MustRegister(cv)
return NewCounter(cv)
}
func NewCounter(cv *prometheus.CounterVec) *Counter {
return &Counter{
cv: cv,
}
}
func (c *Counter) With(labelValues ...string) metrics.Counter {
return &Counter{
cv: c.cv,
lvs: c.lvs.With(labelValues...),
}
}
func (c *Counter) Add(delta float64) {
c.cv.With(makeLabels(c.lvs...)).Add(delta)
}
type Gauge struct {
gv *prometheus.GaugeVec
lvs lv.LabelValues
}
func NewGaugeFrom(opts prometheus.GaugeOpts, labelNames []string) *Gauge {
gv := prometheus.NewGaugeVec(opts, labelNames)
prometheus.MustRegister(gv)
return NewGauge(gv)
}
func NewGauge(gv *prometheus.GaugeVec) *Gauge {
return &Gauge{
gv: gv,
}
}
func (g *Gauge) With(labelValues ...string) metrics.Gauge {
return &Gauge{
gv: g.gv,
lvs: g.lvs.With(labelValues...),
}
}
func (g *Gauge) Set(value float64) {
g.gv.With(makeLabels(g.lvs...)).Set(value)
} | Apache License 2.0 |
google/netstack | tcpip/link/sharedmem/tx.go | getBuffer | go | func getBuffer(fd int) ([]byte, error) {
var s syscall.Stat_t
if err := syscall.Fstat(fd, &s); err != nil {
return nil, err
}
if s.Size > int64(^uint(0)>>1) {
return nil, syscall.EDOM
}
return syscall.Mmap(fd, 0, int(s.Size), syscall.PROT_READ|syscall.PROT_WRITE, syscall.MAP_SHARED|syscall.MAP_FILE)
} | getBuffer returns a memory region mapped to the full contents of the given
file descriptor. | https://github.com/google/netstack/blob/55fcc16cd0eb096d8418f7bc5162483c31a4e82b/tcpip/link/sharedmem/tx.go#L143-L155 | package sharedmem
import (
"math"
"syscall"
"github.com/google/netstack/tcpip/link/sharedmem/queue"
)
const (
nilID = math.MaxUint64
)
type tx struct {
data []byte
q queue.Tx
ids idManager
bufs bufferManager
}
func (t *tx) init(mtu uint32, c *QueueConfig) error {
txPipe, err := getBuffer(c.TxPipeFD)
if err != nil {
return err
}
rxPipe, err := getBuffer(c.RxPipeFD)
if err != nil {
syscall.Munmap(txPipe)
return err
}
data, err := getBuffer(c.DataFD)
if err != nil {
syscall.Munmap(txPipe)
syscall.Munmap(rxPipe)
return err
}
t.q.Init(txPipe, rxPipe)
t.ids.init()
t.bufs.init(0, len(data), int(mtu))
t.data = data
return nil
}
func (t *tx) cleanup() {
a, b := t.q.Bytes()
syscall.Munmap(a)
syscall.Munmap(b)
syscall.Munmap(t.data)
}
func (t *tx) transmit(a, b []byte) bool {
for {
id, ok := t.q.CompletedPacket()
if !ok {
break
}
if buf := t.ids.remove(id); buf != nil {
t.bufs.free(buf)
}
}
bSize := t.bufs.entrySize
total := uint32(len(a) + len(b))
bufCount := (total + bSize - 1) / bSize
var buf *queue.TxBuffer
for i := bufCount; i != 0; i-- {
b := t.bufs.alloc()
if b == nil {
if buf != nil {
t.bufs.free(buf)
}
return false
}
b.Next = buf
buf = b
}
nBuf := buf
var dBuf []byte
for _, data := range [][]byte{a, b} {
for len(data) > 0 {
if len(dBuf) == 0 {
dBuf = t.data[nBuf.Offset:][:nBuf.Size]
nBuf = nBuf.Next
}
n := copy(dBuf, data)
data = data[n:]
dBuf = dBuf[n:]
}
}
id := t.ids.add(buf)
if !t.q.Enqueue(id, total, bufCount, buf) {
t.ids.remove(id)
t.bufs.free(buf)
return false
}
return true
} | Apache License 2.0 |
tommyblue/smugmug-backup | testutil/log.go | LessLogging | go | func LessLogging() (reset func()) {
lvl := logrus.GetLevel()
logrus.SetLevel(logrus.ErrorLevel)
return func() { logrus.SetLevel(lvl) }
} | LessLogging is a test helper that decreases logging (in fact it sets its
level to Error). It returns a function which when called, resets it to its
previous level. Its useful to be called as follows in test/benchmarks:
func TestFoo(t *testing.T) {
defer LessLogging()()
// logging is set to Error for the whole test
} | https://github.com/tommyblue/smugmug-backup/blob/24618148f374b9b8dce66bf341df578edf17ac13/testutil/log.go#L29-L33 | package testutil
import "github.com/sirupsen/logrus"
func DisableLogging() (reset func()) {
lvl := logrus.GetLevel()
logrus.SetLevel(logrus.PanicLevel)
return func() { logrus.SetLevel(lvl) }
} | MIT License |
rajveermalviya/go-wayland | wayland/client/client.go | AddGlobalHandler | go | func (i *Registry) AddGlobalHandler(f RegistryGlobalHandlerFunc) {
if f == nil {
return
}
i.globalHandlers = append(i.globalHandlers, f)
} | AddGlobalHandler : adds handler for RegistryGlobalEvent | https://github.com/rajveermalviya/go-wayland/blob/779b2c59733635e1318f1c0449f00682516d07ab/wayland/client/client.go#L375-L381 | package client
import (
"reflect"
"golang.org/x/sys/unix"
)
type Display struct {
BaseProxy
errorHandlers []DisplayErrorHandlerFunc
deleteIdHandlers []DisplayDeleteIdHandlerFunc
}
func NewDisplay(ctx *Context) *Display {
wlDisplay := &Display{}
ctx.Register(wlDisplay)
return wlDisplay
}
func (i *Display) Sync() (*Callback, error) {
callback := NewCallback(i.Context())
const opcode = 0
const rLen = 8 + 4
r := make([]byte, rLen)
l := 0
PutUint32(r[l:4], i.ID())
l += 4
PutUint32(r[l:l+4], uint32(rLen<<16|opcode&0x0000ffff))
l += 4
PutUint32(r[l:l+4], callback.ID())
l += 4
err := i.Context().WriteMsg(r, nil)
return callback, err
}
func (i *Display) GetRegistry() (*Registry, error) {
registry := NewRegistry(i.Context())
const opcode = 1
const rLen = 8 + 4
r := make([]byte, rLen)
l := 0
PutUint32(r[l:4], i.ID())
l += 4
PutUint32(r[l:l+4], uint32(rLen<<16|opcode&0x0000ffff))
l += 4
PutUint32(r[l:l+4], registry.ID())
l += 4
err := i.Context().WriteMsg(r, nil)
return registry, err
}
func (i *Display) Destroy() error {
i.Context().Unregister(i)
return nil
}
type DisplayError uint32
const (
DisplayErrorInvalidObject DisplayError = 0
DisplayErrorInvalidMethod DisplayError = 1
DisplayErrorNoMemory DisplayError = 2
DisplayErrorImplementation DisplayError = 3
)
func (e DisplayError) Name() string {
switch e {
case DisplayErrorInvalidObject:
return "invalid_object"
case DisplayErrorInvalidMethod:
return "invalid_method"
case DisplayErrorNoMemory:
return "no_memory"
case DisplayErrorImplementation:
return "implementation"
default:
return ""
}
}
func (e DisplayError) Value() string {
switch e {
case DisplayErrorInvalidObject:
return "0"
case DisplayErrorInvalidMethod:
return "1"
case DisplayErrorNoMemory:
return "2"
case DisplayErrorImplementation:
return "3"
default:
return ""
}
}
func (e DisplayError) String() string {
return e.Name() + "=" + e.Value()
}
type DisplayErrorEvent struct {
ObjectId Proxy
Code uint32
Message string
}
type DisplayErrorHandlerFunc func(DisplayErrorEvent)
func (i *Display) AddErrorHandler(f DisplayErrorHandlerFunc) {
if f == nil {
return
}
i.errorHandlers = append(i.errorHandlers, f)
}
func (i *Display) RemoveErrorHandler(f DisplayErrorHandlerFunc) {
for j, e := range i.errorHandlers {
if reflect.ValueOf(e).Pointer() == reflect.ValueOf(f).Pointer() {
i.errorHandlers = append(i.errorHandlers[:j], i.errorHandlers[j+1:]...)
return
}
}
}
type DisplayDeleteIdEvent struct {
Id uint32
}
type DisplayDeleteIdHandlerFunc func(DisplayDeleteIdEvent)
func (i *Display) AddDeleteIdHandler(f DisplayDeleteIdHandlerFunc) {
if f == nil {
return
}
i.deleteIdHandlers = append(i.deleteIdHandlers, f)
}
func (i *Display) RemoveDeleteIdHandler(f DisplayDeleteIdHandlerFunc) {
for j, e := range i.deleteIdHandlers {
if reflect.ValueOf(e).Pointer() == reflect.ValueOf(f).Pointer() {
i.deleteIdHandlers = append(i.deleteIdHandlers[:j], i.deleteIdHandlers[j+1:]...)
return
}
}
}
func (i *Display) Dispatch(opcode uint16, fd uintptr, data []byte) {
switch opcode {
case 0:
if len(i.errorHandlers) == 0 {
return
}
var e DisplayErrorEvent
l := 0
e.ObjectId = i.Context().GetProxy(Uint32(data[l : l+4]))
l += 4
e.Code = Uint32(data[l : l+4])
l += 4
messageLen := PaddedLen(int(Uint32(data[l : l+4])))
l += 4
e.Message = String(data[l : l+messageLen])
l += messageLen
for _, f := range i.errorHandlers {
f(e)
}
case 1:
if len(i.deleteIdHandlers) == 0 {
return
}
var e DisplayDeleteIdEvent
l := 0
e.Id = Uint32(data[l : l+4])
l += 4
for _, f := range i.deleteIdHandlers {
f(e)
}
}
}
type Registry struct {
BaseProxy
globalHandlers []RegistryGlobalHandlerFunc
globalRemoveHandlers []RegistryGlobalRemoveHandlerFunc
}
func NewRegistry(ctx *Context) *Registry {
wlRegistry := &Registry{}
ctx.Register(wlRegistry)
return wlRegistry
}
func (i *Registry) Bind(name uint32, iface string, version uint32, id Proxy) error {
const opcode = 0
ifaceLen := PaddedLen(len(iface) + 1)
rLen := 8 + 4 + (4 + ifaceLen) + 4 + 4
r := make([]byte, rLen)
l := 0
PutUint32(r[l:4], i.ID())
l += 4
PutUint32(r[l:l+4], uint32(rLen<<16|opcode&0x0000ffff))
l += 4
PutUint32(r[l:l+4], uint32(name))
l += 4
PutString(r[l:l+(4+ifaceLen)], iface, ifaceLen)
l += (4 + ifaceLen)
PutUint32(r[l:l+4], uint32(version))
l += 4
PutUint32(r[l:l+4], id.ID())
l += 4
err := i.Context().WriteMsg(r, nil)
return err
}
func (i *Registry) Destroy() error {
i.Context().Unregister(i)
return nil
}
type RegistryGlobalEvent struct {
Name uint32
Interface string
Version uint32
}
type RegistryGlobalHandlerFunc func(RegistryGlobalEvent) | BSD 2-Clause Simplified License |
didi/elastic-trib | vendor/github.com/olivere/elastic/indices_refresh.go | Do | go | func (s *RefreshService) Do(ctx context.Context) (*RefreshResult, error) {
path, params, err := s.buildURL()
if err != nil {
return nil, err
}
res, err := s.client.PerformRequest(ctx, PerformRequestOptions{
Method: "POST",
Path: path,
Params: params,
})
if err != nil {
return nil, err
}
ret := new(RefreshResult)
if err := s.client.decoder.Decode(res.Body, ret); err != nil {
return nil, err
}
return ret, nil
} | Do executes the request. | https://github.com/didi/elastic-trib/blob/e3f6c649e4c165279e4932c4e78b7397eaf49de0/vendor/github.com/olivere/elastic/indices_refresh.go#L69-L91 | package elastic
import (
"context"
"fmt"
"net/url"
"strings"
"github.com/olivere/elastic/uritemplates"
)
type RefreshService struct {
client *Client
index []string
pretty bool
}
func NewRefreshService(client *Client) *RefreshService {
builder := &RefreshService{
client: client,
}
return builder
}
func (s *RefreshService) Index(index ...string) *RefreshService {
s.index = append(s.index, index...)
return s
}
func (s *RefreshService) Pretty(pretty bool) *RefreshService {
s.pretty = pretty
return s
}
func (s *RefreshService) buildURL() (string, url.Values, error) {
var err error
var path string
if len(s.index) > 0 {
path, err = uritemplates.Expand("/{index}/_refresh", map[string]string{
"index": strings.Join(s.index, ","),
})
} else {
path = "/_refresh"
}
if err != nil {
return "", url.Values{}, err
}
params := url.Values{}
if s.pretty {
params.Set("pretty", fmt.Sprintf("%v", s.pretty))
}
return path, params, nil
} | Apache License 2.0 |
jimjibone/goopenzwave | nodes.go | GetNodeMaxBaudRate | go | func GetNodeMaxBaudRate(homeID uint32, nodeID uint8) uint32 {
return uint32(C.manager_getNodeMaxBaudRate(cmanager, C.uint32_t(homeID), C.uint8_t(nodeID)))
} | GetNodeMaxBaudRate returns the maximum baud rate of a node's communications. | https://github.com/jimjibone/goopenzwave/blob/472b2577dc057a9558395277513fe48c7667d9b0/nodes.go#L72-L74 | package goopenzwave
import "C"
import (
"unsafe"
)
func RefreshNodeInfo(homeID uint32, nodeID uint8) bool {
return bool(C.manager_refreshNodeInfo(cmanager, C.uint32_t(homeID), C.uint8_t(nodeID)))
}
func RequestNodeState(homeID uint32, nodeID uint8) bool {
return bool(C.manager_requestNodeState(cmanager, C.uint32_t(homeID), C.uint8_t(nodeID)))
}
func RequestNodeDynamic(homeID uint32, nodeID uint8) bool {
return bool(C.manager_requestNodeDynamic(cmanager, C.uint32_t(homeID), C.uint8_t(nodeID)))
}
func IsNodeListeningDevice(homeID uint32, nodeID uint8) bool {
return bool(C.manager_isNodeListeningDevice(cmanager, C.uint32_t(homeID), C.uint8_t(nodeID)))
}
func IsNodeFrequentListeningDevice(homeID uint32, nodeID uint8) bool {
return bool(C.manager_isNodeFrequentListeningDevice(cmanager, C.uint32_t(homeID), C.uint8_t(nodeID)))
}
func IsNodeBeamingDevice(homeID uint32, nodeID uint8) bool {
return bool(C.manager_isNodeBeamingDevice(cmanager, C.uint32_t(homeID), C.uint8_t(nodeID)))
}
func IsNodeRoutingDevice(homeID uint32, nodeID uint8) bool {
return bool(C.manager_isNodeRoutingDevice(cmanager, C.uint32_t(homeID), C.uint8_t(nodeID)))
}
func IsNodeSecurityDevice(homeID uint32, nodeID uint8) bool {
return bool(C.manager_isNodeSecurityDevice(cmanager, C.uint32_t(homeID), C.uint8_t(nodeID)))
} | MIT License |
skx/monkey | ast/ast.go | String | go | func (fes *ForeachStatement) String() string {
var out bytes.Buffer
out.WriteString("foreach ")
out.WriteString(fes.Ident)
out.WriteString(" ")
out.WriteString(fes.Value.String())
out.WriteString(fes.Body.String())
return out.String()
} | String returns this object as a string. | https://github.com/skx/monkey/blob/0152ee96098dc0374f43d6bb9e3dd917aa0f3e91/ast/ast.go#L437-L445 | package ast
import (
"bytes"
"fmt"
"strings"
"github.com/skx/monkey/token"
)
type Node interface {
TokenLiteral() string
String() string
}
type Statement interface {
Node
statementNode()
}
type Expression interface {
Node
expressionNode()
}
type Program struct {
Statements []Statement
}
func (p *Program) TokenLiteral() string {
if len(p.Statements) > 0 {
return p.Statements[0].TokenLiteral()
}
return ""
}
func (p *Program) String() string {
var out bytes.Buffer
for _, stmt := range p.Statements {
out.WriteString(stmt.String())
}
return out.String()
}
type LetStatement struct {
Token token.Token
Name *Identifier
Value Expression
}
func (ls *LetStatement) statementNode() {}
func (ls *LetStatement) TokenLiteral() string { return ls.Token.Literal }
func (ls *LetStatement) String() string {
var out bytes.Buffer
out.WriteString(ls.TokenLiteral() + " ")
out.WriteString(ls.Name.TokenLiteral())
out.WriteString(" = ")
if ls.Value != nil {
out.WriteString(ls.Value.String())
}
out.WriteString(";")
return out.String()
}
type ConstStatement struct {
Token token.Token
Name *Identifier
Value Expression
}
func (ls *ConstStatement) statementNode() {}
func (ls *ConstStatement) TokenLiteral() string { return ls.Token.Literal }
func (ls *ConstStatement) String() string {
var out bytes.Buffer
out.WriteString(ls.TokenLiteral() + " ")
out.WriteString(ls.Name.TokenLiteral())
out.WriteString(" = ")
if ls.Value != nil {
out.WriteString(ls.Value.String())
}
out.WriteString(";")
return out.String()
}
type Identifier struct {
Token token.Token
Value string
}
func (i *Identifier) expressionNode() {}
func (i *Identifier) TokenLiteral() string { return i.Token.Literal }
func (i *Identifier) String() string {
return i.Value
}
type ReturnStatement struct {
Token token.Token
ReturnValue Expression
}
func (rs *ReturnStatement) statementNode() {}
func (rs *ReturnStatement) TokenLiteral() string { return rs.Token.Literal }
func (rs *ReturnStatement) String() string {
var out bytes.Buffer
out.WriteString(rs.TokenLiteral() + " ")
if rs.ReturnValue != nil {
out.WriteString(rs.ReturnValue.TokenLiteral())
}
out.WriteString(";")
return out.String()
}
type ExpressionStatement struct {
Token token.Token
Expression Expression
}
func (es *ExpressionStatement) statementNode() {}
func (es *ExpressionStatement) TokenLiteral() string { return es.Token.Literal }
func (es *ExpressionStatement) String() string {
if es.Expression != nil {
return es.Expression.String()
}
return ""
}
type IntegerLiteral struct {
Token token.Token
Value int64
}
func (il *IntegerLiteral) expressionNode() {}
func (il *IntegerLiteral) TokenLiteral() string { return il.Token.Literal }
func (il *IntegerLiteral) String() string { return il.Token.Literal }
type FloatLiteral struct {
Token token.Token
Value float64
}
func (fl *FloatLiteral) expressionNode() {}
func (fl *FloatLiteral) TokenLiteral() string { return fl.Token.Literal }
func (fl *FloatLiteral) String() string { return fl.Token.Literal }
type PrefixExpression struct {
Token token.Token
Operator string
Right Expression
}
func (pe *PrefixExpression) expressionNode() {}
func (pe *PrefixExpression) TokenLiteral() string { return pe.Token.Literal }
func (pe *PrefixExpression) String() string {
var out bytes.Buffer
out.WriteString("(")
out.WriteString(pe.Operator)
out.WriteString(pe.Right.String())
out.WriteString(")")
return out.String()
}
type InfixExpression struct {
Token token.Token
Left Expression
Operator string
Right Expression
}
func (ie *InfixExpression) expressionNode() {}
func (ie *InfixExpression) TokenLiteral() string { return ie.Token.Literal }
func (ie *InfixExpression) String() string {
var out bytes.Buffer
out.WriteString("(")
out.WriteString(ie.Left.String())
out.WriteString(" " + ie.Operator + " ")
out.WriteString(ie.Right.String())
out.WriteString(")")
return out.String()
}
type PostfixExpression struct {
Token token.Token
Operator string
}
func (pe *PostfixExpression) expressionNode() {}
func (pe *PostfixExpression) TokenLiteral() string { return pe.Token.Literal }
func (pe *PostfixExpression) String() string {
var out bytes.Buffer
out.WriteString("(")
out.WriteString(pe.Token.Literal)
out.WriteString(pe.Operator)
out.WriteString(")")
return out.String()
}
type NullLiteral struct {
Token token.Token
}
func (n *NullLiteral) expressionNode() {}
func (n *NullLiteral) TokenLiteral() string { return n.Token.Literal }
func (n *NullLiteral) String() string { return n.Token.Literal }
type Boolean struct {
Token token.Token
Value bool
}
func (b *Boolean) expressionNode() {}
func (b *Boolean) TokenLiteral() string { return b.Token.Literal }
func (b *Boolean) String() string { return b.Token.Literal }
type BlockStatement struct {
Token token.Token
Statements []Statement
}
func (bs *BlockStatement) statementNode() {}
func (bs *BlockStatement) TokenLiteral() string { return bs.Token.Literal }
func (bs *BlockStatement) String() string {
var out bytes.Buffer
for _, s := range bs.Statements {
out.WriteString(s.String())
}
return out.String()
}
type IfExpression struct {
Token token.Token
Condition Expression
Consequence *BlockStatement
Alternative *BlockStatement
}
func (ie *IfExpression) expressionNode() {}
func (ie *IfExpression) TokenLiteral() string { return ie.Token.Literal }
func (ie *IfExpression) String() string {
var out bytes.Buffer
out.WriteString("if")
out.WriteString(ie.Condition.String())
out.WriteString(" ")
out.WriteString(ie.Consequence.String())
if ie.Alternative != nil {
out.WriteString("else")
out.WriteString(ie.Alternative.String())
}
return out.String()
}
type TernaryExpression struct {
Token token.Token
Condition Expression
IfTrue Expression
IfFalse Expression
}
type ForeachStatement struct {
Token token.Token
Index string
Ident string
Value Expression
Body *BlockStatement
}
func (fes *ForeachStatement) expressionNode() {}
func (fes *ForeachStatement) TokenLiteral() string { return fes.Token.Literal } | MIT License |
alcacoop/go-github-client | gists/gist.go | IsValid | go | func (cgd *GistDataUpdate) IsValid() bool {
return true
} | validate gists update payload | https://github.com/alcacoop/go-github-client/blob/ee461c44e44389d8f06c1827d7de71b7a90324b1/gists/gist.go#L74-L77 | package gists
import (
"bytes"
"encoding/json"
"errors"
ghclient "github.com/alcacoop/go-github-client/client"
"net/http"
)
var (
ErrInvalidGistDataCreate = errors.New("Invalid or nil Create Gist Data")
ErrInvalidGistDataUpdate = errors.New("Invalid or nil Update Gist Data")
)
func (ghc *Gists) GetGist(gistId string) (res *ghclient.GithubResult, err error) {
req, err := ghc.NewAPIRequest("GET", "gists/"+gistId, nil)
if err != nil {
return
}
httpc := new(http.Client)
res, err = ghc.RunRequest(req, httpc)
return
}
type GistDataCreate struct {
Description string `json:"description,omitempty"`
Public bool `json:"public"`
Files map[string]GistFileContent `json:"files"`
}
func NewGistDataCreate() *GistDataCreate {
data := new(GistDataCreate)
data.Files = make(map[string]GistFileContent)
return data
}
func (cgd *GistDataCreate) IsValid() bool {
return true
}
type GistDataUpdate struct {
Description string `json:"description,omitempty"`
Files map[string]GistFileContent `json:"files"`
}
func NewGistDataUpdate() *GistDataUpdate {
data := new(GistDataUpdate)
data.Files = make(map[string]GistFileContent)
return data
} | BSD 3-Clause New or Revised License |
mattkanwisher/cryptofiend | exchanges/bitfinex/bitfinex.go | GetTrades | go | func (b *Bitfinex) GetTrades(currencyPair string, values url.Values) ([]TradeStructure, error) {
response := []TradeStructure{}
path := common.EncodeURLValues(
bitfinexAPIURL+bitfinexTrades+currencyPair,
values,
)
return response, common.SendHTTPGetRequest(path, true, b.Verbose, &response)
} | GetTrades returns a list of the most recent trades for the given curencyPair
By default the response will return 100 trades
CurrencyPair - Example "BTCUSD"
Values can contain limit amounts for the number of trades returned - Example
"limit_trades" = 1000 | https://github.com/mattkanwisher/cryptofiend/blob/e477184ca4d13d3d372443bcee92c90697decd63/exchanges/bitfinex/bitfinex.go#L261-L268 | package bitfinex
import (
"errors"
"fmt"
"log"
"net/http"
"net/url"
"reflect"
"strconv"
"strings"
"time"
"github.com/gorilla/websocket"
"github.com/mattkanwisher/cryptofiend/common"
"github.com/mattkanwisher/cryptofiend/config"
"github.com/mattkanwisher/cryptofiend/currency/pair"
"github.com/mattkanwisher/cryptofiend/exchanges"
"github.com/mattkanwisher/cryptofiend/exchanges/orderbook"
"github.com/mattkanwisher/cryptofiend/exchanges/ticker"
)
const (
bitfinexAPIURL = "https://api.bitfinex.com/v1/"
bitfinexAPIVersion1 uint8 = 1
bitfinexTicker = "pubticker/"
bitfinexStats = "stats/"
bitfinexLendbook = "lendbook/"
bitfinexOrderbook = "book/"
bitfinexTrades = "trades/"
bitfinexKeyPermissions = "key_info"
bitfinexLends = "lends/"
bitfinexSymbols = "symbols/"
bitfinexSymbolsDetails = "symbols_details/"
bitfinexAccountInfo = "account_infos"
bitfinexAccountFees = "account_fees"
bitfinexAccountSummary = "summary"
bitfinexDeposit = "deposit/new"
bitfinexOrderNew = "order/new"
bitfinexOrderNewMulti = "order/new/multi"
bitfinexOrderCancel = "order/cancel"
bitfinexOrderCancelMulti = "order/cancel/multi"
bitfinexOrderCancelAll = "order/cancel/all"
bitfinexOrderCancelReplace = "order/cancel/replace"
bitfinexOrderStatus = "order/status"
bitfinexOrders = "orders"
bitfinexPositions = "positions"
bitfinexClaimPosition = "position/claim"
bitfinexHistory = "history"
bitfinexHistoryMovements = "history/movements"
bitfinexTradeHistory = "mytrades"
bitfinexOfferNew = "offer/new"
bitfinexOfferCancel = "offer/cancel"
bitfinexOfferStatus = "offer/status"
bitfinexOffers = "offers"
bitfinexMarginActiveFunds = "taken_funds"
bitfinexMarginTotalFunds = "total_taken_funds"
bitfinexMarginUnusedFunds = "unused_taken_funds"
bitfinexMarginClose = "funding/close"
bitfinexBalances = "balances"
bitfinexMarginInfo = "margin_infos"
bitfinexTransfer = "transfer"
bitfinexWithdrawal = "withdraw"
bitfinexActiveCredits = "credits"
bitfinexAPI2URL = "https://api.bitfinex.com/v2/"
bitfinexAPIVersion2 uint8 = 2
bitfinexCalcAvailableBalance = "auth/calc/order/avail"
bitfinexMaxRequests = 90
)
const (
InvalidAPIKeyErrCode = 10100
MaintenanceErrCode = 20060
)
var errRateLimit = errors.New("ERR_RATE_LIMIT")
type Bitfinex struct {
exchange.Base
WebsocketConn *websocket.Conn
WebsocketSubdChannels map[int]WebsocketChanInfo
currencyPairs map[pair.CurrencyItem]*exchange.CurrencyPairInfo
symbolDetails map[pair.CurrencyItem]*SymbolDetails
rateLimits map[string]int64
ipBanStartTime int64
lastBalances []Balance
lastActiveOrders []Order
}
func (b *Bitfinex) SetDefaults() {
b.Name = "Bitfinex"
b.Enabled = false
b.Verbose = false
b.Websocket = false
b.RESTPollingDelay = 10
b.WebsocketSubdChannels = make(map[int]WebsocketChanInfo)
b.RequestCurrencyPairFormat.Delimiter = ""
b.RequestCurrencyPairFormat.Uppercase = true
b.ConfigCurrencyPairFormat.Delimiter = ""
b.ConfigCurrencyPairFormat.Uppercase = true
b.AssetTypes = []string{ticker.Spot}
b.Orderbooks = orderbook.Init()
b.rateLimits = map[string]int64{}
b.lastBalances = []Balance{}
b.lastActiveOrders = []Order{}
}
func (b *Bitfinex) Setup(exch config.ExchangeConfig) {
if !exch.Enabled {
b.SetEnabled(false)
} else {
b.Enabled = true
b.AuthenticatedAPISupport = exch.AuthenticatedAPISupport
b.SetAPIKeys(exch.APIKey, exch.APISecret, "", false)
b.RESTPollingDelay = exch.RESTPollingDelay
b.Verbose = exch.Verbose
b.Websocket = exch.Websocket
b.BaseCurrencies = common.SplitStrings(exch.BaseCurrencies, ",")
b.AvailablePairs = common.SplitStrings(exch.AvailablePairs, ",")
b.EnabledPairs = common.SplitStrings(exch.EnabledPairs, ",")
err := b.SetCurrencyPairFormat()
if err != nil {
log.Fatal(err)
}
err = b.SetAssetTypes()
if err != nil {
log.Fatal(err)
}
}
}
func (b *Bitfinex) CurrencyPairToSymbol(p pair.CurrencyPair) string {
return p.
Display(b.RequestCurrencyPairFormat.Delimiter, b.RequestCurrencyPairFormat.Uppercase).
String()
}
func (b *Bitfinex) SymbolToCurrencyPair(symbol string) (pair.CurrencyPair, error) {
if len(symbol) != 6 {
return pair.CurrencyPair{}, fmt.Errorf("symbol %s is longer than expected", symbol)
}
p := pair.NewCurrencyPair(symbol[0:3], symbol[3:])
return p.FormatPair(b.RequestCurrencyPairFormat.Delimiter, b.RequestCurrencyPairFormat.Uppercase), nil
}
type currencyLimits struct {
exchangeName string
data map[pair.CurrencyItem]*SymbolDetails
}
func newCurrencyLimits(exchangeName string, data map[pair.CurrencyItem]*SymbolDetails) *currencyLimits {
return ¤cyLimits{exchangeName, data}
}
func (cl *currencyLimits) GetPriceDecimalPlaces(p pair.CurrencyPair) int32 {
k := p.Display("/", false)
if v, exists := cl.data[k]; exists {
return int32(v.PricePrecision)
}
return 0
}
func (cl *currencyLimits) GetAmountDecimalPlaces(p pair.CurrencyPair) int32 {
return 8
}
func (cl *currencyLimits) GetMinAmount(p pair.CurrencyPair) float64 {
k := p.Display("/", false)
if v, exists := cl.data[k]; exists {
return v.MinimumOrderSize
}
return 0
}
func (cl *currencyLimits) GetMinTotal(p pair.CurrencyPair) float64 {
return 0
}
func (b *Bitfinex) GetLimits() exchange.ILimits {
return newCurrencyLimits(b.Name, b.symbolDetails)
}
func (b *Bitfinex) GetCurrencyPairs() map[pair.CurrencyItem]*exchange.CurrencyPairInfo {
return b.currencyPairs
}
func (b *Bitfinex) GetTicker(symbol string, values url.Values) (Ticker, error) {
response := Ticker{}
path := common.EncodeURLValues(bitfinexAPIURL+bitfinexTicker+symbol, values)
return response, common.SendHTTPGetRequest(path, true, b.Verbose, &response)
}
func (b *Bitfinex) GetStats(symbol string) ([]Stat, error) {
response := []Stat{}
path := fmt.Sprint(bitfinexAPIURL + bitfinexStats + symbol)
return response, common.SendHTTPGetRequest(path, true, b.Verbose, &response)
}
func (b *Bitfinex) GetFundingBook(symbol string) (FundingBook, error) {
response := FundingBook{}
path := fmt.Sprint(bitfinexAPIURL + bitfinexLendbook + symbol)
return response, common.SendHTTPGetRequest(path, true, b.Verbose, &response)
}
func (b *Bitfinex) GetOrderbook(currencyPair string, values url.Values) (Orderbook, error) {
response := Orderbook{}
path := common.EncodeURLValues(
bitfinexAPIURL+bitfinexOrderbook+currencyPair,
values,
)
return response, common.SendHTTPGetRequest(path, true, b.Verbose, &response)
} | MIT License |
cloudevents/sdk-go | protocol/amqp/v2/protocol.go | NewProtocol | go | func NewProtocol(server, queue string, connOption []amqp.ConnOption, sessionOption []amqp.SessionOption, opts ...Option) (*Protocol, error) {
client, err := amqp.Dial(server, connOption...)
if err != nil {
return nil, err
}
session, err := client.NewSession(sessionOption...)
if err != nil {
_ = client.Close()
return nil, err
}
p, err := NewProtocolFromClient(client, session, queue, opts...)
if err != nil {
return nil, err
}
p.ownedClient = true
return p, nil
} | NewProtocol creates a new amqp transport. | https://github.com/cloudevents/sdk-go/blob/7fe4b6a59cd9963cfc9430d1df0770d22dc1745d/protocol/amqp/v2/protocol.go#L72-L92 | package amqp
import (
"context"
"github.com/Azure/go-amqp"
"github.com/cloudevents/sdk-go/v2/binding"
"github.com/cloudevents/sdk-go/v2/protocol"
)
type Protocol struct {
connOpts []amqp.ConnOption
sessionOpts []amqp.SessionOption
senderLinkOpts []amqp.LinkOption
receiverLinkOpts []amqp.LinkOption
Client *amqp.Client
Session *amqp.Session
ownedClient bool
Node string
Sender *sender
SenderContextDecorators []func(context.Context) context.Context
Receiver *receiver
}
func NewProtocolFromClient(client *amqp.Client, session *amqp.Session, queue string, opts ...Option) (*Protocol, error) {
t := &Protocol{
Node: queue,
senderLinkOpts: []amqp.LinkOption(nil),
receiverLinkOpts: []amqp.LinkOption(nil),
Client: client,
Session: session,
}
if err := t.applyOptions(opts...); err != nil {
return nil, err
}
t.senderLinkOpts = append(t.senderLinkOpts, amqp.LinkTargetAddress(queue))
amqpSender, err := session.NewSender(t.senderLinkOpts...)
if err != nil {
_ = client.Close()
_ = session.Close(context.Background())
return nil, err
}
t.Sender = NewSender(amqpSender).(*sender)
t.SenderContextDecorators = []func(context.Context) context.Context{}
t.receiverLinkOpts = append(t.receiverLinkOpts, amqp.LinkSourceAddress(t.Node))
amqpReceiver, err := t.Session.NewReceiver(t.receiverLinkOpts...)
if err != nil {
return nil, err
}
t.Receiver = NewReceiver(amqpReceiver).(*receiver)
return t, nil
} | Apache License 2.0 |
eeonevision/anychaindb | vendor/github.com/tendermint/tendermint/rpc/lib/server/handlers.go | jsonParamsToArgsWS | go | func jsonParamsToArgsWS(rpcFunc *RPCFunc, cdc *amino.Codec, params json.RawMessage, wsCtx types.WSRPCContext) ([]reflect.Value, error) {
values, err := jsonParamsToArgs(rpcFunc, cdc, params, 1)
if err != nil {
return nil, err
}
return append([]reflect.Value{reflect.ValueOf(wsCtx)}, values...), nil
} | Same as above, but with the first param the websocket connection | https://github.com/eeonevision/anychaindb/blob/eae432a35f903d1b87b7aadda49899d5e3d4478d/vendor/github.com/tendermint/tendermint/rpc/lib/server/handlers.go#L241-L247 | package rpcserver
import (
"bytes"
"context"
"encoding/hex"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"reflect"
"runtime/debug"
"sort"
"strings"
"time"
"github.com/gorilla/websocket"
"github.com/pkg/errors"
amino "github.com/tendermint/go-amino"
cmn "github.com/tendermint/tendermint/libs/common"
"github.com/tendermint/tendermint/libs/log"
types "github.com/tendermint/tendermint/rpc/lib/types"
)
func RegisterRPCFuncs(mux *http.ServeMux, funcMap map[string]*RPCFunc, cdc *amino.Codec, logger log.Logger) {
for funcName, rpcFunc := range funcMap {
mux.HandleFunc("/"+funcName, makeHTTPHandler(rpcFunc, cdc, logger))
}
mux.HandleFunc("/", handleInvalidJSONRPCPaths(makeJSONRPCHandler(funcMap, cdc, logger)))
}
type RPCFunc struct {
f reflect.Value
args []reflect.Type
returns []reflect.Type
argNames []string
ws bool
}
func NewRPCFunc(f interface{}, args string) *RPCFunc {
return newRPCFunc(f, args, false)
}
func NewWSRPCFunc(f interface{}, args string) *RPCFunc {
return newRPCFunc(f, args, true)
}
func newRPCFunc(f interface{}, args string, ws bool) *RPCFunc {
var argNames []string
if args != "" {
argNames = strings.Split(args, ",")
}
return &RPCFunc{
f: reflect.ValueOf(f),
args: funcArgTypes(f),
returns: funcReturnTypes(f),
argNames: argNames,
ws: ws,
}
}
func funcArgTypes(f interface{}) []reflect.Type {
t := reflect.TypeOf(f)
n := t.NumIn()
typez := make([]reflect.Type, n)
for i := 0; i < n; i++ {
typez[i] = t.In(i)
}
return typez
}
func funcReturnTypes(f interface{}) []reflect.Type {
t := reflect.TypeOf(f)
n := t.NumOut()
typez := make([]reflect.Type, n)
for i := 0; i < n; i++ {
typez[i] = t.Out(i)
}
return typez
}
func makeJSONRPCHandler(funcMap map[string]*RPCFunc, cdc *amino.Codec, logger log.Logger) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
b, err := ioutil.ReadAll(r.Body)
if err != nil {
WriteRPCResponseHTTP(w, types.RPCInvalidRequestError("", errors.Wrap(err, "Error reading request body")))
return
}
if len(b) == 0 {
writeListOfEndpoints(w, r, funcMap)
return
}
var request types.RPCRequest
err = json.Unmarshal(b, &request)
if err != nil {
WriteRPCResponseHTTP(w, types.RPCParseError("", errors.Wrap(err, "Error unmarshalling request")))
return
}
if request.ID == "" {
logger.Debug("HTTPJSONRPC received a notification, skipping... (please send a non-empty ID if you want to call a method)")
return
}
if len(r.URL.Path) > 1 {
WriteRPCResponseHTTP(w, types.RPCInvalidRequestError(request.ID, errors.Errorf("Path %s is invalid", r.URL.Path)))
return
}
rpcFunc := funcMap[request.Method]
if rpcFunc == nil || rpcFunc.ws {
WriteRPCResponseHTTP(w, types.RPCMethodNotFoundError(request.ID))
return
}
var args []reflect.Value
if len(request.Params) > 0 {
args, err = jsonParamsToArgsRPC(rpcFunc, cdc, request.Params)
if err != nil {
WriteRPCResponseHTTP(w, types.RPCInvalidParamsError(request.ID, errors.Wrap(err, "Error converting json params to arguments")))
return
}
}
returns := rpcFunc.f.Call(args)
logger.Info("HTTPJSONRPC", "method", request.Method, "args", args, "returns", returns)
result, err := unreflectResult(returns)
if err != nil {
WriteRPCResponseHTTP(w, types.RPCInternalError(request.ID, err))
return
}
WriteRPCResponseHTTP(w, types.NewRPCSuccessResponse(cdc, request.ID, result))
}
}
func handleInvalidJSONRPCPaths(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/" {
http.NotFound(w, r)
return
}
next(w, r)
}
}
func mapParamsToArgs(rpcFunc *RPCFunc, cdc *amino.Codec, params map[string]json.RawMessage, argsOffset int) ([]reflect.Value, error) {
values := make([]reflect.Value, len(rpcFunc.argNames))
for i, argName := range rpcFunc.argNames {
argType := rpcFunc.args[i+argsOffset]
if p, ok := params[argName]; ok && p != nil && len(p) > 0 {
val := reflect.New(argType)
err := cdc.UnmarshalJSON(p, val.Interface())
if err != nil {
return nil, err
}
values[i] = val.Elem()
} else {
values[i] = reflect.Zero(argType)
}
}
return values, nil
}
func arrayParamsToArgs(rpcFunc *RPCFunc, cdc *amino.Codec, params []json.RawMessage, argsOffset int) ([]reflect.Value, error) {
if len(rpcFunc.argNames) != len(params) {
return nil, errors.Errorf("Expected %v parameters (%v), got %v (%v)",
len(rpcFunc.argNames), rpcFunc.argNames, len(params), params)
}
values := make([]reflect.Value, len(params))
for i, p := range params {
argType := rpcFunc.args[i+argsOffset]
val := reflect.New(argType)
err := cdc.UnmarshalJSON(p, val.Interface())
if err != nil {
return nil, err
}
values[i] = val.Elem()
}
return values, nil
}
func jsonParamsToArgs(rpcFunc *RPCFunc, cdc *amino.Codec, raw []byte, argsOffset int) ([]reflect.Value, error) {
var m map[string]json.RawMessage
err := json.Unmarshal(raw, &m)
if err == nil {
return mapParamsToArgs(rpcFunc, cdc, m, argsOffset)
}
var a []json.RawMessage
err = json.Unmarshal(raw, &a)
if err == nil {
return arrayParamsToArgs(rpcFunc, cdc, a, argsOffset)
}
return nil, errors.Errorf("Unknown type for JSON params: %v. Expected map or array", err)
}
func jsonParamsToArgsRPC(rpcFunc *RPCFunc, cdc *amino.Codec, params json.RawMessage) ([]reflect.Value, error) {
return jsonParamsToArgs(rpcFunc, cdc, params, 0)
} | Apache License 2.0 |
vardius/pubsub | mock_proto/mock.go | CloseSend | go | func (mr *MockPubSub_SubscribeClientMockRecorder) CloseSend() *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CloseSend", reflect.TypeOf((*MockPubSub_SubscribeClient)(nil).CloseSend))
} | CloseSend indicates an expected call of CloseSend | https://github.com/vardius/pubsub/blob/ba0dfbf84817d50828b40aec7cd32d13ef8f34fb/mock_proto/mock.go#L157-L160 | package mock_proto
import (
context "context"
reflect "reflect"
gomock "github.com/golang/mock/gomock"
empty "github.com/golang/protobuf/ptypes/empty"
proto "github.com/vardius/pubsub/v2/proto"
grpc "google.golang.org/grpc"
metadata "google.golang.org/grpc/metadata"
)
type MockPubSubClient struct {
ctrl *gomock.Controller
recorder *MockPubSubClientMockRecorder
}
type MockPubSubClientMockRecorder struct {
mock *MockPubSubClient
}
func NewMockPubSubClient(ctrl *gomock.Controller) *MockPubSubClient {
mock := &MockPubSubClient{ctrl: ctrl}
mock.recorder = &MockPubSubClientMockRecorder{mock}
return mock
}
func (m *MockPubSubClient) EXPECT() *MockPubSubClientMockRecorder {
return m.recorder
}
func (m *MockPubSubClient) Publish(ctx context.Context, in *proto.PublishRequest, opts ...grpc.CallOption) (*empty.Empty, error) {
m.ctrl.T.Helper()
varargs := []interface{}{ctx, in}
for _, a := range opts {
varargs = append(varargs, a)
}
ret := m.ctrl.Call(m, "Publish", varargs...)
ret0, _ := ret[0].(*empty.Empty)
ret1, _ := ret[1].(error)
return ret0, ret1
}
func (mr *MockPubSubClientMockRecorder) Publish(ctx, in interface{}, opts ...interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
varargs := append([]interface{}{ctx, in}, opts...)
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Publish", reflect.TypeOf((*MockPubSubClient)(nil).Publish), varargs...)
}
func (m *MockPubSubClient) Subscribe(ctx context.Context, in *proto.SubscribeRequest, opts ...grpc.CallOption) (proto.PubSub_SubscribeClient, error) {
m.ctrl.T.Helper()
varargs := []interface{}{ctx, in}
for _, a := range opts {
varargs = append(varargs, a)
}
ret := m.ctrl.Call(m, "Subscribe", varargs...)
ret0, _ := ret[0].(proto.PubSub_SubscribeClient)
ret1, _ := ret[1].(error)
return ret0, ret1
}
func (mr *MockPubSubClientMockRecorder) Subscribe(ctx, in interface{}, opts ...interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
varargs := append([]interface{}{ctx, in}, opts...)
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Subscribe", reflect.TypeOf((*MockPubSubClient)(nil).Subscribe), varargs...)
}
type MockPubSub_SubscribeClient struct {
ctrl *gomock.Controller
recorder *MockPubSub_SubscribeClientMockRecorder
}
type MockPubSub_SubscribeClientMockRecorder struct {
mock *MockPubSub_SubscribeClient
}
func NewMockPubSub_SubscribeClient(ctrl *gomock.Controller) *MockPubSub_SubscribeClient {
mock := &MockPubSub_SubscribeClient{ctrl: ctrl}
mock.recorder = &MockPubSub_SubscribeClientMockRecorder{mock}
return mock
}
func (m *MockPubSub_SubscribeClient) EXPECT() *MockPubSub_SubscribeClientMockRecorder {
return m.recorder
}
func (m *MockPubSub_SubscribeClient) Recv() (*proto.SubscribeResponse, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "Recv")
ret0, _ := ret[0].(*proto.SubscribeResponse)
ret1, _ := ret[1].(error)
return ret0, ret1
}
func (mr *MockPubSub_SubscribeClientMockRecorder) Recv() *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Recv", reflect.TypeOf((*MockPubSub_SubscribeClient)(nil).Recv))
}
func (m *MockPubSub_SubscribeClient) Header() (metadata.MD, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "Header")
ret0, _ := ret[0].(metadata.MD)
ret1, _ := ret[1].(error)
return ret0, ret1
}
func (mr *MockPubSub_SubscribeClientMockRecorder) Header() *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Header", reflect.TypeOf((*MockPubSub_SubscribeClient)(nil).Header))
}
func (m *MockPubSub_SubscribeClient) Trailer() metadata.MD {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "Trailer")
ret0, _ := ret[0].(metadata.MD)
return ret0
}
func (mr *MockPubSub_SubscribeClientMockRecorder) Trailer() *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Trailer", reflect.TypeOf((*MockPubSub_SubscribeClient)(nil).Trailer))
}
func (m *MockPubSub_SubscribeClient) CloseSend() error {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "CloseSend")
ret0, _ := ret[0].(error)
return ret0
} | MIT License |
kudoochui/kudos | component/web/options.go | CloseTimeout | go | func CloseTimeout(t time.Duration) Option {
return func(options *Options) {
options.CloseTimeout = t
}
} | Deadline to wait for closing. Default is 5s | https://github.com/kudoochui/kudos/blob/2f1c6d5672da4d23423eb9e6134ea5214c35d504/component/web/options.go#L68-L72 | package web
import "time"
type Option func(*Options)
type Options struct {
ListenIp string
ListenPort int
WriteTimeout time.Duration
ReadTimeout time.Duration
IdleTimeout time.Duration
CloseTimeout time.Duration
}
func newOptions(opts ...Option) *Options {
opt := &Options{
ListenIp: "0.0.0.0",
ListenPort: 5050,
WriteTimeout: 15 * time.Second,
ReadTimeout: 15 * time.Second,
IdleTimeout: 60 * time.Second,
CloseTimeout: 5 * time.Second,
}
for _,o := range opts {
o(opt)
}
return opt
}
func ListenIp(ip string) Option {
return func(options *Options) {
options.ListenIp = ip
}
}
func ListenPort(port int) Option {
return func(options *Options) {
options.ListenPort = port
}
}
func WriteTimeout(t time.Duration) Option {
return func(options *Options) {
options.WriteTimeout = t
}
}
func ReadTimeout(t time.Duration) Option {
return func(options *Options) {
options.ReadTimeout = t
}
}
func IdleTimeout(t time.Duration) Option {
return func(options *Options) {
options.IdleTimeout = t
}
} | MIT License |
percolate/charlatan | vendor/golang.org/x/tools/go/ssa/const.go | Int64 | go | func (c *Const) Int64() int64 {
switch x := exact.ToInt(c.Value); x.Kind() {
case exact.Int:
if i, ok := exact.Int64Val(x); ok {
return i
}
return 0
case exact.Float:
f, _ := exact.Float64Val(x)
return int64(f)
}
panic(fmt.Sprintf("unexpected constant value: %T", c.Value))
} | TODO(adonovan): move everything below into golang.org/x/tools/go/ssa/interp.
Int64 returns the numeric value of this constant truncated to fit
a signed 64-bit integer. | https://github.com/percolate/charlatan/blob/4afb7ccdf1b988c863100c983c305b8891b45dce/vendor/golang.org/x/tools/go/ssa/const.go#L123-L135 | package ssa
import (
"fmt"
exact "go/constant"
"go/token"
"go/types"
"strconv"
)
func NewConst(val exact.Value, typ types.Type) *Const {
return &Const{typ, val}
}
func intConst(i int64) *Const {
return NewConst(exact.MakeInt64(i), tInt)
}
func nilConst(typ types.Type) *Const {
return NewConst(nil, typ)
}
func stringConst(s string) *Const {
return NewConst(exact.MakeString(s), tString)
}
func zeroConst(t types.Type) *Const {
switch t := t.(type) {
case *types.Basic:
switch {
case t.Info()&types.IsBoolean != 0:
return NewConst(exact.MakeBool(false), t)
case t.Info()&types.IsNumeric != 0:
return NewConst(exact.MakeInt64(0), t)
case t.Info()&types.IsString != 0:
return NewConst(exact.MakeString(""), t)
case t.Kind() == types.UnsafePointer:
fallthrough
case t.Kind() == types.UntypedNil:
return nilConst(t)
default:
panic(fmt.Sprint("zeroConst for unexpected type:", t))
}
case *types.Pointer, *types.Slice, *types.Interface, *types.Chan, *types.Map, *types.Signature:
return nilConst(t)
case *types.Named:
return NewConst(zeroConst(t.Underlying()).Value, t)
case *types.Array, *types.Struct, *types.Tuple:
panic(fmt.Sprint("zeroConst applied to aggregate:", t))
}
panic(fmt.Sprint("zeroConst: unexpected ", t))
}
func (c *Const) RelString(from *types.Package) string {
var s string
if c.Value == nil {
s = "nil"
} else if c.Value.Kind() == exact.String {
s = exact.StringVal(c.Value)
const max = 20
if len(s) > max {
s = s[:max-3] + "..."
}
s = strconv.Quote(s)
} else {
s = c.Value.String()
}
return s + ":" + relType(c.Type(), from)
}
func (c *Const) Name() string {
return c.RelString(nil)
}
func (c *Const) String() string {
return c.Name()
}
func (c *Const) Type() types.Type {
return c.typ
}
func (c *Const) Referrers() *[]Instruction {
return nil
}
func (c *Const) Parent() *Function { return nil }
func (c *Const) Pos() token.Pos {
return token.NoPos
}
func (c *Const) IsNil() bool {
return c.Value == nil
} | BSD 3-Clause New or Revised License |
tibcosoftware/tgdb-client | api/go/src/tgdb/impl/modelimpl.go | GetGraphMetadata | go | func (obj *Graph) GetGraphMetadata() tgdb.TGGraphMetadata {
return obj.getGraphMetadata()
} | GetGraphMetadata returns the Graph Meta Data - New in GO Lang | https://github.com/tibcosoftware/tgdb-client/blob/90c1b2017c9aafad0a26cebace406744acf48e10/api/go/src/tgdb/impl/modelimpl.go#L789-L791 | package impl
import (
"bytes"
"encoding/gob"
"fmt"
"strings"
"tgdb"
)
var logger = DefaultTGLogManager().GetLogger()
type GraphMetadata struct {
initialized bool
descriptors map[string]tgdb.TGAttributeDescriptor
descriptorsById map[int64]tgdb.TGAttributeDescriptor
edgeTypes map[string]tgdb.TGEdgeType
edgeTypesById map[int]tgdb.TGEdgeType
nodeTypes map[string]tgdb.TGNodeType
nodeTypesById map[int]tgdb.TGNodeType
graphObjFactory *GraphObjectFactory
}
type GraphObjectFactory struct {
graphMData *GraphMetadata
connection tgdb.TGConnection
}
func setAttributeViaDescriptor(obj tgdb.TGEntity, attrDesc *AttributeDescriptor, value interface{}) tgdb.TGError {
if attrDesc == nil {
logger.Error(fmt.Sprint("ERROR: Returning AbstractEntity:setAttributeViaDescriptor as AttrDesc is EMPTY"))
errMsg := fmt.Sprintf("Attribute Descriptor cannot be null")
return GetErrorByType(TGErrorGeneralException, INTERNAL_SERVER_ERROR, errMsg, "")
}
if value == nil {
logger.Error(fmt.Sprint("ERROR: Returning AbstractEntity:setAttributeViaDescriptor as value is EMPTY"))
errMsg := fmt.Sprintf("Attribute value is required")
return GetErrorByType(TGErrorIOException, INTERNAL_SERVER_ERROR, errMsg, "")
}
attrDescName := attrDesc.GetName()
attr := obj.(*AbstractEntity).Attributes[attrDescName]
if attr == nil {
if attrDesc.GetAttrType() == AttributeTypeInvalid {
logger.Error(fmt.Sprint("ERROR: Returning AbstractEntity:setAttributeViaDescriptor as AttrDesc.GetAttrType() == types.AttributeTypeInvalid"))
errMsg := fmt.Sprintf("Attribute descriptor is of incorrect type")
return GetErrorByType(TGErrorIOException, INTERNAL_SERVER_ERROR, errMsg, "")
}
newAttr, aErr := CreateAttributeWithDesc(nil, attrDesc, nil)
if aErr != nil {
logger.Error(fmt.Sprintf("ERROR: Returning AbstractEntity:setAttributeViaDescriptor unable to create attribute '%s' w/ descriptor and value '%+v'", attrDesc, value))
return aErr
}
newAttr.SetOwner(obj)
attr = newAttr
}
if !attr.GetIsModified() {
obj.(*AbstractEntity).ModifiedAttributes = append(obj.(*AbstractEntity).ModifiedAttributes, attr)
}
err := attr.SetValue(value)
if err != nil {
logger.Error(fmt.Sprintf("ERROR: Returning AbstractEntity:setAttributeViaDescriptor unable to set attribute value w/ error '%+v'", err.Error()))
return err
}
obj.(*AbstractEntity).Attributes[attrDesc.Name] = attr
return nil
}
func DefaultGraphMetadata() *GraphMetadata {
gob.Register(GraphMetadata{})
newGraphMetadata := GraphMetadata{
initialized: false,
descriptors: make(map[string]tgdb.TGAttributeDescriptor, 0),
descriptorsById: make(map[int64]tgdb.TGAttributeDescriptor, 0),
edgeTypes: make(map[string]tgdb.TGEdgeType, 0),
edgeTypesById: make(map[int]tgdb.TGEdgeType, 0),
nodeTypes: make(map[string]tgdb.TGNodeType, 0),
nodeTypesById: make(map[int]tgdb.TGNodeType, 0),
}
return &newGraphMetadata
}
func NewGraphMetadata(gof *GraphObjectFactory) *GraphMetadata {
newGraphMetadata := DefaultGraphMetadata()
newGraphMetadata.graphObjFactory = gof
return newGraphMetadata
}
func (obj *GraphMetadata) GetNewAttributeDescriptors() ([]tgdb.TGAttributeDescriptor, tgdb.TGError) {
if obj.descriptors == nil || len(obj.descriptors) == 0 {
logger.Warning(fmt.Sprint("WARNING: Returning GraphMetadata:GetNewAttributeDescriptors as there are NO new AttrDesc`"))
return nil, nil
}
attrDesc := make([]tgdb.TGAttributeDescriptor, 0)
for _, desc := range obj.descriptors {
if desc.(*AttributeDescriptor).GetAttributeId() < 0 {
attrDesc = append(attrDesc, desc)
}
}
return attrDesc, nil
}
func (obj *GraphMetadata) GetConnection() tgdb.TGConnection {
return obj.graphObjFactory.GetConnection()
}
func (obj *GraphMetadata) GetGraphObjectFactory() *GraphObjectFactory {
return obj.graphObjFactory
}
func (obj *GraphMetadata) GetAttributeDescriptorsById() map[int64]tgdb.TGAttributeDescriptor {
return obj.descriptorsById
}
func (obj *GraphMetadata) GetEdgeTypesById() map[int]tgdb.TGEdgeType {
return obj.edgeTypesById
}
func (obj *GraphMetadata) GetNodeTypesById() map[int]tgdb.TGNodeType {
return obj.nodeTypesById
}
func (obj *GraphMetadata) IsInitialized() bool {
return obj.initialized
}
func (obj *GraphMetadata) SetInitialized(flag bool) {
obj.initialized = flag
}
func (obj *GraphMetadata) SetAttributeDescriptors(attrDesc map[string]tgdb.TGAttributeDescriptor) {
obj.descriptors = attrDesc
}
func (obj *GraphMetadata) SetAttributeDescriptorsById(attrDescId map[int64]tgdb.TGAttributeDescriptor) {
obj.descriptorsById = attrDescId
}
func (obj *GraphMetadata) SetEdgeTypes(edgeTypes map[string]tgdb.TGEdgeType) {
obj.edgeTypes = edgeTypes
}
func (obj *GraphMetadata) SetEdgeTypesById(edgeTypesId map[int]tgdb.TGEdgeType) {
obj.edgeTypesById = edgeTypesId
}
func (obj *GraphMetadata) SetNodeTypes(nodeTypes map[string]tgdb.TGNodeType) {
obj.nodeTypes = nodeTypes
}
func (obj *GraphMetadata) SetNodeTypesById(nodeTypes map[int]tgdb.TGNodeType) {
obj.nodeTypesById = nodeTypes
}
func (obj *GraphMetadata) UpdateMetadata(attrDescList []tgdb.TGAttributeDescriptor, nodeTypeList []tgdb.TGNodeType, edgeTypeList []tgdb.TGEdgeType) tgdb.TGError {
if attrDescList != nil {
for _, attrDesc := range attrDescList {
obj.descriptors[attrDesc.GetName()] = attrDesc.(*AttributeDescriptor)
obj.descriptorsById[attrDesc.GetAttributeId()] = attrDesc.(*AttributeDescriptor)
}
}
if nodeTypeList != nil {
for _, nodeType := range nodeTypeList {
nodeType.(*NodeType).UpdateMetadata(obj)
obj.nodeTypes[nodeType.GetName()] = nodeType.(*NodeType)
obj.nodeTypesById[nodeType.GetEntityTypeId()] = nodeType.(*NodeType)
}
}
if edgeTypeList != nil {
for _, edgeType := range edgeTypeList {
edgeType.(*EdgeType).UpdateMetadata(obj)
obj.edgeTypes[edgeType.GetName()] = edgeType.(*EdgeType)
obj.edgeTypesById[edgeType.GetEntityTypeId()] = edgeType.(*EdgeType)
}
}
obj.initialized = true
return nil
}
func (obj *GraphMetadata) CreateAttributeDescriptor(attrName string, attrType int, isArray bool) tgdb.TGAttributeDescriptor {
newAttrDesc := NewAttributeDescriptorAsArray(attrName, attrType, isArray)
obj.descriptors[attrName] = newAttrDesc
return newAttrDesc
}
func (obj *GraphMetadata) CreateAttributeDescriptorForDataType(attrName string, dataTypeClassName string) tgdb.TGAttributeDescriptor {
attrType := GetAttributeTypeFromName(dataTypeClassName)
if logger.IsDebug() {
logger.Debug(fmt.Sprintf("GraphMetadata CreateAttributeDescriptorForDataType creating attribute descriptor for '%+v' w/ type '%+v'", attrName, attrType))
}
newAttrDesc := NewAttributeDescriptorAsArray(attrName, attrType.GetTypeId(), false)
obj.descriptors[attrName] = newAttrDesc
return newAttrDesc
}
func (obj *GraphMetadata) GetAttributeDescriptor(attrName string) (tgdb.TGAttributeDescriptor, tgdb.TGError) {
if obj.descriptors == nil || len(obj.descriptors) == 0 {
logger.Warning(fmt.Sprint("WARNING: Returning GraphMetadata:GetAttributeDescriptor as there are NO AttrDesc`"))
return nil, nil
}
desc := obj.descriptors[attrName]
return desc, nil
}
func (obj *GraphMetadata) GetAttributeDescriptorById(id int64) (tgdb.TGAttributeDescriptor, tgdb.TGError) {
if obj.descriptorsById == nil || len(obj.descriptorsById) == 0 {
logger.Warning(fmt.Sprint("WARNING: Returning GraphMetadata:GetAttributeDescriptorById as there are NO AttrDesc`"))
return nil, nil
}
desc := obj.descriptorsById[id]
return desc, nil
}
func (obj *GraphMetadata) GetAttributeDescriptors() ([]tgdb.TGAttributeDescriptor, tgdb.TGError) {
if obj.descriptors == nil || len(obj.descriptors) == 0 {
logger.Warning(fmt.Sprint("WARNING: Returning GraphMetadata:GetAttributeDescriptors as there are NO AttrDesc`"))
return nil, nil
}
attrDesc := make([]tgdb.TGAttributeDescriptor, 0)
for _, desc := range obj.descriptors {
attrDesc = append(attrDesc, desc)
}
return attrDesc, nil
}
func (obj *GraphMetadata) CreateCompositeKey(nodeTypeName string) tgdb.TGKey {
compKey := NewCompositeKey(obj, nodeTypeName)
return compKey
}
func (obj *GraphMetadata) CreateEdgeType(typeName string, parentEdgeType tgdb.TGEdgeType) tgdb.TGEdgeType {
newEdgeType := NewEdgeType(typeName, parentEdgeType.GetDirectionType(), parentEdgeType)
return newEdgeType
}
func (obj *GraphMetadata) GetEdgeType(typeName string) (tgdb.TGEdgeType, tgdb.TGError) {
if obj.edgeTypes == nil || len(obj.edgeTypes) == 0 {
logger.Warning(fmt.Sprint("WARNING: Returning GraphMetadata:GetEdgeType as there are NO edges`"))
return nil, nil
}
edge := obj.edgeTypes[typeName]
return edge, nil
}
func (obj *GraphMetadata) GetEdgeTypeById(id int) (tgdb.TGEdgeType, tgdb.TGError) {
if obj.edgeTypesById == nil || len(obj.edgeTypesById) == 0 {
logger.Warning(fmt.Sprint("WARNING: Returning GraphMetadata:GetEdgeTypeById as there are NO edges`"))
return nil, nil
}
edge := obj.edgeTypesById[id]
return edge, nil
}
func (obj *GraphMetadata) GetEdgeTypes() ([]tgdb.TGEdgeType, tgdb.TGError) {
if obj.edgeTypes == nil || len(obj.edgeTypes) == 0 {
logger.Warning(fmt.Sprint("WARNING: Returning GraphMetadata:GetEdgeTypes as there are NO edges`"))
return nil, nil
}
edgeTypes := make([]tgdb.TGEdgeType, 0)
for _, edgeType := range obj.edgeTypes {
edgeTypes = append(edgeTypes, edgeType)
}
return edgeTypes, nil
}
func (obj *GraphMetadata) CreateNodeType(typeName string, parentNodeType tgdb.TGNodeType) tgdb.TGNodeType {
newNodeType := NewNodeType(typeName, parentNodeType)
return newNodeType
}
func (obj *GraphMetadata) GetNodeType(typeName string) (tgdb.TGNodeType, tgdb.TGError) {
if obj.nodeTypes == nil || len(obj.nodeTypes) == 0 {
logger.Warning(fmt.Sprint("WARNING: Returning GraphMetadata:GetNodeType as there are NO nodes"))
return nil, nil
}
node := obj.nodeTypes[typeName]
return node, nil
}
func (obj *GraphMetadata) GetNodeTypeById(id int) (tgdb.TGNodeType, tgdb.TGError) {
if obj.nodeTypesById == nil || len(obj.nodeTypesById) == 0 {
logger.Warning(fmt.Sprint("WARNING: Returning GraphMetadata:GetNodeTypeById as there are NO nodes"))
return nil, nil
}
node := obj.nodeTypesById[id]
if logger.IsDebug() {
logger.Debug(fmt.Sprintf("Returning GraphMetadata:GetNodeTypeById read node as '%+v'", node))
}
return node, nil
}
func (obj *GraphMetadata) GetNodeTypes() ([]tgdb.TGNodeType, tgdb.TGError) {
if obj.nodeTypes == nil || len(obj.nodeTypes) == 0 {
logger.Warning(fmt.Sprint("WARNING: Returning GraphMetadata:GetNodeTypes as there are NO nodes"))
return nil, nil
}
nodeTypes := make([]tgdb.TGNodeType, 0)
for _, nodeType := range obj.nodeTypes {
nodeTypes = append(nodeTypes, nodeType)
}
return nodeTypes, nil
}
func (obj *GraphMetadata) ReadExternal(is tgdb.TGInputStream) tgdb.TGError {
return nil
}
func (obj *GraphMetadata) WriteExternal(os tgdb.TGOutputStream) tgdb.TGError {
return nil
}
func (obj *GraphMetadata) MarshalBinary() ([]byte, error) {
var b bytes.Buffer
_, err := fmt.Fprintln(&b, obj.initialized, obj.descriptors, obj.descriptorsById, obj.edgeTypes, obj.edgeTypesById,
obj.nodeTypes, obj.nodeTypesById, obj.graphObjFactory)
if err != nil {
logger.Error(fmt.Sprintf("ERROR: Returning GraphMetadata:MarshalBinary w/ Error: '%+v'", err.Error()))
return nil, err
}
return b.Bytes(), nil
}
func (obj *GraphMetadata) UnmarshalBinary(data []byte) error {
b := bytes.NewBuffer(data)
_, err := fmt.Fscanln(b, &obj.initialized, &obj.descriptors, &obj.descriptorsById, &obj.edgeTypes, &obj.edgeTypesById,
&obj.nodeTypes, &obj.nodeTypesById, &obj.graphObjFactory)
if err != nil {
logger.Error(fmt.Sprintf("ERROR: Returning GraphMetadata:UnmarshalBinary w/ Error: '%+v'", err.Error()))
return err
}
return nil
}
func DefaultGraphObjectFactory() *GraphObjectFactory {
gob.Register(GraphObjectFactory{})
newGraphObjectFactory := GraphObjectFactory{}
return &newGraphObjectFactory
}
func NewGraphObjectFactory(conn tgdb.TGConnection) *GraphObjectFactory {
newGraphObjectFactory := DefaultGraphObjectFactory()
newGraphObjectFactory.graphMData = NewGraphMetadata(newGraphObjectFactory)
newGraphObjectFactory.connection = conn
return newGraphObjectFactory
}
func (obj *GraphObjectFactory) GetConnection() tgdb.TGConnection {
return obj.connection
}
func (obj *GraphObjectFactory) GetGraphMetaData() *GraphMetadata {
return obj.graphMData
}
func (obj *GraphObjectFactory) CreateCompositeKey(nodeTypeName string) (tgdb.TGKey, tgdb.TGError) {
_, err := obj.graphMData.GetNodeType(nodeTypeName)
if err != nil {
logger.Error(fmt.Sprint("ERROR: Returning GraphObjectFactory:CreateCompositeKey as node NOT found"))
errMsg := fmt.Sprintf("Node desc with Name %s not found", nodeTypeName)
return nil, GetErrorByType(TGErrorGeneralException, INTERNAL_SERVER_ERROR, errMsg, "")
}
return NewCompositeKey(obj.graphMData, nodeTypeName), nil
}
func (obj *GraphObjectFactory) CreateEdgeWithEdgeType(fromNode tgdb.TGNode, toNode tgdb.TGNode, edgeType tgdb.TGEdgeType) (tgdb.TGEdge, tgdb.TGError) {
newEdge := NewEdgeWithEdgeType(obj.graphMData, fromNode, toNode, edgeType)
if newEdge.isInitialized != true {
logger.Error(fmt.Sprint("ERROR: Returning GraphObjectFactory:CreateEdgeWithEdgeType as edge in NOT initialized"))
errMsg := fmt.Sprintf("Unable to create an edge with type %s", edgeType.(*EdgeType).Name)
return nil, GetErrorByType(TGErrorGeneralException, INTERNAL_SERVER_ERROR, errMsg, "")
}
fromNode.AddEdge(newEdge)
toNode.AddEdge(newEdge)
return newEdge, nil
}
func (obj *GraphObjectFactory) CreateEdgeWithDirection(fromNode tgdb.TGNode, toNode tgdb.TGNode, directionType tgdb.TGDirectionType) (tgdb.TGEdge, tgdb.TGError) {
newEdge := NewEdgeWithDirection(obj.graphMData, fromNode, toNode, directionType)
if newEdge.isInitialized != true {
logger.Error(fmt.Sprint("ERROR: Returning GraphObjectFactory:CreateEdgeWithDirection as edge in NOT initialized"))
errMsg := fmt.Sprintf("Unable to create an edge with direction %s", directionType)
return nil, GetErrorByType(TGErrorGeneralException, INTERNAL_SERVER_ERROR, errMsg, "")
}
fromNode.AddEdge(newEdge)
toNode.AddEdge(newEdge)
return newEdge, nil
}
func (obj *GraphObjectFactory) CreateEntity(entityKind tgdb.TGEntityKind) (tgdb.TGEntity, tgdb.TGError) {
switch entityKind {
case tgdb.EntityKindNode:
return NewNode(obj.graphMData), nil
case tgdb.EntityKindEdge:
return NewEdge(obj.graphMData), nil
case tgdb.EntityKindGraph:
return NewGraph(obj.graphMData), nil
}
logger.Error(fmt.Sprint("ERROR: Returning GraphObjectFactory:CreateEntity as entity kind specified is INVALID"))
errMsg := fmt.Sprintf("Invalid entity kind %d specified", entityKind)
return nil, GetErrorByType(TGErrorGeneralException, INTERNAL_SERVER_ERROR, errMsg, "")
}
func (obj *GraphObjectFactory) CreateEntityId(buf []byte) (tgdb.TGEntityId, tgdb.TGError) {
return NewByteArrayEntity(buf), nil
}
func (obj *GraphObjectFactory) CreateGraph(name string) (tgdb.TGGraph, tgdb.TGError) {
graph := NewGraphWithName(obj.graphMData, name)
if graph.isInitialized != true {
logger.Error(fmt.Sprint("ERROR: Returning GraphObjectFactory:CreateGraph as graph in NOT initialized"))
errMsg := fmt.Sprint("Unable to create a graph with this Graph Object Factory")
return nil, GetErrorByType(TGErrorGeneralException, INTERNAL_SERVER_ERROR, errMsg, "")
}
return graph, nil
}
func (obj *GraphObjectFactory) CreateNode() (tgdb.TGNode, tgdb.TGError) {
node := NewNode(obj.graphMData)
if node.isInitialized != true {
logger.Error(fmt.Sprint("ERROR: Returning GraphObjectFactory:CreateNode as node in NOT initialized"))
errMsg := fmt.Sprint("Unable to create a node with this Graph Object Factory")
return nil, GetErrorByType(TGErrorGeneralException, INTERNAL_SERVER_ERROR, errMsg, "")
}
return node, nil
}
func (obj *GraphObjectFactory) CreateNodeInGraph(nodeType tgdb.TGNodeType) (tgdb.TGNode, tgdb.TGError) {
node := NewNodeWithType(obj.graphMData, nodeType)
if node.isInitialized != true {
logger.Error(fmt.Sprint("ERROR: Returning GraphObjectFactory:CreateNodeInGraph as node in NOT initialized"))
errMsg := fmt.Sprint("Unable to create a node with this Graph Object Factory")
return nil, GetErrorByType(TGErrorGeneralException, INTERNAL_SERVER_ERROR, errMsg, "")
}
return node, nil
}
func (obj *GraphObjectFactory) MarshalBinary() ([]byte, error) {
var b bytes.Buffer
_, err := fmt.Fprintln(&b, obj.graphMData, obj.connection)
if err != nil {
logger.Error(fmt.Sprintf("ERROR: Returning GraphObjectFactory:MarshalBinary w/ Error: '%+v'", err.Error()))
return nil, err
}
return b.Bytes(), nil
}
func (obj *GraphObjectFactory) UnmarshalBinary(data []byte) error {
b := bytes.NewBuffer(data)
_, err := fmt.Fscanln(b, &obj.graphMData, &obj.connection)
if err != nil {
logger.Error(fmt.Sprintf("ERROR: Returning GraphObjectFactory:UnmarshalBinary w/ Error: '%+v'", err.Error()))
return err
}
return nil
}
type Graph struct {
*Node
name string
}
func DefaultGraph() *Graph {
gob.Register(Graph{})
newGraph := Graph{
Node: DefaultNode(),
}
newGraph.EntityKind = tgdb.EntityKindGraph
return &newGraph
}
func NewGraph(gmd *GraphMetadata) *Graph {
newGraph := DefaultGraph()
newGraph.graphMetadata = gmd
return newGraph
}
func NewGraphWithName(gmd *GraphMetadata, name string) *Graph {
newGraph := NewGraph(gmd)
newGraph.name = name
return newGraph
}
func (obj *Graph) GetModifiedAttributes() []tgdb.TGAttribute {
return obj.getModifiedAttributes()
}
func (obj *Graph) GetName() string {
return obj.name
}
func (obj *Graph) SetName(name string) {
obj.name = name
}
func (obj *Graph) AddNode(node tgdb.TGNode) (tgdb.TGGraph, tgdb.TGError) {
return obj, nil
}
func (obj *Graph) AddEdges(edges []tgdb.TGEdge) (tgdb.TGGraph, tgdb.TGError) {
return obj, nil
}
func (obj *Graph) GetNode(filter tgdb.TGFilter) (tgdb.TGNode, tgdb.TGError) {
return nil, nil
}
func (obj *Graph) ListNodes(filter tgdb.TGFilter, recurseAllSubGraphs bool) (tgdb.TGNode, tgdb.TGError) {
return nil, nil
}
func (obj *Graph) CreateGraph(name string) (tgdb.TGGraph, tgdb.TGError) {
return nil, nil
}
func (obj *Graph) RemoveGraph(name string) (tgdb.TGGraph, tgdb.TGError) {
return nil, nil
}
func (obj *Graph) RemoveNode(node tgdb.TGNode) (tgdb.TGGraph, tgdb.TGError) {
return nil, nil
}
func (obj *Graph) RemoveNodes(filter tgdb.TGFilter) int {
return 0
}
func (obj *Graph) AddEdge(edge tgdb.TGEdge) {
obj.Edges = append(obj.Edges, edge)
}
func (obj *Graph) AddEdgeWithDirectionType(node tgdb.TGNode, edgeType tgdb.TGEdgeType, directionType tgdb.TGDirectionType) tgdb.TGEdge {
newEdge := NewEdgeWithDirection(obj.graphMetadata, obj, node, directionType)
obj.AddEdge(newEdge)
return newEdge
}
func (obj *Graph) GetEdges() []tgdb.TGEdge {
return obj.Edges
}
func (obj *Graph) GetEdgesForDirectionType(directionType tgdb.TGDirectionType) []tgdb.TGEdge {
edgesWithDirections := make([]tgdb.TGEdge, 0)
if len(obj.Edges) == 0 {
logger.Warning(fmt.Sprint("WARNING: Returning Graph:GetEdgesForDirectionType as there are NO edges"))
return edgesWithDirections
}
for _, edge := range obj.Edges {
if edge.(*Edge).directionType == directionType {
edgesWithDirections = append(edgesWithDirections, edge)
}
}
return edgesWithDirections
}
func (obj *Graph) GetEdgesForEdgeType(edgeType tgdb.TGEdgeType, direction tgdb.TGDirection) []tgdb.TGEdge {
edgesWithDirections := make([]tgdb.TGEdge, 0)
if len(obj.Edges) == 0 {
logger.Warning(fmt.Sprint("WARNING: Returning Graph:GetEdgesForEdgeType as there are NO edges"))
return edgesWithDirections
}
if edgeType == nil && direction == tgdb.DirectionAny {
for _, edge := range obj.Edges {
if edge.(*Edge).GetIsInitialized() {
edgesWithDirections = append(edgesWithDirections, edge)
}
}
if logger.IsDebug() {
logger.Debug(fmt.Sprint("Returning Graph:GetEdgesForEdgeType w/ all edges of ANY directions"))
}
return obj.Edges
}
for _, edge := range obj.Edges {
if !edge.(*Edge).GetIsInitialized() {
logger.Warning(fmt.Sprintf("WARNING: Returning Graph:GetEdgesForEdgeType - skipping uninitialized edge '%+v'", edge))
continue
}
eType := edge.GetEntityType()
if edgeType != nil && eType != nil && eType.GetName() != edgeType.GetName() {
logger.Warning(fmt.Sprintf("WARNING: Returning Graph:GetEdgesForEdgeType - skipping (entity type NOT matching) edge '%+v'", edge))
continue
}
if direction == tgdb.DirectionAny {
edgesWithDirections = append(edgesWithDirections, edge)
} else if direction == tgdb.DirectionOutbound {
edgesForThisNode := edge.GetVertices()
if obj.GetVirtualId() == edgesForThisNode[0].GetVirtualId() {
edgesWithDirections = append(edgesWithDirections, edge)
}
} else {
edgesForThisNode := edge.GetVertices()
if obj.GetVirtualId() == edgesForThisNode[1].GetVirtualId() {
edgesWithDirections = append(edgesWithDirections, edge)
}
}
}
return edgesWithDirections
}
func (obj *Graph) GetAttribute(attrName string) tgdb.TGAttribute {
return obj.getAttribute(attrName)
}
func (obj *Graph) GetAttributes() ([]tgdb.TGAttribute, tgdb.TGError) {
return obj.getAttributes()
}
func (obj *Graph) GetEntityKind() tgdb.TGEntityKind {
return obj.getEntityKind()
}
func (obj *Graph) GetEntityType() tgdb.TGEntityType {
return obj.getEntityType()
} | Apache License 2.0 |
faceterteam/onvif4go | mediaService.go | GetAudioOutputs | go | func (s *MediaService) GetAudioOutputs() (res trt.GetAudioOutputsResponse, err error) {
err = s.Client.Call(trt.GetAudioOutputs{}, &res)
return
} | GetAudioOutputs lists all available physical audio outputs of the device. | https://github.com/faceterteam/onvif4go/blob/8994ff013c81b76917ecb8954d1d409a632a2e92/mediaService.go#L60-L63 | package onvif4go
import (
trt "github.com/faceterteam/onvif4go/media"
tt "github.com/faceterteam/onvif4go/onvif"
)
type MediaService struct {
Client onvifCaller
}
func NewMediaService(endpoint string, onvifDevice *OnvifDevice) *MediaService {
return &MediaService{
Client: NewOnvifClient(endpoint, &onvifDevice.auth),
}
}
func (s *MediaService) WithoutAuth() *MediaService {
return &MediaService{
Client: s.Client.WithoutAuth(),
}
}
func (s *MediaService) GetProfiles() (res trt.GetProfilesResponse, err error) {
err = s.Client.Call(trt.GetProfiles{}, &res)
return
}
func (s *MediaService) GetProfile(profileToken string) (res trt.GetProfileResponse, err error) {
err = s.Client.Call(trt.GetProfile{
ProfileToken: tt.ReferenceToken(profileToken),
}, &res)
return
}
func (s *MediaService) GetServiceCapabilities() (res trt.GetServiceCapabilitiesResponse, err error) {
err = s.Client.Call(trt.GetServiceCapabilities{}, &res)
return
}
func (s *MediaService) GetVideoSources() (res trt.GetVideoSourcesResponse, err error) {
err = s.Client.Call(trt.GetVideoSources{}, &res)
return
}
func (s *MediaService) GetAudioSources() (res trt.GetAudioSourcesResponse, err error) {
err = s.Client.Call(trt.GetAudioSources{}, &res)
return
} | MIT License |