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 |
---|---|---|---|---|---|---|---|---|
gabrie30/ghorg | vendor/code.gitea.io/sdk/gitea/user_gpgkey.go | ListMyGPGKeys | go | func (c *Client) ListMyGPGKeys(opt *ListGPGKeysOptions) ([]*GPGKey, *Response, error) {
opt.setDefaults()
keys := make([]*GPGKey, 0, opt.PageSize)
resp, err := c.getParsedResponse("GET", fmt.Sprintf("/user/gpg_keys?%s", opt.getURLQuery().Encode()), nil, nil, &keys)
return keys, resp, err
} | ListMyGPGKeys list all the GPG keys of current user | https://github.com/gabrie30/ghorg/blob/f50372890c4285008fddd6c2f684c311da976d72/vendor/code.gitea.io/sdk/gitea/user_gpgkey.go#L53-L58 | package gitea
import (
"bytes"
"encoding/json"
"fmt"
"time"
)
type GPGKey struct {
ID int64 `json:"id"`
PrimaryKeyID string `json:"primary_key_id"`
KeyID string `json:"key_id"`
PublicKey string `json:"public_key"`
Emails []*GPGKeyEmail `json:"emails"`
SubsKey []*GPGKey `json:"subkeys"`
CanSign bool `json:"can_sign"`
CanEncryptComms bool `json:"can_encrypt_comms"`
CanEncryptStorage bool `json:"can_encrypt_storage"`
CanCertify bool `json:"can_certify"`
Created time.Time `json:"created_at,omitempty"`
Expires time.Time `json:"expires_at,omitempty"`
}
type GPGKeyEmail struct {
Email string `json:"email"`
Verified bool `json:"verified"`
}
type ListGPGKeysOptions struct {
ListOptions
}
func (c *Client) ListGPGKeys(user string, opt ListGPGKeysOptions) ([]*GPGKey, *Response, error) {
if err := escapeValidatePathSegments(&user); err != nil {
return nil, nil, err
}
opt.setDefaults()
keys := make([]*GPGKey, 0, opt.PageSize)
resp, err := c.getParsedResponse("GET", fmt.Sprintf("/users/%s/gpg_keys?%s", user, opt.getURLQuery().Encode()), nil, nil, &keys)
return keys, resp, err
} | Apache License 2.0 |
mosaicnetworks/evm-lite | src/service/http_handlers.go | genesisHandler | go | func genesisHandler(w http.ResponseWriter, r *http.Request, m *Service) {
m.logger.Debug("GET genesis")
genesis, err := m.state.GetGenesis()
if err != nil {
m.logger.WithError(err).Error("Getting Genesis")
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
js, err := json.Marshal(genesis)
if err != nil {
m.logger.WithError(err).Error("Marshaling JSON response")
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
w.Write(js)
} | ------------------------------------------------------------------------------
/*
GET /genesis
returns: JSON Genesis
This endpoint returns the content of the genesis.json file. | https://github.com/mosaicnetworks/evm-lite/blob/730249f55ec76df2fb573c4e62b971afc50d05f7/src/service/http_handlers.go#L391-L410 | package service
import (
"encoding/json"
"fmt"
"io/ioutil"
"math/big"
"net/http"
"strconv"
"time"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/common/hexutil"
ethTypes "github.com/ethereum/go-ethereum/core/types"
"github.com/mosaicnetworks/evm-lite/src/state"
"github.com/mosaicnetworks/evm-lite/src/version"
"github.com/sirupsen/logrus"
comm "github.com/mosaicnetworks/evm-lite/src/common"
)
func accountHandler(w http.ResponseWriter, r *http.Request, m *Service) {
ShowStorage := false
param := r.URL.Path[len("/account/"):]
address := common.HexToAddress(param)
if m.logger.Level > logrus.InfoLevel {
m.logger.WithField("param", param).Debug("GET account")
m.logger.WithField("address", address.Hex()).Debug("GET account")
}
var fromPool bool
qs := r.URL.Query().Get("frompool")
if qs != "" {
fp, err := strconv.ParseBool(qs)
if err != nil {
m.logger.WithError(err).Error("Error converting string to bool")
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
fromPool = fp
}
nonce := m.state.GetNonce(address, fromPool)
balance := m.state.GetBalance(address, fromPool)
code := hexutil.Encode(m.state.GetCode(address, fromPool))
if code == "0x" {
code = ""
}
account := JSONAccount{
Address: address.Hex(),
Balance: balance,
Nonce: nonce,
Code: code,
}
if ShowStorage {
account.Storage = m.state.GetStorage(address, fromPool)
}
js, err := json.Marshal(account)
if err != nil {
m.logger.WithError(err).Error("Marshaling JSON response")
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
w.Write(js)
}
func callHandler(w http.ResponseWriter, r *http.Request, m *Service) {
if m.logger.Level > logrus.InfoLevel {
m.logger.WithField("request", r).Debug("POST call")
}
decoder := json.NewDecoder(r.Body)
var txArgs SendTxArgs
err := decoder.Decode(&txArgs)
if err != nil {
m.logger.WithError(err).Error("Decoding JSON txArgs")
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
defer r.Body.Close()
callMessage, err := prepareCallMessage(txArgs)
if err != nil {
m.logger.WithError(err).Error("Converting to CallMessage")
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
data, err := m.state.Call(*callMessage)
if err != nil {
m.logger.WithError(err).Error("Executing Call")
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
res := JSONCallRes{Data: hexutil.Encode(data)}
js, err := json.Marshal(res)
if err != nil {
m.logger.WithError(err).Error("Marshaling JSON response")
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
w.Write(js)
}
func rawTransactionHandler(w http.ResponseWriter, r *http.Request, m *Service) {
if m.logger.Level > logrus.InfoLevel {
m.logger.WithField("request", r).Debug("POST rawtx")
}
defer r.Body.Close()
body, err := ioutil.ReadAll(r.Body)
if err != nil {
m.logger.WithError(err).Error("Reading request body")
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
sBody := string(body)
if m.logger.Level > logrus.InfoLevel {
m.logger.WithField("body", body)
m.logger.WithField("body (string)", sBody).Debug()
}
rawTxBytes, err := hexutil.Decode(sBody)
if err != nil {
m.logger.WithError(err).Error("Reading raw tx from request body")
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if m.logger.Level > logrus.InfoLevel {
m.logger.WithField("raw tx bytes", rawTxBytes).Debug()
}
tx, err := state.NewEVMLTransaction(rawTxBytes, m.state.GetSigner())
if err != nil {
m.logger.WithError(err).Error("Decoding Transaction")
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if m.logger.Level > logrus.InfoLevel {
m.logger.WithFields(logrus.Fields{
"hash": tx.Hash().Hex(),
"from": tx.From(),
"to": tx.To(),
"payload": fmt.Sprintf("%x", tx.Data()),
"gas": tx.Gas(),
"gasPrice": tx.GasPrice(),
"nonce": tx.Nonce(),
"value": tx.Value(),
}).Debug("Service decoded tx")
}
if m.minGasPrice != nil && tx.GasPrice().Cmp(m.minGasPrice) < 0 {
err := fmt.Errorf("Gasprice too low. Got %v, MIN: %v", tx.GasPrice(), m.minGasPrice)
m.logger.Debug(err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if err := m.state.CheckTx(tx); err != nil {
m.logger.WithError(err).Error("Checking Transaction")
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
promise := m.state.CreateReceiptPromise(tx.Hash())
m.logger.Debug("submitting tx")
m.submitCh <- rawTxBytes
m.logger.Debug("submitted tx")
timeout := time.After(15 * time.Second)
var receipt *comm.JSONReceipt
var respErr error
select {
case resp := <-promise.RespCh:
if resp.Error != nil {
respErr = resp.Error
break
}
receipt = resp.Receipt
case <-timeout:
respErr = fmt.Errorf("Timeout waiting for transaction to go through consensus")
break
}
if respErr != nil {
m.logger.Errorf("RespErr: %v", respErr)
http.Error(w, respErr.Error(), http.StatusInternalServerError)
return
}
js, err := json.Marshal(receipt)
if err != nil {
m.logger.WithError(err).Error("Marshalling JSON Response")
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
w.Write(js)
}
func transactionReceiptHandler(w http.ResponseWriter, r *http.Request, m *Service) {
param := r.URL.Path[len("/tx/"):]
txHash := common.HexToHash(param)
m.logger.WithField("tx_hash", txHash.Hex()).Debug("GET tx")
tx, err := m.state.GetTransaction(txHash)
if err != nil {
m.logger.WithError(err).Error("Getting Transaction")
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
receipt, err := m.state.GetReceipt(txHash)
if err != nil {
m.logger.WithError(err).Error("Getting Receipt")
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
jsonReceipt := comm.ToJSONReceipt(receipt, tx, m.state.GetSigner())
js, err := json.Marshal(jsonReceipt)
if err != nil {
m.logger.WithError(err).Error("Marshaling JSON response")
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
w.Write(js)
}
func infoHandler(w http.ResponseWriter, r *http.Request, m *Service) {
m.logger.Debug("GET info")
stats, err := m.getInfo()
if err != nil {
m.logger.WithError(err).Error("Getting Info")
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if m.minGasPrice != nil {
stats["min_gas_price"] = m.minGasPrice.String()
} else {
stats["min_gas_price"] = "0"
}
js, err := json.Marshal(stats)
if err != nil {
m.logger.WithError(err).Error("Marshaling JSON response")
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
w.Write(js)
}
func poaHandler(w http.ResponseWriter, r *http.Request, m *Service) {
m.logger.Debug("GET poa")
var al JSONContract
al = JSONContract{
Address: common.HexToAddress(m.state.GetAuthorisingAccount()),
ABI: m.state.GetAuthorisingABI(),
}
js, err := json.Marshal(al)
if err != nil {
m.logger.WithError(err).Error("Marshaling JSON response")
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
w.Write(js)
}
func versionHandler(w http.ResponseWriter, r *http.Request, m *Service) {
m.logger.Debug("GET version")
js, err := json.Marshal(version.JSONVersion)
if err != nil {
m.logger.WithError(err).Error("Marshaling Version response")
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
w.Write(js)
} | MIT License |
spaceleap/go-embedded | gpio/gpio.go | NewGPIO | go | func NewGPIO(nr int, direction Direction) (gpio *GPIO, err error) {
if !IsExported(nr) {
err = dry.FilePrintf("/sys/class/gpio/export", "%d", nr)
if err != nil {
return nil, err
}
}
gpio = &GPIO{nr: nr}
err = gpio.SetDirection(direction)
if err != nil {
return nil, err
}
return gpio, nil
} | NewGPIO exports the GPIO pin nr. | https://github.com/spaceleap/go-embedded/blob/2d0cc53efb6327f6bb13bbaea61bf1a0af2bbb8f/gpio/gpio.go#L66-L82 | package gpio
import (
"fmt"
"os"
"runtime"
"syscall"
"time"
"github.com/ungerik/go-dry"
)
type Value int
const (
LOW Value = 0
HIGH Value = 1
_EPOLLET = 1 << 31
)
type Edge string
const (
EDGE_NONE Edge = "none"
EDGE_RISING Edge = "rising"
EDGE_FALLING Edge = "falling"
EDGE_BOTH Edge = "both"
)
type EdgeEvent struct {
Time time.Time
Value Value
}
type Direction string
const (
DIRECTION_IN Direction = "in"
DIRECTION_OUT Direction = "out"
)
type PullUpDown int
const (
PUD_OFF PullUpDown = 0
PUD_DOWN PullUpDown = 1
PUD_UP PullUpDown = 2
)
func IsExported(nr int) bool {
return dry.FileExists(fmt.Sprintf("/sys/class/gpio/gpio%d/", nr))
}
type GPIO struct {
nr int
valueFile *os.File
epollFd dry.SyncInt
edge Edge
} | MIT License |
muka/go-bluetooth | gen/bluez_api.go | Serialize | go | func (g *BluezAPI) Serialize(destFile string) error {
data, err := json.Marshal(g)
if err != nil {
return err
}
return ioutil.WriteFile(destFile, data, 0755)
} | Serialize store the structure as JSON | https://github.com/muka/go-bluetooth/blob/c49e7c952f19d483b59c3a86d6f6e56942306159/gen/bluez_api.go#L16-L24 | package gen
import (
"encoding/json"
"io/ioutil"
"github.com/muka/go-bluetooth/gen/types"
)
type BluezAPI struct {
Version string
Api []*types.ApiGroup
} | Apache License 2.0 |
mattkanwisher/cryptofiend | exchanges/alphapoint/alphapoint.go | GetTrades | go | func (a *Alphapoint) GetTrades(currencyPair string, startIndex, count int) (Trades, error) {
request := make(map[string]interface{})
request["ins"] = currencyPair
request["startIndex"] = startIndex
request["Count"] = count
response := Trades{}
err := a.SendRequest("POST", alphapointTrades, request, &response)
if err != nil {
return response, err
}
if !response.IsAccepted {
return response, errors.New(response.RejectReason)
}
return response, nil
} | GetTrades fetches past trades for the given currency pair
currencyPair: ie "BTCUSD"
StartIndex: specifies the index to begin from, -1 being the first trade on
AlphaPoint Exchange. To begin from the most recent trade, set startIndex to
0 (default: 0)
Count: specifies the number of trades to return (default: 10) | https://github.com/mattkanwisher/cryptofiend/blob/e477184ca4d13d3d372443bcee92c90697decd63/exchanges/alphapoint/alphapoint.go#L79-L94 | package alphapoint
import (
"bytes"
"errors"
"fmt"
"log"
"strconv"
"time"
"github.com/gorilla/websocket"
"github.com/mattkanwisher/cryptofiend/common"
"github.com/mattkanwisher/cryptofiend/exchanges"
"github.com/mattkanwisher/cryptofiend/exchanges/ticker"
)
const (
alphapointDefaultAPIURL = "https://sim3.alphapoint.com:8400"
alphapointAPIVersion = "1"
alphapointTicker = "GetTicker"
alphapointTrades = "GetTrades"
alphapointTradesByDate = "GetTradesByDate"
alphapointOrderbook = "GetOrderBook"
alphapointProductPairs = "GetProductPairs"
alphapointProducts = "GetProducts"
alphapointCreateAccount = "CreateAccount"
alphapointUserInfo = "GetUserInfo"
alphapointAccountInfo = "GetAccountInfo"
alphapointAccountTrades = "GetAccountTrades"
alphapointDepositAddresses = "GetDepositAddresses"
alphapointWithdraw = "Withdraw"
alphapointCreateOrder = "CreateOrder"
alphapointModifyOrder = "ModifyOrder"
alphapointCancelOrder = "CancelOrder"
alphapointCancelAllOrders = "CancelAllOrders"
alphapointOpenOrders = "GetAccountOpenOrders"
alphapointOrderFee = "GetOrderFee"
alphapointMaxRequestsPer10minutes = 500
)
type Alphapoint struct {
exchange.Base
WebsocketConn *websocket.Conn
}
func (a *Alphapoint) SetDefaults() {
a.APIUrl = alphapointDefaultAPIURL
a.WebsocketURL = alphapointDefaultWebsocketURL
a.AssetTypes = []string{ticker.Spot}
}
func (a *Alphapoint) GetTicker(currencyPair string) (Ticker, error) {
request := make(map[string]interface{})
request["productPair"] = currencyPair
response := Ticker{}
err := a.SendRequest("POST", alphapointTicker, request, &response)
if err != nil {
return response, err
}
if !response.IsAccepted {
return response, errors.New(response.RejectReason)
}
return response, nil
} | MIT License |
gosoon/kubernetes-operator | pkg/client/clientset/versioned/typed/ecs/v1/fake/fake_ecs_client.go | RESTClient | go | func (c *FakeEcsV1) RESTClient() rest.Interface {
var ret *rest.RESTClient
return ret
} | RESTClient returns a RESTClient that is used to communicate
with API server by this client implementation. | https://github.com/gosoon/kubernetes-operator/blob/ff55af68d380065a6173dc4028125ed54c0bc60f/pkg/client/clientset/versioned/typed/ecs/v1/fake/fake_ecs_client.go#L37-L40 | package fake
import (
v1 "github.com/gosoon/kubernetes-operator/pkg/client/clientset/versioned/typed/ecs/v1"
rest "k8s.io/client-go/rest"
testing "k8s.io/client-go/testing"
)
type FakeEcsV1 struct {
*testing.Fake
}
func (c *FakeEcsV1) KubernetesClusters(namespace string) v1.KubernetesClusterInterface {
return &FakeKubernetesClusters{c, namespace}
} | Apache License 2.0 |
eaigner/igi | trinary/trits.go | Equals | go | func Equals(t1 []int8, t2 []int8) bool {
if len(t1) != len(t2) {
return false
}
for i, v := range t1 {
if t2[i] != v {
return false
}
}
return true
} | Equals compares two trit buffers. | https://github.com/eaigner/igi/blob/6a013f79d271939da3fc3c244be170ab92fa3ef1/trinary/trits.go#L191-L201 | package trinary
import "errors"
const (
tryteAlphabet = "9ABCDEFGHIJKLMNOPQRSTUVWXYZ"
tritsPerByte = 5
tritsPerTryte = 3
tritRadix int8 = 3
maxTritValue int8 = (tritRadix - 1) / 2
minTritValue int8 = -maxTritValue
)
var (
tryteRuneIndex = make(map[rune]int, len(tryteAlphabet))
bytesToTrits [243][tritsPerByte]int8
trytesToTrits [27][tritsPerTryte]int8
)
var (
errBufferTooSmall = errors.New("buffer too small")
errMultipleThree = errors.New("buffer size must be a multiple of 3")
)
func init() {
var trits [tritsPerByte]int8
for i := 0; i < 243; i++ {
copy(bytesToTrits[i][:], trits[:tritsPerByte])
incrementTrits(trits[:], tritsPerByte)
}
for i := 0; i < 27; i++ {
copy(trytesToTrits[i][:], trits[:tritsPerTryte])
incrementTrits(trits[:], tritsPerTryte)
}
for i, c := range tryteAlphabet {
tryteRuneIndex[c] = i
}
}
func incrementTrits(trits []int8, n int) {
for i := 0; i < n; i++ {
trits[i]++
if trits[i] > maxTritValue {
trits[i] = minTritValue
} else {
break
}
}
}
func Validate(a []int8) bool {
for _, v := range a {
if !validTrit(v) {
return false
}
}
return true
}
func Trits(dst []int8, src []byte) (int, error) {
n := len(src) * tritsPerByte
if len(dst) < n {
return 0, errBufferTooSmall
}
offset := 0
for i := 0; i < len(src) && offset < n; i++ {
x := int(int8(src[i]))
if x < 0 {
x += len(bytesToTrits)
}
o := tritsPerByte
j := n - offset
if j < tritsPerByte {
o = j
}
if len(dst) < offset+o {
return 0, errBufferTooSmall
}
copy(dst[offset:offset+o], bytesToTrits[x][0:o])
offset += tritsPerByte
}
for offset < n {
dst[offset] = 0
offset++
}
return n, nil
}
func TritsFromTrytes(dst []int8, src string) (int, error) {
n := LenTritsFromTrytes(len(src))
if len(dst) < n {
return 0, errBufferTooSmall
}
for i, c := range src {
j := i * tritsPerTryte
copy(dst[j:j+tritsPerTryte], trytesToTrits[tryteRuneIndex[c]][:])
}
return n, nil
}
func validTrit(v int8) bool {
return v >= -1 && v <= 1
}
func LenBytes(n int) int {
return (n + tritsPerByte - 1) / tritsPerByte
}
func LenTrits(n int) int {
return n * tritsPerByte
}
func LenTritsFromTrytes(n int) int {
return n * tritsPerTryte
}
func Bytes(dst []byte, src []int8) (int, error) {
n := LenBytes(len(src))
if len(dst) < n {
return 0, errBufferTooSmall
}
var v int8
var j0 int
for i := 0; i < n; i++ {
v = 0
j0 = len(src) - i*tritsPerByte
if j0 >= 5 {
j0 = tritsPerByte
}
for j := j0 - 1; j >= 0; j-- {
v = v*tritRadix + src[i*tritsPerByte+j]
}
dst[i] = byte(v)
}
return n, nil
}
func Trytes(t []int8) (string, error) {
if len(t)%3 != 0 {
return "", errMultipleThree
}
n := len(t) / 3
v := make([]byte, n)
for i := 0; i < n; i++ {
j := t[i*3] + t[i*3+1]*3 + t[i*3+2]*9
if j < 0 {
j += int8(len(tryteAlphabet))
}
v[i] = tryteAlphabet[j]
}
return string(v), nil
}
func Int64(t []int8) int64 {
var v int64 = 0
for i := len(t) - 1; i >= 0; i-- {
v = v*int64(tritRadix) + int64(t[i])
}
return v
} | MIT License |
segmentio/asm | base64/base64_amd64.go | EncodeToString | go | func (enc *Encoding) EncodeToString(src []byte) string {
buf := make([]byte, enc.base.EncodedLen(len(src)))
enc.Encode(buf, src)
return string(buf)
} | Encode encodes src using the encoding enc, writing
EncodedLen(len(src)) bytes to dst. | https://github.com/segmentio/asm/blob/18af27c3ce38682a2545f2d95e5ef564dd312d6e/base64/base64_amd64.go#L116-L120 | package base64
import (
"encoding/base64"
"github.com/segmentio/asm/cpu"
"github.com/segmentio/asm/internal/unsafebytes"
)
type Encoding struct {
enc func(dst []byte, src []byte, lut *int8) (int, int)
enclut [32]int8
dec func(dst []byte, src []byte, lut *int8) (int, int)
declut [48]int8
base *base64.Encoding
}
const (
minEncodeLen = 28
minDecodeLen = 45
)
func newEncoding(encoder string) *Encoding {
e := &Encoding{base: base64.NewEncoding(encoder)}
if cpu.X86.Has(cpu.AVX2) {
e.enableEncodeAVX2(encoder)
e.enableDecodeAVX2(encoder)
}
return e
}
func (e *Encoding) enableEncodeAVX2(encoder string) {
tab := [32]int8{int8(encoder[0]), int8(encoder[letterRange]) - letterRange}
for i, ch := range encoder[2*letterRange:] {
tab[2+i] = int8(ch) - 2*letterRange - int8(i)
}
e.enc = encodeAVX2
e.enclut = tab
}
func (e *Encoding) enableDecodeAVX2(encoder string) {
c62, c63 := int8(encoder[62]), int8(encoder[63])
url := c63 == '_'
if url {
c63 = '/'
}
tab := [48]int8{
0, 63 - c63, 62 - c62, 4, -65, -65, -71, -71,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x15, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11,
0x11, 0x11, 0x13, 0x1B, 0x1B, 0x1B, 0x1B, 0x1B,
}
tab[(c62&15)+16] = 0x1A
tab[(c63&15)+16] = 0x1A
if url {
e.dec = decodeAVX2URI
} else {
e.dec = decodeAVX2
}
e.declut = tab
}
func (enc Encoding) WithPadding(padding rune) *Encoding {
enc.base = enc.base.WithPadding(padding)
return &enc
}
func (enc Encoding) Strict() *Encoding {
enc.base = enc.base.Strict()
return &enc
}
func (enc *Encoding) Encode(dst, src []byte) {
if len(src) >= minEncodeLen && enc.enc != nil {
d, s := enc.enc(dst, src, &enc.enclut[0])
dst = dst[d:]
src = src[s:]
}
enc.base.Encode(dst, src)
} | MIT License |
nano-gpu/nano-gpu-scheduler | pkg/utils/pod.go | GetUpdatedPodAnnotationSpec | go | func GetUpdatedPodAnnotationSpec(oldPod *v1.Pod, indexes []int) (newPod *v1.Pod) {
newPod = oldPod.DeepCopy()
if len(newPod.Labels) == 0 {
newPod.Labels = map[string]string{}
}
if len(newPod.Annotations) == 0 {
newPod.Annotations = map[string]string{}
}
for i, container := range newPod.Spec.Containers {
newPod.Annotations[fmt.Sprintf(types.AnnotationGPUContainerOn, container.Name)] = strconv.Itoa(indexes[i])
}
newPod.Annotations[types.AnnotationGPUAssume] = "true"
newPod.Labels[types.LabelGPUAssume] = "true"
return newPod
} | GetUpdatedPodAnnotationSpec updates pod annotation with devId | https://github.com/nano-gpu/nano-gpu-scheduler/blob/84c30ba014487038b6bb3ff05017d5a30379643a/pkg/utils/pod.go#L65-L79 | package utils
import (
"fmt"
"strconv"
"strings"
"github.com/nano-gpu/nano-gpu-scheduler/pkg/types"
v1 "k8s.io/api/core/v1"
log "k8s.io/klog/v2"
)
func IsCompletedPod(pod *v1.Pod) bool {
if pod.DeletionTimestamp != nil {
return true
}
if pod.Status.Phase == v1.PodSucceeded || pod.Status.Phase == v1.PodFailed {
return true
}
return false
}
func IsGPUSharingPod(pod *v1.Pod) bool {
return GetGPUPercentFromPodResource(pod) > 0
}
func GetGPUIDFromAnnotation(pod *v1.Pod) (gpuIDs []int) {
if len(pod.ObjectMeta.Annotations) > 0 {
value, found := pod.ObjectMeta.Annotations[fmt.Sprintf(types.AnnotationGPUContainerOn, pod.Spec.Containers[0].Name)]
if found {
gpuIDStrs := strings.Split(value, ",")
for _, idStr := range gpuIDStrs {
id, err := strconv.Atoi(idStr)
if err != nil {
log.Warningf("warn: Failed due to %v for pod %s in ns %s", err, pod.Name, pod.Namespace)
}
gpuIDs = append(gpuIDs, id)
}
}
}
return gpuIDs
}
func GetGPUPercentFromPodResource(pod *v1.Pod) (gpuPercent uint) {
containers := pod.Spec.Containers
for _, container := range containers {
if val, ok := container.Resources.Limits[types.ResourceGPUPercent]; ok {
gpuPercent += uint(val.Value())
}
}
return gpuPercent
}
func arrayToString(array []int, delim string) string {
return strings.Trim(strings.Join(strings.Fields(fmt.Sprint(array)), ","), "[]")
} | Apache License 2.0 |
dhax/go-base | auth/jwt/authenticator.go | Authenticator | go | func Authenticator(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
token, claims, err := jwtauth.FromContext(r.Context())
if err != nil {
logging.GetLogEntry(r).Warn(err)
render.Render(w, r, ErrUnauthorized(ErrTokenUnauthorized))
return
}
if !token.Valid {
render.Render(w, r, ErrUnauthorized(ErrTokenExpired))
return
}
var c AppClaims
err = c.ParseClaims(claims)
if err != nil {
logging.GetLogEntry(r).Error(err)
render.Render(w, r, ErrUnauthorized(ErrInvalidAccessToken))
return
}
ctx := context.WithValue(r.Context(), ctxClaims, c)
next.ServeHTTP(w, r.WithContext(ctx))
})
} | Authenticator is a default authentication middleware to enforce access from the
Verifier middleware request context values. The Authenticator sends a 401 Unauthorized
response for any unverified tokens and passes the good ones through. | https://github.com/dhax/go-base/blob/c3809c7cabc5d64b30d9a413897e261a2e3e819c/auth/jwt/authenticator.go#L33-L61 | package jwt
import (
"context"
"net/http"
"github.com/go-chi/jwtauth"
"github.com/go-chi/render"
"github.com/dhax/go-base/logging"
)
type ctxKey int
const (
ctxClaims ctxKey = iota
ctxRefreshToken
)
func ClaimsFromCtx(ctx context.Context) AppClaims {
return ctx.Value(ctxClaims).(AppClaims)
}
func RefreshTokenFromCtx(ctx context.Context) string {
return ctx.Value(ctxRefreshToken).(string)
} | MIT License |
teh-cmc/seq | vendor/google.golang.org/grpc/benchmark/stats/timeseries.go | set | go | func (ts *timeseries) set(value int64) {
ts.slots[ts.head] = value
} | set sets the current value of the timeseries. | https://github.com/teh-cmc/seq/blob/edc834e7bcfe29f058802cb82c390bc36b84b1e3/vendor/google.golang.org/grpc/benchmark/stats/timeseries.go#L64-L66 | package stats
import (
"math"
"time"
)
type timeseries struct {
size int
resolution time.Duration
stepCount int64
head int
time time.Time
slots []int64
}
func newTimeSeries(initialTime time.Time, period, resolution time.Duration) *timeseries {
size := int(period.Nanoseconds()/resolution.Nanoseconds()) + 1
return ×eries{
size: size,
resolution: resolution,
stepCount: 1,
time: initialTime,
slots: make([]int64, size),
}
}
func (ts *timeseries) advanceTimeWithFill(t time.Time, value int64) {
advanceTo := t.Truncate(ts.resolution)
if !advanceTo.After(ts.time) {
ts.time = advanceTo
return
}
steps := int(advanceTo.Sub(ts.time).Nanoseconds() / ts.resolution.Nanoseconds())
ts.stepCount += int64(steps)
if steps > ts.size {
steps = ts.size
}
for steps > 0 {
ts.head = (ts.head + 1) % ts.size
ts.slots[ts.head] = value
steps--
}
ts.time = advanceTo
}
func (ts *timeseries) advanceTime(t time.Time) {
ts.advanceTimeWithFill(t, ts.slots[ts.head])
} | MIT License |
rackerlabs/cs-reboot-info | Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/cdn/v1/services/fixtures.go | HandleDeleteCDNServiceSuccessfully | go | func HandleDeleteCDNServiceSuccessfully(t *testing.T) {
th.Mux.HandleFunc("/services/96737ae3-cfc1-4c72-be88-5d0e7cc9a3f0", func(w http.ResponseWriter, r *http.Request) {
th.TestMethod(t, r, "DELETE")
th.TestHeader(t, r, "X-Auth-Token", fake.TokenID)
w.WriteHeader(http.StatusAccepted)
})
} | HandleDeleteCDNServiceSuccessfully creates an HTTP handler at `/services/{id}` on the test handler mux
that responds with a `Delete` response. | https://github.com/rackerlabs/cs-reboot-info/blob/acd1293844a39bf54f2e1049756499ef1b5bdf02/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/cdn/v1/services/fixtures.go#L366-L372 | package services
import (
"fmt"
"net/http"
"testing"
th "github.com/rackspace/gophercloud/testhelper"
fake "github.com/rackspace/gophercloud/testhelper/client"
)
func HandleListCDNServiceSuccessfully(t *testing.T) {
th.Mux.HandleFunc("/services", func(w http.ResponseWriter, r *http.Request) {
th.TestMethod(t, r, "GET")
th.TestHeader(t, r, "X-Auth-Token", fake.TokenID)
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
r.ParseForm()
marker := r.Form.Get("marker")
switch marker {
case "":
fmt.Fprintf(w, `
{
"links": [
{
"rel": "next",
"href": "https://www.poppycdn.io/v1.0/services?marker=96737ae3-cfc1-4c72-be88-5d0e7cc9a3f0&limit=20"
}
],
"services": [
{
"id": "96737ae3-cfc1-4c72-be88-5d0e7cc9a3f0",
"name": "mywebsite.com",
"domains": [
{
"domain": "www.mywebsite.com"
}
],
"origins": [
{
"origin": "mywebsite.com",
"port": 80,
"ssl": false
}
],
"caching": [
{
"name": "default",
"ttl": 3600
},
{
"name": "home",
"ttl": 17200,
"rules": [
{
"name": "index",
"request_url": "/index.htm"
}
]
},
{
"name": "images",
"ttl": 12800,
"rules": [
{
"name": "images",
"request_url": "*.png"
}
]
}
],
"restrictions": [
{
"name": "website only",
"rules": [
{
"name": "mywebsite.com",
"referrer": "www.mywebsite.com"
}
]
}
],
"flavor_id": "asia",
"status": "deployed",
"errors" : [],
"links": [
{
"href": "https://www.poppycdn.io/v1.0/services/96737ae3-cfc1-4c72-be88-5d0e7cc9a3f0",
"rel": "self"
},
{
"href": "mywebsite.com.cdn123.poppycdn.net",
"rel": "access_url"
},
{
"href": "https://www.poppycdn.io/v1.0/flavors/asia",
"rel": "flavor"
}
]
},
{
"id": "96737ae3-cfc1-4c72-be88-5d0e7cc9a3f1",
"name": "myothersite.com",
"domains": [
{
"domain": "www.myothersite.com"
}
],
"origins": [
{
"origin": "44.33.22.11",
"port": 80,
"ssl": false
},
{
"origin": "77.66.55.44",
"port": 80,
"ssl": false,
"rules": [
{
"name": "videos",
"request_url": "^/videos/*.m3u"
}
]
}
],
"caching": [
{
"name": "default",
"ttl": 3600
}
],
"restrictions": [
{}
],
"flavor_id": "europe",
"status": "deployed",
"links": [
{
"href": "https://www.poppycdn.io/v1.0/services/96737ae3-cfc1-4c72-be88-5d0e7cc9a3f1",
"rel": "self"
},
{
"href": "myothersite.com.poppycdn.net",
"rel": "access_url"
},
{
"href": "https://www.poppycdn.io/v1.0/flavors/europe",
"rel": "flavor"
}
]
}
]
}
`)
case "96737ae3-cfc1-4c72-be88-5d0e7cc9a3f1":
fmt.Fprintf(w, `{
"services": []
}`)
default:
t.Fatalf("Unexpected marker: [%s]", marker)
}
})
}
func HandleCreateCDNServiceSuccessfully(t *testing.T) {
th.Mux.HandleFunc("/services", func(w http.ResponseWriter, r *http.Request) {
th.TestMethod(t, r, "POST")
th.TestHeader(t, r, "X-Auth-Token", fake.TokenID)
th.TestJSONRequest(t, r, `
{
"name": "mywebsite.com",
"domains": [
{
"domain": "www.mywebsite.com"
},
{
"domain": "blog.mywebsite.com"
}
],
"origins": [
{
"origin": "mywebsite.com",
"port": 80,
"ssl": false
}
],
"restrictions": [
{
"name": "website only",
"rules": [
{
"name": "mywebsite.com",
"referrer": "www.mywebsite.com"
}
]
}
],
"caching": [
{
"name": "default",
"ttl": 3600
}
],
"flavor_id": "cdn"
}
`)
w.Header().Add("Location", "https://global.cdn.api.rackspacecloud.com/v1.0/services/96737ae3-cfc1-4c72-be88-5d0e7cc9a3f0")
w.WriteHeader(http.StatusAccepted)
})
}
func HandleGetCDNServiceSuccessfully(t *testing.T) {
th.Mux.HandleFunc("/services/96737ae3-cfc1-4c72-be88-5d0e7cc9a3f0", func(w http.ResponseWriter, r *http.Request) {
th.TestMethod(t, r, "GET")
th.TestHeader(t, r, "X-Auth-Token", fake.TokenID)
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
fmt.Fprintf(w, `
{
"id": "96737ae3-cfc1-4c72-be88-5d0e7cc9a3f0",
"name": "mywebsite.com",
"domains": [
{
"domain": "www.mywebsite.com",
"protocol": "http"
}
],
"origins": [
{
"origin": "mywebsite.com",
"port": 80,
"ssl": false
}
],
"caching": [
{
"name": "default",
"ttl": 3600
},
{
"name": "home",
"ttl": 17200,
"rules": [
{
"name": "index",
"request_url": "/index.htm"
}
]
},
{
"name": "images",
"ttl": 12800,
"rules": [
{
"name": "images",
"request_url": "*.png"
}
]
}
],
"restrictions": [
{
"name": "website only",
"rules": [
{
"name": "mywebsite.com",
"referrer": "www.mywebsite.com"
}
]
}
],
"flavor_id": "cdn",
"status": "deployed",
"errors" : [],
"links": [
{
"href": "https://global.cdn.api.rackspacecloud.com/v1.0/110011/services/96737ae3-cfc1-4c72-be88-5d0e7cc9a3f0",
"rel": "self"
},
{
"href": "blog.mywebsite.com.cdn1.raxcdn.com",
"rel": "access_url"
},
{
"href": "https://global.cdn.api.rackspacecloud.com/v1.0/110011/flavors/cdn",
"rel": "flavor"
}
]
}
`)
})
}
func HandleUpdateCDNServiceSuccessfully(t *testing.T) {
th.Mux.HandleFunc("/services/96737ae3-cfc1-4c72-be88-5d0e7cc9a3f0", func(w http.ResponseWriter, r *http.Request) {
th.TestMethod(t, r, "PATCH")
th.TestHeader(t, r, "X-Auth-Token", fake.TokenID)
th.TestJSONRequest(t, r, `
[
{
"op": "add",
"path": "/domains/-",
"value": {"domain": "appended.mocksite4.com"}
},
{
"op": "add",
"path": "/domains/4",
"value": {"domain": "inserted.mocksite4.com"}
},
{
"op": "add",
"path": "/domains",
"value": [
{"domain": "bulkadded1.mocksite4.com"},
{"domain": "bulkadded2.mocksite4.com"}
]
},
{
"op": "replace",
"path": "/origins/2",
"value": {"origin": "44.33.22.11", "port": 80, "ssl": false}
},
{
"op": "replace",
"path": "/origins",
"value": [
{"origin": "44.33.22.11", "port": 80, "ssl": false},
{"origin": "55.44.33.22", "port": 443, "ssl": true}
]
},
{
"op": "remove",
"path": "/caching/8"
},
{
"op": "remove",
"path": "/caching"
},
{
"op": "replace",
"path": "/name",
"value": "differentServiceName"
}
]
`)
w.Header().Add("Location", "https://www.poppycdn.io/v1.0/services/96737ae3-cfc1-4c72-be88-5d0e7cc9a3f0")
w.WriteHeader(http.StatusAccepted)
})
} | Apache License 2.0 |
haproxytech/dataplaneapi | operations/service_discovery/get_consuls_responses.go | SetPayload | go | func (o *GetConsulsOK) SetPayload(payload *GetConsulsOKBody) {
o.Payload = payload
} | SetPayload sets the payload to the get consuls o k response | https://github.com/haproxytech/dataplaneapi/blob/b362aae0b04d0e330bd9dcfbf9f315b670de013b/operations/service_discovery/get_consuls_responses.go#L59-L61 | package service_discovery
import (
"net/http"
"github.com/go-openapi/runtime"
"github.com/haproxytech/client-native/v2/models"
)
const GetConsulsOKCode int = 200
type GetConsulsOK struct {
Payload *GetConsulsOKBody `json:"body,omitempty"`
}
func NewGetConsulsOK() *GetConsulsOK {
return &GetConsulsOK{}
}
func (o *GetConsulsOK) WithPayload(payload *GetConsulsOKBody) *GetConsulsOK {
o.Payload = payload
return o
} | Apache License 2.0 |
sparebankenvest/azure-key-vault-to-kubernetes | cmd/azure-keyvault-controller/controller/secret_handler.go | NewAzureSecretHandler | go | func NewAzureSecretHandler(secretSpec *akv.AzureKeyVaultSecret, vaultService vault.Service, transformator transformers.Transformator) *azureSecretHandler {
return &azureSecretHandler{
secretSpec: secretSpec,
vaultService: vaultService,
transformator: transformator,
}
} | NewAzureSecretHandler return a new AzureSecretHandler | https://github.com/sparebankenvest/azure-key-vault-to-kubernetes/blob/6bcc978e2ccc2b86d505a2b2f04d457f15b72311/cmd/azure-keyvault-controller/controller/secret_handler.go#L65-L71 | package controller
import (
"encoding/base64"
"encoding/json"
"fmt"
"strings"
"github.com/SparebankenVest/azure-key-vault-to-kubernetes/pkg/akv2k8s/transformers"
vault "github.com/SparebankenVest/azure-key-vault-to-kubernetes/pkg/azure/keyvault/client"
akv "github.com/SparebankenVest/azure-key-vault-to-kubernetes/pkg/k8s/apis/azurekeyvault/v2beta1"
yaml "gopkg.in/yaml.v2"
corev1 "k8s.io/api/core/v1"
"k8s.io/klog/v2"
)
type KubernetesHandler interface {
HandleSecret() (map[string][]byte, error)
HandleConfigMap() (map[string]string, error)
}
type azureSecretHandler struct {
secretSpec *akv.AzureKeyVaultSecret
vaultService vault.Service
transformator transformers.Transformator
}
type azureCertificateHandler struct {
secretSpec *akv.AzureKeyVaultSecret
vaultService vault.Service
}
type azureKeyHandler struct {
secretSpec *akv.AzureKeyVaultSecret
vaultService vault.Service
}
type azureMultiValueSecretHandler struct {
secretSpec *akv.AzureKeyVaultSecret
vaultService vault.Service
} | Apache License 2.0 |
bankex/plasma-research | src/contracts/api/BankexPlasma.go | MAINCOINASSETID | go | func (_BankexPlasma *BankexPlasmaSession) MAINCOINASSETID() (common.Address, error) {
return _BankexPlasma.Contract.MAINCOINASSETID(&_BankexPlasma.CallOpts)
} | MAINCOINASSETID is a free data retrieval call binding the contract method 0x9c6a3907.
Solidity: function MAIN_COIN_ASSET_ID() constant returns(address) | https://github.com/bankex/plasma-research/blob/9fddba86cb7c44cc658ec6b777c41d9cf892fa69/src/contracts/api/BankexPlasma.go#L258-L260 | package api
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
_ = abi.U256
_ = bind.Bind
_ = common.Big1
_ = types.BloomLookup
_ = event.NewSubscription
)
const BankexPlasmaABI = "[{\"constant\":false,\"inputs\":[{\"name\":\"operator\",\"type\":\"address\"},{\"name\":\"\",\"type\":\"address\"},{\"name\":\"tokenId\",\"type\":\"uint256\"},{\"name\":\"\",\"type\":\"bytes\"}],\"name\":\"onERC721Received\",\"outputs\":[{\"name\":\"\",\"type\":\"bytes4\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"inputBytes\",\"type\":\"bytes\"},{\"name\":\"txProofBytes\",\"type\":\"bytes\"},{\"name\":\"blockIndex\",\"type\":\"uint64\"},{\"name\":\"\",\"type\":\"uint8\"}],\"name\":\"withdrawalChallangeSpend\",\"outputs\":[{\"name\":\"\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"ASSET_DECIMALS_TRUNCATION\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"fromIndex\",\"type\":\"uint256\"},{\"name\":\"newBlocks\",\"type\":\"bytes\"},{\"name\":\"rsv\",\"type\":\"bytes\"}],\"name\":\"submitBlocksSigned\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[],\"name\":\"renounceOwnership\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"blocksLength\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"owner\",\"outputs\":[{\"name\":\"\",\"type\":\"address\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"isOwner\",\"outputs\":[{\"name\":\"\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"token\",\"type\":\"address\"},{\"name\":\"amountArg\",\"type\":\"uint256\"}],\"name\":\"depositERC20\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"asset\",\"type\":\"address\"},{\"name\":\"assetOffset\",\"type\":\"uint256\"}],\"name\":\"setAssetOffset\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"MAIN_COIN_ASSET_ID\",\"outputs\":[{\"name\":\"\",\"type\":\"address\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"inputBytes\",\"type\":\"bytes\"}],\"name\":\"withdrawalBegin\",\"outputs\":[{\"name\":\"\",\"type\":\"bool\"}],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"fromIndex\",\"type\":\"uint256\"},{\"name\":\"newBlocks\",\"type\":\"bytes\"}],\"name\":\"submitBlocks\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"ERC721_ASSET_ID\",\"outputs\":[{\"name\":\"\",\"type\":\"address\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"asset\",\"type\":\"address\"}],\"name\":\"assetOffsets\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[],\"name\":\"deposit\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"token\",\"type\":\"address\"},{\"name\":\"tokenId\",\"type\":\"uint256\"}],\"name\":\"depositERC721\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"inputBytes\",\"type\":\"bytes\"},{\"name\":\"intervalId\",\"type\":\"uint64\"},{\"name\":\"token\",\"type\":\"address\"},{\"name\":\"tokenId\",\"type\":\"uint256\"}],\"name\":\"withdrawalEnd\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"i\",\"type\":\"uint256\"}],\"name\":\"blocks\",\"outputs\":[{\"name\":\"\",\"type\":\"address\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"newOwner\",\"type\":\"address\"}],\"name\":\"transferOwnership\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"PLASMA_ASSETS_TOTAL_SIZE\",\"outputs\":[{\"name\":\"\",\"type\":\"uint32\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"name\":\"token\",\"type\":\"address\"},{\"indexed\":true,\"name\":\"who\",\"type\":\"address\"},{\"indexed\":false,\"name\":\"intervalId\",\"type\":\"uint64\"},{\"indexed\":false,\"name\":\"begin\",\"type\":\"uint64\"},{\"indexed\":false,\"name\":\"end\",\"type\":\"uint64\"}],\"name\":\"AssetDeposited\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"name\":\"who\",\"type\":\"address\"},{\"indexed\":false,\"name\":\"amount\",\"type\":\"uint256\"}],\"name\":\"CoinDeposited\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"name\":\"token\",\"type\":\"address\"},{\"indexed\":true,\"name\":\"who\",\"type\":\"address\"},{\"indexed\":false,\"name\":\"amount\",\"type\":\"uint256\"}],\"name\":\"ERC20Deposited\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"name\":\"token\",\"type\":\"address\"},{\"indexed\":true,\"name\":\"who\",\"type\":\"address\"},{\"indexed\":false,\"name\":\"tokenId\",\"type\":\"uint256\"},{\"indexed\":true,\"name\":\"begin\",\"type\":\"uint64\"}],\"name\":\"ERC721Deposited\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"name\":\"owner\",\"type\":\"address\"},{\"indexed\":false,\"name\":\"blockIndex\",\"type\":\"uint32\"},{\"indexed\":false,\"name\":\"txIndex\",\"type\":\"uint32\"},{\"indexed\":false,\"name\":\"outputIndex\",\"type\":\"uint8\"},{\"indexed\":false,\"name\":\"assetId\",\"type\":\"address\"},{\"indexed\":false,\"name\":\"begin\",\"type\":\"uint64\"},{\"indexed\":false,\"name\":\"end\",\"type\":\"uint64\"}],\"name\":\"WithdrawalBegin\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"name\":\"length\",\"type\":\"uint256\"},{\"indexed\":false,\"name\":\"time\",\"type\":\"uint256\"}],\"name\":\"BlocksSubmitted\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"name\":\"previousOwner\",\"type\":\"address\"},{\"indexed\":true,\"name\":\"newOwner\",\"type\":\"address\"}],\"name\":\"OwnershipTransferred\",\"type\":\"event\"}]"
const BankexPlasmaBin = `0x6080604081905260008054600160a060020a0319163317808255600160a060020a0316917f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0908290a36000805260046020526200008a7f17ef568e3e12ab5b9c7254a8d58478811de00f9e6eb34345acd53bf8fd09d3ec640100000000620021d9620000d382021704565b60016000526004602052620000cd7fabd6e7cb50984ff9c2f3e18a2660c3353dadf4e3291deeb275dae2cd1e44fe05640100000000620021d9620000d382021704565b62000201565b8054156200012d576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252602b81526020018062003c56602b913960400191505060405180910390fd5b604080516080810182526000808252602080830182815293830182815260608401838152865460018101885596845291909220925192909401805493519151945167ffffffffffffffff1990941667ffffffffffffffff93841617604060020a608060020a031916680100000000000000009284169290920291909117608060020a60c060020a0319167001000000000000000000000000000000009483169490940293909317600160c060020a031678010000000000000000000000000000000000000000000000009190921602179055565b613a4580620002116000396000f3fe60806040526004361061012e5760003560e060020a900480639c6a3907116100af578063d0e30db011610073578063d0e30db0146107a3578063d29a4bf6146107ab578063e9755357146107e4578063f25b3f99146108b4578063f2fde38b146108de578063f93a936f146109115761012e565b80639c6a3907146105e6578063b964a183146105fb578063bada1164146106a1578063bfa6c37c1461075b578063cf616025146107705761012e565b80638ce0b5a2116100f65780638ce0b5a2146105195780638da5cb5b1461052e5780638f32d59b1461055f57806397feb926146105745780639b65e579146105ad5761012e565b8063150b7a02146101335780631718904a1461023b5780631b044c3c1461039a5780631f10e5da146103c1578063715018a614610502575b600080fd5b34801561013f57600080fd5b506102066004803603608081101561015657600080fd5b600160a060020a0382358116926020810135909116916040820135919081019060808101606082013564010000000081111561019157600080fd5b8201836020820111156101a357600080fd5b803590602001918460018302840111640100000000831117156101c557600080fd5b91908080601f01602080910402602001604051908101604052809392919081815260200183838082843760009201919091525092955061093f945050505050565b604080517fffffffff000000000000000000000000000000000000000000000000000000009092168252519081900360200190f35b34801561024757600080fd5b506103866004803603608081101561025e57600080fd5b81019060208101813564010000000081111561027957600080fd5b82018360208201111561028b57600080fd5b803590602001918460018302840111640100000000831117156102ad57600080fd5b91908080601f016020809104026020016040519081016040528093929190818152602001838380828437600092019190915250929594936020810193503591505064010000000081111561030057600080fd5b82018360208201111561031257600080fd5b8035906020019184600183028401116401000000008311171561033457600080fd5b91908080601f016020809104026020016040519081016040528093929190818152602001838380828437600092019190915250929550505081356001604060020a03169250506020013560ff16610a48565b604080519115158252519081900360200190f35b3480156103a657600080fd5b506103af610bc5565b60408051918252519081900360200190f35b3480156103cd57600080fd5b506103af600480360360608110156103e457600080fd5b8135919081019060408101602082013564010000000081111561040657600080fd5b82018360208201111561041857600080fd5b8035906020019184600183028401116401000000008311171561043a57600080fd5b91908080601f016020809104026020016040519081016040528093929190818152602001838380828437600092019190915250929594936020810193503591505064010000000081111561048d57600080fd5b82018360208201111561049f57600080fd5b803590602001918460018302840111640100000000831117156104c157600080fd5b91908080601f016020809104026020016040519081016040528093929190818152602001838380828437600092019190915250929550610bcf945050505050565b34801561050e57600080fd5b50610517610ce4565b005b34801561052557600080fd5b506103af610d4e565b34801561053a57600080fd5b50610543610d55565b60408051600160a060020a039092168252519081900360200190f35b34801561056b57600080fd5b50610386610d64565b34801561058057600080fd5b506105176004803603604081101561059757600080fd5b50600160a060020a038135169060200135610d75565b3480156105b957600080fd5b50610517600480360360408110156105d057600080fd5b50600160a060020a038135169060200135611086565b3480156105f257600080fd5b5061054361118a565b6103866004803603602081101561061157600080fd5b81019060208101813564010000000081111561062c57600080fd5b82018360208201111561063e57600080fd5b8035906020019184600183028401116401000000008311171561066057600080fd5b91908080601f01602080910402602001604051908101604052809392919081815260200183838082843760009201919091525092955061118f945050505050565b3480156106ad57600080fd5b506103af600480360360408110156106c457600080fd5b813591908101906040810160208201356401000000008111156106e657600080fd5b8201836020820111156106f857600080fd5b8035906020019184600183028401116401000000008311171561071a57600080fd5b91908080601f016020809104026020016040519081016040528093929190818152602001838380828437600092019190915250929550611364945050505050565b34801561076757600080fd5b5061054361138a565b34801561077c57600080fd5b506103af6004803603602081101561079357600080fd5b5035600160a060020a031661138f565b6105176113aa565b3480156107b757600080fd5b50610517600480360360408110156107ce57600080fd5b50600160a060020a0381351690602001356114ec565b3480156107f057600080fd5b506105176004803603608081101561080757600080fd5b81019060208101813564010000000081111561082257600080fd5b82018360208201111561083457600080fd5b8035906020019184600183028401116401000000008311171561085657600080fd5b91908080601f016020809104026020016040519081016040528093929190818152602001838380828437600092019190915250929550505081356001604060020a03169250506020810135600160a060020a031690604001356117ba565b3480156108c057600080fd5b50610543600480360360208110156108d757600080fd5b5035611c2d565b3480156108ea57600080fd5b506105176004803603602081101561090157600080fd5b5035600160a060020a0316611c59565b34801561091d57600080fd5b50610926611c78565b6040805163ffffffff9092168252519081900360200190f35b60408051606060020a330260208083019190915260348083018690528351808403909101815260549092019092528051910120600090600160a060020a03861630146109bf5760405160e560020a62461bcd02815260040180806020018281038252602f8152602001806139eb602f913960400191505060405180910390fd5b6002548114610a18576040805160e560020a62461bcd02815260206004820152601d60248201527f45524337323120746f6b656e20776173206e6f74206578706563746564000000604482015290519081900360640190fd5b505060006002557f150b7a0200000000000000000000000000000000000000000000000000000000949350505050565b6000610a526136d1565b610a5b86611c7f565b9050610a6561370d565b610a6e86611ca6565b82516020808501516040808701516060880151608089015160a08a015160c08b01518551606060020a600160a060020a039a8b168102828b015260e060020a63ffffffff998a168102603484015298909616909702603888015260f860020a60ff94851602603c88015297909116909202603d85015260c060020a6001604060020a03928316810260518601529190951602605983015280516041818403018152606190920181528151918301919091206000818152600690935291205492935091161515610b715760405160e560020a62461bcd0281526004018080602001828103825260218152602001806138f66021913960400191505060405180910390fd5b610b97610b86876001604060020a0316611c2d565b839062ffffff63ffffffff611cc216565b1515610ba257600080fd5b6000908152600660205260409020805460ff191690555060019695505050505050565b6509184e72a00081565b60008084846040516020018083815260200182805190602001908083835b60208310610c0c5780518252601f199092019160209182019101610bed565b6001836020036101000a038019825116818451168082178552505050505050905001925050506040516020818303038152906040528051906020012090506000610c5582611e0f565b9050610c618185611e60565b600160a060020a0316610c72610d55565b600160a060020a031614610cd0576040805160e560020a62461bcd02815260206004820152601160248201527f496e76616c6964207369676e6174757265000000000000000000000000000000604482015290519081900360640190fd5b610cda8686611f37565b9695505050505050565b610cec610d64565b1515610cf757600080fd5b60008054604051600160a060020a03909116907f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0908390a36000805473ffffffffffffffffffffffffffffffffffffffff19169055565b6001545b90565b600054600160a060020a031690565b600054600160a060020a0316331490565b600160a060020a0382166000908152600460205260409020610d9690612096565b1515610dd65760405160e560020a62461bcd0281526004018080602001828103825260248152602001806139a06024913960400191505060405180910390fd5b600160a060020a03821660009081526004602052604081206509184e72a0008304919081908190610e07908561209d565b925092509250600086600160a060020a03166370a08231306040518263ffffffff1660e060020a0281526004018082600160a060020a0316600160a060020a0316815260200191505060206040518083038186803b158015610e6857600080fd5b505afa158015610e7c573d6000803e3d6000fd5b505050506040513d6020811015610e9257600080fd5b50519050610ec2600160a060020a03881633306001604060020a0389166509184e72a0000263ffffffff61211916565b6000610f598289600160a060020a03166370a08231306040518263ffffffff1660e060020a0281526004018082600160a060020a0316600160a060020a0316815260200191505060206040518083038186803b158015610f2157600080fd5b505afa158015610f35573d6000803e3d6000fd5b505050506040513d6020811015610f4b57600080fd5b50519063ffffffff6121c416565b6040805182815290519192503391600160a060020a038b16917fe33e9822e3317b004d587136bab2627ea1ecfbba4eb79abddd0a56cfdd09c0e1919081900360200190a3604080516001604060020a038088168252808716602083015285168183015290513391600160a060020a038b16917f9032c225a61b3707cb5287484fb18ea898ee87a267f5ad3566cbef48ddc24fba9181900360600190a3505060408051606060020a600160a060020a03909816880260208083019190915233988902603483015260c060020a6001604060020a0396871681026048840152948616850260508301529490921690920260588201528151808203830181526060909101825280519083012060009586526005835290852080546001810182559086529190942001929092555050565b61108e610d64565b151561109957600080fd5b6001811180156110aa575061010081105b15156110ea5760405160e560020a62461bcd0281526004018080602001828103825260278152602001806139c46027913960400191505060405180910390fd5b600160a060020a03821660009081526003602052604090205415611158576040805160e560020a62461bcd02815260206004820152601b60248201527f61737365744f66667365742077617320616c7265616479207365740000000000604482015290519081900360640190fd5b600160a060020a038216600090815260036020908152604080832084905560049091529020611186906121d9565b5050565b600081565b60006111996136d1565b6111a283611c7f565b90507f7bdb2cf01b63deccbb5bd6324837d4263466ea905850e0adcc6c7ddb448181a3816000015182602001518360400151846060015185608001518660a001518760c001516040518088600160a060020a0316600160a060020a031681526020018763ffffffff1663ffffffff1681526020018663ffffffff1663ffffffff1681526020018560ff1660ff16815260200184600160a060020a0316600160a060020a03168152602001836001604060020a03166001604060020a03168152602001826001604060020a03166001604060020a0316815260200197505050505050505060405180910390a180516020808301516040808501516060860151608087015160a088015160c0909801518451606060020a600160a060020a03998a168102828a015260e060020a63ffffffff9889168102603484015297909516909602603887015260f860020a60ff90931692909202603c8601529590951602603d83015260c060020a6001604060020a03958616810260518401529490931690930260598401528151604181850301815260619093018252825192810192909220600090815260069092529020805460ff1916600190811790915590505b919050565b600061136e610d64565b151561137957600080fd5b6113838383611f37565b5092915050565b600181565b600160a060020a031660009081526003602052604090205490565b600080805260046020526509184e72a00034049080806113ea7f17ef568e3e12ab5b9c7254a8d58478811de00f9e6eb34345acd53bf8fd09d3ec8561209d565b604080516001604060020a03891681529051939650919450925033917f7d6babeeae6799e032644c4c2d100c2ab47a967aec6115cf3ec5c09b818a62b69181900360200190a2604080516001604060020a0380861682528085166020830152831681830152905133916000917f9032c225a61b3707cb5287484fb18ea898ee87a267f5ad3566cbef48ddc24fba9181900360600190a350506040805133606060020a81026020808401919091526001604060020a039590951660c060020a0260348301528251808303601c018152603c909201835281519185019190912060009182526005855291812080546001810182559082529390209092019190915550565b60408051600160a060020a038416606060020a810260208084019190915260348084018690528451808503909101815260548401808652815191909201206002557f42842e0e0000000000000000000000000000000000000000000000000000000090523360588301523060788301526098820184905291516342842e0e9160b88082019260009290919082900301818387803b15801561158c57600080fd5b505af11580156115a0573d6000803e3d6000fd5b50506002541591506115fe9050576040805160e560020a62461bcd02815260206004820152601960248201527f45524337323120746f6b656e206e6f7420726563656976656400000000000000604482015290519081900360640190fd5b6001600081815260046020529081908190611640907fabd6e7cb50984ff9c2f3e18a2660c3353dadf4e3291deeb275dae2cd1e44fe059063ffffffff61209d16565b925092509250816001604060020a031633600160a060020a031686600160a060020a03167f9e49df316dc5092c01f8b43df9e0a400cf0ce3c7f7d943da44da5a6a3446aa50876040518082815260200191505060405180910390a4604080516001604060020a0380861682528085166020830152831681830152905133916001917f9032c225a61b3707cb5287484fb18ea898ee87a267f5ad3566cbef48ddc24fba9181900360600190a360408051606060020a602080830182905233828102603485015260c060020a6001604060020a03988916810260488601529688168702605085018190529790951690950260588301528251808303840181526060830184528051908601206000948552600586528385208054600181810183559187528787200191909155600160a060020a0398909816026080820152609481019590955260b48501939093528251609c81860301815260bc90940183528351938201939093208352600790529020805460ff19169091179055565b6117c26136d1565b6117cb85611c7f565b80516020808301516040808501516060860151608087015160a088015160c08901518551606060020a600160a060020a039a8b168102828b015260e060020a63ffffffff998a168102603484015298909616909702603888015260f860020a60ff94851602603c88015297909116909202603d85015260c060020a6001604060020a039283168102605186015291909516026059830152805160418184030181526061909201815281519183019190912060008181526006909352912054929350911615156118ce5760405160e560020a62461bcd0281526004018080602001828103825260218152602001806138f66021913960400191505060405180910390fd5b6000818152600660209081526040808320805460ff1916905560a085015160c08601516080870151600160a060020a031685526004909352922061191c92909188919063ffffffff6122eb16565b506080820151600160a060020a031615156119b5578160000151600160a060020a03166108fc6119856509184e72a0006119798660a001516001604060020a03168760c001516001604060020a03166121c490919063ffffffff16565b9063ffffffff61277a16565b6040518115909202916000818181858888f193505050501580156119ad573d6000803e3d6000fd5b505050611c27565b6080820151600160a060020a031660011415611b69578160a001516001016001604060020a03168260c001516001604060020a0316141515611a2b5760405160e560020a62461bcd0281526004018080602001828103825260378152602001806139696037913960400191505060405180910390fd5b60a082015160408051600160a060020a038716606060020a02602080830191909152603482018790526001604060020a0390931660c060020a0260548201528151808203603c018152605c90910182528051908301206000818152600790935291205460ff161515611ad15760405160e560020a62461bcd0281526004018080602001828103825260218152602001806138d56021913960400191505060405180910390fd5b600081815260076020526040808220805460ff1916905580517f095ea7b3000000000000000000000000000000000000000000000000000000008152336004820152602481018790529051600160a060020a0388169263095ea7b3926044808201939182900301818387803b158015611b4957600080fd5b505af1158015611b5d573d6000803e3d6000fd5b50505050505050611c27565b83600160a060020a031663a9059cbb33611ba68560a001516001604060020a03168660c001516001604060020a03166121c490919063ffffffff16565b6040518363ffffffff1660e060020a0281526004018083600160a060020a0316600160a060020a0316815260200182815260200192505050602060405180830381600087803b158015611bf857600080fd5b505af1158015611c0c573d6000803e3d6000fd5b505050506040513d6020811015611c2257600080fd5b505050505b50505050565b6000600182815481101515611c3e57fe5b600091825260209091200154600160a060020a031692915050565b611c61610d64565b1515611c6c57600080fd5b611c75816127ac565b50565b62ffffff81565b611c876136d1565b611ca0611c9b611c9684612829565b61284e565b61291e565b92915050565b611cae61370d565b611ca0611cbd611c9684612829565b612a27565b6000806018856060015151811515611cd657fe5b0490506000611d0486602001516000015187602001516020015163ffffffff16612acf90919063ffffffff16565b60408701516020880151518851929350909160005b858160ff161015611dc557600080611d388c606001518460ff16612ae7565b909250905060018085161415611d8757611d5482888389612b0a565b9550611d6a63ffffffff808716908490612acf16565b9450611d8063ffffffff808916908490612b6c16565b9650611dac565b611d9387838884612b0a565b9550611da963ffffffff808916908490612b6c16565b96505b5050600263ffffffff9092169190910490600101611d19565b5063ffffffff8216158015611de557508663ffffffff168463ffffffff16145b8015611e02575087600160a060020a031683600160a060020a0316145b9998505050505050505050565b604080517f19457468657265756d205369676e6564204d6573736167653a0a333200000000602080830191909152603c8083019490945282518083039094018452605c909101909152815191012090565b60008060008084516041141515611e7d5760009350505050611ca0565b50505060208201516040830151606084015160001a601b60ff82161015611ea257601b015b8060ff16601b14158015611eba57508060ff16601c14155b15611ecb5760009350505050611ca0565b6040805160008152602080820180845289905260ff8416828401526060820186905260808201859052915160019260a0808401939192601f1981019281900390910190855afa158015611f22573d6000803e3d6000fd5b5050604051601f190151979650505050505050565b60008060148351811515611f4757fe5b60015491900491508414611fa5576040805160e560020a62461bcd02815260206004820152601160248201527f496e76616c69642066726f6d496e646578000000000000000000000000000000604482015290519081900360640190fd5b600154600090611fbb908663ffffffff6121c416565b9050611fcd858363ffffffff612b8716565b611fd860018261373c565b50805b8281101561204d57600080826014026020019050606060020a81880151049150816001848a0181548110151561200d57fe5b6000918252602090912001805473ffffffffffffffffffffffffffffffffffffffff1916600160a060020a03929092169190911790555050600101611fdb565b508181101561208d576001546040805142815290517ff32c68e7736e0f3f51cf7e6d33003550534f6ce10665ed8430cd92d66b0bbb999181900360200190a25b90039392505050565b5460001090565b600182015482546000918291829182918791604060020a90046001604060020a03169081106120c857fe5b60009182526020822001805460018901546001604060020a03604060020a92839004811697506000198a890101965092945061210f938a9392909104909116908686612b99565b9350509250925092565b604080517f23b872dd000000000000000000000000000000000000000000000000000000008152600160a060020a0385811660048301528481166024830152604482018490529151918616916323b872dd916064808201926020929091908290030181600087803b15801561218d57600080fd5b505af11580156121a1573d6000803e3d6000fd5b505050506040513d60208110156121b757600080fd5b50511515611c2757600080fd5b6000828211156121d357600080fd5b50900390565b80541561221a5760405160e560020a62461bcd02815260040180806020018281038252602b81526020018061393e602b913960400191505060405180910390fd5b604080516080810182526000808252602080830182815293830182815260608401838152865460018101885596845291909220925192909401805493519151945167ffffffffffffffff199094166001604060020a03938416176fffffffffffffffff00000000000000001916604060020a928416929092029190911777ffffffffffffffff000000000000000000000000000000001916608060020a948316949094029390931777ffffffffffffffffffffffffffffffffffffffffffffffff1660c060020a9190921602179055565b60006001604060020a0380831690841610612350576040805160e560020a62461bcd02815260206004820181905260248201527f726967687420626f756e64206c657373207468616e206c65667420626f756e64604482015290519081900360640190fd5b84546001604060020a038516106123b1576040805160e560020a62461bcd02815260206004820152601260248201527f76616c696420696e64657820626f756e64730000000000000000000000000000604482015290519081900360640190fd5b845460009086906001604060020a0387169081106123cb57fe5b6000918252602082200180548854919350889160c060020a9091046001604060020a03169081106123f857fe5b60009182526020822084548a5491909201935089916001604060020a03608060020a9091041690811061242757fe5b60009182526020909120845491019150604060020a90046001604060020a0316151561249d576040805160e560020a62461bcd02815260206004820152601f60248201527f72656d6f76656420696e74657276616c20646f65736e27742065786973747300604482015290519081900360640190fd5b82546001604060020a038088169116118015906124cf575082546001604060020a03604060020a909104811690861611155b1515612525576040805160e560020a62461bcd02815260206004820152601e60248201527f696e636f72726563742072656d6f7665642072616e676520626f756e64730000604482015290519081900360640190fd5b82546001604060020a038082168882161491604060020a900481169087161481801561254e5750805b1561268d578454600060c060020a9091046001604060020a031611156125aa578454845477ffffffffffffffff000000000000000000000000000000001916608060020a918290046001604060020a03169091021784556125d7565b845460018b018054608060020a9092046001604060020a031667ffffffffffffffff199092169190911790555b84546000608060020a9091046001604060020a0316111561262d578454835477ffffffffffffffffffffffffffffffffffffffffffffffff1660c060020a918290046001604060020a0316909102178355612666565b845460018b0180546fffffffffffffffff0000000000000000191660c060020a9092046001604060020a0316604060020a029190911790555b89548a906001604060020a038b1690811061267d57fe5b600091825260208220015561276d565b81156126b257845467ffffffffffffffff19166001604060020a03881617855561276d565b80156126e55784546fffffffffffffffff00000000000000001916604060020a6001604060020a038a160217855561276d565b84546001604060020a03898116604060020a9081026fffffffffffffffff0000000000000000198416178089559204811691612731918d918d91608060020a909104168b856001612ba6565b865477ffffffffffffffff000000000000000000000000000000001916608060020a6001604060020a0392831681029190911780895504169650505b5050505050949350505050565b600082151561278b57506000611ca0565b82820282848281151561279a57fe5b04146127a557600080fd5b9392505050565b600160a060020a03811615156127c157600080fd5b60008054604051600160a060020a03808516939216917f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e091a36000805473ffffffffffffffffffffffffffffffffffffffff1916600160a060020a0392909216919091179055565b612831613760565b506040805180820190915281518152602082810190820152919050565b6060612859826133ce565b151561286457600080fd5b600061286f8361340d565b9050806040519080825280602002602001820160405280156128ab57816020015b612898613760565b8152602001906001900390816128905790505b50915060006128bd846020015161346b565b60208501510190506000805b83811015612915576128da836134d4565b915060408051908101604052808381526020018481525085828151811015156128ff57fe5b60209081029091010152918101916001016128c9565b50505050919050565b6129266136d1565b60e06040519081016040528061295384600081518110151561294457fe5b90602001906020020151613564565b600160a060020a0316815260200161298284600181518110151561297357fe5b9060200190602002015161357b565b63ffffffff16815260200161299f84600281518110151561297357fe5b63ffffffff1681526020016129bc84600381518110151561297357fe5b60ff1681526020016129d684600481518110151561294457fe5b600160a060020a031681526020016129f684600581518110151561297357fe5b6001604060020a03168152602001612a1684600681518110151561297357fe5b6001604060020a0316905292915050565b612a2f61370d565b608060405190810160405280612a4d84600081518110151561297357fe5b63ffffffff168152602001612a81612a7c856001815181101515612a6d57fe5b9060200190602002015161284e565b6135b8565b8152602001612a9884600281518110151561294457fe5b600160a060020a03168152602001612ac7846003815181101515612ab857fe5b90602001906020020151613608565b905292915050565b600063ffffffff80841690831611156121d357600080fd5b60180201602081015160249091015160e060020a90910491606060020a90910490565b6040805160e060020a63ffffffff9687168102602080840191909152959096169095026024860152606060020a600160a060020a03938416810260288701529190921602603c8401528051603081850301815260509093019052815191012090565b600082820163ffffffff80851690821610156127a557600080fd5b6000828201838110156127a557600080fd5b6000610cda868686868660005b60006001604060020a0380841690851610612bf55760405160e560020a62461bcd0281526004018080602001828103825260278152602001806137f36027913960400191505060405180910390fd5b600187015460006001604060020a0391821611908716151580612c2057506001604060020a03861615155b151514612c615760405160e560020a62461bcd02815260040180806020018281038252602c815260200180613841602c913960400191505060405180910390fd5b612c6a87612096565b1515612c7957612c79876121d9565b865460009088906001604060020a038916908110612c9357fe5b6000918252602082208a549101925089906001604060020a038916908110612cb757fe5b906000526020600020019050876001604060020a031660001480612cf0575081546001604060020a03604060020a909104811690871610155b1515612d305760405160e560020a62461bcd02815260040180806020018281038252602781526020018061381a6027913960400191505060405180910390fd5b6001604060020a0387161580612d54575080546001604060020a0390811690861611155b1515612d945760405160e560020a62461bcd0281526004018080602001828103825260258152602001806138b06025913960400191505060405180910390fd5b6000876001604060020a03161115156000896001604060020a03161115151415612e335781546001604060020a03888116608060020a90920416148015612dee575080546001604060020a0389811660c060020a90920416145b1515612e2e5760405160e560020a62461bcd0281526004018080602001828103825260378152602001806137bc6037913960400191505060405180910390fd5b612fbb565b6000876001604060020a03161115612eb35760018901546001604060020a038881169116148015612e735750805460c060020a90046001604060020a0316155b1515612e2e5760405160e560020a62461bcd0281526004018080602001828103825260278152602001806139176027913960400191505060405180910390fd5b6000886001604060020a03161115612fbb5760018901546001604060020a03898116604060020a90920416148015612efa57508154608060020a90046001604060020a0316155b1515612f3a5760405160e560020a62461bcd0281526004018080602001828103825260268152602001806137966026913960400191505060405180910390fd5b8380612f5d575060018901546001604060020a03898116604060020a9092041614155b80612f7b575081546001604060020a03878116604060020a90920416145b1515612fbb5760405160e560020a62461bcd02815260040180806020018281038252604381526020018061386d6043913960600191505060405180910390fd5b600080896001604060020a0316118015612fe8575082546001604060020a03888116604060020a90920416145b9050600080896001604060020a0316118015613010575082546001604060020a038881169116145b90508115801561301e575080155b15613233578a6000018054905094508a6000016080604051908101604052808a6001604060020a03168152602001896001604060020a031681526020018b6001604060020a031681526020018c6001604060020a031681525090806001815401808255809150509060018203906000526020600020016000909192909190915060008201518160000160006101000a8154816001604060020a0302191690836001604060020a0316021790555060208201518160000160086101000a8154816001604060020a0302191690836001604060020a0316021790555060408201518160000160106101000a8154816001604060020a0302191690836001604060020a0316021790555060608201518160000160186101000a8154816001604060020a0302191690836001604060020a031602179055505050506000896001604060020a0316111561319b57825477ffffffffffffffffffffffffffffffffffffffffffffffff1660c060020a6001604060020a038716021783556131c8565b60018b0180546fffffffffffffffff00000000000000001916604060020a6001604060020a038816021790555b60008a6001604060020a0316111561320f57835477ffffffffffffffff000000000000000000000000000000001916608060020a6001604060020a0387160217845561322e565b60018b01805467ffffffffffffffff19166001604060020a0387161790555b6133c0565b81801561323d5750805b1561336657825484546001604060020a03604060020a92839004811683026fffffffffffffffff000000000000000019909216919091178087558554608060020a9081900483160277ffffffffffffffff000000000000000000000000000000001990911617865560018d01548c97508b82169290041614156132eb5760018b0180546fffffffffffffffff00000000000000001916604060020a6001604060020a0388160217905561333f565b82548b5486918d91608060020a9091046001604060020a031690811061330d57fe5b9060005260206000200160000160186101000a8154816001604060020a0302191690836001604060020a031602179055505b8a548b906001604060020a038b1690811061335657fe5b60009182526020822001556133c0565b811561339c5783546fffffffffffffffff00000000000000001916604060020a6001604060020a038916021784558994506133c0565b80156133c057825467ffffffffffffffff19166001604060020a0389161783558894505b505050509695505050505050565b805160009015156133e15750600061135f565b6020820151805160001a9060c060ff831610156134035760009250505061135f565b5060019392505050565b805160009015156134205750600061135f565b60008090506000613434846020015161346b565b602085015185519181019250015b8082101561346257613453826134d4565b60019093019290910190613442565b50909392505050565b8051600090811a608081101561348557600091505061135f565b60b88110806134a0575060c081108015906134a0575060f881105b156134af57600191505061135f565b60c08110156134c35760b51901905061135f565b60f51901905061135f565b50919050565b8051600090811a60808110156134ee57600191505061135f565b60b881101561350257607e1901905061135f565b60c081101561352f5760b78103600184019350806020036101000a845104600182018101935050506134ce565b60f88110156135435760be1901905061135f565b60019290920151602083900360f7016101000a900490910160f51901919050565b80516000906015101561357657600080fd5b611ca0825b8051600090811061358b57600080fd5b600061359a836020015161346b565b83516020948501518201519190039093036101000a90920492915050565b6135c0613760565b60408051908101604052806135dd84600081518110151561297357fe5b63ffffffff1681526020016135fa84600181518110151561297357fe5b63ffffffff16905292915050565b805160609060001061361957600080fd5b6000613628836020015161346b565b83516040805191839003808352601f19601f820116830160200190915291925060609082801561365f576020820181803883390190505b509050600081602001905061367b848760200151018285613684565b50949350505050565b801515613690576136cc565b5b602081106136b0578251825260209283019290910190601f1901613691565b8251825160208390036101000a60001901801990921691161782525b505050565b6040805160e081018252600080825260208201819052918101829052606081018290526080810182905260a0810182905260c081019190915290565b6040805160a081019091526000815260208101613728613760565b815260006020820152606060409091015290565b8154818355818111156136cc576000838152602090206136cc918101908301613777565b604080518082019091526000808252602082015290565b610d5291905b80821115613791576000815560010161377d565b509056fe707265762073686f756c6420726566657220746f20746865206c61737420696e74657276616c7072657620616e64206e6578742073686f756c6420726566657220746f20746865206e65696768626f72696e6720696e74657276616c73726967687420626f756e64206c657373206f7220657175616c20746f206c65667420626f756e64626567696e20636f756c64206e6f7420696e74657273656374207072657620696e74657276616c7072657620616e64206e65787420636f756c64206265207a65726f20696666206e6f20696e74657276616c7373686f756c6420626567696e2066726f6d2074686520656e64206f66206c617465737420696e74657276616c207768656e20616464696e6720746f2074686520656e64656e6420636f756c64206e6f7420696e74657273656374206e65787420696e74657276616c496e76616c696420746f6b656e206f7220746f6b65496420617267756d656e7473596f752073686f756c64207374617274207769746864726177616c2066697273746e6578742073686f756c6420726566657220746f2074686520666972737420696e74657276616c4f726465726564496e74657276616c4c6973742077617320616c726561647920696e697469616c697a6564497420697320616c6c6f77656420746f207769746864726177206f6e6c7920312045524337323120706572207472616e73616374696f6e4f70657261746f722073686f756c6420616464207468697320746f6b656e20666972737461737365744f66667365742073686f756c6420626520696e2072616e6765205b322c203235355d4f6e6c79207468697320636f6e74726163742073686f756c64206465706f7369742045524337323120746f6b656e73a165627a7a72305820911ce706247907596285ae93d27d017416411e201fb5f9aae977a2fff16b472500294f726465726564496e74657276616c4c6973742077617320616c726561647920696e697469616c697a6564`
func DeployBankexPlasma(auth *bind.TransactOpts, backend bind.ContractBackend) (common.Address, *types.Transaction, *BankexPlasma, error) {
parsed, err := abi.JSON(strings.NewReader(BankexPlasmaABI))
if err != nil {
return common.Address{}, nil, nil, err
}
address, tx, contract, err := bind.DeployContract(auth, parsed, common.FromHex(BankexPlasmaBin), backend)
if err != nil {
return common.Address{}, nil, nil, err
}
return address, tx, &BankexPlasma{BankexPlasmaCaller: BankexPlasmaCaller{contract: contract}, BankexPlasmaTransactor: BankexPlasmaTransactor{contract: contract}, BankexPlasmaFilterer: BankexPlasmaFilterer{contract: contract}}, nil
}
type BankexPlasma struct {
BankexPlasmaCaller
BankexPlasmaTransactor
BankexPlasmaFilterer
}
type BankexPlasmaCaller struct {
contract *bind.BoundContract
}
type BankexPlasmaTransactor struct {
contract *bind.BoundContract
}
type BankexPlasmaFilterer struct {
contract *bind.BoundContract
}
type BankexPlasmaSession struct {
Contract *BankexPlasma
CallOpts bind.CallOpts
TransactOpts bind.TransactOpts
}
type BankexPlasmaCallerSession struct {
Contract *BankexPlasmaCaller
CallOpts bind.CallOpts
}
type BankexPlasmaTransactorSession struct {
Contract *BankexPlasmaTransactor
TransactOpts bind.TransactOpts
}
type BankexPlasmaRaw struct {
Contract *BankexPlasma
}
type BankexPlasmaCallerRaw struct {
Contract *BankexPlasmaCaller
}
type BankexPlasmaTransactorRaw struct {
Contract *BankexPlasmaTransactor
}
func NewBankexPlasma(address common.Address, backend bind.ContractBackend) (*BankexPlasma, error) {
contract, err := bindBankexPlasma(address, backend, backend, backend)
if err != nil {
return nil, err
}
return &BankexPlasma{BankexPlasmaCaller: BankexPlasmaCaller{contract: contract}, BankexPlasmaTransactor: BankexPlasmaTransactor{contract: contract}, BankexPlasmaFilterer: BankexPlasmaFilterer{contract: contract}}, nil
}
func NewBankexPlasmaCaller(address common.Address, caller bind.ContractCaller) (*BankexPlasmaCaller, error) {
contract, err := bindBankexPlasma(address, caller, nil, nil)
if err != nil {
return nil, err
}
return &BankexPlasmaCaller{contract: contract}, nil
}
func NewBankexPlasmaTransactor(address common.Address, transactor bind.ContractTransactor) (*BankexPlasmaTransactor, error) {
contract, err := bindBankexPlasma(address, nil, transactor, nil)
if err != nil {
return nil, err
}
return &BankexPlasmaTransactor{contract: contract}, nil
}
func NewBankexPlasmaFilterer(address common.Address, filterer bind.ContractFilterer) (*BankexPlasmaFilterer, error) {
contract, err := bindBankexPlasma(address, nil, nil, filterer)
if err != nil {
return nil, err
}
return &BankexPlasmaFilterer{contract: contract}, nil
}
func bindBankexPlasma(address common.Address, caller bind.ContractCaller, transactor bind.ContractTransactor, filterer bind.ContractFilterer) (*bind.BoundContract, error) {
parsed, err := abi.JSON(strings.NewReader(BankexPlasmaABI))
if err != nil {
return nil, err
}
return bind.NewBoundContract(address, parsed, caller, transactor, filterer), nil
}
func (_BankexPlasma *BankexPlasmaRaw) Call(opts *bind.CallOpts, result interface{}, method string, params ...interface{}) error {
return _BankexPlasma.Contract.BankexPlasmaCaller.contract.Call(opts, result, method, params...)
}
func (_BankexPlasma *BankexPlasmaRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) {
return _BankexPlasma.Contract.BankexPlasmaTransactor.contract.Transfer(opts)
}
func (_BankexPlasma *BankexPlasmaRaw) Transact(opts *bind.TransactOpts, method string, params ...interface{}) (*types.Transaction, error) {
return _BankexPlasma.Contract.BankexPlasmaTransactor.contract.Transact(opts, method, params...)
}
func (_BankexPlasma *BankexPlasmaCallerRaw) Call(opts *bind.CallOpts, result interface{}, method string, params ...interface{}) error {
return _BankexPlasma.Contract.contract.Call(opts, result, method, params...)
}
func (_BankexPlasma *BankexPlasmaTransactorRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) {
return _BankexPlasma.Contract.contract.Transfer(opts)
}
func (_BankexPlasma *BankexPlasmaTransactorRaw) Transact(opts *bind.TransactOpts, method string, params ...interface{}) (*types.Transaction, error) {
return _BankexPlasma.Contract.contract.Transact(opts, method, params...)
}
func (_BankexPlasma *BankexPlasmaCaller) ASSETDECIMALSTRUNCATION(opts *bind.CallOpts) (*big.Int, error) {
var (
ret0 = new(*big.Int)
)
out := ret0
err := _BankexPlasma.contract.Call(opts, out, "ASSET_DECIMALS_TRUNCATION")
return *ret0, err
}
func (_BankexPlasma *BankexPlasmaSession) ASSETDECIMALSTRUNCATION() (*big.Int, error) {
return _BankexPlasma.Contract.ASSETDECIMALSTRUNCATION(&_BankexPlasma.CallOpts)
}
func (_BankexPlasma *BankexPlasmaCallerSession) ASSETDECIMALSTRUNCATION() (*big.Int, error) {
return _BankexPlasma.Contract.ASSETDECIMALSTRUNCATION(&_BankexPlasma.CallOpts)
}
func (_BankexPlasma *BankexPlasmaCaller) ERC721ASSETID(opts *bind.CallOpts) (common.Address, error) {
var (
ret0 = new(common.Address)
)
out := ret0
err := _BankexPlasma.contract.Call(opts, out, "ERC721_ASSET_ID")
return *ret0, err
}
func (_BankexPlasma *BankexPlasmaSession) ERC721ASSETID() (common.Address, error) {
return _BankexPlasma.Contract.ERC721ASSETID(&_BankexPlasma.CallOpts)
}
func (_BankexPlasma *BankexPlasmaCallerSession) ERC721ASSETID() (common.Address, error) {
return _BankexPlasma.Contract.ERC721ASSETID(&_BankexPlasma.CallOpts)
}
func (_BankexPlasma *BankexPlasmaCaller) MAINCOINASSETID(opts *bind.CallOpts) (common.Address, error) {
var (
ret0 = new(common.Address)
)
out := ret0
err := _BankexPlasma.contract.Call(opts, out, "MAIN_COIN_ASSET_ID")
return *ret0, err
} | Apache License 2.0 |
ethsana/sana | pkg/localstore/mode_put_test.go | benchmarkPutUpload | go | func benchmarkPutUpload(b *testing.B, o *Options, count, maxParallelUploads int) {
b.StopTimer()
db := newTestDB(b, o)
chunks := make([]swarm.Chunk, count)
for i := 0; i < count; i++ {
chunks[i] = generateTestRandomChunk()
}
errs := make(chan error)
b.StartTimer()
go func() {
sem := make(chan struct{}, maxParallelUploads)
for i := 0; i < count; i++ {
sem <- struct{}{}
go func(i int) {
defer func() { <-sem }()
_, err := db.Put(context.Background(), storage.ModePutUpload, chunks[i])
errs <- err
}(i)
}
}()
for i := 0; i < count; i++ {
err := <-errs
if err != nil {
b.Fatal(err)
}
}
} | benchmarkPutUpload runs a benchmark by uploading a specific number
of chunks with specified max parallel uploads. | https://github.com/ethsana/sana/blob/eb538a0f1800a322993040c2c2b8bb6649c443ae/pkg/localstore/mode_put_test.go#L738-L769 | package localstore
import (
"bytes"
"context"
"encoding/binary"
"errors"
"fmt"
"sync"
"testing"
"time"
"github.com/ethsana/sana/pkg/postage"
postagetesting "github.com/ethsana/sana/pkg/postage/testing"
"github.com/ethsana/sana/pkg/shed"
"github.com/ethsana/sana/pkg/storage"
"github.com/ethsana/sana/pkg/swarm"
"github.com/syndtr/goleveldb/leveldb"
)
var putModes = []storage.ModePut{
storage.ModePutRequest,
storage.ModePutRequestPin,
storage.ModePutSync,
storage.ModePutUpload,
storage.ModePutUploadPin,
storage.ModePutRequestCache,
}
func TestModePutRequest(t *testing.T) {
t.Cleanup(setWithinRadiusFunc(func(_ *DB, _ shed.Item) bool { return false }))
for _, tc := range multiChunkTestCases {
t.Run(tc.name, func(t *testing.T) {
db := newTestDB(t, nil)
chunks := generateTestRandomChunks(tc.count)
unreserveChunkBatch(t, db, 0, chunks...)
var storeTimestamp int64
t.Run("first put", func(t *testing.T) {
wantTimestamp := time.Now().UTC().UnixNano()
defer setNow(func() (t int64) {
return wantTimestamp
})()
storeTimestamp = wantTimestamp
_, err := db.Put(context.Background(), storage.ModePutRequest, chunks...)
if err != nil {
t.Fatal(err)
}
for _, ch := range chunks {
newRetrieveIndexesTestWithAccess(db, ch, wantTimestamp, wantTimestamp)(t)
}
newItemsCountTest(db.gcIndex, tc.count)(t)
newItemsCountTest(db.pullIndex, tc.count)(t)
newItemsCountTest(db.postageIndexIndex, tc.count)(t)
newIndexGCSizeTest(db)(t)
})
t.Run("second put", func(t *testing.T) {
wantTimestamp := time.Now().UTC().UnixNano()
defer setNow(func() (t int64) {
return wantTimestamp
})()
_, err := db.Put(context.Background(), storage.ModePutRequest, chunks...)
if err != nil {
t.Fatal(err)
}
for _, ch := range chunks {
newRetrieveIndexesTestWithAccess(db, ch, storeTimestamp, storeTimestamp)(t)
}
newItemsCountTest(db.gcIndex, tc.count)(t)
newItemsCountTest(db.pullIndex, tc.count)(t)
newItemsCountTest(db.postageIndexIndex, tc.count)(t)
newIndexGCSizeTest(db)(t)
})
})
}
}
func TestModePutRequestPin(t *testing.T) {
t.Cleanup(setWithinRadiusFunc(func(_ *DB, _ shed.Item) bool { return false }))
for _, tc := range multiChunkTestCases {
t.Run(tc.name, func(t *testing.T) {
db := newTestDB(t, nil)
chunks := generateTestRandomChunks(tc.count)
unreserveChunkBatch(t, db, 0, chunks...)
wantTimestamp := time.Now().UTC().UnixNano()
defer setNow(func() (t int64) {
return wantTimestamp
})()
_, err := db.Put(context.Background(), storage.ModePutRequestPin, chunks...)
if err != nil {
t.Fatal(err)
}
for _, ch := range chunks {
newRetrieveIndexesTestWithAccess(db, ch, wantTimestamp, wantTimestamp)(t)
newPinIndexTest(db, ch, nil)(t)
}
newItemsCountTest(db.postageChunksIndex, tc.count)(t)
newItemsCountTest(db.postageIndexIndex, tc.count)(t)
newItemsCountTest(db.gcIndex, 0)(t)
newIndexGCSizeTest(db)(t)
})
}
}
func TestModePutRequestCache(t *testing.T) {
t.Cleanup(setWithinRadiusFunc(func(_ *DB, _ shed.Item) bool { return true }))
for _, tc := range multiChunkTestCases {
t.Run(tc.name, func(t *testing.T) {
db := newTestDB(t, nil)
var chunks []swarm.Chunk
for i := 0; i < tc.count; i++ {
chunk := generateTestRandomChunkAt(swarm.NewAddress(db.baseKey), 2)
chunks = append(chunks, chunk)
}
unreserveChunkBatch(t, db, 2, chunks...)
wantTimestamp := time.Now().UTC().UnixNano()
defer setNow(func() (t int64) {
return wantTimestamp
})()
_, err := db.Put(context.Background(), storage.ModePutRequestCache, chunks...)
if err != nil {
t.Fatal(err)
}
for _, ch := range chunks {
newRetrieveIndexesTestWithAccess(db, ch, wantTimestamp, wantTimestamp)(t)
newPinIndexTest(db, ch, leveldb.ErrNotFound)(t)
}
newItemsCountTest(db.postageChunksIndex, tc.count)(t)
newItemsCountTest(db.postageIndexIndex, tc.count)(t)
newItemsCountTest(db.gcIndex, tc.count)(t)
newIndexGCSizeTest(db)(t)
})
}
}
func TestModePutSync(t *testing.T) {
t.Cleanup(setWithinRadiusFunc(func(_ *DB, _ shed.Item) bool { return false }))
for _, tc := range multiChunkTestCases {
t.Run(tc.name, func(t *testing.T) {
db := newTestDB(t, nil)
wantTimestamp := time.Now().UTC().UnixNano()
defer setNow(func() (t int64) {
return wantTimestamp
})()
chunks := generateTestRandomChunks(tc.count)
unreserveChunkBatch(t, db, 0, chunks...)
_, err := db.Put(context.Background(), storage.ModePutSync, chunks...)
if err != nil {
t.Fatal(err)
}
binIDs := make(map[uint8]uint64)
for _, ch := range chunks {
po := db.po(ch.Address())
binIDs[po]++
newRetrieveIndexesTestWithAccess(db, ch, wantTimestamp, wantTimestamp)(t)
newPullIndexTest(db, ch, binIDs[po], nil)(t)
newPinIndexTest(db, ch, leveldb.ErrNotFound)(t)
newIndexGCSizeTest(db)(t)
}
newItemsCountTest(db.postageChunksIndex, tc.count)(t)
newItemsCountTest(db.postageIndexIndex, tc.count)(t)
newItemsCountTest(db.gcIndex, tc.count)(t)
newIndexGCSizeTest(db)(t)
})
}
}
func TestModePutUpload(t *testing.T) {
for _, tc := range multiChunkTestCases {
t.Run(tc.name, func(t *testing.T) {
db := newTestDB(t, nil)
wantTimestamp := time.Now().UTC().UnixNano()
defer setNow(func() (t int64) {
return wantTimestamp
})()
chunks := generateTestRandomChunks(tc.count)
unreserveChunkBatch(t, db, 0, chunks...)
_, err := db.Put(context.Background(), storage.ModePutUpload, chunks...)
if err != nil {
t.Fatal(err)
}
binIDs := make(map[uint8]uint64)
for _, ch := range chunks {
po := db.po(ch.Address())
binIDs[po]++
newRetrieveIndexesTest(db, ch, wantTimestamp, 0)(t)
newPullIndexTest(db, ch, binIDs[po], nil)(t)
newPushIndexTest(db, ch, wantTimestamp, nil)(t)
newPinIndexTest(db, ch, leveldb.ErrNotFound)(t)
}
newItemsCountTest(db.postageIndexIndex, tc.count)(t)
newIndexGCSizeTest(db)(t)
})
}
}
func TestModePutUploadPin(t *testing.T) {
for _, tc := range multiChunkTestCases {
t.Run(tc.name, func(t *testing.T) {
db := newTestDB(t, nil)
wantTimestamp := time.Now().UTC().UnixNano()
defer setNow(func() (t int64) {
return wantTimestamp
})()
chunks := generateTestRandomChunks(tc.count)
unreserveChunkBatch(t, db, 0, chunks...)
_, err := db.Put(context.Background(), storage.ModePutUploadPin, chunks...)
if err != nil {
t.Fatal(err)
}
binIDs := make(map[uint8]uint64)
for _, ch := range chunks {
po := db.po(ch.Address())
binIDs[po]++
newRetrieveIndexesTest(db, ch, wantTimestamp, 0)(t)
newPullIndexTest(db, ch, binIDs[po], nil)(t)
newPushIndexTest(db, ch, wantTimestamp, nil)(t)
newPinIndexTest(db, ch, nil)(t)
}
newItemsCountTest(db.postageIndexIndex, tc.count)(t)
newIndexGCSizeTest(db)(t)
})
}
}
func TestModePutUpload_parallel(t *testing.T) {
for _, tc := range []struct {
name string
count int
}{
{
name: "one",
count: 1,
},
{
name: "two",
count: 2,
},
{
name: "eight",
count: 8,
},
} {
t.Run(tc.name, func(t *testing.T) {
db := newTestDB(t, nil)
uploadsCount := 100
workerCount := 100
chunksChan := make(chan []swarm.Chunk)
errChan := make(chan error)
doneChan := make(chan struct{})
defer close(doneChan)
for i := 0; i < workerCount; i++ {
go func(i int) {
for {
select {
case chunks, ok := <-chunksChan:
if !ok {
return
}
_, err := db.Put(context.Background(), storage.ModePutUpload, chunks...)
select {
case errChan <- err:
case <-doneChan:
}
case <-doneChan:
return
}
}
}(i)
}
chunks := make([]swarm.Chunk, 0)
var chunksMu sync.Mutex
go func() {
for i := 0; i < uploadsCount; i++ {
chs := generateTestRandomChunks(tc.count)
unreserveChunkBatch(t, db, 0, chunks...)
select {
case chunksChan <- chs:
case <-doneChan:
return
}
chunksMu.Lock()
chunks = append(chunks, chs...)
chunksMu.Unlock()
}
close(chunksChan)
}()
for i := 0; i < uploadsCount; i++ {
err := <-errChan
if err != nil {
t.Fatal(err)
}
}
chunksMu.Lock()
defer chunksMu.Unlock()
for _, ch := range chunks {
got, err := db.Get(context.Background(), storage.ModeGetRequest, ch.Address())
if err != nil {
t.Fatal(err)
}
if !bytes.Equal(got.Data(), ch.Data()) {
t.Fatalf("got chunk %s data %x, want %x", ch.Address(), got.Data(), ch.Data())
}
}
})
}
}
func TestModePut_sameChunk(t *testing.T) {
for _, tc := range multiChunkTestCases {
t.Run(tc.name, func(t *testing.T) {
chunks := generateTestRandomChunks(tc.count)
for _, tcn := range []struct {
name string
mode storage.ModePut
pullIndex bool
pushIndex bool
}{
{
name: "ModePutRequest",
mode: storage.ModePutRequest,
pullIndex: true,
pushIndex: false,
},
{
name: "ModePutRequestPin",
mode: storage.ModePutRequest,
pullIndex: true,
pushIndex: false,
},
{
name: "ModePutRequestCache",
mode: storage.ModePutRequestCache,
pullIndex: false,
pushIndex: false,
},
{
name: "ModePutUpload",
mode: storage.ModePutUpload,
pullIndex: true,
pushIndex: true,
},
{
name: "ModePutSync",
mode: storage.ModePutSync,
pullIndex: true,
pushIndex: false,
},
} {
t.Run(tcn.name, func(t *testing.T) {
db := newTestDB(t, nil)
unreserveChunkBatch(t, db, 0, chunks...)
for i := 0; i < 10; i++ {
exist, err := db.Put(context.Background(), tcn.mode, chunks...)
if err != nil {
t.Fatal(err)
}
for _, exists := range exist {
switch exists {
case false:
if i != 0 {
t.Fatal("should not exist only on first Put")
}
case true:
if i == 0 {
t.Fatal("should exist on all cases other than the first one")
}
}
}
count := func(b bool) (c int) {
if b {
return tc.count
}
return 0
}
newItemsCountTest(db.retrievalDataIndex, tc.count)(t)
newItemsCountTest(db.pullIndex, count(tcn.pullIndex))(t)
newItemsCountTest(db.pushIndex, count(tcn.pushIndex))(t)
newIndexGCSizeTest(db)(t)
}
})
}
})
}
}
func TestModePut_SameStamp(t *testing.T) {
ctx := context.Background()
stamp := postagetesting.MustNewStamp()
ts := time.Now().Unix()
for _, modeTc1 := range putModes {
for _, modeTc2 := range putModes {
for _, tc := range []struct {
persistChunk swarm.Chunk
discardChunk swarm.Chunk
}{
{
persistChunk: generateChunkWithTimestamp(stamp, ts),
discardChunk: generateChunkWithTimestamp(stamp, ts),
},
{
persistChunk: generateChunkWithTimestamp(stamp, ts+1),
discardChunk: generateChunkWithTimestamp(stamp, ts),
},
{
persistChunk: generateChunkWithTimestamp(stamp, ts),
discardChunk: generateChunkWithTimestamp(stamp, ts-1),
},
} {
t.Run(modeTc1.String()+modeTc2.String(), func(t *testing.T) {
db := newTestDB(t, nil)
unreserveChunkBatch(t, db, 0, tc.persistChunk, tc.discardChunk)
_, err := db.Put(ctx, modeTc1, tc.persistChunk)
if err != nil {
t.Fatal(err)
}
_, err = db.Put(ctx, modeTc2, tc.discardChunk)
if err != nil {
t.Fatal(err)
}
newItemsCountTest(db.retrievalDataIndex, 1)(t)
newItemsCountTest(db.postageChunksIndex, 1)(t)
newItemsCountTest(db.postageRadiusIndex, 1)(t)
newItemsCountTest(db.postageIndexIndex, 1)(t)
if modeTc1 != storage.ModePutRequestCache {
newItemsCountTest(db.pullIndex, 1)(t)
}
_, err = db.Get(ctx, storage.ModeGetLookup, tc.persistChunk.Address())
if err != nil {
t.Fatalf("expected no error, got %v", err)
}
_, err = db.Get(ctx, storage.ModeGetLookup, tc.discardChunk.Address())
if !errors.Is(err, storage.ErrNotFound) {
t.Fatalf("expected %v, got %v", storage.ErrNotFound, err)
}
})
}
}
}
}
func TestModePut_ImmutableStamp(t *testing.T) {
ctx := context.Background()
stamp := postagetesting.MustNewStamp()
ts := time.Now().Unix()
for _, modeTc1 := range putModes {
for _, modeTc2 := range putModes {
for _, tc := range []struct {
name string
persistChunk swarm.Chunk
discardChunk swarm.Chunk
}{
{
name: "same timestamps",
persistChunk: generateImmutableChunkWithTimestamp(stamp, ts),
discardChunk: generateImmutableChunkWithTimestamp(stamp, ts),
},
{
name: "higher timestamp",
persistChunk: generateImmutableChunkWithTimestamp(stamp, ts),
discardChunk: generateImmutableChunkWithTimestamp(stamp, ts+1),
},
{
name: "higher timestamp first",
persistChunk: generateImmutableChunkWithTimestamp(stamp, ts+1),
discardChunk: generateImmutableChunkWithTimestamp(stamp, ts),
},
} {
testName := fmt.Sprintf("%s %s %s", modeTc1.String(), modeTc2.String(), tc.name)
t.Run(testName, func(t *testing.T) {
db := newTestDB(t, nil)
unreserveChunkBatch(t, db, 0, tc.persistChunk, tc.discardChunk)
_, err := db.Put(ctx, modeTc1, tc.persistChunk)
if err != nil {
t.Fatal(err)
}
_, err = db.Put(ctx, modeTc2, tc.discardChunk)
if !errors.Is(err, ErrOverwrite) {
t.Fatalf("expected overwrite error on immutable stamp got %v", err)
}
newItemsCountTest(db.retrievalDataIndex, 1)(t)
newItemsCountTest(db.postageChunksIndex, 1)(t)
newItemsCountTest(db.postageRadiusIndex, 1)(t)
newItemsCountTest(db.postageIndexIndex, 1)(t)
if modeTc1 != storage.ModePutRequestCache {
newItemsCountTest(db.pullIndex, 1)(t)
}
_, err = db.Get(ctx, storage.ModeGetLookup, tc.persistChunk.Address())
if err != nil {
t.Fatalf("expected no error, got %v", err)
}
_, err = db.Get(ctx, storage.ModeGetLookup, tc.discardChunk.Address())
if !errors.Is(err, storage.ErrNotFound) {
t.Fatalf("expected %v, got %v", storage.ErrNotFound, err)
}
})
}
}
}
}
func generateChunkWithTimestamp(stamp *postage.Stamp, timestamp int64) swarm.Chunk {
tsBuf := make([]byte, 8)
binary.BigEndian.PutUint64(tsBuf, uint64(timestamp))
chunk := generateTestRandomChunk()
return chunk.WithStamp(postage.NewStamp(stamp.BatchID(), stamp.Index(), tsBuf, stamp.Sig()))
}
func generateImmutableChunkWithTimestamp(stamp *postage.Stamp, timestamp int64) swarm.Chunk {
return generateChunkWithTimestamp(stamp, timestamp).WithBatch(4, 12, 8, true)
}
func TestPutDuplicateChunks(t *testing.T) {
for _, mode := range []storage.ModePut{
storage.ModePutUpload,
storage.ModePutRequest,
storage.ModePutSync,
} {
t.Run(mode.String(), func(t *testing.T) {
db := newTestDB(t, nil)
ch := generateTestRandomChunk()
unreserveChunkBatch(t, db, 0, ch)
exist, err := db.Put(context.Background(), mode, ch, ch)
if err != nil {
t.Fatal(err)
}
if exist[0] {
t.Error("first chunk should not exist")
}
if !exist[1] {
t.Error("second chunk should exist")
}
newItemsCountTest(db.retrievalDataIndex, 1)(t)
got, err := db.Get(context.Background(), storage.ModeGetLookup, ch.Address())
if err != nil {
t.Fatal(err)
}
if !got.Address().Equal(ch.Address()) {
t.Errorf("got chunk address %s, want %s", got.Address(), ch.Address())
}
})
}
}
func BenchmarkPutUpload(b *testing.B) {
for _, count := range []int{
100,
1000,
10000,
100000,
} {
for _, maxParallelUploads := range []int{
1,
2,
4,
8,
16,
32,
} {
name := fmt.Sprintf("count %v parallel %v", count, maxParallelUploads)
b.Run(name, func(b *testing.B) {
for n := 0; n < b.N; n++ {
benchmarkPutUpload(b, nil, count, maxParallelUploads)
}
})
}
}
} | BSD 3-Clause New or Revised License |
nttdots/go-dots | dots_server/models/xorm_telemetry_pre_mitigation_dao.go | RegisterAttackDetail | go | func RegisterAttackDetail(session *xorm.Session, telePreMitigationId int64, attackDetail AttackDetail) (*db_models.AttackDetail, error) {
newAttackDetail := db_models.AttackDetail{
TelePreMitigationId: telePreMitigationId,
VendorId: attackDetail.VendorId,
AttackId: attackDetail.AttackId,
AttackName: attackDetail.AttackName,
AttackSeverity: ConvertAttackSeverityToString(attackDetail.AttackSeverity),
StartTime: attackDetail.StartTime,
EndTime: attackDetail.EndTime,
}
_, err := session.Insert(&newAttackDetail)
if err != nil {
log.Errorf("attack detail insert err: %s", err)
return nil, err
}
return &newAttackDetail, nil
} | Registered attack detail | https://github.com/nttdots/go-dots/blob/10ab8b86136dc9001a686a6276056218f9222cbc/dots_server/models/xorm_telemetry_pre_mitigation_dao.go#L645-L661 | package models
import (
"fmt"
"reflect"
"strconv"
"strings"
"github.com/go-xorm/xorm"
"github.com/nttdots/go-dots/dots_common/messages"
"github.com/nttdots/go-dots/dots_server/db_models"
log "github.com/sirupsen/logrus"
types "github.com/nttdots/go-dots/dots_common/types/data"
)
type PercentileType string
const (
LOW_PERCENTILE_L PercentileType = "LOW_PERCENTILE_L"
MID_PERCENTILE_L PercentileType = "MID_PERCENTILE_L"
HIGH_PERCENTILE_L PercentileType = "HIGH_PERCENTILE_L"
PEAK_L PercentileType = "PEAK_L"
LOW_PERCENTILE_C PercentileType = "LOW_PERCENTILE_C"
MID_PERCENTILE_C PercentileType = "MID_PERCENTILE_C"
HIGH_PERCENTILE_C PercentileType = "HIGH_PERCENTILE_C"
PEAK_C PercentileType = "PEAK_C"
)
func CreateTelemetryPreMitigation(customer *Customer, cuid string, cdid string, tmid int, dataRequest messages.PreOrOngoingMitigation, aliases types.Aliases, isPresent bool) error {
engine, err := ConnectDB()
if err != nil {
log.Errorf("Database connect error: %s", err)
return err
}
session := engine.NewSession()
defer session.Close()
err = session.Begin()
if err != nil {
return err
}
newPreMitigation, err := NewTelemetryPreMitigation(customer, cuid, dataRequest, aliases)
if err != nil {
return err
}
currentPreMitgations, err := GetTelemetryPreMitigationByCustomerIdAndCuid(customer.Id, cuid)
if err != nil {
return err
}
for _, currentPreMitigation := range currentPreMitgations {
targets, err := GetTelemetryTargets(engine, customer.Id, cuid, currentPreMitigation.Id)
if err != nil {
return err
}
if tmid == currentPreMitigation.Tmid {
continue
}
isOverlap := CheckOverlapTargetList(newPreMitigation.Targets.TargetList, targets.TargetList)
if isOverlap && tmid > currentPreMitigation.Tmid {
log.Debugf("Delete telemetry pre-mitigation aggregated by client with tmid = %+v", currentPreMitigation.Tmid)
err = DeleteCurrentTelemetryPreMitigation(engine, session, customer.Id, cuid, false, currentPreMitigation.Id)
if err != nil {
session.Rollback()
return err
}
}
}
currentUriFilteringTarget, err := GetUriFilteringPreMitigationList(engine, customer.Id, cuid)
if err != nil {
session.Rollback()
return err
}
for _, ufTarget := range currentUriFilteringTarget {
if tmid == ufTarget.Tmid {
continue
}
isOverlap := CheckOverlapTargetList(newPreMitigation.Targets.TargetList, ufTarget.TargetList)
if isOverlap && tmid > ufTarget.Tmid {
log.Debugf("Delete telemetry pre-mitigation aggregated by server with tmid = %+v", ufTarget.Tmid)
err = DeleteCurrentUriFilteringTelemetryPreMitigation(engine, session, customer.Id, cuid, ufTarget.Tmid)
if err != nil {
session.Rollback()
return err
}
}
}
if len(dataRequest.TotalTraffic) == 0 && len(dataRequest.TotalTrafficProtocol) == 0 && len(dataRequest.TotalTrafficPort) == 0 && len(dataRequest.TotalAttackTraffic) == 0 &&
len(dataRequest.TotalAttackTrafficProtocol) == 0 && len(dataRequest.TotalAttackTrafficPort) == 0 && !isExistedTotalAttackConnection(dataRequest.TotalAttackConnection) &&
!isExistedTotalAttackConnectionPort(dataRequest.TotalAttackConnectionPort) && len(dataRequest.AttackDetail) == 0 {
if !isPresent {
log.Debugf("Create telemetry pre-mitigation aggregated by server")
err = RegisterUriFilteringTelemetryPreMitigation(session, customer.Id, cuid, cdid, tmid, newPreMitigation)
if err != nil {
session.Rollback()
return err
}
} else {
log.Debugf("Update telemetry pre-mitigation aggregated by server")
err = updateUriFilteringTelemetryPreMitigation(session, customer.Id, cuid, cdid, tmid, newPreMitigation)
if err != nil {
session.Rollback()
return err
}
}
} else {
if !isPresent {
log.Debug("Create telemetry pre-mitigation aggregated by client")
err = createTelemetryPreMitigation(session, customer.Id, cuid, cdid, tmid, nil, newPreMitigation, nil)
if err != nil {
session.Rollback()
return err
}
} else {
log.Debug("Update telemetry pre-mitigation aggregated by client")
err = updateTelemetryPreMitigation(engine, session, customer.Id, cuid, cdid, tmid, newPreMitigation)
if err != nil {
session.Rollback()
return err
}
}
}
err = session.Commit()
return err
}
func createTelemetryPreMitigation(session *xorm.Session, customerId int, cuid string, cdid string, tmid int, currentPreMitigation *db_models.TelemetryPreMitigation, newPreMitigation *TelemetryPreMitigation, preMitigation *TelemetryPreMitigation) error {
var currentPreMitigationId int64
if currentPreMitigation == nil {
newTelePreMitigation, err := RegisterTelemetryPreMitigation(session, customerId, cuid, cdid, tmid)
if err != nil {
return err
}
currentPreMitigationId = newTelePreMitigation.Id
} else if preMitigation != nil {
currentPreMitigationId = currentPreMitigation.Id
if !reflect.DeepEqual(GetModelsTelemetryPreMitigation(*newPreMitigation), GetModelsTelemetryPreMitigation(*preMitigation)) {
_, err := session.Id(currentPreMitigation.Id).Update(currentPreMitigation)
if err != nil {
log.Errorf("telemetry_pre_mitigation update err: %s", err)
return err
}
}
}
err := CreateTargets(session, currentPreMitigationId, newPreMitigation.Targets)
if err != nil {
return err
}
err = RegisterTraffic(session, string(TELEMETRY), string(TARGET_PREFIX), currentPreMitigationId, string(TOTAL_TRAFFIC), newPreMitigation.TotalTraffic)
if err != nil {
return err
}
err = RegisterTrafficPerProtocol(session, string(TELEMETRY), currentPreMitigationId, string(TOTAL_TRAFFIC), newPreMitigation.TotalTrafficProtocol)
if err != nil {
return err
}
err = RegisterTrafficPerPort(session, string(TELEMETRY), currentPreMitigationId, string(TOTAL_TRAFFIC), newPreMitigation.TotalTrafficPort)
if err != nil {
return err
}
err = RegisterTraffic(session, string(TELEMETRY), string(TARGET_PREFIX), currentPreMitigationId, string(TOTAL_ATTACK_TRAFFIC), newPreMitigation.TotalAttackTraffic)
if err != nil {
return err
}
err = RegisterTrafficPerProtocol(session, string(TELEMETRY), currentPreMitigationId, string(TOTAL_ATTACK_TRAFFIC), newPreMitigation.TotalAttackTrafficProtocol)
if err != nil {
return err
}
err = RegisterTrafficPerPort(session, string(TELEMETRY), currentPreMitigationId, string(TOTAL_ATTACK_TRAFFIC), newPreMitigation.TotalAttackTrafficPort)
if err != nil {
return err
}
err = CreateTotalAttackConnection(session, string(TARGET_PREFIX),currentPreMitigationId, newPreMitigation.TotalAttackConnection)
if err != nil {
return err
}
err = CreateTotalAttackConnectionPort(session, currentPreMitigationId, newPreMitigation.TotalAttackConnectionPort)
if err != nil {
return err
}
err = CreateAttackDetail(session, currentPreMitigationId, newPreMitigation.AttackDetail)
if err != nil {
return err
}
return nil
}
func updateUriFilteringTelemetryPreMitigation(session *xorm.Session, customerId int, cuid string, cdid string, tmid int, newPreMitigation *TelemetryPreMitigation) error {
currentPreMitigation, err := db_models.GetTelemetryPreMitigationByTmid(engine, customerId, cuid, tmid)
if err != nil {
log.Errorf("Failed to get telemetry pre-mitigation. Error: %+v", err)
return err
}
if currentPreMitigation.Id > 0 {
log.Debugf("Delete telemetry pre-mitigation aggregated by client with tmid = %+v", tmid)
err = DeleteCurrentTelemetryPreMitigation(engine, session, customerId, cuid, false, currentPreMitigation.Id)
if err != nil {
return err
}
} else {
err = DeleteCurrentUriFilteringTelemetryPreMitigation(engine, session, customerId, cuid, tmid)
if err != nil {
return err
}
}
err = RegisterUriFilteringTelemetryPreMitigation(session, customerId, cuid, cdid, tmid, newPreMitigation)
if err != nil {
return err
}
return nil
}
func updateTelemetryPreMitigation(engine *xorm.Engine, session *xorm.Session, customerId int, cuid string, cdid string, tmid int, newPreMitigation *TelemetryPreMitigation) error {
currentPreMitigation, err := db_models.GetTelemetryPreMitigationByTmid(engine, customerId, cuid, tmid)
if err != nil {
log.Errorf("Failed to get telemetry pre-mitigation. Error: %+v", err)
return err
}
var preMitigation *TelemetryPreMitigation
if currentPreMitigation.Id > 0 {
preMitigationTmp, err := GetTelemetryPreMitigationAttributes(customerId, cuid, currentPreMitigation.Id)
if err != nil {
return err
}
preMitigation = &preMitigationTmp
err = DeleteCurrentTelemetryPreMitigation(engine, session, customerId, cuid, true, currentPreMitigation.Id)
if err != nil {
return err
}
} else {
preMitigation = nil
currentPreMitigation = nil
log.Debugf("Delete telemetry pre-mitigation aggregated by server with tmid=%+v", tmid)
err = DeleteCurrentUriFilteringTelemetryPreMitigation(engine, session, customerId, cuid, tmid)
if err != nil {
return err
}
}
err = createTelemetryPreMitigation(session, customerId, cuid, cdid, tmid, currentPreMitigation, newPreMitigation, preMitigation)
return nil
}
func UpdateTelemetryTotalAttackTraffic(engine *xorm.Engine, session *xorm.Session, mitigationScopeId int64, totalAttackTraffic []Traffic) (err error) {
trafficList, err := db_models.GetTelemetryTraffic(engine, string(TARGET_PREFIX), mitigationScopeId, string(TOTAL_ATTACK_TRAFFIC))
if err != nil {
return err
}
if len(trafficList) > 0 {
log.Debugf("Delete telemetry attributes as total-attack-traffic")
err = db_models.DeleteTelemetryTraffic(session, string(TARGET_PREFIX), mitigationScopeId, string(TOTAL_ATTACK_TRAFFIC))
if err != nil {
log.Errorf("Failed to delete total-attack-traffic. Error: %+v", err)
return
}
}
if len(totalAttackTraffic) > 0 {
log.Debugf("Create new telemetry attributes as total-attack-traffic")
err = RegisterTelemetryTraffic(session, string(TARGET_PREFIX), mitigationScopeId, string(TOTAL_ATTACK_TRAFFIC), totalAttackTraffic)
if err != nil {
return
}
}
return
}
func UpdateTelemetryAttackDetail(engine *xorm.Engine, session *xorm.Session, mitigationScopeId int64, attackDetailList []TelemetryAttackDetail) (err error) {
err = DeleteTelemetryAttackDetail(engine, session, mitigationScopeId, attackDetailList)
if err != nil {
return
}
if len(attackDetailList) > 0 {
err = CreateTelemetryAttackDetail(session, mitigationScopeId, attackDetailList)
if err != nil {
return
}
}
return
}
func RegisterTelemetryPreMitigation(session *xorm.Session, customerId int, cuid string, cdid string, tmid int) (*db_models.TelemetryPreMitigation, error) {
newTelemetryPreMitigation := db_models.TelemetryPreMitigation{
CustomerId: customerId,
Cuid: cuid,
Cdid: cdid,
Tmid: tmid,
}
_, err := session.Insert(&newTelemetryPreMitigation)
if err != nil {
log.Errorf("telemetry pre-mitigation insert err: %s", err)
return nil, err
}
return &newTelemetryPreMitigation , nil
}
func CreateTargets(session *xorm.Session, telePreMitigationId int64, targets Targets) error {
err := RegisterTelemetryPrefix(session, string(TELEMETRY), telePreMitigationId, string(TARGET_PREFIX), targets.TargetPrefix)
if err != nil {
return err
}
err = RegisterTelemetryPortRange(session, string(TELEMETRY), telePreMitigationId, string(TARGET_PREFIX), targets.TargetPortRange)
if err != nil {
return err
}
err = CreateTelemetryParameterValue(session, string(TELEMETRY), telePreMitigationId, targets.TargetProtocol, targets.FQDN, targets.URI, targets.AliasName)
if err != nil {
return err
}
return nil
}
func CreateTotalAttackConnection(session *xorm.Session, prefixType string, prefixId int64, tac TotalAttackConnection) error {
if tac.LowPercentileL != nil {
err := RegisterTotalAttackConnection(session, prefixType, prefixId, string(LOW_PERCENTILE_L), tac.LowPercentileL)
if err != nil {
return err
}
}
if tac.MidPercentileL != nil {
err := RegisterTotalAttackConnection(session, prefixType, prefixId, string(MID_PERCENTILE_L), tac.MidPercentileL)
if err != nil {
return err
}
}
if tac.HighPercentileL != nil {
err := RegisterTotalAttackConnection(session, prefixType, prefixId, string(HIGH_PERCENTILE_L), tac.HighPercentileL)
if err != nil {
return err
}
}
if tac.PeakL != nil {
err := RegisterTotalAttackConnection(session, prefixType, prefixId, string(PEAK_L), tac.PeakL)
if err != nil {
return err
}
}
return nil
}
func CreateTotalAttackConnectionPort(session *xorm.Session, telemetryPreMitigationId int64, tac TotalAttackConnectionPort) error {
if tac.LowPercentileL != nil {
err := RegisterTotalAttackConnectionPort(session, telemetryPreMitigationId, string(LOW_PERCENTILE_L), tac.LowPercentileL)
if err != nil {
return err
}
}
if tac.MidPercentileL != nil {
err := RegisterTotalAttackConnectionPort(session, telemetryPreMitigationId, string(MID_PERCENTILE_L), tac.MidPercentileL)
if err != nil {
return err
}
}
if tac.HighPercentileL != nil {
err := RegisterTotalAttackConnectionPort(session, telemetryPreMitigationId, string(HIGH_PERCENTILE_L), tac.HighPercentileL)
if err != nil {
return err
}
}
if tac.PeakL != nil {
err := RegisterTotalAttackConnectionPort(session, telemetryPreMitigationId, string(PEAK_L), tac.PeakL)
if err != nil {
return err
}
}
return nil
}
func CreateAttackDetail(session *xorm.Session, telePreMitigationId int64, attackDetails []AttackDetail) error {
for _, attackDetail := range attackDetails {
newAttackDetail, err := RegisterAttackDetail(session, telePreMitigationId, attackDetail)
if err != nil {
return err
}
if !reflect.DeepEqual(GetModelsSourceCount(&attackDetail.SourceCount), GetModelsSourceCount(nil)) {
err := RegisterSourceCount(session, newAttackDetail.Id, attackDetail.SourceCount)
if err != nil {
return err
}
}
if len(attackDetail.TopTalker) > 0 {
err := CreateTopTalker(session, newAttackDetail.Id, attackDetail.TopTalker)
if err != nil {
return err
}
}
}
return nil
}
func CreateTopTalker(session *xorm.Session, adId int64, topTalkers []TopTalker) error {
for _, topTalker := range topTalkers {
newTopTalker, err := RegisterTopTalker(session, adId, topTalker.SpoofedStatus)
if err != nil {
return err
}
prefixs := []Prefix{}
prefixs = append(prefixs, topTalker.SourcePrefix)
err = RegisterTelemetryPrefix(session, string(TELEMETRY), newTopTalker.Id, string(SOURCE_PREFIX), prefixs)
if err != nil {
return err
}
err = RegisterTelemetryPortRange(session, string(TELEMETRY), newTopTalker.Id, string(SOURCE_PREFIX), topTalker.SourcePortRange)
if err != nil {
return err
}
err = RegisterTelemetryIcmpTypeRange(session, newTopTalker.Id, topTalker.SourceIcmpTypeRange)
if err != nil {
return err
}
err = RegisterTraffic(session, string(TELEMETRY), string(SOURCE_PREFIX), newTopTalker.Id, string(TOTAL_ATTACK_TRAFFIC), topTalker.TotalAttackTraffic)
if err != nil {
return err
}
err = CreateTotalAttackConnection(session, string(SOURCE_PREFIX), newTopTalker.Id, topTalker.TotalAttackConnection)
if err != nil {
return err
}
}
return nil
}
func CreateTelemetryAttackDetail(session *xorm.Session, mitigationScopeId int64, attackDetailList []TelemetryAttackDetail) error {
log.Debugf("Create new telemetry attributes as attack-detail")
for _, attackDetail := range attackDetailList {
newAttackDetail, err := RegisterTelemetryAttackDetail(session, mitigationScopeId, attackDetail)
if err != nil {
return err
}
if !reflect.DeepEqual(GetModelsSourceCount(&attackDetail.SourceCount), GetModelsSourceCount(nil)) {
err := RegisterTelemetrySourceCount(session, newAttackDetail.Id, attackDetail.SourceCount)
if err != nil {
return err
}
}
if len(attackDetail.TopTalker) > 0 {
err := CreateTelemetryTopTalker(session, newAttackDetail.Id, attackDetail.TopTalker)
if err != nil {
return err
}
}
}
return nil
}
func CreateTelemetryTopTalker(session *xorm.Session, adId int64, topTalkers []TelemetryTopTalker) error {
for _, topTalker := range topTalkers {
newTopTalker, err := RegisterTelemetryTopTalker(session, adId, topTalker.SpoofedStatus)
if err != nil {
return err
}
err = RegisterTelemetrySourcePrefix(session, newTopTalker.Id, topTalker.SourcePrefix)
if err != nil {
return err
}
err = RegisterTelemetrySourcePortRange(session, newTopTalker.Id, topTalker.SourcePortRange)
if err != nil {
return err
}
err = RegisterTelemetrySourceIcmpTypeRange(session, newTopTalker.Id, topTalker.SourceIcmpTypeRange)
if err != nil {
return err
}
err = RegisterTelemetryTraffic(session, string(SOURCE_PREFIX), newTopTalker.Id, string(TOTAL_ATTACK_TRAFFIC), topTalker.TotalAttackTraffic)
if err != nil {
return err
}
err = CreateTelemetryTotalAttackConnection(session, string(SOURCE_PREFIX), newTopTalker.Id, topTalker.TotalAttackConnection)
if err != nil {
return err
}
}
return nil
}
func CreateTelemetryTotalAttackConnection(session *xorm.Session, prefixType string, prefixId int64, tac TelemetryTotalAttackConnection) error {
if !reflect.DeepEqual(GetModelsTelemetryConnectionPercentile(&tac.LowPercentileC), GetModelsTelemetryConnectionPercentile(nil)) {
err := RegisterTelemetryTotalAttackConnection(session, prefixType, prefixId, string(LOW_PERCENTILE_C), tac.LowPercentileC)
if err != nil {
return err
}
}
if !reflect.DeepEqual(GetModelsTelemetryConnectionPercentile(&tac.MidPercentileC), GetModelsTelemetryConnectionPercentile(nil)) {
err := RegisterTelemetryTotalAttackConnection(session, prefixType, prefixId, string(MID_PERCENTILE_C), tac.MidPercentileC)
if err != nil {
return err
}
}
if !reflect.DeepEqual(GetModelsTelemetryConnectionPercentile(&tac.HighPercentileC), GetModelsTelemetryConnectionPercentile(nil)) {
err := RegisterTelemetryTotalAttackConnection(session, prefixType, prefixId, string(HIGH_PERCENTILE_C), tac.HighPercentileC)
if err != nil {
return err
}
}
if !reflect.DeepEqual(GetModelsTelemetryConnectionPercentile(&tac.PeakC), GetModelsTelemetryConnectionPercentile(nil)) {
err := RegisterTelemetryTotalAttackConnection(session, prefixType, prefixId, string(PEAK_C), tac.PeakC)
if err != nil {
return err
}
}
return nil
}
func RegisterTotalAttackConnection(session *xorm.Session, prefixType string, prefixId int64, percentileType string, cpps []ConnectionProtocolPercentile) error {
tacList := []db_models.TotalAttackConnection{}
for _, v := range cpps {
tac := db_models.TotalAttackConnection{
PrefixType: prefixType,
PrefixTypeId: prefixId,
PercentileType: percentileType,
Protocol: v.Protocol,
Connection: v.Connection,
Embryonic: v.Embryonic,
ConnectionPs: v.ConnectionPs,
RequestPs: v.RequestPs,
PartialRequestPs: v.PartialRequestPs,
}
tacList = append(tacList, tac)
}
if len(tacList) > 0 {
_, err := session.Insert(&tacList)
if err != nil {
log.Errorf("total attack connection insert err: %s", err)
return err
}
}
return nil
}
func RegisterTotalAttackConnectionPort(session *xorm.Session, telePreMitigationId int64, percentileType string, cpps []ConnectionProtocolPortPercentile) error {
tacList := []db_models.TotalAttackConnectionPort{}
for _, v := range cpps {
tac := db_models.TotalAttackConnectionPort{
TelePreMitigationId: telePreMitigationId,
PercentileType: percentileType,
Protocol: v.Protocol,
Port: v.Port,
Connection: v.Connection,
Embryonic: v.Embryonic,
ConnectionPs: v.ConnectionPs,
RequestPs: v.RequestPs,
PartialRequestPs: v.PartialRequestPs,
}
tacList = append(tacList, tac)
}
if len(tacList) > 0 {
_, err := session.Insert(&tacList)
if err != nil {
log.Errorf("total attack connection port insert err: %s", err)
return err
}
}
return nil
} | Apache License 2.0 |
tikv/client-go | internal/locate/region_cache.go | String | go | func (l *KeyLocation) String() string {
return fmt.Sprintf("region %s,startKey:%s,endKey:%s", l.Region.String(), kv.StrKey(l.StartKey), kv.StrKey(l.EndKey))
} | String implements fmt.Stringer interface. | https://github.com/tikv/client-go/blob/a7d8ea1587e085fa951389656998493e841bccf7/internal/locate/region_cache.go#L717-L719 | package locate
import (
"bytes"
"context"
"fmt"
"math/rand"
"strings"
"sync"
"sync/atomic"
"time"
"unsafe"
"github.com/gogo/protobuf/proto"
"github.com/google/btree"
"github.com/opentracing/opentracing-go"
"github.com/pingcap/errors"
"github.com/pingcap/kvproto/pkg/metapb"
"github.com/tikv/client-go/v2/config"
tikverr "github.com/tikv/client-go/v2/error"
"github.com/tikv/client-go/v2/internal/client"
"github.com/tikv/client-go/v2/internal/logutil"
"github.com/tikv/client-go/v2/internal/retry"
"github.com/tikv/client-go/v2/kv"
"github.com/tikv/client-go/v2/metrics"
"github.com/tikv/client-go/v2/tikvrpc"
"github.com/tikv/client-go/v2/util"
pd "github.com/tikv/pd/client"
atomic2 "go.uber.org/atomic"
"go.uber.org/zap"
"golang.org/x/sync/singleflight"
"google.golang.org/grpc"
"google.golang.org/grpc/backoff"
"google.golang.org/grpc/credentials"
healthpb "google.golang.org/grpc/health/grpc_health_v1"
"google.golang.org/grpc/keepalive"
)
const (
btreeDegree = 32
invalidatedLastAccessTime = -1
defaultRegionsPerBatch = 128
)
var regionCacheTTLSec int64 = 600
func SetRegionCacheTTLSec(t int64) {
regionCacheTTLSec = t
}
const (
updated int32 = iota
needSync
)
type InvalidReason int32
const (
Ok InvalidReason = iota
NoLeader
RegionNotFound
EpochNotMatch
StoreNotFound
Other
)
type Region struct {
meta *metapb.Region
store unsafe.Pointer
syncFlag int32
lastAccess int64
invalidReason InvalidReason
}
type AccessIndex int
type regionStore struct {
workTiKVIdx AccessIndex
proxyTiKVIdx AccessIndex
workTiFlashIdx int32
stores []*Store
storeEpochs []uint32
accessIndex [numAccessMode][]int
}
func (r *regionStore) accessStore(mode accessMode, idx AccessIndex) (int, *Store) {
sidx := r.accessIndex[mode][idx]
return sidx, r.stores[sidx]
}
func (r *regionStore) getAccessIndex(mode accessMode, store *Store) AccessIndex {
for index, sidx := range r.accessIndex[mode] {
if r.stores[sidx].storeID == store.storeID {
return AccessIndex(index)
}
}
return -1
}
func (r *regionStore) accessStoreNum(mode accessMode) int {
return len(r.accessIndex[mode])
}
func (r *regionStore) clone() *regionStore {
storeEpochs := make([]uint32, len(r.stores))
rs := ®ionStore{
workTiFlashIdx: r.workTiFlashIdx,
proxyTiKVIdx: r.proxyTiKVIdx,
workTiKVIdx: r.workTiKVIdx,
stores: r.stores,
storeEpochs: storeEpochs,
}
copy(storeEpochs, r.storeEpochs)
for i := 0; i < int(numAccessMode); i++ {
rs.accessIndex[i] = make([]int, len(r.accessIndex[i]))
copy(rs.accessIndex[i], r.accessIndex[i])
}
return rs
}
func (r *regionStore) follower(seed uint32, op *storeSelectorOp) AccessIndex {
l := uint32(r.accessStoreNum(tiKVOnly))
if l <= 1 {
return r.workTiKVIdx
}
for retry := l - 1; retry > 0; retry-- {
followerIdx := AccessIndex(seed % (l - 1))
if followerIdx >= r.workTiKVIdx {
followerIdx++
}
storeIdx, s := r.accessStore(tiKVOnly, followerIdx)
if r.storeEpochs[storeIdx] == atomic.LoadUint32(&s.epoch) && r.filterStoreCandidate(followerIdx, op) {
return followerIdx
}
seed++
}
return r.workTiKVIdx
}
func (r *regionStore) kvPeer(seed uint32, op *storeSelectorOp) AccessIndex {
if op.leaderOnly {
return r.workTiKVIdx
}
candidates := make([]AccessIndex, 0, r.accessStoreNum(tiKVOnly))
for i := 0; i < r.accessStoreNum(tiKVOnly); i++ {
accessIdx := AccessIndex(i)
storeIdx, s := r.accessStore(tiKVOnly, accessIdx)
if r.storeEpochs[storeIdx] != atomic.LoadUint32(&s.epoch) || !r.filterStoreCandidate(accessIdx, op) {
continue
}
candidates = append(candidates, accessIdx)
}
if len(candidates) == 0 {
return r.workTiKVIdx
}
return candidates[seed%uint32(len(candidates))]
}
func (r *regionStore) filterStoreCandidate(aidx AccessIndex, op *storeSelectorOp) bool {
_, s := r.accessStore(tiKVOnly, aidx)
return s.IsLabelsMatch(op.labels)
}
func (r *Region) init(bo *retry.Backoffer, c *RegionCache) error {
rs := ®ionStore{
workTiKVIdx: 0,
proxyTiKVIdx: -1,
workTiFlashIdx: 0,
stores: make([]*Store, 0, len(r.meta.Peers)),
storeEpochs: make([]uint32, 0, len(r.meta.Peers)),
}
availablePeers := r.meta.GetPeers()[:0]
for _, p := range r.meta.Peers {
c.storeMu.RLock()
store, exists := c.storeMu.stores[p.StoreId]
c.storeMu.RUnlock()
if !exists {
store = c.getStoreByStoreID(p.StoreId)
}
addr, err := store.initResolve(bo, c)
if err != nil {
return err
}
if addr == "" {
continue
}
availablePeers = append(availablePeers, p)
switch store.storeType {
case tikvrpc.TiKV:
rs.accessIndex[tiKVOnly] = append(rs.accessIndex[tiKVOnly], len(rs.stores))
case tikvrpc.TiFlash:
rs.accessIndex[tiFlashOnly] = append(rs.accessIndex[tiFlashOnly], len(rs.stores))
}
rs.stores = append(rs.stores, store)
rs.storeEpochs = append(rs.storeEpochs, atomic.LoadUint32(&store.epoch))
}
if len(availablePeers) == 0 {
return errors.Errorf("no available peers, region: {%v}", r.meta)
}
r.meta.Peers = availablePeers
atomic.StorePointer(&r.store, unsafe.Pointer(rs))
r.lastAccess = time.Now().Unix()
return nil
}
func (r *Region) getStore() (store *regionStore) {
store = (*regionStore)(atomic.LoadPointer(&r.store))
return
}
func (r *Region) compareAndSwapStore(oldStore, newStore *regionStore) bool {
return atomic.CompareAndSwapPointer(&r.store, unsafe.Pointer(oldStore), unsafe.Pointer(newStore))
}
func (r *Region) checkRegionCacheTTL(ts int64) bool {
if _, err := util.EvalFailpoint("invalidateRegionCache"); err == nil {
r.invalidate(Other)
}
for {
lastAccess := atomic.LoadInt64(&r.lastAccess)
if ts-lastAccess > regionCacheTTLSec {
return false
}
if atomic.CompareAndSwapInt64(&r.lastAccess, lastAccess, ts) {
return true
}
}
}
func (r *Region) invalidate(reason InvalidReason) {
metrics.RegionCacheCounterWithInvalidateRegionFromCacheOK.Inc()
atomic.StoreInt32((*int32)(&r.invalidReason), int32(reason))
atomic.StoreInt64(&r.lastAccess, invalidatedLastAccessTime)
}
func (r *Region) scheduleReload() {
oldValue := atomic.LoadInt32(&r.syncFlag)
if oldValue != updated {
return
}
atomic.CompareAndSwapInt32(&r.syncFlag, oldValue, needSync)
}
func (r *Region) checkNeedReloadAndMarkUpdated() bool {
oldValue := atomic.LoadInt32(&r.syncFlag)
if oldValue == updated {
return false
}
return atomic.CompareAndSwapInt32(&r.syncFlag, oldValue, updated)
}
func (r *Region) checkNeedReload() bool {
v := atomic.LoadInt32(&r.syncFlag)
return v != updated
}
func (r *Region) isValid() bool {
return r != nil && !r.checkNeedReload() && r.checkRegionCacheTTL(time.Now().Unix())
}
type RegionCache struct {
pdClient pd.Client
enableForwarding bool
mu struct {
sync.RWMutex
regions map[RegionVerID]*Region
latestVersions map[uint64]RegionVerID
sorted *btree.BTree
}
storeMu struct {
sync.RWMutex
stores map[uint64]*Store
}
notifyCheckCh chan struct{}
closeCh chan struct{}
testingKnobs struct {
mockRequestLiveness func(s *Store, bo *retry.Backoffer) livenessState
}
}
func NewRegionCache(pdClient pd.Client) *RegionCache {
c := &RegionCache{
pdClient: pdClient,
}
c.mu.regions = make(map[RegionVerID]*Region)
c.mu.latestVersions = make(map[uint64]RegionVerID)
c.mu.sorted = btree.New(btreeDegree)
c.storeMu.stores = make(map[uint64]*Store)
c.notifyCheckCh = make(chan struct{}, 1)
c.closeCh = make(chan struct{})
interval := config.GetGlobalConfig().StoresRefreshInterval
go c.asyncCheckAndResolveLoop(time.Duration(interval) * time.Second)
c.enableForwarding = config.GetGlobalConfig().EnableForwarding
return c
}
func (c *RegionCache) clear() {
c.mu.Lock()
c.mu.regions = make(map[RegionVerID]*Region)
c.mu.latestVersions = make(map[uint64]RegionVerID)
c.mu.sorted = btree.New(btreeDegree)
c.mu.Unlock()
c.storeMu.Lock()
c.storeMu.stores = make(map[uint64]*Store)
c.storeMu.Unlock()
}
func (c *RegionCache) Close() {
close(c.closeCh)
}
func (c *RegionCache) asyncCheckAndResolveLoop(interval time.Duration) {
ticker := time.NewTicker(interval)
defer ticker.Stop()
var needCheckStores []*Store
for {
needCheckStores = needCheckStores[:0]
select {
case <-c.closeCh:
return
case <-c.notifyCheckCh:
c.checkAndResolve(needCheckStores, func(s *Store) bool {
return s.getResolveState() == needCheck
})
case <-ticker.C:
c.checkAndResolve(needCheckStores, func(s *Store) bool {
state := s.getResolveState()
return state != unresolved && state != tombstone && state != deleted
})
}
}
}
func (c *RegionCache) checkAndResolve(needCheckStores []*Store, needCheck func(*Store) bool) {
defer func() {
r := recover()
if r != nil {
logutil.BgLogger().Error("panic in the checkAndResolve goroutine",
zap.Reflect("r", r),
zap.Stack("stack trace"))
}
}()
c.storeMu.RLock()
for _, store := range c.storeMu.stores {
if needCheck(store) {
needCheckStores = append(needCheckStores, store)
}
}
c.storeMu.RUnlock()
for _, store := range needCheckStores {
_, err := store.reResolve(c)
tikverr.Log(err)
}
}
func (c *RegionCache) SetRegionCacheStore(id uint64, storeType tikvrpc.EndpointType, state uint64, labels []*metapb.StoreLabel) {
c.storeMu.Lock()
defer c.storeMu.Unlock()
c.storeMu.stores[id] = &Store{
storeID: id,
storeType: storeType,
state: state,
labels: labels,
}
}
func (c *RegionCache) SetPDClient(client pd.Client) {
c.pdClient = client
}
type RPCContext struct {
Region RegionVerID
Meta *metapb.Region
Peer *metapb.Peer
AccessIdx AccessIndex
Store *Store
Addr string
AccessMode accessMode
ProxyStore *Store
ProxyAddr string
TiKVNum int
}
func (c *RPCContext) String() string {
var runStoreType string
if c.Store != nil {
runStoreType = c.Store.storeType.Name()
}
res := fmt.Sprintf("region ID: %d, meta: %s, peer: %s, addr: %s, idx: %d, reqStoreType: %s, runStoreType: %s",
c.Region.GetID(), c.Meta, c.Peer, c.Addr, c.AccessIdx, c.AccessMode, runStoreType)
if c.ProxyStore != nil {
res += fmt.Sprintf(", proxy store id: %d, proxy addr: %s", c.ProxyStore.storeID, c.ProxyStore.addr)
}
return res
}
type storeSelectorOp struct {
leaderOnly bool
labels []*metapb.StoreLabel
}
type StoreSelectorOption func(*storeSelectorOp)
func WithMatchLabels(labels []*metapb.StoreLabel) StoreSelectorOption {
return func(op *storeSelectorOp) {
op.labels = append(op.labels, labels...)
}
}
func WithLeaderOnly() StoreSelectorOption {
return func(op *storeSelectorOp) {
op.leaderOnly = true
}
}
func (c *RegionCache) GetTiKVRPCContext(bo *retry.Backoffer, id RegionVerID, replicaRead kv.ReplicaReadType, followerStoreSeed uint32, opts ...StoreSelectorOption) (*RPCContext, error) {
ts := time.Now().Unix()
cachedRegion := c.GetCachedRegionWithRLock(id)
if cachedRegion == nil {
return nil, nil
}
if cachedRegion.checkNeedReload() {
return nil, nil
}
if !cachedRegion.checkRegionCacheTTL(ts) {
return nil, nil
}
regionStore := cachedRegion.getStore()
var (
store *Store
peer *metapb.Peer
storeIdx int
accessIdx AccessIndex
)
options := &storeSelectorOp{}
for _, op := range opts {
op(options)
}
isLeaderReq := false
switch replicaRead {
case kv.ReplicaReadFollower:
store, peer, accessIdx, storeIdx = cachedRegion.FollowerStorePeer(regionStore, followerStoreSeed, options)
case kv.ReplicaReadMixed:
store, peer, accessIdx, storeIdx = cachedRegion.AnyStorePeer(regionStore, followerStoreSeed, options)
default:
isLeaderReq = true
store, peer, accessIdx, storeIdx = cachedRegion.WorkStorePeer(regionStore)
}
addr, err := c.getStoreAddr(bo, cachedRegion, store)
if err != nil {
return nil, err
}
if val, err := util.EvalFailpoint("injectWrongStoreAddr"); err == nil {
if a, ok := val.(string); ok && len(a) > 0 {
addr = a
}
}
if store == nil || len(addr) == 0 {
cachedRegion.invalidate(StoreNotFound)
return nil, nil
}
storeFailEpoch := atomic.LoadUint32(&store.epoch)
if storeFailEpoch != regionStore.storeEpochs[storeIdx] {
cachedRegion.invalidate(Other)
logutil.BgLogger().Info("invalidate current region, because others failed on same store",
zap.Uint64("region", id.GetID()),
zap.String("store", store.addr))
return nil, nil
}
var (
proxyStore *Store
proxyAddr string
)
if c.enableForwarding && isLeaderReq {
if atomic.LoadInt32(&store.unreachable) == 0 {
regionStore.unsetProxyStoreIfNeeded(cachedRegion)
} else {
proxyStore, _, _ = c.getProxyStore(cachedRegion, store, regionStore, accessIdx)
if proxyStore != nil {
proxyAddr, err = c.getStoreAddr(bo, cachedRegion, proxyStore)
if err != nil {
return nil, err
}
}
}
}
return &RPCContext{
Region: id,
Meta: cachedRegion.meta,
Peer: peer,
AccessIdx: accessIdx,
Store: store,
Addr: addr,
AccessMode: tiKVOnly,
ProxyStore: proxyStore,
ProxyAddr: proxyAddr,
TiKVNum: regionStore.accessStoreNum(tiKVOnly),
}, nil
}
func (c *RegionCache) GetAllValidTiFlashStores(id RegionVerID, currentStore *Store) []uint64 {
allStores := make([]uint64, 0, 2)
allStores = append(allStores, currentStore.storeID)
ts := time.Now().Unix()
cachedRegion := c.GetCachedRegionWithRLock(id)
if cachedRegion == nil {
return allStores
}
if !cachedRegion.checkRegionCacheTTL(ts) {
return allStores
}
regionStore := cachedRegion.getStore()
currentIndex := regionStore.getAccessIndex(tiFlashOnly, currentStore)
if currentIndex == -1 {
return allStores
}
for startOffset := 1; startOffset < regionStore.accessStoreNum(tiFlashOnly); startOffset++ {
accessIdx := AccessIndex((int(currentIndex) + startOffset) % regionStore.accessStoreNum(tiFlashOnly))
storeIdx, store := regionStore.accessStore(tiFlashOnly, accessIdx)
if store.getResolveState() == needCheck {
continue
}
storeFailEpoch := atomic.LoadUint32(&store.epoch)
if storeFailEpoch != regionStore.storeEpochs[storeIdx] {
continue
}
allStores = append(allStores, store.storeID)
}
return allStores
}
func (c *RegionCache) GetTiFlashRPCContext(bo *retry.Backoffer, id RegionVerID, loadBalance bool) (*RPCContext, error) {
ts := time.Now().Unix()
cachedRegion := c.GetCachedRegionWithRLock(id)
if cachedRegion == nil {
return nil, nil
}
if !cachedRegion.checkRegionCacheTTL(ts) {
return nil, nil
}
regionStore := cachedRegion.getStore()
var sIdx int
if loadBalance {
sIdx = int(atomic.AddInt32(®ionStore.workTiFlashIdx, 1))
} else {
sIdx = int(atomic.LoadInt32(®ionStore.workTiFlashIdx))
}
for i := 0; i < regionStore.accessStoreNum(tiFlashOnly); i++ {
accessIdx := AccessIndex((sIdx + i) % regionStore.accessStoreNum(tiFlashOnly))
storeIdx, store := regionStore.accessStore(tiFlashOnly, accessIdx)
addr, err := c.getStoreAddr(bo, cachedRegion, store)
if err != nil {
return nil, err
}
if len(addr) == 0 {
cachedRegion.invalidate(StoreNotFound)
return nil, nil
}
if store.getResolveState() == needCheck {
_, err := store.reResolve(c)
tikverr.Log(err)
}
atomic.StoreInt32(®ionStore.workTiFlashIdx, int32(accessIdx))
peer := cachedRegion.meta.Peers[storeIdx]
storeFailEpoch := atomic.LoadUint32(&store.epoch)
if storeFailEpoch != regionStore.storeEpochs[storeIdx] {
cachedRegion.invalidate(Other)
logutil.BgLogger().Info("invalidate current region, because others failed on same store",
zap.Uint64("region", id.GetID()),
zap.String("store", store.addr))
continue
}
return &RPCContext{
Region: id,
Meta: cachedRegion.meta,
Peer: peer,
AccessIdx: accessIdx,
Store: store,
Addr: addr,
AccessMode: tiFlashOnly,
TiKVNum: regionStore.accessStoreNum(tiKVOnly),
}, nil
}
cachedRegion.invalidate(Other)
return nil, nil
}
type KeyLocation struct {
Region RegionVerID
StartKey []byte
EndKey []byte
}
func (l *KeyLocation) Contains(key []byte) bool {
return bytes.Compare(l.StartKey, key) <= 0 &&
(bytes.Compare(key, l.EndKey) < 0 || len(l.EndKey) == 0)
} | Apache License 2.0 |
topfreegames/pitaya | mocks/app.go | RPCTo | go | func (m *MockPitaya) RPCTo(arg0 context.Context, arg1, arg2 string, arg3, arg4 proto.Message) error {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "RPCTo", arg0, arg1, arg2, arg3, arg4)
ret0, _ := ret[0].(error)
return ret0
} | RPCTo mocks base method | https://github.com/topfreegames/pitaya/blob/d2ff6dc24bb104c76ab4bdcf2896cfcf5f3f01ce/mocks/app.go#L390-L395 | package mocks
import (
context "context"
gomock "github.com/golang/mock/gomock"
proto "github.com/golang/protobuf/proto"
cluster "github.com/topfreegames/pitaya/v2/cluster"
component "github.com/topfreegames/pitaya/v2/component"
config "github.com/topfreegames/pitaya/v2/config"
interfaces "github.com/topfreegames/pitaya/v2/interfaces"
metrics "github.com/topfreegames/pitaya/v2/metrics"
router "github.com/topfreegames/pitaya/v2/router"
session "github.com/topfreegames/pitaya/v2/session"
worker "github.com/topfreegames/pitaya/v2/worker"
reflect "reflect"
time "time"
)
type MockPitaya struct {
ctrl *gomock.Controller
recorder *MockPitayaMockRecorder
}
type MockPitayaMockRecorder struct {
mock *MockPitaya
}
func NewMockPitaya(ctrl *gomock.Controller) *MockPitaya {
mock := &MockPitaya{ctrl: ctrl}
mock.recorder = &MockPitayaMockRecorder{mock}
return mock
}
func (m *MockPitaya) EXPECT() *MockPitayaMockRecorder {
return m.recorder
}
func (m *MockPitaya) AddRoute(arg0 string, arg1 router.RoutingFunc) error {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "AddRoute", arg0, arg1)
ret0, _ := ret[0].(error)
return ret0
}
func (mr *MockPitayaMockRecorder) AddRoute(arg0, arg1 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AddRoute", reflect.TypeOf((*MockPitaya)(nil).AddRoute), arg0, arg1)
}
func (m *MockPitaya) Documentation(arg0 bool) (map[string]interface{}, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "Documentation", arg0)
ret0, _ := ret[0].(map[string]interface{})
ret1, _ := ret[1].(error)
return ret0, ret1
}
func (mr *MockPitayaMockRecorder) Documentation(arg0 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Documentation", reflect.TypeOf((*MockPitaya)(nil).Documentation), arg0)
}
func (m *MockPitaya) GetDieChan() chan bool {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "GetDieChan")
ret0, _ := ret[0].(chan bool)
return ret0
}
func (mr *MockPitayaMockRecorder) GetDieChan() *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetDieChan", reflect.TypeOf((*MockPitaya)(nil).GetDieChan))
}
func (m *MockPitaya) GetMetricsReporters() []metrics.Reporter {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "GetMetricsReporters")
ret0, _ := ret[0].([]metrics.Reporter)
return ret0
}
func (mr *MockPitayaMockRecorder) GetMetricsReporters() *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetMetricsReporters", reflect.TypeOf((*MockPitaya)(nil).GetMetricsReporters))
}
func (m *MockPitaya) GetModule(arg0 string) (interfaces.Module, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "GetModule", arg0)
ret0, _ := ret[0].(interfaces.Module)
ret1, _ := ret[1].(error)
return ret0, ret1
}
func (mr *MockPitayaMockRecorder) GetModule(arg0 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetModule", reflect.TypeOf((*MockPitaya)(nil).GetModule), arg0)
}
func (m *MockPitaya) GetServer() *cluster.Server {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "GetServer")
ret0, _ := ret[0].(*cluster.Server)
return ret0
}
func (mr *MockPitayaMockRecorder) GetServer() *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetServer", reflect.TypeOf((*MockPitaya)(nil).GetServer))
}
func (m *MockPitaya) GetServerByID(arg0 string) (*cluster.Server, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "GetServerByID", arg0)
ret0, _ := ret[0].(*cluster.Server)
ret1, _ := ret[1].(error)
return ret0, ret1
}
func (mr *MockPitayaMockRecorder) GetServerByID(arg0 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetServerByID", reflect.TypeOf((*MockPitaya)(nil).GetServerByID), arg0)
}
func (m *MockPitaya) GetServerID() string {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "GetServerID")
ret0, _ := ret[0].(string)
return ret0
}
func (mr *MockPitayaMockRecorder) GetServerID() *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetServerID", reflect.TypeOf((*MockPitaya)(nil).GetServerID))
}
func (m *MockPitaya) GetServers() []*cluster.Server {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "GetServers")
ret0, _ := ret[0].([]*cluster.Server)
return ret0
}
func (mr *MockPitayaMockRecorder) GetServers() *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetServers", reflect.TypeOf((*MockPitaya)(nil).GetServers))
}
func (m *MockPitaya) GetServersByType(arg0 string) (map[string]*cluster.Server, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "GetServersByType", arg0)
ret0, _ := ret[0].(map[string]*cluster.Server)
ret1, _ := ret[1].(error)
return ret0, ret1
}
func (mr *MockPitayaMockRecorder) GetServersByType(arg0 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetServersByType", reflect.TypeOf((*MockPitaya)(nil).GetServersByType), arg0)
}
func (m *MockPitaya) GetSessionFromCtx(arg0 context.Context) session.Session {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "GetSessionFromCtx", arg0)
ret0, _ := ret[0].(session.Session)
return ret0
}
func (mr *MockPitayaMockRecorder) GetSessionFromCtx(arg0 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetSessionFromCtx", reflect.TypeOf((*MockPitaya)(nil).GetSessionFromCtx), arg0)
}
func (m *MockPitaya) GroupAddMember(arg0 context.Context, arg1, arg2 string) error {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "GroupAddMember", arg0, arg1, arg2)
ret0, _ := ret[0].(error)
return ret0
}
func (mr *MockPitayaMockRecorder) GroupAddMember(arg0, arg1, arg2 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GroupAddMember", reflect.TypeOf((*MockPitaya)(nil).GroupAddMember), arg0, arg1, arg2)
}
func (m *MockPitaya) GroupBroadcast(arg0 context.Context, arg1, arg2, arg3 string, arg4 interface{}) error {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "GroupBroadcast", arg0, arg1, arg2, arg3, arg4)
ret0, _ := ret[0].(error)
return ret0
}
func (mr *MockPitayaMockRecorder) GroupBroadcast(arg0, arg1, arg2, arg3, arg4 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GroupBroadcast", reflect.TypeOf((*MockPitaya)(nil).GroupBroadcast), arg0, arg1, arg2, arg3, arg4)
}
func (m *MockPitaya) GroupContainsMember(arg0 context.Context, arg1, arg2 string) (bool, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "GroupContainsMember", arg0, arg1, arg2)
ret0, _ := ret[0].(bool)
ret1, _ := ret[1].(error)
return ret0, ret1
}
func (mr *MockPitayaMockRecorder) GroupContainsMember(arg0, arg1, arg2 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GroupContainsMember", reflect.TypeOf((*MockPitaya)(nil).GroupContainsMember), arg0, arg1, arg2)
}
func (m *MockPitaya) GroupCountMembers(arg0 context.Context, arg1 string) (int, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "GroupCountMembers", arg0, arg1)
ret0, _ := ret[0].(int)
ret1, _ := ret[1].(error)
return ret0, ret1
}
func (mr *MockPitayaMockRecorder) GroupCountMembers(arg0, arg1 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GroupCountMembers", reflect.TypeOf((*MockPitaya)(nil).GroupCountMembers), arg0, arg1)
}
func (m *MockPitaya) GroupCreate(arg0 context.Context, arg1 string) error {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "GroupCreate", arg0, arg1)
ret0, _ := ret[0].(error)
return ret0
}
func (mr *MockPitayaMockRecorder) GroupCreate(arg0, arg1 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GroupCreate", reflect.TypeOf((*MockPitaya)(nil).GroupCreate), arg0, arg1)
}
func (m *MockPitaya) GroupCreateWithTTL(arg0 context.Context, arg1 string, arg2 time.Duration) error {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "GroupCreateWithTTL", arg0, arg1, arg2)
ret0, _ := ret[0].(error)
return ret0
}
func (mr *MockPitayaMockRecorder) GroupCreateWithTTL(arg0, arg1, arg2 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GroupCreateWithTTL", reflect.TypeOf((*MockPitaya)(nil).GroupCreateWithTTL), arg0, arg1, arg2)
}
func (m *MockPitaya) GroupDelete(arg0 context.Context, arg1 string) error {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "GroupDelete", arg0, arg1)
ret0, _ := ret[0].(error)
return ret0
}
func (mr *MockPitayaMockRecorder) GroupDelete(arg0, arg1 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GroupDelete", reflect.TypeOf((*MockPitaya)(nil).GroupDelete), arg0, arg1)
}
func (m *MockPitaya) GroupMembers(arg0 context.Context, arg1 string) ([]string, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "GroupMembers", arg0, arg1)
ret0, _ := ret[0].([]string)
ret1, _ := ret[1].(error)
return ret0, ret1
}
func (mr *MockPitayaMockRecorder) GroupMembers(arg0, arg1 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GroupMembers", reflect.TypeOf((*MockPitaya)(nil).GroupMembers), arg0, arg1)
}
func (m *MockPitaya) GroupRemoveAll(arg0 context.Context, arg1 string) error {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "GroupRemoveAll", arg0, arg1)
ret0, _ := ret[0].(error)
return ret0
}
func (mr *MockPitayaMockRecorder) GroupRemoveAll(arg0, arg1 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GroupRemoveAll", reflect.TypeOf((*MockPitaya)(nil).GroupRemoveAll), arg0, arg1)
}
func (m *MockPitaya) GroupRemoveMember(arg0 context.Context, arg1, arg2 string) error {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "GroupRemoveMember", arg0, arg1, arg2)
ret0, _ := ret[0].(error)
return ret0
}
func (mr *MockPitayaMockRecorder) GroupRemoveMember(arg0, arg1, arg2 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GroupRemoveMember", reflect.TypeOf((*MockPitaya)(nil).GroupRemoveMember), arg0, arg1, arg2)
}
func (m *MockPitaya) GroupRenewTTL(arg0 context.Context, arg1 string) error {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "GroupRenewTTL", arg0, arg1)
ret0, _ := ret[0].(error)
return ret0
}
func (mr *MockPitayaMockRecorder) GroupRenewTTL(arg0, arg1 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GroupRenewTTL", reflect.TypeOf((*MockPitaya)(nil).GroupRenewTTL), arg0, arg1)
}
func (m *MockPitaya) IsRunning() bool {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "IsRunning")
ret0, _ := ret[0].(bool)
return ret0
}
func (mr *MockPitayaMockRecorder) IsRunning() *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "IsRunning", reflect.TypeOf((*MockPitaya)(nil).IsRunning))
}
func (m *MockPitaya) RPC(arg0 context.Context, arg1 string, arg2, arg3 proto.Message) error {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "RPC", arg0, arg1, arg2, arg3)
ret0, _ := ret[0].(error)
return ret0
}
func (mr *MockPitayaMockRecorder) RPC(arg0, arg1, arg2, arg3 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "RPC", reflect.TypeOf((*MockPitaya)(nil).RPC), arg0, arg1, arg2, arg3)
} | MIT License |
kyverno/kyverno | pkg/engine/variables/operator/equal.go | Evaluate | go | func (eh EqualHandler) Evaluate(key, value interface{}) bool {
switch typedKey := key.(type) {
case bool:
return eh.validateValueWithBoolPattern(typedKey, value)
case int:
return eh.validateValueWithIntPattern(int64(typedKey), value)
case int64:
return eh.validateValueWithIntPattern(typedKey, value)
case float64:
return eh.validateValueWithFloatPattern(typedKey, value)
case string:
return eh.validateValueWithStringPattern(typedKey, value)
case map[string]interface{}:
return eh.validateValueWithMapPattern(typedKey, value)
case []interface{}:
return eh.validateValueWithSlicePattern(typedKey, value)
default:
eh.log.Info("Unsupported type", "value", typedKey, "type", fmt.Sprintf("%T", typedKey))
return false
}
} | Evaluate evaluates expression with Equal Operator | https://github.com/kyverno/kyverno/blob/63f5c09297d0cbf292a74d2e2913d3ed4ec92328/pkg/engine/variables/operator/equal.go#L30-L51 | package operator
import (
"fmt"
"math"
"reflect"
"strconv"
"github.com/minio/pkg/wildcard"
"github.com/go-logr/logr"
"github.com/kyverno/kyverno/pkg/engine/context"
)
func NewEqualHandler(log logr.Logger, ctx context.EvalInterface) OperatorHandler {
return EqualHandler{
ctx: ctx,
log: log,
}
}
type EqualHandler struct {
ctx context.EvalInterface
log logr.Logger
} | Apache License 2.0 |
srishanbhattarai/nepcal | nepcal/nepcal.go | Year | go | func (t Time) Year() int {
return t.year
} | Year returns the B.S. year value for this date. | https://github.com/srishanbhattarai/nepcal/blob/3b33fbd5a150650c3e0d8e8f5a6968018a9c3baa/nepcal/nepcal.go#L130-L132 | package nepcal
import (
"bytes"
"errors"
"fmt"
"io"
"time"
)
var ErrOutOfBounds = errors.New("Provided date out of bounds; consult function/method documentation")
type Time struct {
in time.Time
year int
month Month
day int
}
type raw struct {
year int
month Month
day int
}
func Now() Time {
return FromGregorianUnchecked(time.Now())
}
func CalendarNow() io.Reader {
t := Now()
return t.Calendar()
}
func FromGregorian(t time.Time) (Time, error) {
if !IsInRangeGregorian(t) {
return Time{}, ErrOutOfBounds
}
return FromGregorianUnchecked(t), nil
}
func FromGregorianUnchecked(t time.Time) Time {
return fromGregorian(t)
}
func Date(year int, month Month, day int) (Time, error) {
if !IsInRangeBS(year, month, day) {
return Time{}, ErrOutOfBounds
}
inraw := raw{year, month, day}
return fromRaw(inraw), nil
}
func DateUnchecked(year int, month Month, day int) Time {
inraw := raw{year, month, day}
return fromRaw(inraw)
}
func (t Time) Gregorian() time.Time {
return t.in
}
func (t Time) Date() (int, Month, int) {
return t.Year(), t.Month(), t.Day()
} | MIT License |
porter-dev/porter | api/server/shared/requestutils/validator.go | SafeExternalError | go | func (obj *ValidationErrObject) SafeExternalError() string {
var sb strings.Builder
sb.WriteString(fmt.Sprintf("validation failed on field '%s' on condition '%s'", obj.Field, obj.Condition))
if obj.Param != "" {
sb.WriteString(fmt.Sprintf(" [ %s ]: got %s", obj.Param, obj.getActualValueString()))
}
return sb.String()
} | SafeExternalError converts the ValidationErrObject to a string that is readable and safe
to send externally. In this case, "safe" means that when the `ActualValue` field is cast
to a string, it is type-checked so that only certain types are passed to the user. We
don't want an upstream command accidentally setting a complex object in the request field
that could leak sensitive information to the user. To limit this, we only support sending
static `ActualValue` types: `string`, `int`, `[]string`, and `[]int`. Otherwise, we say that
the actual value is "invalid type".
Note: the test cases split on "," to parse out the different errors. Don't add commas to the
safe external error. | https://github.com/porter-dev/porter/blob/d026d13f913293742ff88544281ee16928510ab1/api/server/shared/requestutils/validator.go#L115-L125 | package requestutils
import (
"fmt"
"net/http"
"strings"
"github.com/porter-dev/porter/api/server/shared/apierrors"
"github.com/go-playground/validator/v10"
)
type Validator interface {
Validate(s interface{}) apierrors.RequestError
}
type DefaultValidator struct {
v10 *validator.Validate
}
func NewDefaultValidator() Validator {
v10 := validator.New()
v10.SetTagName("form")
return &DefaultValidator{v10}
}
func (v *DefaultValidator) Validate(s interface{}) apierrors.RequestError {
err := v.v10.Struct(s)
if err == nil {
return nil
}
errs, ok := err.(validator.ValidationErrors)
if !ok {
return apierrors.NewErrInternal(fmt.Errorf("could not cast err to validator.ValidationErrors"))
}
errorStrs := make([]string, len(errs))
for i, field := range errs {
errObj := NewValidationErrObject(field)
errorStrs[i] = errObj.SafeExternalError()
}
return NewErrFailedRequestValidation(strings.Join(errorStrs, ","))
}
func NewErrFailedRequestValidation(valError string) apierrors.RequestError {
return apierrors.NewErrPassThroughToClient(fmt.Errorf(valError), http.StatusBadRequest)
}
type ValidationErrObject struct {
Field string
Condition string
Param string
ActualValue interface{}
}
func NewValidationErrObject(fieldErr validator.FieldError) *ValidationErrObject {
return &ValidationErrObject{
Field: fieldErr.Field(),
Condition: fieldErr.ActualTag(),
Param: fieldErr.Param(),
ActualValue: fieldErr.Value(),
}
} | MIT License |
containerbuilding/cbi | vendor/k8s.io/api/settings/v1alpha1/zz_generated.deepcopy.go | DeepCopyInto | go | func (in *PodPresetSpec) DeepCopyInto(out *PodPresetSpec) {
*out = *in
in.Selector.DeepCopyInto(&out.Selector)
if in.Env != nil {
in, out := &in.Env, &out.Env
*out = make([]v1.EnvVar, len(*in))
for i := range *in {
(*in)[i].DeepCopyInto(&(*out)[i])
}
}
if in.EnvFrom != nil {
in, out := &in.EnvFrom, &out.EnvFrom
*out = make([]v1.EnvFromSource, len(*in))
for i := range *in {
(*in)[i].DeepCopyInto(&(*out)[i])
}
}
if in.Volumes != nil {
in, out := &in.Volumes, &out.Volumes
*out = make([]v1.Volume, len(*in))
for i := range *in {
(*in)[i].DeepCopyInto(&(*out)[i])
}
}
if in.VolumeMounts != nil {
in, out := &in.VolumeMounts, &out.VolumeMounts
*out = make([]v1.VolumeMount, len(*in))
for i := range *in {
(*in)[i].DeepCopyInto(&(*out)[i])
}
}
return
} | DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. | https://github.com/containerbuilding/cbi/blob/1f3ccebc2b71abfa108e48071bf1009e5f68016c/vendor/k8s.io/api/settings/v1alpha1/zz_generated.deepcopy.go#L89-L121 | package v1alpha1
import (
v1 "k8s.io/api/core/v1"
runtime "k8s.io/apimachinery/pkg/runtime"
)
func (in *PodPreset) DeepCopyInto(out *PodPreset) {
*out = *in
out.TypeMeta = in.TypeMeta
in.ObjectMeta.DeepCopyInto(&out.ObjectMeta)
in.Spec.DeepCopyInto(&out.Spec)
return
}
func (in *PodPreset) DeepCopy() *PodPreset {
if in == nil {
return nil
}
out := new(PodPreset)
in.DeepCopyInto(out)
return out
}
func (in *PodPreset) DeepCopyObject() runtime.Object {
if c := in.DeepCopy(); c != nil {
return c
}
return nil
}
func (in *PodPresetList) DeepCopyInto(out *PodPresetList) {
*out = *in
out.TypeMeta = in.TypeMeta
out.ListMeta = in.ListMeta
if in.Items != nil {
in, out := &in.Items, &out.Items
*out = make([]PodPreset, len(*in))
for i := range *in {
(*in)[i].DeepCopyInto(&(*out)[i])
}
}
return
}
func (in *PodPresetList) DeepCopy() *PodPresetList {
if in == nil {
return nil
}
out := new(PodPresetList)
in.DeepCopyInto(out)
return out
}
func (in *PodPresetList) DeepCopyObject() runtime.Object {
if c := in.DeepCopy(); c != nil {
return c
}
return nil
} | Apache License 2.0 |
cider/cider | Godeps/_workspace/src/github.com/meeko/go-meeko/meeko/services/rpc/service.go | NewService | go | func NewService(factory ServiceFactory) (srv *Service, err error) {
defer func() {
if r := recover(); r != nil {
if ex, ok := r.(error); ok {
err = ex
} else {
err = services.ErrFactoryPanic
}
}
}()
transport, err := factory()
if err != nil {
return nil, err
}
srv = &Service{
transport: transport,
executor: newExecutor(transport),
dispatcher: newDispatcher(transport),
closedCh: make(chan struct{}),
}
go func() {
<-srv.executor.terminated()
<-srv.dispatcher.terminated()
close(srv.closedCh)
}()
go func() {
select {
case err := <-srv.transport.ErrorChan():
srv.err = err
srv.Close()
case <-srv.Closed():
return
}
}()
return srv, nil
} | NewService uses factory to construct a Transport instance that is then used
for creating the Service instance itself.
factory can panic without any worries, it just makes NewService return an
error, so some if-errs can be saved. | https://github.com/cider/cider/blob/f2f6987c13d4861c4869f4b6c1b0e2ab755169cb/Godeps/_workspace/src/github.com/meeko/go-meeko/meeko/services/rpc/service.go#L39-L79 | package rpc
import (
"errors"
"github.com/meeko/go-meeko/meeko/services"
log "github.com/cihub/seelog"
)
const (
CmdRegister int = iota
CmdUnregister
CmdCall
CmdInterrupt
CmdSignalProgress
CmdSendStreamFrame
CmdReply
CmdClose
)
type Service struct {
transport Transport
*executor
*dispatcher
closedCh chan struct{}
}
type ServiceFactory func() (Transport, error) | MIT License |
gopasspw/gopass | pkg/gopass/secrets/plain.go | Bytes | go | func (p *Plain) Bytes() []byte {
return p.buf
} | Bytes returns the complete secret | https://github.com/gopasspw/gopass/blob/a4ee6a191c07429a07fc2bf1be83866d07c00868/pkg/gopass/secrets/plain.go#L38-L40 | package secrets
import (
"bufio"
"bytes"
"fmt"
"io"
"strings"
"github.com/gopasspw/gopass/pkg/debug"
"github.com/gopasspw/gopass/pkg/gopass"
)
var _ gopass.Secret = &Plain{}
type Plain struct {
buf []byte
}
func ParsePlain(in []byte) *Plain {
p := &Plain{
buf: make([]byte, len(in)),
}
copy(p.buf, in)
return p
} | MIT License |
domechn/msg-pusher | vendor/github.com/uber/jaeger-client-go/context.go | SpanID | go | func (c SpanContext) SpanID() SpanID {
return c.spanID
} | SpanID returns the span ID of this span context | https://github.com/domechn/msg-pusher/blob/3d0adf2cd9f945a3ca49331eaa0520ae981cd050/vendor/github.com/uber/jaeger-client-go/context.go#L137-L139 | package jaeger
import (
"errors"
"fmt"
"strconv"
"strings"
)
const (
flagSampled = byte(1)
flagDebug = byte(2)
)
var (
errEmptyTracerStateString = errors.New("Cannot convert empty string to tracer state")
errMalformedTracerStateString = errors.New("String does not match tracer state format")
emptyContext = SpanContext{}
)
type TraceID struct {
High, Low uint64
}
type SpanID uint64
type SpanContext struct {
traceID TraceID
spanID SpanID
parentID SpanID
flags byte
baggage map[string]string
debugID string
}
func (c SpanContext) ForeachBaggageItem(handler func(k, v string) bool) {
for k, v := range c.baggage {
if !handler(k, v) {
break
}
}
}
func (c SpanContext) IsSampled() bool {
return (c.flags & flagSampled) == flagSampled
}
func (c SpanContext) IsDebug() bool {
return (c.flags & flagDebug) == flagDebug
}
func (c SpanContext) IsValid() bool {
return c.traceID.IsValid() && c.spanID != 0
}
func (c SpanContext) String() string {
if c.traceID.High == 0 {
return fmt.Sprintf("%x:%x:%x:%x", c.traceID.Low, uint64(c.spanID), uint64(c.parentID), c.flags)
}
return fmt.Sprintf("%x%016x:%x:%x:%x", c.traceID.High, c.traceID.Low, uint64(c.spanID), uint64(c.parentID), c.flags)
}
func ContextFromString(value string) (SpanContext, error) {
var context SpanContext
if value == "" {
return emptyContext, errEmptyTracerStateString
}
parts := strings.Split(value, ":")
if len(parts) != 4 {
return emptyContext, errMalformedTracerStateString
}
var err error
if context.traceID, err = TraceIDFromString(parts[0]); err != nil {
return emptyContext, err
}
if context.spanID, err = SpanIDFromString(parts[1]); err != nil {
return emptyContext, err
}
if context.parentID, err = SpanIDFromString(parts[2]); err != nil {
return emptyContext, err
}
flags, err := strconv.ParseUint(parts[3], 10, 8)
if err != nil {
return emptyContext, err
}
context.flags = byte(flags)
return context, nil
}
func (c SpanContext) TraceID() TraceID {
return c.traceID
} | MIT License |