text
stringlengths
11
4.05M
package doorman import ( "encoding/base64" "encoding/binary" "encoding/json" "errors" "log" "math" "math/big" mathrand "math/rand" "net/http" "sync" "time" "github.com/dchest/siphash" "github.com/didiercrunch/doorman/shared" ) var ONE *big.Rat = big.NewRat(1, 1) var rand *mathrand.Rand func initRandomSeed() { kindOfRandomSeed := mathrand.NewSource(time.Now().Unix()) rand = mathrand.New(kindOfRandomSeed) } func init() { initRandomSeed() } func IsEqual(f1, f2 *big.Rat) bool { return f1.Cmp(f2) == 0 } type Doorman struct { Id string // the id of the doorman LastChangeTimestamp int64 // an always increasing int that represent the last time the doorman has beed updated Probabilities []*big.Rat // The probability of each cases. The sum of probabilities needs to be one wg sync.WaitGroup // waitgroup for goroutine safety hashKey []byte // the decoded id } func New(id string, probabilities []*big.Rat) (*Doorman, error) { wab := &Doorman{} if bid, err := base64.URLEncoding.DecodeString(id); err != nil { return nil, err } else if len(bid) != 16 { return nil, errors.New("id must be base64 encoded of a 16 bytes array") } else { wab.hashKey = bid wab.Id = id } wab.Probabilities = probabilities return wab, wab.Validate() } func (w *Doorman) Length() int { return len(w.Probabilities) } func (w *Doorman) UpdateHard(baseURL string) error { r, err := http.Get(baseURL + "/" + w.Id) if err != nil { return err } message := new(shared.DoormanUpdater) d := json.NewDecoder(r.Body) if err := d.Decode(message); err != nil { return err } else { return w.Update(message) } } func (w *Doorman) Update(wu *shared.DoormanUpdater) error { if wu.Timestamp <= w.LastChangeTimestamp { return nil } if w.Id != wu.Id { return errors.New("bad doorman id") } w.wg.Add(1) defer w.wg.Done() w.LastChangeTimestamp = wu.Timestamp if !IsEqual(w.sum(wu.Probabilities), ONE) { return errors.New("the sum of probabilities cannot be different than 1") } w.Probabilities = wu.Probabilities log.Printf("Updated doorman %v with new probabilities %v with timestamp %v", wu.Id, wu.Probabilities, wu.Timestamp) return nil } func (w *Doorman) sum(prob []*big.Rat) *big.Rat { ret := big.NewRat(0, 1) for _, p := range prob { ret = new(big.Rat).Add(ret, p) } return ret } func (w *Doorman) Validate() error { if len(w.Probabilities) == 0 { return errors.New("not initiated") } s := w.sum(w.Probabilities) if !IsEqual(s, ONE) { return errors.New("The sum of probabilities is not one") } return nil } func (w *Doorman) GetCase(choosenRandomPosition *big.Rat) uint { w.wg.Wait() var prob = big.NewRat(0, 1) for i, p := range w.Probabilities { prob = new(big.Rat).Add(prob, p) if choosenRandomPosition.Cmp(prob) <= 0 { return uint(i) } } panic("cannot have a probability above 1") } func (w *Doorman) GenerateRandomProbabilityFromInteger(data uint64) *big.Rat { var ret float64 = 0 for i := 0; data > 0; i++ { if data&1 == 1 { ret += 1.0 / math.Pow(2, float64(i+1)) } data >>= 1 } rat := new(big.Rat) return rat.SetFloat64(ret) } func (w *Doorman) Hash(data ...[]byte) uint64 { h := siphash.New(w.hashKey) for _, datum := range data { h.Write(datum) } return h.Sum64() } func (w *Doorman) GetCaseFromData(data ...[]byte) uint { random := w.GenerateRandomProbabilityFromInteger(w.Hash(data...)) return w.GetCase(random) } func (w *Doorman) GetCaseFromString(data string) uint { return w.GetCaseFromData([]byte(data)) } // not yet in spect func (w *Doorman) getCaseFromInt(data int) uint { b := make([]byte, 10) binary.LittleEndian.PutUint64(b, uint64(data)) return w.GetCaseFromData(b) } func (w *Doorman) GetRandomCase() uint { r := rand.Float64() return w.GetCase(new(big.Rat).SetFloat64(r)) }
package v1 import ( "bytes" "context" "fmt" "io/ioutil" "k8s.io/client-go/tools/clientcmd" "testing" ) func TestPods_Exec(t *testing.T) { c, err := clientcmd.BuildConfigFromKubeconfigGetter("", KubeConfigGetter) if err != nil { t.Fatal(err) } client, _ := NewForConfig(c) ctx, cancel := context.WithCancel(context.Background()) defer cancel() namespace := "dev-xiaomai-server" pod := "dev-app-gateway-latest-76ddb96f4c-nbkrr" container := "app-gateway" commands := []string{"/bin/bash", "-c"} commands = append(commands, fmt.Sprintf("ls -l")) var stdout bytes.Buffer stderr, err := client.Pods(namespace).Exec(ctx, pod, container, commands, nil, &stdout) if err != nil { t.Fatal(err) } fmt.Println(stderr) fmt.Println(stdout.String()) } func TestPods_CopyToPod(t *testing.T) { c, err := clientcmd.BuildConfigFromKubeconfigGetter("", KubeConfigGetter) if err != nil { t.Fatal(err) } client, _ := NewForConfig(c) ctx, cancel := context.WithCancel(context.Background()) defer cancel() namespace := "dev-xiaomai-server" pod := "dev-app-gateway-latest-76ddb96f4c-nbkrr" container := "app-gateway" testFile, err := ioutil.ReadFile("D:/tmp/awesomeProject") if err != nil { t.Fatal(err) } stderr, err := client.Pods(namespace).CopyToPod(ctx, pod, container, bytes.NewReader(testFile), "/tmp/main") if err != nil { t.Fatal(err) } t.Logf("stderr : %s", string(stderr)) }
package main import ( "encoding/gob" "fmt" "log" "strconv" "time" "github.com/patrickmn/go-cache" "github.com/zgs225/youdao" ) const ( CACHE_EXPIRES time.Duration = 30 * 24 * time.Hour CACHE_FILE string = "cache.dat" CACHE_HISTORY_FILE string = "history.dat" // Local cache file for history data ) type agentClient struct { Client *youdao.Client Cache *cache.Cache History *cache.Cache Dirty bool } func (a *agentClient) Query(q string) (*youdao.Result, error) { k := fmt.Sprintf("from:%s,to:%s,q:%s", a.Client.GetFrom(), a.Client.GetTo(), q) v, ok := a.Cache.Get(k) if ok { log.Println("Cache hit") return v.(*youdao.Result), nil } log.Println("Cache miss") r, err := a.Client.Query(q) if err != nil { return nil, err } a.Cache.Set(k, r, CACHE_EXPIRES) a.Dirty = true return r, nil } // Write the history data func (a *agentClient) writeHistory(queue []string) error { for i, v := range queue { a.History.Set(strconv.Itoa(i), v, CACHE_EXPIRES) log.Println(strconv.Itoa(i), v) } a.Dirty = true return nil } // Retrieve the history data func (a *agentClient) readHistory() ([]string, error) { queue := make([]string, 0, QUEUE_SIZE) for i := 0; i < QUEUE_SIZE; i++ { v, ok := a.History.Get(strconv.Itoa(i)) if ok { log.Println("History Cache hit", strconv.Itoa(i), v) queue = append(queue, v.(string)) } else { log.Println("History Cache miss") } } return queue, nil } func newAgent(c *youdao.Client) *agentClient { gob.Register(&youdao.Result{}) c2 := cache.New(CACHE_EXPIRES, CACHE_EXPIRES) c3 := cache.New(CACHE_EXPIRES, CACHE_EXPIRES) // new err := c2.LoadFile(CACHE_FILE) if err != nil { log.Println(err) } err = c3.LoadFile(CACHE_HISTORY_FILE) // new if err != nil { log.Println(err) } log.Println("Cache count:", c2.ItemCount()) log.Println("History count:", c3.ItemCount()) // new return &agentClient{c, c2, c3, false} }
// Copyright 2021 Google LLC. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package server import ( "context" "github.com/GoogleCloudPlatform/declarative-resource-client-library/dcl" computepb "github.com/GoogleCloudPlatform/declarative-resource-client-library/python/proto/compute/compute_go_proto" emptypb "github.com/GoogleCloudPlatform/declarative-resource-client-library/python/proto/empty_go_proto" "github.com/GoogleCloudPlatform/declarative-resource-client-library/services/google/compute" ) // Server implements the gRPC interface for Router. type RouterServer struct{} // ProtoToRouterNatsLogConfigFilterEnum converts a RouterNatsLogConfigFilterEnum enum from its proto representation. func ProtoToComputeRouterNatsLogConfigFilterEnum(e computepb.ComputeRouterNatsLogConfigFilterEnum) *compute.RouterNatsLogConfigFilterEnum { if e == 0 { return nil } if n, ok := computepb.ComputeRouterNatsLogConfigFilterEnum_name[int32(e)]; ok { e := compute.RouterNatsLogConfigFilterEnum(n[len("ComputeRouterNatsLogConfigFilterEnum"):]) return &e } return nil } // ProtoToRouterNatsSourceSubnetworkIPRangesToNatEnum converts a RouterNatsSourceSubnetworkIPRangesToNatEnum enum from its proto representation. func ProtoToComputeRouterNatsSourceSubnetworkIPRangesToNatEnum(e computepb.ComputeRouterNatsSourceSubnetworkIPRangesToNatEnum) *compute.RouterNatsSourceSubnetworkIPRangesToNatEnum { if e == 0 { return nil } if n, ok := computepb.ComputeRouterNatsSourceSubnetworkIPRangesToNatEnum_name[int32(e)]; ok { e := compute.RouterNatsSourceSubnetworkIPRangesToNatEnum(n[len("ComputeRouterNatsSourceSubnetworkIPRangesToNatEnum"):]) return &e } return nil } // ProtoToRouterNatsNatIPAllocateOptionEnum converts a RouterNatsNatIPAllocateOptionEnum enum from its proto representation. func ProtoToComputeRouterNatsNatIPAllocateOptionEnum(e computepb.ComputeRouterNatsNatIPAllocateOptionEnum) *compute.RouterNatsNatIPAllocateOptionEnum { if e == 0 { return nil } if n, ok := computepb.ComputeRouterNatsNatIPAllocateOptionEnum_name[int32(e)]; ok { e := compute.RouterNatsNatIPAllocateOptionEnum(n[len("ComputeRouterNatsNatIPAllocateOptionEnum"):]) return &e } return nil } // ProtoToRouterInterfacesManagementTypeEnum converts a RouterInterfacesManagementTypeEnum enum from its proto representation. func ProtoToComputeRouterInterfacesManagementTypeEnum(e computepb.ComputeRouterInterfacesManagementTypeEnum) *compute.RouterInterfacesManagementTypeEnum { if e == 0 { return nil } if n, ok := computepb.ComputeRouterInterfacesManagementTypeEnum_name[int32(e)]; ok { e := compute.RouterInterfacesManagementTypeEnum(n[len("ComputeRouterInterfacesManagementTypeEnum"):]) return &e } return nil } // ProtoToRouterBgpPeersAdvertisedGroupsEnum converts a RouterBgpPeersAdvertisedGroupsEnum enum from its proto representation. func ProtoToComputeRouterBgpPeersAdvertisedGroupsEnum(e computepb.ComputeRouterBgpPeersAdvertisedGroupsEnum) *compute.RouterBgpPeersAdvertisedGroupsEnum { if e == 0 { return nil } if n, ok := computepb.ComputeRouterBgpPeersAdvertisedGroupsEnum_name[int32(e)]; ok { e := compute.RouterBgpPeersAdvertisedGroupsEnum(n[len("ComputeRouterBgpPeersAdvertisedGroupsEnum"):]) return &e } return nil } // ProtoToRouterBgpAdvertiseModeEnum converts a RouterBgpAdvertiseModeEnum enum from its proto representation. func ProtoToComputeRouterBgpAdvertiseModeEnum(e computepb.ComputeRouterBgpAdvertiseModeEnum) *compute.RouterBgpAdvertiseModeEnum { if e == 0 { return nil } if n, ok := computepb.ComputeRouterBgpAdvertiseModeEnum_name[int32(e)]; ok { e := compute.RouterBgpAdvertiseModeEnum(n[len("ComputeRouterBgpAdvertiseModeEnum"):]) return &e } return nil } // ProtoToRouterNats converts a RouterNats resource from its proto representation. func ProtoToComputeRouterNats(p *computepb.ComputeRouterNats) *compute.RouterNats { if p == nil { return nil } obj := &compute.RouterNats{ Name: dcl.StringOrNil(p.Name), LogConfig: ProtoToComputeRouterNatsLogConfig(p.GetLogConfig()), SourceSubnetworkIPRangesToNat: ProtoToComputeRouterNatsSourceSubnetworkIPRangesToNatEnum(p.GetSourceSubnetworkIpRangesToNat()), MinPortsPerVm: dcl.Int64OrNil(p.MinPortsPerVm), UdpIdleTimeoutSec: dcl.Int64OrNil(p.UdpIdleTimeoutSec), IcmpIdleTimeoutSec: dcl.Int64OrNil(p.IcmpIdleTimeoutSec), TcpEstablishedIdleTimeoutSec: dcl.Int64OrNil(p.TcpEstablishedIdleTimeoutSec), TcpTransitoryIdleTimeoutSec: dcl.Int64OrNil(p.TcpTransitoryIdleTimeoutSec), } for _, r := range p.GetNatIps() { obj.NatIps = append(obj.NatIps, r) } for _, r := range p.GetDrainNatIps() { obj.DrainNatIps = append(obj.DrainNatIps, r) } for _, r := range p.GetNatIpAllocateOption() { obj.NatIPAllocateOption = append(obj.NatIPAllocateOption, *ProtoToComputeRouterNatsNatIPAllocateOptionEnum(r)) } for _, r := range p.GetSubnetworks() { obj.Subnetworks = append(obj.Subnetworks, *ProtoToComputeRouterNatsSubnetworks(r)) } return obj } // ProtoToRouterNatsLogConfig converts a RouterNatsLogConfig resource from its proto representation. func ProtoToComputeRouterNatsLogConfig(p *computepb.ComputeRouterNatsLogConfig) *compute.RouterNatsLogConfig { if p == nil { return nil } obj := &compute.RouterNatsLogConfig{ Enable: dcl.Bool(p.Enable), Filter: ProtoToComputeRouterNatsLogConfigFilterEnum(p.GetFilter()), } return obj } // ProtoToRouterNatsSubnetworks converts a RouterNatsSubnetworks resource from its proto representation. func ProtoToComputeRouterNatsSubnetworks(p *computepb.ComputeRouterNatsSubnetworks) *compute.RouterNatsSubnetworks { if p == nil { return nil } obj := &compute.RouterNatsSubnetworks{ Name: dcl.StringOrNil(p.Name), SourceIPRangesToNat: dcl.StringOrNil(p.SourceIpRangesToNat), SecondaryIPRangeNames: dcl.StringOrNil(p.SecondaryIpRangeNames), } return obj } // ProtoToRouterInterfaces converts a RouterInterfaces resource from its proto representation. func ProtoToComputeRouterInterfaces(p *computepb.ComputeRouterInterfaces) *compute.RouterInterfaces { if p == nil { return nil } obj := &compute.RouterInterfaces{ Name: dcl.StringOrNil(p.Name), LinkedVpnTunnel: dcl.StringOrNil(p.LinkedVpnTunnel), IPRange: dcl.StringOrNil(p.IpRange), ManagementType: ProtoToComputeRouterInterfacesManagementTypeEnum(p.GetManagementType()), } return obj } // ProtoToRouterBgpPeers converts a RouterBgpPeers resource from its proto representation. func ProtoToComputeRouterBgpPeers(p *computepb.ComputeRouterBgpPeers) *compute.RouterBgpPeers { if p == nil { return nil } obj := &compute.RouterBgpPeers{ Name: dcl.StringOrNil(p.Name), InterfaceName: dcl.StringOrNil(p.InterfaceName), IPAddress: dcl.StringOrNil(p.IpAddress), PeerIPAddress: dcl.StringOrNil(p.PeerIpAddress), PeerAsn: dcl.Int64OrNil(p.PeerAsn), AdvertisedRoutePriority: dcl.Int64OrNil(p.AdvertisedRoutePriority), AdvertiseMode: dcl.StringOrNil(p.AdvertiseMode), ManagementType: dcl.StringOrNil(p.ManagementType), } for _, r := range p.GetAdvertisedGroups() { obj.AdvertisedGroups = append(obj.AdvertisedGroups, *ProtoToComputeRouterBgpPeersAdvertisedGroupsEnum(r)) } for _, r := range p.GetAdvertisedIpRanges() { obj.AdvertisedIPRanges = append(obj.AdvertisedIPRanges, *ProtoToComputeRouterBgpPeersAdvertisedIPRanges(r)) } return obj } // ProtoToRouterBgpPeersAdvertisedIPRanges converts a RouterBgpPeersAdvertisedIPRanges resource from its proto representation. func ProtoToComputeRouterBgpPeersAdvertisedIPRanges(p *computepb.ComputeRouterBgpPeersAdvertisedIPRanges) *compute.RouterBgpPeersAdvertisedIPRanges { if p == nil { return nil } obj := &compute.RouterBgpPeersAdvertisedIPRanges{ Range: dcl.StringOrNil(p.Range), Description: dcl.StringOrNil(p.Description), } return obj } // ProtoToRouterBgp converts a RouterBgp resource from its proto representation. func ProtoToComputeRouterBgp(p *computepb.ComputeRouterBgp) *compute.RouterBgp { if p == nil { return nil } obj := &compute.RouterBgp{ Asn: dcl.Int64OrNil(p.Asn), AdvertiseMode: ProtoToComputeRouterBgpAdvertiseModeEnum(p.GetAdvertiseMode()), } for _, r := range p.GetAdvertisedGroups() { obj.AdvertisedGroups = append(obj.AdvertisedGroups, r) } for _, r := range p.GetAdvertisedIpRanges() { obj.AdvertisedIPRanges = append(obj.AdvertisedIPRanges, *ProtoToComputeRouterBgpAdvertisedIPRanges(r)) } return obj } // ProtoToRouterBgpAdvertisedIPRanges converts a RouterBgpAdvertisedIPRanges resource from its proto representation. func ProtoToComputeRouterBgpAdvertisedIPRanges(p *computepb.ComputeRouterBgpAdvertisedIPRanges) *compute.RouterBgpAdvertisedIPRanges { if p == nil { return nil } obj := &compute.RouterBgpAdvertisedIPRanges{ Range: dcl.StringOrNil(p.Range), Description: dcl.StringOrNil(p.Description), } return obj } // ProtoToRouter converts a Router resource from its proto representation. func ProtoToRouter(p *computepb.ComputeRouter) *compute.Router { obj := &compute.Router{ CreationTimestamp: dcl.StringOrNil(p.GetCreationTimestamp()), Name: dcl.StringOrNil(p.Name), Network: dcl.StringOrNil(p.Network), Description: dcl.StringOrNil(p.Description), Bgp: ProtoToComputeRouterBgp(p.GetBgp()), Region: dcl.StringOrNil(p.Region), Project: dcl.StringOrNil(p.Project), SelfLink: dcl.StringOrNil(p.SelfLink), } for _, r := range p.GetNats() { obj.Nats = append(obj.Nats, *ProtoToComputeRouterNats(r)) } for _, r := range p.GetInterfaces() { obj.Interfaces = append(obj.Interfaces, *ProtoToComputeRouterInterfaces(r)) } for _, r := range p.GetBgpPeers() { obj.BgpPeers = append(obj.BgpPeers, *ProtoToComputeRouterBgpPeers(r)) } return obj } // RouterNatsLogConfigFilterEnumToProto converts a RouterNatsLogConfigFilterEnum enum to its proto representation. func ComputeRouterNatsLogConfigFilterEnumToProto(e *compute.RouterNatsLogConfigFilterEnum) computepb.ComputeRouterNatsLogConfigFilterEnum { if e == nil { return computepb.ComputeRouterNatsLogConfigFilterEnum(0) } if v, ok := computepb.ComputeRouterNatsLogConfigFilterEnum_value["RouterNatsLogConfigFilterEnum"+string(*e)]; ok { return computepb.ComputeRouterNatsLogConfigFilterEnum(v) } return computepb.ComputeRouterNatsLogConfigFilterEnum(0) } // RouterNatsSourceSubnetworkIPRangesToNatEnumToProto converts a RouterNatsSourceSubnetworkIPRangesToNatEnum enum to its proto representation. func ComputeRouterNatsSourceSubnetworkIPRangesToNatEnumToProto(e *compute.RouterNatsSourceSubnetworkIPRangesToNatEnum) computepb.ComputeRouterNatsSourceSubnetworkIPRangesToNatEnum { if e == nil { return computepb.ComputeRouterNatsSourceSubnetworkIPRangesToNatEnum(0) } if v, ok := computepb.ComputeRouterNatsSourceSubnetworkIPRangesToNatEnum_value["RouterNatsSourceSubnetworkIPRangesToNatEnum"+string(*e)]; ok { return computepb.ComputeRouterNatsSourceSubnetworkIPRangesToNatEnum(v) } return computepb.ComputeRouterNatsSourceSubnetworkIPRangesToNatEnum(0) } // RouterNatsNatIPAllocateOptionEnumToProto converts a RouterNatsNatIPAllocateOptionEnum enum to its proto representation. func ComputeRouterNatsNatIPAllocateOptionEnumToProto(e *compute.RouterNatsNatIPAllocateOptionEnum) computepb.ComputeRouterNatsNatIPAllocateOptionEnum { if e == nil { return computepb.ComputeRouterNatsNatIPAllocateOptionEnum(0) } if v, ok := computepb.ComputeRouterNatsNatIPAllocateOptionEnum_value["RouterNatsNatIPAllocateOptionEnum"+string(*e)]; ok { return computepb.ComputeRouterNatsNatIPAllocateOptionEnum(v) } return computepb.ComputeRouterNatsNatIPAllocateOptionEnum(0) } // RouterInterfacesManagementTypeEnumToProto converts a RouterInterfacesManagementTypeEnum enum to its proto representation. func ComputeRouterInterfacesManagementTypeEnumToProto(e *compute.RouterInterfacesManagementTypeEnum) computepb.ComputeRouterInterfacesManagementTypeEnum { if e == nil { return computepb.ComputeRouterInterfacesManagementTypeEnum(0) } if v, ok := computepb.ComputeRouterInterfacesManagementTypeEnum_value["RouterInterfacesManagementTypeEnum"+string(*e)]; ok { return computepb.ComputeRouterInterfacesManagementTypeEnum(v) } return computepb.ComputeRouterInterfacesManagementTypeEnum(0) } // RouterBgpPeersAdvertisedGroupsEnumToProto converts a RouterBgpPeersAdvertisedGroupsEnum enum to its proto representation. func ComputeRouterBgpPeersAdvertisedGroupsEnumToProto(e *compute.RouterBgpPeersAdvertisedGroupsEnum) computepb.ComputeRouterBgpPeersAdvertisedGroupsEnum { if e == nil { return computepb.ComputeRouterBgpPeersAdvertisedGroupsEnum(0) } if v, ok := computepb.ComputeRouterBgpPeersAdvertisedGroupsEnum_value["RouterBgpPeersAdvertisedGroupsEnum"+string(*e)]; ok { return computepb.ComputeRouterBgpPeersAdvertisedGroupsEnum(v) } return computepb.ComputeRouterBgpPeersAdvertisedGroupsEnum(0) } // RouterBgpAdvertiseModeEnumToProto converts a RouterBgpAdvertiseModeEnum enum to its proto representation. func ComputeRouterBgpAdvertiseModeEnumToProto(e *compute.RouterBgpAdvertiseModeEnum) computepb.ComputeRouterBgpAdvertiseModeEnum { if e == nil { return computepb.ComputeRouterBgpAdvertiseModeEnum(0) } if v, ok := computepb.ComputeRouterBgpAdvertiseModeEnum_value["RouterBgpAdvertiseModeEnum"+string(*e)]; ok { return computepb.ComputeRouterBgpAdvertiseModeEnum(v) } return computepb.ComputeRouterBgpAdvertiseModeEnum(0) } // RouterNatsToProto converts a RouterNats resource to its proto representation. func ComputeRouterNatsToProto(o *compute.RouterNats) *computepb.ComputeRouterNats { if o == nil { return nil } p := &computepb.ComputeRouterNats{ Name: dcl.ValueOrEmptyString(o.Name), LogConfig: ComputeRouterNatsLogConfigToProto(o.LogConfig), SourceSubnetworkIpRangesToNat: ComputeRouterNatsSourceSubnetworkIPRangesToNatEnumToProto(o.SourceSubnetworkIPRangesToNat), MinPortsPerVm: dcl.ValueOrEmptyInt64(o.MinPortsPerVm), UdpIdleTimeoutSec: dcl.ValueOrEmptyInt64(o.UdpIdleTimeoutSec), IcmpIdleTimeoutSec: dcl.ValueOrEmptyInt64(o.IcmpIdleTimeoutSec), TcpEstablishedIdleTimeoutSec: dcl.ValueOrEmptyInt64(o.TcpEstablishedIdleTimeoutSec), TcpTransitoryIdleTimeoutSec: dcl.ValueOrEmptyInt64(o.TcpTransitoryIdleTimeoutSec), } for _, r := range o.NatIps { p.NatIps = append(p.NatIps, r) } for _, r := range o.DrainNatIps { p.DrainNatIps = append(p.DrainNatIps, r) } for _, r := range o.NatIPAllocateOption { p.NatIpAllocateOption = append(p.NatIpAllocateOption, computepb.ComputeRouterNatsNatIPAllocateOptionEnum(computepb.ComputeRouterNatsNatIPAllocateOptionEnum_value[string(r)])) } for _, r := range o.Subnetworks { p.Subnetworks = append(p.Subnetworks, ComputeRouterNatsSubnetworksToProto(&r)) } return p } // RouterNatsLogConfigToProto converts a RouterNatsLogConfig resource to its proto representation. func ComputeRouterNatsLogConfigToProto(o *compute.RouterNatsLogConfig) *computepb.ComputeRouterNatsLogConfig { if o == nil { return nil } p := &computepb.ComputeRouterNatsLogConfig{ Enable: dcl.ValueOrEmptyBool(o.Enable), Filter: ComputeRouterNatsLogConfigFilterEnumToProto(o.Filter), } return p } // RouterNatsSubnetworksToProto converts a RouterNatsSubnetworks resource to its proto representation. func ComputeRouterNatsSubnetworksToProto(o *compute.RouterNatsSubnetworks) *computepb.ComputeRouterNatsSubnetworks { if o == nil { return nil } p := &computepb.ComputeRouterNatsSubnetworks{ Name: dcl.ValueOrEmptyString(o.Name), SourceIpRangesToNat: dcl.ValueOrEmptyString(o.SourceIPRangesToNat), SecondaryIpRangeNames: dcl.ValueOrEmptyString(o.SecondaryIPRangeNames), } return p } // RouterInterfacesToProto converts a RouterInterfaces resource to its proto representation. func ComputeRouterInterfacesToProto(o *compute.RouterInterfaces) *computepb.ComputeRouterInterfaces { if o == nil { return nil } p := &computepb.ComputeRouterInterfaces{ Name: dcl.ValueOrEmptyString(o.Name), LinkedVpnTunnel: dcl.ValueOrEmptyString(o.LinkedVpnTunnel), IpRange: dcl.ValueOrEmptyString(o.IPRange), ManagementType: ComputeRouterInterfacesManagementTypeEnumToProto(o.ManagementType), } return p } // RouterBgpPeersToProto converts a RouterBgpPeers resource to its proto representation. func ComputeRouterBgpPeersToProto(o *compute.RouterBgpPeers) *computepb.ComputeRouterBgpPeers { if o == nil { return nil } p := &computepb.ComputeRouterBgpPeers{ Name: dcl.ValueOrEmptyString(o.Name), InterfaceName: dcl.ValueOrEmptyString(o.InterfaceName), IpAddress: dcl.ValueOrEmptyString(o.IPAddress), PeerIpAddress: dcl.ValueOrEmptyString(o.PeerIPAddress), PeerAsn: dcl.ValueOrEmptyInt64(o.PeerAsn), AdvertisedRoutePriority: dcl.ValueOrEmptyInt64(o.AdvertisedRoutePriority), AdvertiseMode: dcl.ValueOrEmptyString(o.AdvertiseMode), ManagementType: dcl.ValueOrEmptyString(o.ManagementType), } for _, r := range o.AdvertisedGroups { p.AdvertisedGroups = append(p.AdvertisedGroups, computepb.ComputeRouterBgpPeersAdvertisedGroupsEnum(computepb.ComputeRouterBgpPeersAdvertisedGroupsEnum_value[string(r)])) } for _, r := range o.AdvertisedIPRanges { p.AdvertisedIpRanges = append(p.AdvertisedIpRanges, ComputeRouterBgpPeersAdvertisedIPRangesToProto(&r)) } return p } // RouterBgpPeersAdvertisedIPRangesToProto converts a RouterBgpPeersAdvertisedIPRanges resource to its proto representation. func ComputeRouterBgpPeersAdvertisedIPRangesToProto(o *compute.RouterBgpPeersAdvertisedIPRanges) *computepb.ComputeRouterBgpPeersAdvertisedIPRanges { if o == nil { return nil } p := &computepb.ComputeRouterBgpPeersAdvertisedIPRanges{ Range: dcl.ValueOrEmptyString(o.Range), Description: dcl.ValueOrEmptyString(o.Description), } return p } // RouterBgpToProto converts a RouterBgp resource to its proto representation. func ComputeRouterBgpToProto(o *compute.RouterBgp) *computepb.ComputeRouterBgp { if o == nil { return nil } p := &computepb.ComputeRouterBgp{ Asn: dcl.ValueOrEmptyInt64(o.Asn), AdvertiseMode: ComputeRouterBgpAdvertiseModeEnumToProto(o.AdvertiseMode), } for _, r := range o.AdvertisedGroups { p.AdvertisedGroups = append(p.AdvertisedGroups, r) } for _, r := range o.AdvertisedIPRanges { p.AdvertisedIpRanges = append(p.AdvertisedIpRanges, ComputeRouterBgpAdvertisedIPRangesToProto(&r)) } return p } // RouterBgpAdvertisedIPRangesToProto converts a RouterBgpAdvertisedIPRanges resource to its proto representation. func ComputeRouterBgpAdvertisedIPRangesToProto(o *compute.RouterBgpAdvertisedIPRanges) *computepb.ComputeRouterBgpAdvertisedIPRanges { if o == nil { return nil } p := &computepb.ComputeRouterBgpAdvertisedIPRanges{ Range: dcl.ValueOrEmptyString(o.Range), Description: dcl.ValueOrEmptyString(o.Description), } return p } // RouterToProto converts a Router resource to its proto representation. func RouterToProto(resource *compute.Router) *computepb.ComputeRouter { p := &computepb.ComputeRouter{ CreationTimestamp: dcl.ValueOrEmptyString(resource.CreationTimestamp), Name: dcl.ValueOrEmptyString(resource.Name), Network: dcl.ValueOrEmptyString(resource.Network), Description: dcl.ValueOrEmptyString(resource.Description), Bgp: ComputeRouterBgpToProto(resource.Bgp), Region: dcl.ValueOrEmptyString(resource.Region), Project: dcl.ValueOrEmptyString(resource.Project), SelfLink: dcl.ValueOrEmptyString(resource.SelfLink), } for _, r := range resource.Nats { p.Nats = append(p.Nats, ComputeRouterNatsToProto(&r)) } for _, r := range resource.Interfaces { p.Interfaces = append(p.Interfaces, ComputeRouterInterfacesToProto(&r)) } for _, r := range resource.BgpPeers { p.BgpPeers = append(p.BgpPeers, ComputeRouterBgpPeersToProto(&r)) } return p } // ApplyRouter handles the gRPC request by passing it to the underlying Router Apply() method. func (s *RouterServer) applyRouter(ctx context.Context, c *compute.Client, request *computepb.ApplyComputeRouterRequest) (*computepb.ComputeRouter, error) { p := ProtoToRouter(request.GetResource()) res, err := c.ApplyRouter(ctx, p) if err != nil { return nil, err } r := RouterToProto(res) return r, nil } // ApplyRouter handles the gRPC request by passing it to the underlying Router Apply() method. func (s *RouterServer) ApplyComputeRouter(ctx context.Context, request *computepb.ApplyComputeRouterRequest) (*computepb.ComputeRouter, error) { cl, err := createConfigRouter(ctx, request.ServiceAccountFile) if err != nil { return nil, err } return s.applyRouter(ctx, cl, request) } // DeleteRouter handles the gRPC request by passing it to the underlying Router Delete() method. func (s *RouterServer) DeleteComputeRouter(ctx context.Context, request *computepb.DeleteComputeRouterRequest) (*emptypb.Empty, error) { cl, err := createConfigRouter(ctx, request.ServiceAccountFile) if err != nil { return nil, err } return &emptypb.Empty{}, cl.DeleteRouter(ctx, ProtoToRouter(request.GetResource())) } // ListComputeRouter handles the gRPC request by passing it to the underlying RouterList() method. func (s *RouterServer) ListComputeRouter(ctx context.Context, request *computepb.ListComputeRouterRequest) (*computepb.ListComputeRouterResponse, error) { cl, err := createConfigRouter(ctx, request.ServiceAccountFile) if err != nil { return nil, err } resources, err := cl.ListRouter(ctx, request.Project, request.Region) if err != nil { return nil, err } var protos []*computepb.ComputeRouter for _, r := range resources.Items { rp := RouterToProto(r) protos = append(protos, rp) } return &computepb.ListComputeRouterResponse{Items: protos}, nil } func createConfigRouter(ctx context.Context, service_account_file string) (*compute.Client, error) { conf := dcl.NewConfig(dcl.WithUserAgent("dcl-test"), dcl.WithCredentialsFile(service_account_file)) return compute.NewClient(conf), nil }
package service import ( "fmt" "log" "net/rpc" "sync" "../config" ) // TODO // - Add timeout for dead machines // Client for querying logs func Client(expressionPtr *string) { logs := make(chan string) var wg sync.WaitGroup addresses, err := config.Addresses() if err != nil { log.Fatal(err) } fmt.Println(addresses) for _, address := range addresses { log.Println(address) wg.Add(1) go grepLogs(address, expressionPtr, &wg, logs) } go func() { wg.Wait() close(logs) }() counter := 0 for msg := range logs { fmt.Println(msg) counter++ } log.Printf("Received %d messages.", counter) } func grepLogs(address string, expressionPtr *string, wg *sync.WaitGroup, logs chan string) { defer wg.Done() log.Println("Dispatching RPC for", address) var reply string client, err := rpc.DialHTTP("tcp", address) if err != nil { log.Println("Error - GrepLogs:", err) } else { client.Call("Logly.GrepLogs", *expressionPtr, &reply) log.Println("done:", address, len(reply)) logs <- reply } }
package Problem0467 import ( "fmt" "testing" "github.com/stretchr/testify/assert" ) // tcs is testcase slice var tcs = []struct { p string ans int }{ { "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz", 259259, }, { "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz", 33475, }, { "abce", 7, }, { "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz", 2379, }, { "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz", 1027, }, { "abcdcde", 13, }, { "abcdabc", 10, }, { "abcd", 10, }, { "a", 1, }, { "cac", 2, }, { "zab", 6, }, // 可以有多个 testcase } func Test_findSubstringInWraproundString(t *testing.T) { ast := assert.New(t) for _, tc := range tcs { fmt.Printf("~~%v~~\n", tc) ast.Equal(tc.ans, findSubstringInWraproundString(tc.p), "输入:%v", tc) } } func Benchmark_findSubstringInWraproundString(b *testing.B) { for i := 0; i < b.N; i++ { for _, tc := range tcs { findSubstringInWraproundString(tc.p) } } }
package writer import "github.com/efark/data-receiver/logger" var log, slog = logger.GetLogger()
package x // GENERATED BY XO. DO NOT EDIT. import ( "errors" "strings" //"time" "ms/sun/shared/helper" "strconv" "github.com/jmoiron/sqlx" ) // (shortname .TableNameGo "err" "res" "sqlstr" "db" "XOLog") -}}//(schema .Schema .Table.TableName) -}}// .TableNameGo}}// PushChat represents a row from 'sun_push.push_chat'. // Manualy copy this to project type PushChat__ struct { PushId int `json:"PushId"` // PushId - ToUserId int `json:"ToUserId"` // ToUserId - PushTypeId int `json:"PushTypeId"` // PushTypeId - RoomKey string `json:"RoomKey"` // RoomKey - ChatKey string `json:"ChatKey"` // ChatKey - Seq int `json:"Seq"` // Seq - UnseenCount int `json:"UnseenCount"` // UnseenCount - FromHighMessageId int `json:"FromHighMessageId"` // FromHighMessageId - ToLowMessageId int `json:"ToLowMessageId"` // ToLowMessageId - MessageId int `json:"MessageId"` // MessageId - MessageFileId int `json:"MessageFileId"` // MessageFileId - MessagePb []byte `json:"MessagePb"` // MessagePb - MessageJson string `json:"MessageJson"` // MessageJson - CreatedTime int `json:"CreatedTime"` // CreatedTime - // xo fields _exists, _deleted bool } // Exists determines if the PushChat exists in the database. func (pc *PushChat) Exists() bool { return pc._exists } // Deleted provides information if the PushChat has been deleted from the database. func (pc *PushChat) Deleted() bool { return pc._deleted } // Insert inserts the PushChat to the database. func (pc *PushChat) Insert(db XODB) error { var err error // if already exist, bail if pc._exists { return errors.New("insert failed: already exists") } // sql insert query, primary key must be provided const sqlstr = `INSERT INTO sun_push.push_chat (` + `PushId, ToUserId, PushTypeId, RoomKey, ChatKey, Seq, UnseenCount, FromHighMessageId, ToLowMessageId, MessageId, MessageFileId, MessagePb, MessageJson, CreatedTime` + `) VALUES (` + `?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?` + `)` // run query if LogTableSqlReq.PushChat { XOLog(sqlstr, pc.PushId, pc.ToUserId, pc.PushTypeId, pc.RoomKey, pc.ChatKey, pc.Seq, pc.UnseenCount, pc.FromHighMessageId, pc.ToLowMessageId, pc.MessageId, pc.MessageFileId, pc.MessagePb, pc.MessageJson, pc.CreatedTime) } _, err = db.Exec(sqlstr, pc.PushId, pc.ToUserId, pc.PushTypeId, pc.RoomKey, pc.ChatKey, pc.Seq, pc.UnseenCount, pc.FromHighMessageId, pc.ToLowMessageId, pc.MessageId, pc.MessageFileId, pc.MessagePb, pc.MessageJson, pc.CreatedTime) if err != nil { return err } // set existence pc._exists = true OnPushChat_AfterInsert(pc) return nil } // Insert inserts the PushChat to the database. func (pc *PushChat) Replace(db XODB) error { var err error // sql query const sqlstr = `REPLACE INTO sun_push.push_chat (` + `PushId, ToUserId, PushTypeId, RoomKey, ChatKey, Seq, UnseenCount, FromHighMessageId, ToLowMessageId, MessageId, MessageFileId, MessagePb, MessageJson, CreatedTime` + `) VALUES (` + `?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?` + `)` // run query if LogTableSqlReq.PushChat { XOLog(sqlstr, pc.PushId, pc.ToUserId, pc.PushTypeId, pc.RoomKey, pc.ChatKey, pc.Seq, pc.UnseenCount, pc.FromHighMessageId, pc.ToLowMessageId, pc.MessageId, pc.MessageFileId, pc.MessagePb, pc.MessageJson, pc.CreatedTime) } _, err = db.Exec(sqlstr, pc.PushId, pc.ToUserId, pc.PushTypeId, pc.RoomKey, pc.ChatKey, pc.Seq, pc.UnseenCount, pc.FromHighMessageId, pc.ToLowMessageId, pc.MessageId, pc.MessageFileId, pc.MessagePb, pc.MessageJson, pc.CreatedTime) if err != nil { if LogTableSqlReq.PushChat { XOLogErr(err) } return err } pc._exists = true OnPushChat_AfterInsert(pc) return nil } // Update updates the PushChat in the database. func (pc *PushChat) Update(db XODB) error { var err error // if doesn't exist, bail if !pc._exists { return errors.New("update failed: does not exist") } // if deleted, bail if pc._deleted { return errors.New("update failed: marked for deletion") } // sql query const sqlstr = `UPDATE sun_push.push_chat SET ` + `ToUserId = ?, PushTypeId = ?, RoomKey = ?, ChatKey = ?, Seq = ?, UnseenCount = ?, FromHighMessageId = ?, ToLowMessageId = ?, MessageId = ?, MessageFileId = ?, MessagePb = ?, MessageJson = ?, CreatedTime = ?` + ` WHERE PushId = ?` // run query if LogTableSqlReq.PushChat { XOLog(sqlstr, pc.ToUserId, pc.PushTypeId, pc.RoomKey, pc.ChatKey, pc.Seq, pc.UnseenCount, pc.FromHighMessageId, pc.ToLowMessageId, pc.MessageId, pc.MessageFileId, pc.MessagePb, pc.MessageJson, pc.CreatedTime, pc.PushId) } _, err = db.Exec(sqlstr, pc.ToUserId, pc.PushTypeId, pc.RoomKey, pc.ChatKey, pc.Seq, pc.UnseenCount, pc.FromHighMessageId, pc.ToLowMessageId, pc.MessageId, pc.MessageFileId, pc.MessagePb, pc.MessageJson, pc.CreatedTime, pc.PushId) if LogTableSqlReq.PushChat { XOLogErr(err) } OnPushChat_AfterUpdate(pc) return err } // Save saves the PushChat to the database. func (pc *PushChat) Save(db XODB) error { if pc.Exists() { return pc.Update(db) } return pc.Replace(db) } // Delete deletes the PushChat from the database. func (pc *PushChat) Delete(db XODB) error { var err error // if doesn't exist, bail if !pc._exists { return nil } // if deleted, bail if pc._deleted { return nil } // sql query const sqlstr = `DELETE FROM sun_push.push_chat WHERE PushId = ?` // run query if LogTableSqlReq.PushChat { XOLog(sqlstr, pc.PushId) } _, err = db.Exec(sqlstr, pc.PushId) if err != nil { if LogTableSqlReq.PushChat { XOLogErr(err) } return err } // set deleted pc._deleted = true OnPushChat_AfterDelete(pc) return nil } //////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////// Querify gen - ME ///////////////////////////////////////// //.TableNameGo= table name // _Deleter, _Updater // orma types type __PushChat_Deleter struct { wheres []whereClause whereSep string dollarIndex int isMysql bool } type __PushChat_Updater struct { wheres []whereClause // updates map[string]interface{} updates []updateCol whereSep string dollarIndex int isMysql bool } type __PushChat_Selector struct { wheres []whereClause selectCol string whereSep string orderBy string //" order by id desc //for ints limit int offset int dollarIndex int isMysql bool } func NewPushChat_Deleter() *__PushChat_Deleter { d := __PushChat_Deleter{whereSep: " AND ", isMysql: true} return &d } func NewPushChat_Updater() *__PushChat_Updater { u := __PushChat_Updater{whereSep: " AND ", isMysql: true} //u.updates = make(map[string]interface{},10) return &u } func NewPushChat_Selector() *__PushChat_Selector { u := __PushChat_Selector{whereSep: " AND ", selectCol: "*", isMysql: true} return &u } /*/// mysql or cockroach ? or $1 handlers func (m *__PushChat_Selector)nextDollars(size int) string { r := DollarsForSqlIn(size,m.dollarIndex,m.isMysql) m.dollarIndex += size return r } func (m *__PushChat_Selector)nextDollar() string { r := DollarsForSqlIn(1,m.dollarIndex,m.isMysql) m.dollarIndex += 1 return r } */ /////////////////////////////// Where for all ///////////////////////////// //// for ints all selector updater, deleter /// mysql or cockroach ? or $1 handlers func (m *__PushChat_Deleter) nextDollars(size int) string { r := DollarsForSqlIn(size, m.dollarIndex, m.isMysql) m.dollarIndex += size return r } func (m *__PushChat_Deleter) nextDollar() string { r := DollarsForSqlIn(1, m.dollarIndex, m.isMysql) m.dollarIndex += 1 return r } ////////ints func (u *__PushChat_Deleter) Or() *__PushChat_Deleter { u.whereSep = " OR " return u } func (u *__PushChat_Deleter) PushId_In(ins []int) *__PushChat_Deleter { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " PushId IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (u *__PushChat_Deleter) PushId_Ins(ins ...int) *__PushChat_Deleter { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " PushId IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (u *__PushChat_Deleter) PushId_NotIn(ins []int) *__PushChat_Deleter { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " PushId NOT IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (d *__PushChat_Deleter) PushId_Eq(val int) *__PushChat_Deleter { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " PushId = " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__PushChat_Deleter) PushId_NotEq(val int) *__PushChat_Deleter { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " PushId != " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__PushChat_Deleter) PushId_LT(val int) *__PushChat_Deleter { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " PushId < " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__PushChat_Deleter) PushId_LE(val int) *__PushChat_Deleter { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " PushId <= " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__PushChat_Deleter) PushId_GT(val int) *__PushChat_Deleter { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " PushId > " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__PushChat_Deleter) PushId_GE(val int) *__PushChat_Deleter { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " PushId >= " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (u *__PushChat_Deleter) ToUserId_In(ins []int) *__PushChat_Deleter { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " ToUserId IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (u *__PushChat_Deleter) ToUserId_Ins(ins ...int) *__PushChat_Deleter { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " ToUserId IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (u *__PushChat_Deleter) ToUserId_NotIn(ins []int) *__PushChat_Deleter { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " ToUserId NOT IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (d *__PushChat_Deleter) ToUserId_Eq(val int) *__PushChat_Deleter { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " ToUserId = " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__PushChat_Deleter) ToUserId_NotEq(val int) *__PushChat_Deleter { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " ToUserId != " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__PushChat_Deleter) ToUserId_LT(val int) *__PushChat_Deleter { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " ToUserId < " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__PushChat_Deleter) ToUserId_LE(val int) *__PushChat_Deleter { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " ToUserId <= " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__PushChat_Deleter) ToUserId_GT(val int) *__PushChat_Deleter { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " ToUserId > " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__PushChat_Deleter) ToUserId_GE(val int) *__PushChat_Deleter { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " ToUserId >= " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (u *__PushChat_Deleter) PushTypeId_In(ins []int) *__PushChat_Deleter { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " PushTypeId IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (u *__PushChat_Deleter) PushTypeId_Ins(ins ...int) *__PushChat_Deleter { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " PushTypeId IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (u *__PushChat_Deleter) PushTypeId_NotIn(ins []int) *__PushChat_Deleter { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " PushTypeId NOT IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (d *__PushChat_Deleter) PushTypeId_Eq(val int) *__PushChat_Deleter { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " PushTypeId = " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__PushChat_Deleter) PushTypeId_NotEq(val int) *__PushChat_Deleter { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " PushTypeId != " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__PushChat_Deleter) PushTypeId_LT(val int) *__PushChat_Deleter { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " PushTypeId < " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__PushChat_Deleter) PushTypeId_LE(val int) *__PushChat_Deleter { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " PushTypeId <= " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__PushChat_Deleter) PushTypeId_GT(val int) *__PushChat_Deleter { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " PushTypeId > " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__PushChat_Deleter) PushTypeId_GE(val int) *__PushChat_Deleter { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " PushTypeId >= " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (u *__PushChat_Deleter) Seq_In(ins []int) *__PushChat_Deleter { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " Seq IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (u *__PushChat_Deleter) Seq_Ins(ins ...int) *__PushChat_Deleter { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " Seq IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (u *__PushChat_Deleter) Seq_NotIn(ins []int) *__PushChat_Deleter { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " Seq NOT IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (d *__PushChat_Deleter) Seq_Eq(val int) *__PushChat_Deleter { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " Seq = " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__PushChat_Deleter) Seq_NotEq(val int) *__PushChat_Deleter { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " Seq != " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__PushChat_Deleter) Seq_LT(val int) *__PushChat_Deleter { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " Seq < " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__PushChat_Deleter) Seq_LE(val int) *__PushChat_Deleter { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " Seq <= " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__PushChat_Deleter) Seq_GT(val int) *__PushChat_Deleter { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " Seq > " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__PushChat_Deleter) Seq_GE(val int) *__PushChat_Deleter { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " Seq >= " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (u *__PushChat_Deleter) UnseenCount_In(ins []int) *__PushChat_Deleter { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " UnseenCount IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (u *__PushChat_Deleter) UnseenCount_Ins(ins ...int) *__PushChat_Deleter { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " UnseenCount IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (u *__PushChat_Deleter) UnseenCount_NotIn(ins []int) *__PushChat_Deleter { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " UnseenCount NOT IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (d *__PushChat_Deleter) UnseenCount_Eq(val int) *__PushChat_Deleter { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " UnseenCount = " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__PushChat_Deleter) UnseenCount_NotEq(val int) *__PushChat_Deleter { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " UnseenCount != " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__PushChat_Deleter) UnseenCount_LT(val int) *__PushChat_Deleter { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " UnseenCount < " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__PushChat_Deleter) UnseenCount_LE(val int) *__PushChat_Deleter { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " UnseenCount <= " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__PushChat_Deleter) UnseenCount_GT(val int) *__PushChat_Deleter { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " UnseenCount > " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__PushChat_Deleter) UnseenCount_GE(val int) *__PushChat_Deleter { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " UnseenCount >= " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (u *__PushChat_Deleter) FromHighMessageId_In(ins []int) *__PushChat_Deleter { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " FromHighMessageId IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (u *__PushChat_Deleter) FromHighMessageId_Ins(ins ...int) *__PushChat_Deleter { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " FromHighMessageId IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (u *__PushChat_Deleter) FromHighMessageId_NotIn(ins []int) *__PushChat_Deleter { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " FromHighMessageId NOT IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (d *__PushChat_Deleter) FromHighMessageId_Eq(val int) *__PushChat_Deleter { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " FromHighMessageId = " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__PushChat_Deleter) FromHighMessageId_NotEq(val int) *__PushChat_Deleter { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " FromHighMessageId != " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__PushChat_Deleter) FromHighMessageId_LT(val int) *__PushChat_Deleter { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " FromHighMessageId < " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__PushChat_Deleter) FromHighMessageId_LE(val int) *__PushChat_Deleter { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " FromHighMessageId <= " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__PushChat_Deleter) FromHighMessageId_GT(val int) *__PushChat_Deleter { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " FromHighMessageId > " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__PushChat_Deleter) FromHighMessageId_GE(val int) *__PushChat_Deleter { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " FromHighMessageId >= " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (u *__PushChat_Deleter) ToLowMessageId_In(ins []int) *__PushChat_Deleter { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " ToLowMessageId IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (u *__PushChat_Deleter) ToLowMessageId_Ins(ins ...int) *__PushChat_Deleter { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " ToLowMessageId IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (u *__PushChat_Deleter) ToLowMessageId_NotIn(ins []int) *__PushChat_Deleter { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " ToLowMessageId NOT IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (d *__PushChat_Deleter) ToLowMessageId_Eq(val int) *__PushChat_Deleter { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " ToLowMessageId = " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__PushChat_Deleter) ToLowMessageId_NotEq(val int) *__PushChat_Deleter { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " ToLowMessageId != " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__PushChat_Deleter) ToLowMessageId_LT(val int) *__PushChat_Deleter { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " ToLowMessageId < " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__PushChat_Deleter) ToLowMessageId_LE(val int) *__PushChat_Deleter { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " ToLowMessageId <= " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__PushChat_Deleter) ToLowMessageId_GT(val int) *__PushChat_Deleter { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " ToLowMessageId > " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__PushChat_Deleter) ToLowMessageId_GE(val int) *__PushChat_Deleter { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " ToLowMessageId >= " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (u *__PushChat_Deleter) MessageId_In(ins []int) *__PushChat_Deleter { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " MessageId IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (u *__PushChat_Deleter) MessageId_Ins(ins ...int) *__PushChat_Deleter { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " MessageId IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (u *__PushChat_Deleter) MessageId_NotIn(ins []int) *__PushChat_Deleter { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " MessageId NOT IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (d *__PushChat_Deleter) MessageId_Eq(val int) *__PushChat_Deleter { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " MessageId = " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__PushChat_Deleter) MessageId_NotEq(val int) *__PushChat_Deleter { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " MessageId != " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__PushChat_Deleter) MessageId_LT(val int) *__PushChat_Deleter { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " MessageId < " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__PushChat_Deleter) MessageId_LE(val int) *__PushChat_Deleter { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " MessageId <= " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__PushChat_Deleter) MessageId_GT(val int) *__PushChat_Deleter { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " MessageId > " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__PushChat_Deleter) MessageId_GE(val int) *__PushChat_Deleter { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " MessageId >= " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (u *__PushChat_Deleter) MessageFileId_In(ins []int) *__PushChat_Deleter { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " MessageFileId IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (u *__PushChat_Deleter) MessageFileId_Ins(ins ...int) *__PushChat_Deleter { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " MessageFileId IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (u *__PushChat_Deleter) MessageFileId_NotIn(ins []int) *__PushChat_Deleter { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " MessageFileId NOT IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (d *__PushChat_Deleter) MessageFileId_Eq(val int) *__PushChat_Deleter { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " MessageFileId = " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__PushChat_Deleter) MessageFileId_NotEq(val int) *__PushChat_Deleter { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " MessageFileId != " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__PushChat_Deleter) MessageFileId_LT(val int) *__PushChat_Deleter { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " MessageFileId < " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__PushChat_Deleter) MessageFileId_LE(val int) *__PushChat_Deleter { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " MessageFileId <= " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__PushChat_Deleter) MessageFileId_GT(val int) *__PushChat_Deleter { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " MessageFileId > " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__PushChat_Deleter) MessageFileId_GE(val int) *__PushChat_Deleter { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " MessageFileId >= " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (u *__PushChat_Deleter) CreatedTime_In(ins []int) *__PushChat_Deleter { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " CreatedTime IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (u *__PushChat_Deleter) CreatedTime_Ins(ins ...int) *__PushChat_Deleter { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " CreatedTime IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (u *__PushChat_Deleter) CreatedTime_NotIn(ins []int) *__PushChat_Deleter { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " CreatedTime NOT IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (d *__PushChat_Deleter) CreatedTime_Eq(val int) *__PushChat_Deleter { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " CreatedTime = " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__PushChat_Deleter) CreatedTime_NotEq(val int) *__PushChat_Deleter { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " CreatedTime != " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__PushChat_Deleter) CreatedTime_LT(val int) *__PushChat_Deleter { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " CreatedTime < " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__PushChat_Deleter) CreatedTime_LE(val int) *__PushChat_Deleter { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " CreatedTime <= " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__PushChat_Deleter) CreatedTime_GT(val int) *__PushChat_Deleter { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " CreatedTime > " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__PushChat_Deleter) CreatedTime_GE(val int) *__PushChat_Deleter { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " CreatedTime >= " + d.nextDollar() d.wheres = append(d.wheres, w) return d } /// mysql or cockroach ? or $1 handlers func (m *__PushChat_Updater) nextDollars(size int) string { r := DollarsForSqlIn(size, m.dollarIndex, m.isMysql) m.dollarIndex += size return r } func (m *__PushChat_Updater) nextDollar() string { r := DollarsForSqlIn(1, m.dollarIndex, m.isMysql) m.dollarIndex += 1 return r } ////////ints func (u *__PushChat_Updater) Or() *__PushChat_Updater { u.whereSep = " OR " return u } func (u *__PushChat_Updater) PushId_In(ins []int) *__PushChat_Updater { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " PushId IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (u *__PushChat_Updater) PushId_Ins(ins ...int) *__PushChat_Updater { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " PushId IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (u *__PushChat_Updater) PushId_NotIn(ins []int) *__PushChat_Updater { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " PushId NOT IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (d *__PushChat_Updater) PushId_Eq(val int) *__PushChat_Updater { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " PushId = " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__PushChat_Updater) PushId_NotEq(val int) *__PushChat_Updater { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " PushId != " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__PushChat_Updater) PushId_LT(val int) *__PushChat_Updater { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " PushId < " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__PushChat_Updater) PushId_LE(val int) *__PushChat_Updater { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " PushId <= " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__PushChat_Updater) PushId_GT(val int) *__PushChat_Updater { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " PushId > " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__PushChat_Updater) PushId_GE(val int) *__PushChat_Updater { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " PushId >= " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (u *__PushChat_Updater) ToUserId_In(ins []int) *__PushChat_Updater { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " ToUserId IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (u *__PushChat_Updater) ToUserId_Ins(ins ...int) *__PushChat_Updater { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " ToUserId IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (u *__PushChat_Updater) ToUserId_NotIn(ins []int) *__PushChat_Updater { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " ToUserId NOT IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (d *__PushChat_Updater) ToUserId_Eq(val int) *__PushChat_Updater { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " ToUserId = " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__PushChat_Updater) ToUserId_NotEq(val int) *__PushChat_Updater { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " ToUserId != " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__PushChat_Updater) ToUserId_LT(val int) *__PushChat_Updater { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " ToUserId < " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__PushChat_Updater) ToUserId_LE(val int) *__PushChat_Updater { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " ToUserId <= " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__PushChat_Updater) ToUserId_GT(val int) *__PushChat_Updater { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " ToUserId > " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__PushChat_Updater) ToUserId_GE(val int) *__PushChat_Updater { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " ToUserId >= " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (u *__PushChat_Updater) PushTypeId_In(ins []int) *__PushChat_Updater { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " PushTypeId IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (u *__PushChat_Updater) PushTypeId_Ins(ins ...int) *__PushChat_Updater { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " PushTypeId IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (u *__PushChat_Updater) PushTypeId_NotIn(ins []int) *__PushChat_Updater { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " PushTypeId NOT IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (d *__PushChat_Updater) PushTypeId_Eq(val int) *__PushChat_Updater { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " PushTypeId = " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__PushChat_Updater) PushTypeId_NotEq(val int) *__PushChat_Updater { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " PushTypeId != " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__PushChat_Updater) PushTypeId_LT(val int) *__PushChat_Updater { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " PushTypeId < " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__PushChat_Updater) PushTypeId_LE(val int) *__PushChat_Updater { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " PushTypeId <= " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__PushChat_Updater) PushTypeId_GT(val int) *__PushChat_Updater { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " PushTypeId > " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__PushChat_Updater) PushTypeId_GE(val int) *__PushChat_Updater { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " PushTypeId >= " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (u *__PushChat_Updater) Seq_In(ins []int) *__PushChat_Updater { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " Seq IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (u *__PushChat_Updater) Seq_Ins(ins ...int) *__PushChat_Updater { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " Seq IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (u *__PushChat_Updater) Seq_NotIn(ins []int) *__PushChat_Updater { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " Seq NOT IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (d *__PushChat_Updater) Seq_Eq(val int) *__PushChat_Updater { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " Seq = " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__PushChat_Updater) Seq_NotEq(val int) *__PushChat_Updater { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " Seq != " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__PushChat_Updater) Seq_LT(val int) *__PushChat_Updater { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " Seq < " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__PushChat_Updater) Seq_LE(val int) *__PushChat_Updater { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " Seq <= " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__PushChat_Updater) Seq_GT(val int) *__PushChat_Updater { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " Seq > " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__PushChat_Updater) Seq_GE(val int) *__PushChat_Updater { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " Seq >= " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (u *__PushChat_Updater) UnseenCount_In(ins []int) *__PushChat_Updater { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " UnseenCount IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (u *__PushChat_Updater) UnseenCount_Ins(ins ...int) *__PushChat_Updater { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " UnseenCount IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (u *__PushChat_Updater) UnseenCount_NotIn(ins []int) *__PushChat_Updater { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " UnseenCount NOT IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (d *__PushChat_Updater) UnseenCount_Eq(val int) *__PushChat_Updater { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " UnseenCount = " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__PushChat_Updater) UnseenCount_NotEq(val int) *__PushChat_Updater { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " UnseenCount != " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__PushChat_Updater) UnseenCount_LT(val int) *__PushChat_Updater { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " UnseenCount < " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__PushChat_Updater) UnseenCount_LE(val int) *__PushChat_Updater { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " UnseenCount <= " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__PushChat_Updater) UnseenCount_GT(val int) *__PushChat_Updater { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " UnseenCount > " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__PushChat_Updater) UnseenCount_GE(val int) *__PushChat_Updater { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " UnseenCount >= " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (u *__PushChat_Updater) FromHighMessageId_In(ins []int) *__PushChat_Updater { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " FromHighMessageId IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (u *__PushChat_Updater) FromHighMessageId_Ins(ins ...int) *__PushChat_Updater { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " FromHighMessageId IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (u *__PushChat_Updater) FromHighMessageId_NotIn(ins []int) *__PushChat_Updater { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " FromHighMessageId NOT IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (d *__PushChat_Updater) FromHighMessageId_Eq(val int) *__PushChat_Updater { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " FromHighMessageId = " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__PushChat_Updater) FromHighMessageId_NotEq(val int) *__PushChat_Updater { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " FromHighMessageId != " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__PushChat_Updater) FromHighMessageId_LT(val int) *__PushChat_Updater { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " FromHighMessageId < " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__PushChat_Updater) FromHighMessageId_LE(val int) *__PushChat_Updater { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " FromHighMessageId <= " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__PushChat_Updater) FromHighMessageId_GT(val int) *__PushChat_Updater { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " FromHighMessageId > " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__PushChat_Updater) FromHighMessageId_GE(val int) *__PushChat_Updater { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " FromHighMessageId >= " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (u *__PushChat_Updater) ToLowMessageId_In(ins []int) *__PushChat_Updater { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " ToLowMessageId IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (u *__PushChat_Updater) ToLowMessageId_Ins(ins ...int) *__PushChat_Updater { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " ToLowMessageId IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (u *__PushChat_Updater) ToLowMessageId_NotIn(ins []int) *__PushChat_Updater { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " ToLowMessageId NOT IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (d *__PushChat_Updater) ToLowMessageId_Eq(val int) *__PushChat_Updater { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " ToLowMessageId = " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__PushChat_Updater) ToLowMessageId_NotEq(val int) *__PushChat_Updater { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " ToLowMessageId != " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__PushChat_Updater) ToLowMessageId_LT(val int) *__PushChat_Updater { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " ToLowMessageId < " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__PushChat_Updater) ToLowMessageId_LE(val int) *__PushChat_Updater { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " ToLowMessageId <= " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__PushChat_Updater) ToLowMessageId_GT(val int) *__PushChat_Updater { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " ToLowMessageId > " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__PushChat_Updater) ToLowMessageId_GE(val int) *__PushChat_Updater { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " ToLowMessageId >= " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (u *__PushChat_Updater) MessageId_In(ins []int) *__PushChat_Updater { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " MessageId IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (u *__PushChat_Updater) MessageId_Ins(ins ...int) *__PushChat_Updater { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " MessageId IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (u *__PushChat_Updater) MessageId_NotIn(ins []int) *__PushChat_Updater { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " MessageId NOT IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (d *__PushChat_Updater) MessageId_Eq(val int) *__PushChat_Updater { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " MessageId = " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__PushChat_Updater) MessageId_NotEq(val int) *__PushChat_Updater { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " MessageId != " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__PushChat_Updater) MessageId_LT(val int) *__PushChat_Updater { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " MessageId < " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__PushChat_Updater) MessageId_LE(val int) *__PushChat_Updater { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " MessageId <= " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__PushChat_Updater) MessageId_GT(val int) *__PushChat_Updater { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " MessageId > " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__PushChat_Updater) MessageId_GE(val int) *__PushChat_Updater { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " MessageId >= " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (u *__PushChat_Updater) MessageFileId_In(ins []int) *__PushChat_Updater { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " MessageFileId IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (u *__PushChat_Updater) MessageFileId_Ins(ins ...int) *__PushChat_Updater { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " MessageFileId IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (u *__PushChat_Updater) MessageFileId_NotIn(ins []int) *__PushChat_Updater { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " MessageFileId NOT IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (d *__PushChat_Updater) MessageFileId_Eq(val int) *__PushChat_Updater { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " MessageFileId = " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__PushChat_Updater) MessageFileId_NotEq(val int) *__PushChat_Updater { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " MessageFileId != " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__PushChat_Updater) MessageFileId_LT(val int) *__PushChat_Updater { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " MessageFileId < " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__PushChat_Updater) MessageFileId_LE(val int) *__PushChat_Updater { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " MessageFileId <= " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__PushChat_Updater) MessageFileId_GT(val int) *__PushChat_Updater { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " MessageFileId > " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__PushChat_Updater) MessageFileId_GE(val int) *__PushChat_Updater { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " MessageFileId >= " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (u *__PushChat_Updater) CreatedTime_In(ins []int) *__PushChat_Updater { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " CreatedTime IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (u *__PushChat_Updater) CreatedTime_Ins(ins ...int) *__PushChat_Updater { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " CreatedTime IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (u *__PushChat_Updater) CreatedTime_NotIn(ins []int) *__PushChat_Updater { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " CreatedTime NOT IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (d *__PushChat_Updater) CreatedTime_Eq(val int) *__PushChat_Updater { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " CreatedTime = " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__PushChat_Updater) CreatedTime_NotEq(val int) *__PushChat_Updater { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " CreatedTime != " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__PushChat_Updater) CreatedTime_LT(val int) *__PushChat_Updater { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " CreatedTime < " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__PushChat_Updater) CreatedTime_LE(val int) *__PushChat_Updater { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " CreatedTime <= " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__PushChat_Updater) CreatedTime_GT(val int) *__PushChat_Updater { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " CreatedTime > " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__PushChat_Updater) CreatedTime_GE(val int) *__PushChat_Updater { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " CreatedTime >= " + d.nextDollar() d.wheres = append(d.wheres, w) return d } /// mysql or cockroach ? or $1 handlers func (m *__PushChat_Selector) nextDollars(size int) string { r := DollarsForSqlIn(size, m.dollarIndex, m.isMysql) m.dollarIndex += size return r } func (m *__PushChat_Selector) nextDollar() string { r := DollarsForSqlIn(1, m.dollarIndex, m.isMysql) m.dollarIndex += 1 return r } ////////ints func (u *__PushChat_Selector) Or() *__PushChat_Selector { u.whereSep = " OR " return u } func (u *__PushChat_Selector) PushId_In(ins []int) *__PushChat_Selector { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " PushId IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (u *__PushChat_Selector) PushId_Ins(ins ...int) *__PushChat_Selector { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " PushId IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (u *__PushChat_Selector) PushId_NotIn(ins []int) *__PushChat_Selector { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " PushId NOT IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (d *__PushChat_Selector) PushId_Eq(val int) *__PushChat_Selector { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " PushId = " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__PushChat_Selector) PushId_NotEq(val int) *__PushChat_Selector { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " PushId != " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__PushChat_Selector) PushId_LT(val int) *__PushChat_Selector { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " PushId < " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__PushChat_Selector) PushId_LE(val int) *__PushChat_Selector { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " PushId <= " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__PushChat_Selector) PushId_GT(val int) *__PushChat_Selector { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " PushId > " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__PushChat_Selector) PushId_GE(val int) *__PushChat_Selector { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " PushId >= " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (u *__PushChat_Selector) ToUserId_In(ins []int) *__PushChat_Selector { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " ToUserId IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (u *__PushChat_Selector) ToUserId_Ins(ins ...int) *__PushChat_Selector { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " ToUserId IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (u *__PushChat_Selector) ToUserId_NotIn(ins []int) *__PushChat_Selector { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " ToUserId NOT IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (d *__PushChat_Selector) ToUserId_Eq(val int) *__PushChat_Selector { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " ToUserId = " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__PushChat_Selector) ToUserId_NotEq(val int) *__PushChat_Selector { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " ToUserId != " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__PushChat_Selector) ToUserId_LT(val int) *__PushChat_Selector { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " ToUserId < " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__PushChat_Selector) ToUserId_LE(val int) *__PushChat_Selector { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " ToUserId <= " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__PushChat_Selector) ToUserId_GT(val int) *__PushChat_Selector { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " ToUserId > " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__PushChat_Selector) ToUserId_GE(val int) *__PushChat_Selector { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " ToUserId >= " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (u *__PushChat_Selector) PushTypeId_In(ins []int) *__PushChat_Selector { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " PushTypeId IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (u *__PushChat_Selector) PushTypeId_Ins(ins ...int) *__PushChat_Selector { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " PushTypeId IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (u *__PushChat_Selector) PushTypeId_NotIn(ins []int) *__PushChat_Selector { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " PushTypeId NOT IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (d *__PushChat_Selector) PushTypeId_Eq(val int) *__PushChat_Selector { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " PushTypeId = " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__PushChat_Selector) PushTypeId_NotEq(val int) *__PushChat_Selector { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " PushTypeId != " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__PushChat_Selector) PushTypeId_LT(val int) *__PushChat_Selector { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " PushTypeId < " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__PushChat_Selector) PushTypeId_LE(val int) *__PushChat_Selector { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " PushTypeId <= " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__PushChat_Selector) PushTypeId_GT(val int) *__PushChat_Selector { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " PushTypeId > " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__PushChat_Selector) PushTypeId_GE(val int) *__PushChat_Selector { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " PushTypeId >= " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (u *__PushChat_Selector) Seq_In(ins []int) *__PushChat_Selector { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " Seq IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (u *__PushChat_Selector) Seq_Ins(ins ...int) *__PushChat_Selector { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " Seq IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (u *__PushChat_Selector) Seq_NotIn(ins []int) *__PushChat_Selector { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " Seq NOT IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (d *__PushChat_Selector) Seq_Eq(val int) *__PushChat_Selector { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " Seq = " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__PushChat_Selector) Seq_NotEq(val int) *__PushChat_Selector { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " Seq != " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__PushChat_Selector) Seq_LT(val int) *__PushChat_Selector { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " Seq < " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__PushChat_Selector) Seq_LE(val int) *__PushChat_Selector { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " Seq <= " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__PushChat_Selector) Seq_GT(val int) *__PushChat_Selector { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " Seq > " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__PushChat_Selector) Seq_GE(val int) *__PushChat_Selector { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " Seq >= " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (u *__PushChat_Selector) UnseenCount_In(ins []int) *__PushChat_Selector { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " UnseenCount IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (u *__PushChat_Selector) UnseenCount_Ins(ins ...int) *__PushChat_Selector { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " UnseenCount IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (u *__PushChat_Selector) UnseenCount_NotIn(ins []int) *__PushChat_Selector { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " UnseenCount NOT IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (d *__PushChat_Selector) UnseenCount_Eq(val int) *__PushChat_Selector { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " UnseenCount = " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__PushChat_Selector) UnseenCount_NotEq(val int) *__PushChat_Selector { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " UnseenCount != " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__PushChat_Selector) UnseenCount_LT(val int) *__PushChat_Selector { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " UnseenCount < " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__PushChat_Selector) UnseenCount_LE(val int) *__PushChat_Selector { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " UnseenCount <= " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__PushChat_Selector) UnseenCount_GT(val int) *__PushChat_Selector { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " UnseenCount > " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__PushChat_Selector) UnseenCount_GE(val int) *__PushChat_Selector { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " UnseenCount >= " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (u *__PushChat_Selector) FromHighMessageId_In(ins []int) *__PushChat_Selector { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " FromHighMessageId IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (u *__PushChat_Selector) FromHighMessageId_Ins(ins ...int) *__PushChat_Selector { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " FromHighMessageId IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (u *__PushChat_Selector) FromHighMessageId_NotIn(ins []int) *__PushChat_Selector { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " FromHighMessageId NOT IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (d *__PushChat_Selector) FromHighMessageId_Eq(val int) *__PushChat_Selector { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " FromHighMessageId = " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__PushChat_Selector) FromHighMessageId_NotEq(val int) *__PushChat_Selector { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " FromHighMessageId != " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__PushChat_Selector) FromHighMessageId_LT(val int) *__PushChat_Selector { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " FromHighMessageId < " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__PushChat_Selector) FromHighMessageId_LE(val int) *__PushChat_Selector { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " FromHighMessageId <= " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__PushChat_Selector) FromHighMessageId_GT(val int) *__PushChat_Selector { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " FromHighMessageId > " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__PushChat_Selector) FromHighMessageId_GE(val int) *__PushChat_Selector { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " FromHighMessageId >= " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (u *__PushChat_Selector) ToLowMessageId_In(ins []int) *__PushChat_Selector { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " ToLowMessageId IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (u *__PushChat_Selector) ToLowMessageId_Ins(ins ...int) *__PushChat_Selector { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " ToLowMessageId IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (u *__PushChat_Selector) ToLowMessageId_NotIn(ins []int) *__PushChat_Selector { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " ToLowMessageId NOT IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (d *__PushChat_Selector) ToLowMessageId_Eq(val int) *__PushChat_Selector { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " ToLowMessageId = " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__PushChat_Selector) ToLowMessageId_NotEq(val int) *__PushChat_Selector { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " ToLowMessageId != " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__PushChat_Selector) ToLowMessageId_LT(val int) *__PushChat_Selector { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " ToLowMessageId < " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__PushChat_Selector) ToLowMessageId_LE(val int) *__PushChat_Selector { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " ToLowMessageId <= " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__PushChat_Selector) ToLowMessageId_GT(val int) *__PushChat_Selector { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " ToLowMessageId > " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__PushChat_Selector) ToLowMessageId_GE(val int) *__PushChat_Selector { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " ToLowMessageId >= " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (u *__PushChat_Selector) MessageId_In(ins []int) *__PushChat_Selector { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " MessageId IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (u *__PushChat_Selector) MessageId_Ins(ins ...int) *__PushChat_Selector { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " MessageId IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (u *__PushChat_Selector) MessageId_NotIn(ins []int) *__PushChat_Selector { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " MessageId NOT IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (d *__PushChat_Selector) MessageId_Eq(val int) *__PushChat_Selector { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " MessageId = " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__PushChat_Selector) MessageId_NotEq(val int) *__PushChat_Selector { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " MessageId != " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__PushChat_Selector) MessageId_LT(val int) *__PushChat_Selector { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " MessageId < " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__PushChat_Selector) MessageId_LE(val int) *__PushChat_Selector { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " MessageId <= " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__PushChat_Selector) MessageId_GT(val int) *__PushChat_Selector { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " MessageId > " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__PushChat_Selector) MessageId_GE(val int) *__PushChat_Selector { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " MessageId >= " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (u *__PushChat_Selector) MessageFileId_In(ins []int) *__PushChat_Selector { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " MessageFileId IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (u *__PushChat_Selector) MessageFileId_Ins(ins ...int) *__PushChat_Selector { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " MessageFileId IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (u *__PushChat_Selector) MessageFileId_NotIn(ins []int) *__PushChat_Selector { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " MessageFileId NOT IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (d *__PushChat_Selector) MessageFileId_Eq(val int) *__PushChat_Selector { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " MessageFileId = " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__PushChat_Selector) MessageFileId_NotEq(val int) *__PushChat_Selector { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " MessageFileId != " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__PushChat_Selector) MessageFileId_LT(val int) *__PushChat_Selector { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " MessageFileId < " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__PushChat_Selector) MessageFileId_LE(val int) *__PushChat_Selector { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " MessageFileId <= " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__PushChat_Selector) MessageFileId_GT(val int) *__PushChat_Selector { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " MessageFileId > " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__PushChat_Selector) MessageFileId_GE(val int) *__PushChat_Selector { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " MessageFileId >= " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (u *__PushChat_Selector) CreatedTime_In(ins []int) *__PushChat_Selector { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " CreatedTime IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (u *__PushChat_Selector) CreatedTime_Ins(ins ...int) *__PushChat_Selector { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " CreatedTime IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (u *__PushChat_Selector) CreatedTime_NotIn(ins []int) *__PushChat_Selector { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " CreatedTime NOT IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (d *__PushChat_Selector) CreatedTime_Eq(val int) *__PushChat_Selector { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " CreatedTime = " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__PushChat_Selector) CreatedTime_NotEq(val int) *__PushChat_Selector { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " CreatedTime != " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__PushChat_Selector) CreatedTime_LT(val int) *__PushChat_Selector { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " CreatedTime < " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__PushChat_Selector) CreatedTime_LE(val int) *__PushChat_Selector { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " CreatedTime <= " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__PushChat_Selector) CreatedTime_GT(val int) *__PushChat_Selector { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " CreatedTime > " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__PushChat_Selector) CreatedTime_GE(val int) *__PushChat_Selector { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " CreatedTime >= " + d.nextDollar() d.wheres = append(d.wheres, w) return d } ///// for strings //copy of above with type int -> string + rm if eq + $ms_str_cond ////////ints func (u *__PushChat_Deleter) RoomKey_In(ins []string) *__PushChat_Deleter { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " RoomKey IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (u *__PushChat_Deleter) RoomKey_NotIn(ins []string) *__PushChat_Deleter { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " RoomKey NOT IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } //must be used like: UserName_like("hamid%") func (u *__PushChat_Deleter) RoomKey_Like(val string) *__PushChat_Deleter { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " RoomKey LIKE " + u.nextDollar() u.wheres = append(u.wheres, w) return u } func (d *__PushChat_Deleter) RoomKey_Eq(val string) *__PushChat_Deleter { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " RoomKey = " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__PushChat_Deleter) RoomKey_NotEq(val string) *__PushChat_Deleter { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " RoomKey != " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (u *__PushChat_Deleter) ChatKey_In(ins []string) *__PushChat_Deleter { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " ChatKey IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (u *__PushChat_Deleter) ChatKey_NotIn(ins []string) *__PushChat_Deleter { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " ChatKey NOT IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } //must be used like: UserName_like("hamid%") func (u *__PushChat_Deleter) ChatKey_Like(val string) *__PushChat_Deleter { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " ChatKey LIKE " + u.nextDollar() u.wheres = append(u.wheres, w) return u } func (d *__PushChat_Deleter) ChatKey_Eq(val string) *__PushChat_Deleter { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " ChatKey = " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__PushChat_Deleter) ChatKey_NotEq(val string) *__PushChat_Deleter { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " ChatKey != " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (u *__PushChat_Deleter) MessageJson_In(ins []string) *__PushChat_Deleter { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " MessageJson IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (u *__PushChat_Deleter) MessageJson_NotIn(ins []string) *__PushChat_Deleter { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " MessageJson NOT IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } //must be used like: UserName_like("hamid%") func (u *__PushChat_Deleter) MessageJson_Like(val string) *__PushChat_Deleter { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " MessageJson LIKE " + u.nextDollar() u.wheres = append(u.wheres, w) return u } func (d *__PushChat_Deleter) MessageJson_Eq(val string) *__PushChat_Deleter { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " MessageJson = " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__PushChat_Deleter) MessageJson_NotEq(val string) *__PushChat_Deleter { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " MessageJson != " + d.nextDollar() d.wheres = append(d.wheres, w) return d } ////////ints func (u *__PushChat_Updater) RoomKey_In(ins []string) *__PushChat_Updater { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " RoomKey IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (u *__PushChat_Updater) RoomKey_NotIn(ins []string) *__PushChat_Updater { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " RoomKey NOT IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } //must be used like: UserName_like("hamid%") func (u *__PushChat_Updater) RoomKey_Like(val string) *__PushChat_Updater { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " RoomKey LIKE " + u.nextDollar() u.wheres = append(u.wheres, w) return u } func (d *__PushChat_Updater) RoomKey_Eq(val string) *__PushChat_Updater { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " RoomKey = " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__PushChat_Updater) RoomKey_NotEq(val string) *__PushChat_Updater { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " RoomKey != " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (u *__PushChat_Updater) ChatKey_In(ins []string) *__PushChat_Updater { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " ChatKey IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (u *__PushChat_Updater) ChatKey_NotIn(ins []string) *__PushChat_Updater { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " ChatKey NOT IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } //must be used like: UserName_like("hamid%") func (u *__PushChat_Updater) ChatKey_Like(val string) *__PushChat_Updater { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " ChatKey LIKE " + u.nextDollar() u.wheres = append(u.wheres, w) return u } func (d *__PushChat_Updater) ChatKey_Eq(val string) *__PushChat_Updater { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " ChatKey = " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__PushChat_Updater) ChatKey_NotEq(val string) *__PushChat_Updater { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " ChatKey != " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (u *__PushChat_Updater) MessageJson_In(ins []string) *__PushChat_Updater { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " MessageJson IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (u *__PushChat_Updater) MessageJson_NotIn(ins []string) *__PushChat_Updater { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " MessageJson NOT IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } //must be used like: UserName_like("hamid%") func (u *__PushChat_Updater) MessageJson_Like(val string) *__PushChat_Updater { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " MessageJson LIKE " + u.nextDollar() u.wheres = append(u.wheres, w) return u } func (d *__PushChat_Updater) MessageJson_Eq(val string) *__PushChat_Updater { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " MessageJson = " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__PushChat_Updater) MessageJson_NotEq(val string) *__PushChat_Updater { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " MessageJson != " + d.nextDollar() d.wheres = append(d.wheres, w) return d } ////////ints func (u *__PushChat_Selector) RoomKey_In(ins []string) *__PushChat_Selector { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " RoomKey IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (u *__PushChat_Selector) RoomKey_NotIn(ins []string) *__PushChat_Selector { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " RoomKey NOT IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } //must be used like: UserName_like("hamid%") func (u *__PushChat_Selector) RoomKey_Like(val string) *__PushChat_Selector { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " RoomKey LIKE " + u.nextDollar() u.wheres = append(u.wheres, w) return u } func (d *__PushChat_Selector) RoomKey_Eq(val string) *__PushChat_Selector { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " RoomKey = " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__PushChat_Selector) RoomKey_NotEq(val string) *__PushChat_Selector { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " RoomKey != " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (u *__PushChat_Selector) ChatKey_In(ins []string) *__PushChat_Selector { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " ChatKey IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (u *__PushChat_Selector) ChatKey_NotIn(ins []string) *__PushChat_Selector { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " ChatKey NOT IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } //must be used like: UserName_like("hamid%") func (u *__PushChat_Selector) ChatKey_Like(val string) *__PushChat_Selector { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " ChatKey LIKE " + u.nextDollar() u.wheres = append(u.wheres, w) return u } func (d *__PushChat_Selector) ChatKey_Eq(val string) *__PushChat_Selector { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " ChatKey = " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__PushChat_Selector) ChatKey_NotEq(val string) *__PushChat_Selector { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " ChatKey != " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (u *__PushChat_Selector) MessageJson_In(ins []string) *__PushChat_Selector { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " MessageJson IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (u *__PushChat_Selector) MessageJson_NotIn(ins []string) *__PushChat_Selector { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " MessageJson NOT IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } //must be used like: UserName_like("hamid%") func (u *__PushChat_Selector) MessageJson_Like(val string) *__PushChat_Selector { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " MessageJson LIKE " + u.nextDollar() u.wheres = append(u.wheres, w) return u } func (d *__PushChat_Selector) MessageJson_Eq(val string) *__PushChat_Selector { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " MessageJson = " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__PushChat_Selector) MessageJson_NotEq(val string) *__PushChat_Selector { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " MessageJson != " + d.nextDollar() d.wheres = append(d.wheres, w) return d } /// End of wheres for selectors , updators, deletor /////////////////////////////// Updater ///////////////////////////// //ints func (u *__PushChat_Updater) PushId(newVal int) *__PushChat_Updater { up := updateCol{" PushId = " + u.nextDollar(), newVal} u.updates = append(u.updates, up) // u.updates[" PushId = " + u.nextDollar()] = newVal return u } func (u *__PushChat_Updater) PushId_Increment(count int) *__PushChat_Updater { if count > 0 { up := updateCol{" PushId = PushId+ " + u.nextDollar(), count} u.updates = append(u.updates, up) //u.updates[" PushId = PushId+ " + u.nextDollar()] = count } if count < 0 { up := updateCol{" PushId = PushId- " + u.nextDollar(), count} u.updates = append(u.updates, up) // u.updates[" PushId = PushId- " + u.nextDollar() ] = -(count) //make it positive } return u } //string //ints func (u *__PushChat_Updater) ToUserId(newVal int) *__PushChat_Updater { up := updateCol{" ToUserId = " + u.nextDollar(), newVal} u.updates = append(u.updates, up) // u.updates[" ToUserId = " + u.nextDollar()] = newVal return u } func (u *__PushChat_Updater) ToUserId_Increment(count int) *__PushChat_Updater { if count > 0 { up := updateCol{" ToUserId = ToUserId+ " + u.nextDollar(), count} u.updates = append(u.updates, up) //u.updates[" ToUserId = ToUserId+ " + u.nextDollar()] = count } if count < 0 { up := updateCol{" ToUserId = ToUserId- " + u.nextDollar(), count} u.updates = append(u.updates, up) // u.updates[" ToUserId = ToUserId- " + u.nextDollar() ] = -(count) //make it positive } return u } //string //ints func (u *__PushChat_Updater) PushTypeId(newVal int) *__PushChat_Updater { up := updateCol{" PushTypeId = " + u.nextDollar(), newVal} u.updates = append(u.updates, up) // u.updates[" PushTypeId = " + u.nextDollar()] = newVal return u } func (u *__PushChat_Updater) PushTypeId_Increment(count int) *__PushChat_Updater { if count > 0 { up := updateCol{" PushTypeId = PushTypeId+ " + u.nextDollar(), count} u.updates = append(u.updates, up) //u.updates[" PushTypeId = PushTypeId+ " + u.nextDollar()] = count } if count < 0 { up := updateCol{" PushTypeId = PushTypeId- " + u.nextDollar(), count} u.updates = append(u.updates, up) // u.updates[" PushTypeId = PushTypeId- " + u.nextDollar() ] = -(count) //make it positive } return u } //string //ints //string func (u *__PushChat_Updater) RoomKey(newVal string) *__PushChat_Updater { up := updateCol{"RoomKey = " + u.nextDollar(), newVal} u.updates = append(u.updates, up) // u.updates[" RoomKey = "+ u.nextDollar()] = newVal return u } //ints //string func (u *__PushChat_Updater) ChatKey(newVal string) *__PushChat_Updater { up := updateCol{"ChatKey = " + u.nextDollar(), newVal} u.updates = append(u.updates, up) // u.updates[" ChatKey = "+ u.nextDollar()] = newVal return u } //ints func (u *__PushChat_Updater) Seq(newVal int) *__PushChat_Updater { up := updateCol{" Seq = " + u.nextDollar(), newVal} u.updates = append(u.updates, up) // u.updates[" Seq = " + u.nextDollar()] = newVal return u } func (u *__PushChat_Updater) Seq_Increment(count int) *__PushChat_Updater { if count > 0 { up := updateCol{" Seq = Seq+ " + u.nextDollar(), count} u.updates = append(u.updates, up) //u.updates[" Seq = Seq+ " + u.nextDollar()] = count } if count < 0 { up := updateCol{" Seq = Seq- " + u.nextDollar(), count} u.updates = append(u.updates, up) // u.updates[" Seq = Seq- " + u.nextDollar() ] = -(count) //make it positive } return u } //string //ints func (u *__PushChat_Updater) UnseenCount(newVal int) *__PushChat_Updater { up := updateCol{" UnseenCount = " + u.nextDollar(), newVal} u.updates = append(u.updates, up) // u.updates[" UnseenCount = " + u.nextDollar()] = newVal return u } func (u *__PushChat_Updater) UnseenCount_Increment(count int) *__PushChat_Updater { if count > 0 { up := updateCol{" UnseenCount = UnseenCount+ " + u.nextDollar(), count} u.updates = append(u.updates, up) //u.updates[" UnseenCount = UnseenCount+ " + u.nextDollar()] = count } if count < 0 { up := updateCol{" UnseenCount = UnseenCount- " + u.nextDollar(), count} u.updates = append(u.updates, up) // u.updates[" UnseenCount = UnseenCount- " + u.nextDollar() ] = -(count) //make it positive } return u } //string //ints func (u *__PushChat_Updater) FromHighMessageId(newVal int) *__PushChat_Updater { up := updateCol{" FromHighMessageId = " + u.nextDollar(), newVal} u.updates = append(u.updates, up) // u.updates[" FromHighMessageId = " + u.nextDollar()] = newVal return u } func (u *__PushChat_Updater) FromHighMessageId_Increment(count int) *__PushChat_Updater { if count > 0 { up := updateCol{" FromHighMessageId = FromHighMessageId+ " + u.nextDollar(), count} u.updates = append(u.updates, up) //u.updates[" FromHighMessageId = FromHighMessageId+ " + u.nextDollar()] = count } if count < 0 { up := updateCol{" FromHighMessageId = FromHighMessageId- " + u.nextDollar(), count} u.updates = append(u.updates, up) // u.updates[" FromHighMessageId = FromHighMessageId- " + u.nextDollar() ] = -(count) //make it positive } return u } //string //ints func (u *__PushChat_Updater) ToLowMessageId(newVal int) *__PushChat_Updater { up := updateCol{" ToLowMessageId = " + u.nextDollar(), newVal} u.updates = append(u.updates, up) // u.updates[" ToLowMessageId = " + u.nextDollar()] = newVal return u } func (u *__PushChat_Updater) ToLowMessageId_Increment(count int) *__PushChat_Updater { if count > 0 { up := updateCol{" ToLowMessageId = ToLowMessageId+ " + u.nextDollar(), count} u.updates = append(u.updates, up) //u.updates[" ToLowMessageId = ToLowMessageId+ " + u.nextDollar()] = count } if count < 0 { up := updateCol{" ToLowMessageId = ToLowMessageId- " + u.nextDollar(), count} u.updates = append(u.updates, up) // u.updates[" ToLowMessageId = ToLowMessageId- " + u.nextDollar() ] = -(count) //make it positive } return u } //string //ints func (u *__PushChat_Updater) MessageId(newVal int) *__PushChat_Updater { up := updateCol{" MessageId = " + u.nextDollar(), newVal} u.updates = append(u.updates, up) // u.updates[" MessageId = " + u.nextDollar()] = newVal return u } func (u *__PushChat_Updater) MessageId_Increment(count int) *__PushChat_Updater { if count > 0 { up := updateCol{" MessageId = MessageId+ " + u.nextDollar(), count} u.updates = append(u.updates, up) //u.updates[" MessageId = MessageId+ " + u.nextDollar()] = count } if count < 0 { up := updateCol{" MessageId = MessageId- " + u.nextDollar(), count} u.updates = append(u.updates, up) // u.updates[" MessageId = MessageId- " + u.nextDollar() ] = -(count) //make it positive } return u } //string //ints func (u *__PushChat_Updater) MessageFileId(newVal int) *__PushChat_Updater { up := updateCol{" MessageFileId = " + u.nextDollar(), newVal} u.updates = append(u.updates, up) // u.updates[" MessageFileId = " + u.nextDollar()] = newVal return u } func (u *__PushChat_Updater) MessageFileId_Increment(count int) *__PushChat_Updater { if count > 0 { up := updateCol{" MessageFileId = MessageFileId+ " + u.nextDollar(), count} u.updates = append(u.updates, up) //u.updates[" MessageFileId = MessageFileId+ " + u.nextDollar()] = count } if count < 0 { up := updateCol{" MessageFileId = MessageFileId- " + u.nextDollar(), count} u.updates = append(u.updates, up) // u.updates[" MessageFileId = MessageFileId- " + u.nextDollar() ] = -(count) //make it positive } return u } //string //ints //string //ints //string func (u *__PushChat_Updater) MessageJson(newVal string) *__PushChat_Updater { up := updateCol{"MessageJson = " + u.nextDollar(), newVal} u.updates = append(u.updates, up) // u.updates[" MessageJson = "+ u.nextDollar()] = newVal return u } //ints func (u *__PushChat_Updater) CreatedTime(newVal int) *__PushChat_Updater { up := updateCol{" CreatedTime = " + u.nextDollar(), newVal} u.updates = append(u.updates, up) // u.updates[" CreatedTime = " + u.nextDollar()] = newVal return u } func (u *__PushChat_Updater) CreatedTime_Increment(count int) *__PushChat_Updater { if count > 0 { up := updateCol{" CreatedTime = CreatedTime+ " + u.nextDollar(), count} u.updates = append(u.updates, up) //u.updates[" CreatedTime = CreatedTime+ " + u.nextDollar()] = count } if count < 0 { up := updateCol{" CreatedTime = CreatedTime- " + u.nextDollar(), count} u.updates = append(u.updates, up) // u.updates[" CreatedTime = CreatedTime- " + u.nextDollar() ] = -(count) //make it positive } return u } //string ///////////////////////////////////////////////////////////////////// /////////////////////// Selector /////////////////////////////////// //Select_* can just be used with: .GetString() , .GetStringSlice(), .GetInt() ..GetIntSlice() func (u *__PushChat_Selector) OrderBy_PushId_Desc() *__PushChat_Selector { u.orderBy = " ORDER BY PushId DESC " return u } func (u *__PushChat_Selector) OrderBy_PushId_Asc() *__PushChat_Selector { u.orderBy = " ORDER BY PushId ASC " return u } func (u *__PushChat_Selector) Select_PushId() *__PushChat_Selector { u.selectCol = "PushId" return u } func (u *__PushChat_Selector) OrderBy_ToUserId_Desc() *__PushChat_Selector { u.orderBy = " ORDER BY ToUserId DESC " return u } func (u *__PushChat_Selector) OrderBy_ToUserId_Asc() *__PushChat_Selector { u.orderBy = " ORDER BY ToUserId ASC " return u } func (u *__PushChat_Selector) Select_ToUserId() *__PushChat_Selector { u.selectCol = "ToUserId" return u } func (u *__PushChat_Selector) OrderBy_PushTypeId_Desc() *__PushChat_Selector { u.orderBy = " ORDER BY PushTypeId DESC " return u } func (u *__PushChat_Selector) OrderBy_PushTypeId_Asc() *__PushChat_Selector { u.orderBy = " ORDER BY PushTypeId ASC " return u } func (u *__PushChat_Selector) Select_PushTypeId() *__PushChat_Selector { u.selectCol = "PushTypeId" return u } func (u *__PushChat_Selector) OrderBy_RoomKey_Desc() *__PushChat_Selector { u.orderBy = " ORDER BY RoomKey DESC " return u } func (u *__PushChat_Selector) OrderBy_RoomKey_Asc() *__PushChat_Selector { u.orderBy = " ORDER BY RoomKey ASC " return u } func (u *__PushChat_Selector) Select_RoomKey() *__PushChat_Selector { u.selectCol = "RoomKey" return u } func (u *__PushChat_Selector) OrderBy_ChatKey_Desc() *__PushChat_Selector { u.orderBy = " ORDER BY ChatKey DESC " return u } func (u *__PushChat_Selector) OrderBy_ChatKey_Asc() *__PushChat_Selector { u.orderBy = " ORDER BY ChatKey ASC " return u } func (u *__PushChat_Selector) Select_ChatKey() *__PushChat_Selector { u.selectCol = "ChatKey" return u } func (u *__PushChat_Selector) OrderBy_Seq_Desc() *__PushChat_Selector { u.orderBy = " ORDER BY Seq DESC " return u } func (u *__PushChat_Selector) OrderBy_Seq_Asc() *__PushChat_Selector { u.orderBy = " ORDER BY Seq ASC " return u } func (u *__PushChat_Selector) Select_Seq() *__PushChat_Selector { u.selectCol = "Seq" return u } func (u *__PushChat_Selector) OrderBy_UnseenCount_Desc() *__PushChat_Selector { u.orderBy = " ORDER BY UnseenCount DESC " return u } func (u *__PushChat_Selector) OrderBy_UnseenCount_Asc() *__PushChat_Selector { u.orderBy = " ORDER BY UnseenCount ASC " return u } func (u *__PushChat_Selector) Select_UnseenCount() *__PushChat_Selector { u.selectCol = "UnseenCount" return u } func (u *__PushChat_Selector) OrderBy_FromHighMessageId_Desc() *__PushChat_Selector { u.orderBy = " ORDER BY FromHighMessageId DESC " return u } func (u *__PushChat_Selector) OrderBy_FromHighMessageId_Asc() *__PushChat_Selector { u.orderBy = " ORDER BY FromHighMessageId ASC " return u } func (u *__PushChat_Selector) Select_FromHighMessageId() *__PushChat_Selector { u.selectCol = "FromHighMessageId" return u } func (u *__PushChat_Selector) OrderBy_ToLowMessageId_Desc() *__PushChat_Selector { u.orderBy = " ORDER BY ToLowMessageId DESC " return u } func (u *__PushChat_Selector) OrderBy_ToLowMessageId_Asc() *__PushChat_Selector { u.orderBy = " ORDER BY ToLowMessageId ASC " return u } func (u *__PushChat_Selector) Select_ToLowMessageId() *__PushChat_Selector { u.selectCol = "ToLowMessageId" return u } func (u *__PushChat_Selector) OrderBy_MessageId_Desc() *__PushChat_Selector { u.orderBy = " ORDER BY MessageId DESC " return u } func (u *__PushChat_Selector) OrderBy_MessageId_Asc() *__PushChat_Selector { u.orderBy = " ORDER BY MessageId ASC " return u } func (u *__PushChat_Selector) Select_MessageId() *__PushChat_Selector { u.selectCol = "MessageId" return u } func (u *__PushChat_Selector) OrderBy_MessageFileId_Desc() *__PushChat_Selector { u.orderBy = " ORDER BY MessageFileId DESC " return u } func (u *__PushChat_Selector) OrderBy_MessageFileId_Asc() *__PushChat_Selector { u.orderBy = " ORDER BY MessageFileId ASC " return u } func (u *__PushChat_Selector) Select_MessageFileId() *__PushChat_Selector { u.selectCol = "MessageFileId" return u } func (u *__PushChat_Selector) OrderBy_MessagePb_Desc() *__PushChat_Selector { u.orderBy = " ORDER BY MessagePb DESC " return u } func (u *__PushChat_Selector) OrderBy_MessagePb_Asc() *__PushChat_Selector { u.orderBy = " ORDER BY MessagePb ASC " return u } func (u *__PushChat_Selector) Select_MessagePb() *__PushChat_Selector { u.selectCol = "MessagePb" return u } func (u *__PushChat_Selector) OrderBy_MessageJson_Desc() *__PushChat_Selector { u.orderBy = " ORDER BY MessageJson DESC " return u } func (u *__PushChat_Selector) OrderBy_MessageJson_Asc() *__PushChat_Selector { u.orderBy = " ORDER BY MessageJson ASC " return u } func (u *__PushChat_Selector) Select_MessageJson() *__PushChat_Selector { u.selectCol = "MessageJson" return u } func (u *__PushChat_Selector) OrderBy_CreatedTime_Desc() *__PushChat_Selector { u.orderBy = " ORDER BY CreatedTime DESC " return u } func (u *__PushChat_Selector) OrderBy_CreatedTime_Asc() *__PushChat_Selector { u.orderBy = " ORDER BY CreatedTime ASC " return u } func (u *__PushChat_Selector) Select_CreatedTime() *__PushChat_Selector { u.selectCol = "CreatedTime" return u } func (u *__PushChat_Selector) Limit(num int) *__PushChat_Selector { u.limit = num return u } func (u *__PushChat_Selector) Offset(num int) *__PushChat_Selector { u.offset = num return u } func (u *__PushChat_Selector) Order_Rand() *__PushChat_Selector { u.orderBy = " ORDER BY RAND() " return u } ///////////////////////// Queryer Selector ////////////////////////////////// func (u *__PushChat_Selector) _stoSql() (string, []interface{}) { sqlWherrs, whereArgs := whereClusesToSql(u.wheres, u.whereSep) sqlstr := "SELECT " + u.selectCol + " FROM sun_push.push_chat" if len(strings.Trim(sqlWherrs, " ")) > 0 { //2 for safty sqlstr += " WHERE " + sqlWherrs } if u.orderBy != "" { sqlstr += u.orderBy } if u.limit != 0 { sqlstr += " LIMIT " + strconv.Itoa(u.limit) } if u.offset != 0 { sqlstr += " OFFSET " + strconv.Itoa(u.offset) } return sqlstr, whereArgs } func (u *__PushChat_Selector) GetRow(db *sqlx.DB) (*PushChat, error) { var err error sqlstr, whereArgs := u._stoSql() if LogTableSqlReq.PushChat { XOLog(sqlstr, whereArgs) } row := &PushChat{} //by Sqlx err = db.Get(row, sqlstr, whereArgs...) if err != nil { if LogTableSqlReq.PushChat { XOLogErr(err) } return nil, err } row._exists = true OnPushChat_LoadOne(row) return row, nil } func (u *__PushChat_Selector) GetRows(db *sqlx.DB) ([]*PushChat, error) { var err error sqlstr, whereArgs := u._stoSql() if LogTableSqlReq.PushChat { XOLog(sqlstr, whereArgs) } var rows []*PushChat //by Sqlx err = db.Unsafe().Select(&rows, sqlstr, whereArgs...) if err != nil { if LogTableSqlReq.PushChat { XOLogErr(err) } return nil, err } /*for i:=0;i< len(rows);i++ { rows[i]._exists = true }*/ for i := 0; i < len(rows); i++ { rows[i]._exists = true } OnPushChat_LoadMany(rows) return rows, nil } //dep use GetRows() func (u *__PushChat_Selector) GetRows2(db *sqlx.DB) ([]PushChat, error) { var err error sqlstr, whereArgs := u._stoSql() if LogTableSqlReq.PushChat { XOLog(sqlstr, whereArgs) } var rows []*PushChat //by Sqlx err = db.Unsafe().Select(&rows, sqlstr, whereArgs...) if err != nil { if LogTableSqlReq.PushChat { XOLogErr(err) } return nil, err } /*for i:=0;i< len(rows);i++ { rows[i]._exists = true }*/ for i := 0; i < len(rows); i++ { rows[i]._exists = true } OnPushChat_LoadMany(rows) rows2 := make([]PushChat, len(rows)) for i := 0; i < len(rows); i++ { cp := *rows[i] rows2[i] = cp } return rows2, nil } func (u *__PushChat_Selector) GetString(db *sqlx.DB) (string, error) { var err error sqlstr, whereArgs := u._stoSql() if LogTableSqlReq.PushChat { XOLog(sqlstr, whereArgs) } var res string //by Sqlx err = db.Get(&res, sqlstr, whereArgs...) if err != nil { if LogTableSqlReq.PushChat { XOLogErr(err) } return "", err } return res, nil } func (u *__PushChat_Selector) GetStringSlice(db *sqlx.DB) ([]string, error) { var err error sqlstr, whereArgs := u._stoSql() if LogTableSqlReq.PushChat { XOLog(sqlstr, whereArgs) } var rows []string //by Sqlx err = db.Select(&rows, sqlstr, whereArgs...) if err != nil { if LogTableSqlReq.PushChat { XOLogErr(err) } return nil, err } return rows, nil } func (u *__PushChat_Selector) GetIntSlice(db *sqlx.DB) ([]int, error) { var err error sqlstr, whereArgs := u._stoSql() if LogTableSqlReq.PushChat { XOLog(sqlstr, whereArgs) } var rows []int //by Sqlx err = db.Select(&rows, sqlstr, whereArgs...) if err != nil { if LogTableSqlReq.PushChat { XOLogErr(err) } return nil, err } return rows, nil } func (u *__PushChat_Selector) GetInt(db *sqlx.DB) (int, error) { var err error sqlstr, whereArgs := u._stoSql() if LogTableSqlReq.PushChat { XOLog(sqlstr, whereArgs) } var res int //by Sqlx err = db.Get(&res, sqlstr, whereArgs...) if err != nil { if LogTableSqlReq.PushChat { XOLogErr(err) } return 0, err } return res, nil } ///////////////////////// Queryer Update Delete ////////////////////////////////// func (u *__PushChat_Updater) Update(db XODB) (int, error) { var err error var updateArgs []interface{} var sqlUpdateArr []string /*for up, newVal := range u.updates { sqlUpdateArr = append(sqlUpdateArr, up) updateArgs = append(updateArgs, newVal) }*/ for _, up := range u.updates { sqlUpdateArr = append(sqlUpdateArr, up.col) updateArgs = append(updateArgs, up.val) } sqlUpdate := strings.Join(sqlUpdateArr, ",") sqlWherrs, whereArgs := whereClusesToSql(u.wheres, u.whereSep) var allArgs []interface{} allArgs = append(allArgs, updateArgs...) allArgs = append(allArgs, whereArgs...) sqlstr := `UPDATE sun_push.push_chat SET ` + sqlUpdate if len(strings.Trim(sqlWherrs, " ")) > 0 { //2 for safty sqlstr += " WHERE " + sqlWherrs } if LogTableSqlReq.PushChat { XOLog(sqlstr, allArgs) } res, err := db.Exec(sqlstr, allArgs...) if err != nil { if LogTableSqlReq.PushChat { XOLogErr(err) } return 0, err } num, err := res.RowsAffected() if err != nil { if LogTableSqlReq.PushChat { XOLogErr(err) } return 0, err } return int(num), nil } func (d *__PushChat_Deleter) Delete(db XODB) (int, error) { var err error var wheresArr []string for _, w := range d.wheres { wheresArr = append(wheresArr, w.condition) } wheresStr := strings.Join(wheresArr, d.whereSep) var args []interface{} for _, w := range d.wheres { args = append(args, w.args...) } sqlstr := "DELETE FROM sun_push.push_chat WHERE " + wheresStr // run query if LogTableSqlReq.PushChat { XOLog(sqlstr, args) } res, err := db.Exec(sqlstr, args...) if err != nil { if LogTableSqlReq.PushChat { XOLogErr(err) } return 0, err } // retrieve id num, err := res.RowsAffected() if err != nil { if LogTableSqlReq.PushChat { XOLogErr(err) } return 0, err } return int(num), nil } ///////////////////////// Mass insert - replace for PushChat //////////////// func MassInsert_PushChat(rows []PushChat, db XODB) error { if len(rows) == 0 { return errors.New("rows slice should not be empty - inserted nothing") } var err error ln := len(rows) // insVals_:= strings.Repeat(s, ln) // insVals := insVals_[0:len(insVals_)-1] insVals := helper.SqlManyDollars(14, ln, true) // sql query sqlstr := "INSERT INTO sun_push.push_chat (" + "PushId, ToUserId, PushTypeId, RoomKey, ChatKey, Seq, UnseenCount, FromHighMessageId, ToLowMessageId, MessageId, MessageFileId, MessagePb, MessageJson, CreatedTime" + ") VALUES " + insVals // run query vals := make([]interface{}, 0, ln*5) //5 fields for _, row := range rows { // vals = append(vals,row.UserId) vals = append(vals, row.PushId) vals = append(vals, row.ToUserId) vals = append(vals, row.PushTypeId) vals = append(vals, row.RoomKey) vals = append(vals, row.ChatKey) vals = append(vals, row.Seq) vals = append(vals, row.UnseenCount) vals = append(vals, row.FromHighMessageId) vals = append(vals, row.ToLowMessageId) vals = append(vals, row.MessageId) vals = append(vals, row.MessageFileId) vals = append(vals, row.MessagePb) vals = append(vals, row.MessageJson) vals = append(vals, row.CreatedTime) } if LogTableSqlReq.PushChat { XOLog(sqlstr, " MassInsert len = ", ln, vals) } _, err = db.Exec(sqlstr, vals...) if err != nil { if LogTableSqlReq.PushChat { XOLogErr(err) } return err } return nil } func MassReplace_PushChat(rows []PushChat, db XODB) error { if len(rows) == 0 { return errors.New("rows slice should not be empty - inserted nothing") } var err error ln := len(rows) // insVals_:= strings.Repeat(s, ln) // insVals := insVals_[0:len(insVals_)-1] insVals := helper.SqlManyDollars(14, ln, true) // sql query sqlstr := "REPLACE INTO sun_push.push_chat (" + "PushId, ToUserId, PushTypeId, RoomKey, ChatKey, Seq, UnseenCount, FromHighMessageId, ToLowMessageId, MessageId, MessageFileId, MessagePb, MessageJson, CreatedTime" + ") VALUES " + insVals // run query vals := make([]interface{}, 0, ln*5) //5 fields for _, row := range rows { // vals = append(vals,row.UserId) vals = append(vals, row.PushId) vals = append(vals, row.ToUserId) vals = append(vals, row.PushTypeId) vals = append(vals, row.RoomKey) vals = append(vals, row.ChatKey) vals = append(vals, row.Seq) vals = append(vals, row.UnseenCount) vals = append(vals, row.FromHighMessageId) vals = append(vals, row.ToLowMessageId) vals = append(vals, row.MessageId) vals = append(vals, row.MessageFileId) vals = append(vals, row.MessagePb) vals = append(vals, row.MessageJson) vals = append(vals, row.CreatedTime) } if LogTableSqlReq.PushChat { XOLog(sqlstr, " MassReplace len = ", ln, vals) } _, err = db.Exec(sqlstr, vals...) if err != nil { if LogTableSqlReq.PushChat { XOLogErr(err) } return err } return nil } //////////////////// Play /////////////////////////////// // // // // // // // // // // // // // //
package cryhel_test import ( "testing" . "gopkg.in/check.v1" "github.com/qeek-dev/cryhel" ) func Test(t *testing.T) { TestingT(t) } type MySuite struct { c *cryhel.Crypto } func (s *MySuite) SetUpTest(c *C) { s.c, _ = cryhel.NewCrypto("AES256Key-32Characters1234567890") } var _ = Suite(&MySuite{}) func (s *MySuite) Test_Encrypt(chk *C) { sourceString := "1/fFAGRNJru1FTz70BzhT3Zg" if encryptString, err := s.c.Encrypt.Msg(sourceString).Do(); err != nil { chk.Error(err.Error()) } else { chk.Logf("encrypt base64 encode string: %q", encryptString) } } func (s *MySuite) Test_Decrypt(chk *C) { encryptString := "cLcbvk4rpVRTj1kvu5pOi7ktZiCezDWcm8VR1f+XpP12eie0/cI6lagGcWXRMt8a" if creds, err := s.c.Decrypt.Msg(encryptString).Do(); err != nil { chk.Error(err.Error()) } else { if creds != "1/fFAGRNJru1FTz70BzhT3Zg" { chk.Errorf("got access_token %q expected %q", creds, "1/fFAGRNJru1FTz70BzhT3Zg") } else { chk.Logf("decrypt string: %q", creds) } } } func (s *MySuite) Test_Encrypt_QueryEscapeMsg(chk *C) { sourceString := "1/fFAGRNJru1FTz70BzhT3Zg" if encryptString, err := s.c.Encrypt.QueryEscapeMsg(sourceString).Do(); err != nil { chk.Error(err.Error()) } else { chk.Logf("encrypt base64 encode string: %q", encryptString) } } func (s *MySuite) Test_Decrypt_QueryEscapeMsg(chk *C) { encryptBase64String := "%2BDldN9TgkkWuH5V68jOVB9uNVXMpGam5Yixh0fRCr3qHVZG7Jn1JNZwhGVaPw%2B3z" if decryptString, err := s.c.Decrypt.QueryEscapeMsg(encryptBase64String).Do(); err != nil { chk.Error(err.Error()) } else { if decryptString != "1/fFAGRNJru1FTz70BzhT3Zg" { chk.Errorf("got access_token %q expected %q", decryptString, "1/fFAGRNJru1FTz70BzhT3Zg") } else { chk.Logf("decrypt base64 encode string: %q", decryptString) } } } func (s *MySuite) Test_Encrypt_Decrypt_Msg(chk *C) { sourceString := `{"user":"admin","type":"2","streamKey":"live?token=b31d0e541427f52debea0f6d0ca368454f5323b384571b466f5894a3e100dd5d94cfb4a49ded"}` if encryptBase64String, err := s.c.Encrypt.Msg(sourceString).Do(); err != nil { chk.Error(err.Error()) } else { if decryptString, err := s.c.Decrypt.Msg(encryptBase64String).Do(); err != nil { chk.Errorf("got descrypt %q expected %q", decryptString, sourceString) } else { chk.Logf("decrypt base64 encode string: %q", decryptString) } } } func (s *MySuite) Test_Encrypt_Decrypt_QueryEscapeMsg(chk *C) { sourceString := `{"user":"admin","type":"2","streamKey":"live?token=b31d0e541427f52debea0f6d0ca368454f5323b384571b466f5894a3e100dd5d94cfb4a49ded"}` if encryptBase64String, err := s.c.Encrypt.QueryEscapeMsg(sourceString).Do(); err != nil { chk.Error(err.Error()) } else { if decryptString, err := s.c.Decrypt.QueryEscapeMsg(encryptBase64String).Do(); err != nil { chk.Errorf("got descrypt %q expected %q", decryptString, sourceString) } else { chk.Logf("decrypt base64 encode string: %q", decryptString) } } } func (s *MySuite) Test_Encrypt_Decrypt_Out_Msg(chk *C) { type Info struct { User string `json:"user"` Type string `json:"type"` StreamKey string `json:"streamKey"` } sourceString := `{"user":"admin","type":"2","streamKey":"live?token=b31d0e541427f52debea0f6d0ca368454f5323b384571b466f5894a3e100dd5d94cfb4a49ded"}` if encryptBase64String, err := s.c.Encrypt.Msg(sourceString).Do(); err != nil { chk.Error(err.Error()) } else { var b Info if err := s.c.Decrypt.Msg(encryptBase64String).Out(&b); err != nil { chk.Errorf("got descrypt %v expected %q", b, sourceString) } else { chk.Logf("decrypt base64 encode struct: %v", b) } } } func (s *MySuite) Test_Encrypt_Decrypt_Out_QueryEscapeMsg(chk *C) { type Info struct { User string `json:"user"` Type string `json:"type"` StreamKey string `json:"streamKey"` } sourceString := `{"user":"admin","type":"2","streamKey":"live?token=b31d0e541427f52debea0f6d0ca368454f5323b384571b466f5894a3e100dd5d94cfb4a49ded"}` if encryptBase64String, err := s.c.Encrypt.QueryEscapeMsg(sourceString).Do(); err != nil { chk.Error(err.Error()) } else { var b Info if err := s.c.Decrypt.QueryEscapeMsg(encryptBase64String).Out(&b); err != nil { chk.Errorf("got descrypt %v expected %q", b, sourceString) } else { chk.Logf("decrypt base64 encode struct: %v", b) } } }
package main import ( "flag" "log" "net/http" "os" //if this is not being picked up make sure all referenced package files have no errors //if they have errors GOLand will not pull in mod reference correctly snippets "github.com/chriswilliams1977/protos/internal/app/snippets" ) func main(){ //NOTE EACH REQUEST GETS ITS OWN GO ROUTINE = RACE CONDITIONS //Mux is a request handler - It matches the URL of each incoming request against a list of registered patterns //and calls the handler for the pattern that most closely matches the URL. // Define a new command-line flag with the name 'addr', a default value of ":4000" // and some short help text explaining what the flag controls. The value of the // flag will be stored in the addr variable at runtime. //can also use flag.Int(), flag.Bool() and flag.Float64() addr := flag.String("addr", ":4000", "HTTP network address") // Importantly, we use the flag.Parse() function to parse the command-line flag. // This reads in the command-line flag value and assigns it to the addr // variable. You need to call this *before* you use the addr variable // otherwise it will always contain the default value of ":4000". If any errors are // encountered during parsing the application will be terminated. flag.Parse() // Use log.New() to create a logger for writing information messages. This takes // three parameters: the destination to write the logs to (os.Stdout), a string // prefix for message (INFO followed by a tab), and flags to indicate what // additional information to include (local date and time). Note that the flags // are joined using the bitwise OR operator |. infoLog := log.New(os.Stdout, "INFO\t", log.Ldate|log.Ltime) // Create a logger for writing error messages in the same way, but use stderr as // the destination and use the log.Lshortfile flag to include the relevant // file name and line number. errorLog := log.New(os.Stderr, "ERROR\t", log.Ldate|log.Ltime|log.Lshortfile) //Get static files path and set to defaul if no value is passed uiPath := snippets.GetEnv("UI_PATH","./web/") // Initialize a new instance of application containing the dependencies. app := &snippets.Application{ ErrorLog: errorLog, InfoLog: infoLog, UiPath: uiPath, } // Initialize a new http.Server struct. We set the Addr and Handler fields so // that the server uses the same network address and routes as before, and set // the ErrorLog field so that the server now uses the custom errorLog logger in // the event of any problems. srv := &http.Server{ Addr: *addr, ErrorLog: errorLog, Handler: app.Routes(), // Call the new app.routes() method } // Use the http.ListenAndServe() function to start a new web server. We pass in // two parameters: the TCP network address to listen on (in this case ":4000") // and the servemux we just created. If http.ListenAndServe() returns an error // we use the log.Fatal() function to log the error message and exit. //address should be in format :port //only specific host if machine has multi network interfaces //if you use :name (:http) go will look up port number from /ect/services infoLog.Printf("Starting server on %s", *addr) //The http.ListenAndServe() function takes a http.Handler object as the second //func ListenAndServe(addr string, handler Handler) error //parameter but mux satisfies the http.Handler interface thus can pass mux //servemux is just being a special kind of handler, //which instead of providing a response itself passes the request on to a second handler // The value returned from the flag.String() function is a pointer to the flag // value, not the value itself. So we need to dereference the pointer (i.e. // prefix it with the * symbol) before using it. //err := http.ListenAndServe(*addr, mux) //this uses the srv struct so we can append custom error logging //By default, if Go’s HTTP server encounters an error it will log it using the standard logger err := srv.ListenAndServe() //log.fatal calls os.Exit(1) after writing message thus causing app to exit immediately //log.Fatal(err) errorLog.Fatal(err) }
package Core type RecordRow struct { values map[int]interface{} } func NewDataRow() *RecordRow { v := &RecordRow{values: make(map[int]interface{})} return v } func (row *RecordRow) SetValue(index int, value interface{}) { row.values[index] = value } func (row *RecordRow) GetInt(index int) int { i := row.values[index] return i.(int) } func (row *RecordRow) GetFloat(index int) float32 { i := row.values[index] return i.(float32) } func (row *RecordRow) GetString(index int) string { i := row.values[index] return i.(string) } func (row *RecordRow) GetObj(index int) GUID { i := row.values[index] return i.(GUID) } func (row *RecordRow) GetValue(index int) interface{} { i := row.values[index] return i }
package main import ( "bufio" "encoding/json" "flag" "fmt" "log" "net" "os" "strings" "time" "golang.org/x/crypto/ssh" ) type sshConfig struct { User, Password, Host string } type configuration struct { Hosts []sshConfig } type cmdTask struct { cmd string host net.Addr } var ( cfg configuration clients []*ssh.Client channel chan cmdTask ) func parseConfig() { file, err := os.Open("./cfg.json") if err != nil { log.Fatal(err) } defer file.Close() decoder := json.NewDecoder(file) cfg = configuration{} err = decoder.Decode(&cfg) if err != nil { log.Fatal(err) } } func main() { fmt.Println("Welcome to multi ssh client") flag.Parse() channel = make(chan cmdTask) timeout := time.After(25 * time.Second) parseConfig() fmt.Println(cfg) clients = make([]*ssh.Client, len(cfg.Hosts)) for i, h := range cfg.Hosts { client, e := ssh.Dial("tcp", h.Host, &ssh.ClientConfig{ User: h.User, Auth: []ssh.AuthMethod{ ssh.Password(h.Password), }, HostKeyCallback: ssh.InsecureIgnoreHostKey(), }) if e != nil { log.Println(e.Error()) } clients[i] = client } reader := bufio.NewReader(os.Stdin) for { cmd, _ := reader.ReadString('\n') if strings.TrimSpace(cmd) == "" { continue } for _, c := range clients { go executeCommand(strings.TrimSpace(cmd), c) } for i := len(clients); i != 0; { select { case res := <-channel: fmt.Printf("hostname: %s\n", res.host) fmt.Println(res.cmd) i-- case <-timeout: fmt.Println("Execution timeout...") break } } if cmd == "exit" { return } } } func executeCommand(cmd string, c *ssh.Client) { start := time.Now() session, e := c.NewSession() if e != nil { log.Fatal(e) } o, e := session.Output(cmd) channel <- cmdTask{host: c.Conn.RemoteAddr(), cmd: string(o)} fmt.Printf("Estimated time %f\n", time.Now().Sub(start).Seconds()) defer session.Close() }
package mts import ( "encoding/json" "github.com/aliyun/alibaba-cloud-sdk-go/sdk" "github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/credentials" "github.com/aliyun/alibaba-cloud-sdk-go/services/mts" "log" "net/url" "os" "sync" ) var ( regionId = "<regionId>" bucket = "<bucket>" location = "<location>" accessKeyId = "<accessKeyId>" accessKeySecret = "<accessKeySecret>" instance *mts.Client once sync.Once ) type PipelineId string type TemplateId string func NewClient() (*mts.Client, error) { once.Do(func() { // get from env regionId = os.Getenv("ALI_SDK_MTS_REGION_ID") accessKeyId = os.Getenv("ALI_SDK_MTS_APP_ID") accessKeySecret = os.Getenv("ALI_SDK_MTS_APP_SECRET") bucket = os.Getenv("ALI_SDK_MTS_BUCKET") location = os.Getenv("ALI_SDK_MTS_LOCATION") // 创建授权对象 credential := &credentials.AccessKeyCredential{ accessKeyId, accessKeySecret, } // 自定义config config := sdk.NewConfig() config.AutoRetry = true // 失败是否自动重试 config.MaxRetryTime = 3 // 最大重试次数 config.Timeout = 3000000000 // 连接超时,单位:纳秒;默认为3秒 var err error instance, err = mts.NewClientWithOptions(regionId, config, credential) if err != nil { log.Fatal(err) } }) return instance, nil } // 转码接口 - 提交转码作业 func SubmitJobs(client *mts.Client, inObjId string, outObjId string, templateId TemplateId, pipelineId PipelineId) (*mts.SubmitJobsResponse, error) { inputJson, _ := json.Marshal(map[string]string{ "Bucket": bucket, "Location": location, "Object": url.QueryEscape(inObjId), }) outputJson, _ := json.Marshal([]map[string]string{ { "OutputObject": url.QueryEscape(outObjId), "TemplateId": string(templateId), }, }) request := mts.CreateSubmitJobsRequest() request.PipelineId = string(pipelineId) request.Input = string(inputJson) request.OutputBucket = bucket request.OutputLocation = location request.Outputs = string(outputJson) response, err := client.SubmitJobs(request) if err != nil { return nil, err } return response, err } // 转码接口 - 取消转码作业 func CancelJob() {} // 转码接口 - 查询转码作业 func QueryJobList() { } // 转码接口 - 列出转码作业 func ListJob() { } func AddTemplate() { } func UpdateTemplate() { } func QueryTemplateList() { } func SearchTemplate() { } func DeleteTemplate() { }
// robustirc-merge-coverage is a tool to merge two coverage reports, summing // their counters. // // See coverage.sh for how to use it. package main import ( "bufio" "flag" "fmt" "log" "os" "strings" ) var ( inputName = flag.String("input", "", "comma-separated list of paths to input files to read") outputName = flag.String("output", "", "path to write output to") ) type coverBlock struct { Stmts uint16 Count uint32 } func main() { flag.Parse() total := make(map[string]coverBlock) for _, name := range strings.Split(*inputName, ",") { in, err := os.Open(name) if err != nil { log.Fatal(err) } defer in.Close() scanner := bufio.NewScanner(in) // Skip the first line, it contains “mode: count” scanner.Scan() for scanner.Scan() { var b coverBlock var name string _, err := fmt.Sscanf(scanner.Text(), "%s %d %d", &name, &b.Stmts, &b.Count) if err != nil { log.Fatal(err) } if existing, ok := total[name]; !ok { total[name] = b } else { existing.Count += b.Count total[name] = existing } } if err := scanner.Err(); err != nil { log.Fatal(err) } } out, err := os.Create(*outputName) if err != nil { log.Fatal(err) } defer out.Close() fmt.Fprintf(out, "mode: count\n") for name, block := range total { _, err := fmt.Fprintf(out, "%s %d %d\n", name, block.Stmts, block.Count) if err != nil { log.Fatal(err) } } }
package intersect import ( "sort" "github.com/dgraph-io/dgraph/task" ) func IntersectWith(u, v *task.List) { n := len(u.Uids) m := len(v.Uids) if n > m { n, m = m, n } if n == 0 { n += 1 } // Select appropriate function based on heuristics. ratio := float64(m) / float64(n) if ratio < 100 { IntersectWithLin(u, v) } else if ratio < 500 { IntersectWithJump(u, v) } else { IntersectWithBin(u, v) } } // IntersectWith intersects u with v. The update is made to u. // u, v should be sorted. func IntersectWithLin(u, v *task.List) { out := u.Uids[:0] n := len(u.Uids) m := len(v.Uids) for i, k := 0, 0; i < n && k < m; { uid := u.Uids[i] vid := v.Uids[k] if uid > vid { for k = k + 1; k < m && v.Uids[k] < uid; k++ { } } else if uid == vid { out = append(out, uid) k++ i++ } else { for i = i + 1; i < n && u.Uids[i] < vid; i++ { } } } //u.Uids = out } func IntersectWithJump(u, v *task.List) { out := u.Uids[:0] n := len(u.Uids) m := len(v.Uids) jump := 30 for i, k := 0, 0; i < n && k < m; { uid := u.Uids[i] vid := v.Uids[k] if uid == vid { out = append(out, uid) k++ i++ } else if k+jump < m && uid > v.Uids[k+jump] { k = k + jump } else if i+jump < n && vid > u.Uids[i+jump] { i = i + jump } else if uid > vid { for k = k + 1; k < m && v.Uids[k] < uid; k++ { } } else { for i = i + 1; i < n && u.Uids[i] < vid; i++ { } } } //u.Uids = out } func IntersectWithBin(u, v *task.List) { out := u.Uids[:0] m := len(u.Uids) n := len(v.Uids) // We want to do binary search on bigger list. smallList, bigList := u.Uids, v.Uids if m > n { smallList, bigList = bigList, smallList } // This is reduce the search space after every match. searchList := bigList for _, uid := range smallList { idx := sort.Search(len(searchList), func(i int) bool { return searchList[i] >= uid }) if idx < len(searchList) && searchList[idx] == uid { out = append(out, uid) // The next UID would never be at less than this idx // as the list is sorted. searchList = searchList[idx:] } } //u.Uids = out }
package ping import ( scrap "github.com/zairza-cetb/bench-routes/src/lib/filters/scraps" "github.com/zairza-cetb/bench-routes/src/lib/utils" "github.com/zairza-cetb/bench-routes/tsdb" "log" "sync" "time" ) // const ( // // PathPing stores the defualt address of storage directory of ping data // PathPing = "storage/ping" // ) // HandlePing is the main handler for ping operations func HandlePing(globalChain []*tsdb.ChainPing, urlRaw string, packets int, tsdbNameHash string, wg *sync.WaitGroup, isTest bool) { tsdbNameHash = utils.PathPing + "/" + "chunk_ping_" + tsdbNameHash + ".json" // launch a goroutine to handle ping operations resp, err := utils.CLIPing(urlRaw, packets) if err != nil { log.Println(*resp) wg.Done() return } result := *scrap.CLIPingScrap(resp) newBlock := createNewBlock(result) urlExists := false for index := range globalChain { if globalChain[index].Path == tsdbNameHash { urlExists = true globalChain[index] = globalChain[index].AppendPing(newBlock) globalChain[index].SavePing() break } } if !urlExists && !isTest { panic("faulty hashing! impossible to look for a hash match.") } wg.Done() } func createNewBlock(val utils.TypePingScrap) tsdb.BlockPing { return tsdb.BlockPing{ Timestamp: time.Now(), Datapoint: tsdb.PingType{ Min: val.Min, Mean: val.Avg, Max: val.Max, MDev: val.Mdev, }, } }
package main import ( "calc" "fmt" //만약 패키지 디렉터리가 GOPATH/src/hello/calc라면 다음과 같이 사용합니다. //즉 기준이 되는 디렉터리는 GOPATH/src입니다.용 //"hello/calc" ) func main() { fmt.Println("hello, word!") fmt.Println(calc.Sum(1, 2)) // calc 패키지의 Sum 함수 사용 }
package kubectl import ( "strings" "github.com/pkg/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime/schema" "k8s.io/client-go/kubernetes/scheme" restclient "k8s.io/client-go/rest" ) // GenericRequestOptions are the options for the request type GenericRequestOptions struct { Resource string APIVersion string Name string LabelSelector string Namespace string } // GenericRequest makes a new request to the given server with the specified options func (client *client) GenericRequest(options *GenericRequestOptions) (string, error) { // Create new client var restClient restclient.Interface if options.APIVersion != "" { splitted := strings.Split(options.APIVersion, "/") if len(splitted) != 2 { return "", errors.Errorf("Error parsing %s: expected version to be group/version", options.APIVersion) } config, err := client.ClientConfig.ClientConfig() if err != nil { return "", err } version := schema.GroupVersion{Group: splitted[0], Version: splitted[1]} config.GroupVersion = &version config.APIPath = "/apis" config.NegotiatedSerializer = scheme.Codecs.WithoutConversion() if config.UserAgent == "" { config.UserAgent = restclient.DefaultKubernetesUserAgent() } restClient, err = restclient.RESTClientFor(config) if err != nil { return "", err } } else { restClient = client.KubeClient().CoreV1().RESTClient() } req := restClient.Get() if options.Namespace != "" { req = req.Namespace(options.Namespace) } req = req.Resource(options.Resource) if options.Name != "" { req = req.Name(options.Name) } else { reqOptions := &metav1.ListOptions{} if options.LabelSelector != "" { reqOptions.LabelSelector = options.LabelSelector } req = req.VersionedParams(reqOptions, metav1.ParameterCodec) } // Make request out, err := req.DoRaw() if err != nil { return "", errors.Wrap(err, "request") } return string(out), nil }
package main import ( "fmt" "github.com/dgrijalva/jwt-go" "log" "time" ) //密钥 key const ( SIGNED_KEY = "7d8b0b1a8e2746ec9b32eddd1aa9acc2" ) // 载荷,可以加一些自己需要的信息 type CustomClaims struct { OpenId string `json:"open_id"` Name string `json:"name"` Email string `json:"email"` Administrator bool `json:"administrator"` jwt.StandardClaims } //加密 func jwtTokenEncode() string{ /* //另外一种声明claims方式 claim := jwt.MapClaims{ "open_id":"a2a7fd8138ab480ea96a6ccfcb783a00",//固定 "name": "", "email": "", "administrator": false, "exp": time.Now().UnixNano() / 1e6,//13位时间戳 "iss": "c4f772063dcfa98e9c50",//固定 "aud": "edx.unipus.cn",//固定 } */ clims := CustomClaims{ OpenId:"a2a7fd8138ab480ea96a6ccfcb783a00",//固定 Name: "", Email: "", Administrator: false, StandardClaims:jwt.StandardClaims{ ExpiresAt: time.Now().UnixNano() / 1e6,//13位时间戳 Issuer: "c4f772063dcfa98e9c50",//固定 Audience: "edx.unipus.cn",//固定 }, } token := jwt.NewWithClaims(jwt.SigningMethodHS256, clims) ss, err := token.SignedString([]byte(SIGNED_KEY)) if err != nil { log.Println(err) } return ss } func main() { fmt.Println(jwtTokenEncode()) }
// Copyright 2023 Google LLC. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package server import ( "context" "github.com/GoogleCloudPlatform/declarative-resource-client-library/dcl" computepb "github.com/GoogleCloudPlatform/declarative-resource-client-library/python/proto/compute/compute_go_proto" emptypb "github.com/GoogleCloudPlatform/declarative-resource-client-library/python/proto/empty_go_proto" "github.com/GoogleCloudPlatform/declarative-resource-client-library/services/google/compute" ) // ServiceAttachmentServer implements the gRPC interface for ServiceAttachment. type ServiceAttachmentServer struct{} // ProtoToServiceAttachmentConnectionPreferenceEnum converts a ServiceAttachmentConnectionPreferenceEnum enum from its proto representation. func ProtoToComputeServiceAttachmentConnectionPreferenceEnum(e computepb.ComputeServiceAttachmentConnectionPreferenceEnum) *compute.ServiceAttachmentConnectionPreferenceEnum { if e == 0 { return nil } if n, ok := computepb.ComputeServiceAttachmentConnectionPreferenceEnum_name[int32(e)]; ok { e := compute.ServiceAttachmentConnectionPreferenceEnum(n[len("ComputeServiceAttachmentConnectionPreferenceEnum"):]) return &e } return nil } // ProtoToServiceAttachmentConnectedEndpointsStatusEnum converts a ServiceAttachmentConnectedEndpointsStatusEnum enum from its proto representation. func ProtoToComputeServiceAttachmentConnectedEndpointsStatusEnum(e computepb.ComputeServiceAttachmentConnectedEndpointsStatusEnum) *compute.ServiceAttachmentConnectedEndpointsStatusEnum { if e == 0 { return nil } if n, ok := computepb.ComputeServiceAttachmentConnectedEndpointsStatusEnum_name[int32(e)]; ok { e := compute.ServiceAttachmentConnectedEndpointsStatusEnum(n[len("ComputeServiceAttachmentConnectedEndpointsStatusEnum"):]) return &e } return nil } // ProtoToServiceAttachmentConnectedEndpoints converts a ServiceAttachmentConnectedEndpoints object from its proto representation. func ProtoToComputeServiceAttachmentConnectedEndpoints(p *computepb.ComputeServiceAttachmentConnectedEndpoints) *compute.ServiceAttachmentConnectedEndpoints { if p == nil { return nil } obj := &compute.ServiceAttachmentConnectedEndpoints{ Status: ProtoToComputeServiceAttachmentConnectedEndpointsStatusEnum(p.GetStatus()), PscConnectionId: dcl.Int64OrNil(p.GetPscConnectionId()), Endpoint: dcl.StringOrNil(p.GetEndpoint()), } return obj } // ProtoToServiceAttachmentConsumerAcceptLists converts a ServiceAttachmentConsumerAcceptLists object from its proto representation. func ProtoToComputeServiceAttachmentConsumerAcceptLists(p *computepb.ComputeServiceAttachmentConsumerAcceptLists) *compute.ServiceAttachmentConsumerAcceptLists { if p == nil { return nil } obj := &compute.ServiceAttachmentConsumerAcceptLists{ ProjectIdOrNum: dcl.StringOrNil(p.GetProjectIdOrNum()), ConnectionLimit: dcl.Int64OrNil(p.GetConnectionLimit()), } return obj } // ProtoToServiceAttachmentPscServiceAttachmentId converts a ServiceAttachmentPscServiceAttachmentId object from its proto representation. func ProtoToComputeServiceAttachmentPscServiceAttachmentId(p *computepb.ComputeServiceAttachmentPscServiceAttachmentId) *compute.ServiceAttachmentPscServiceAttachmentId { if p == nil { return nil } obj := &compute.ServiceAttachmentPscServiceAttachmentId{ High: dcl.Int64OrNil(p.GetHigh()), Low: dcl.Int64OrNil(p.GetLow()), } return obj } // ProtoToServiceAttachment converts a ServiceAttachment resource from its proto representation. func ProtoToServiceAttachment(p *computepb.ComputeServiceAttachment) *compute.ServiceAttachment { obj := &compute.ServiceAttachment{ Id: dcl.Int64OrNil(p.GetId()), Name: dcl.StringOrNil(p.GetName()), Description: dcl.StringOrNil(p.GetDescription()), SelfLink: dcl.StringOrNil(p.GetSelfLink()), Region: dcl.StringOrNil(p.GetRegion()), TargetService: dcl.StringOrNil(p.GetTargetService()), ConnectionPreference: ProtoToComputeServiceAttachmentConnectionPreferenceEnum(p.GetConnectionPreference()), EnableProxyProtocol: dcl.Bool(p.GetEnableProxyProtocol()), PscServiceAttachmentId: ProtoToComputeServiceAttachmentPscServiceAttachmentId(p.GetPscServiceAttachmentId()), Fingerprint: dcl.StringOrNil(p.GetFingerprint()), Project: dcl.StringOrNil(p.GetProject()), Location: dcl.StringOrNil(p.GetLocation()), } for _, r := range p.GetConnectedEndpoints() { obj.ConnectedEndpoints = append(obj.ConnectedEndpoints, *ProtoToComputeServiceAttachmentConnectedEndpoints(r)) } for _, r := range p.GetNatSubnets() { obj.NatSubnets = append(obj.NatSubnets, r) } for _, r := range p.GetConsumerRejectLists() { obj.ConsumerRejectLists = append(obj.ConsumerRejectLists, r) } for _, r := range p.GetConsumerAcceptLists() { obj.ConsumerAcceptLists = append(obj.ConsumerAcceptLists, *ProtoToComputeServiceAttachmentConsumerAcceptLists(r)) } return obj } // ServiceAttachmentConnectionPreferenceEnumToProto converts a ServiceAttachmentConnectionPreferenceEnum enum to its proto representation. func ComputeServiceAttachmentConnectionPreferenceEnumToProto(e *compute.ServiceAttachmentConnectionPreferenceEnum) computepb.ComputeServiceAttachmentConnectionPreferenceEnum { if e == nil { return computepb.ComputeServiceAttachmentConnectionPreferenceEnum(0) } if v, ok := computepb.ComputeServiceAttachmentConnectionPreferenceEnum_value["ServiceAttachmentConnectionPreferenceEnum"+string(*e)]; ok { return computepb.ComputeServiceAttachmentConnectionPreferenceEnum(v) } return computepb.ComputeServiceAttachmentConnectionPreferenceEnum(0) } // ServiceAttachmentConnectedEndpointsStatusEnumToProto converts a ServiceAttachmentConnectedEndpointsStatusEnum enum to its proto representation. func ComputeServiceAttachmentConnectedEndpointsStatusEnumToProto(e *compute.ServiceAttachmentConnectedEndpointsStatusEnum) computepb.ComputeServiceAttachmentConnectedEndpointsStatusEnum { if e == nil { return computepb.ComputeServiceAttachmentConnectedEndpointsStatusEnum(0) } if v, ok := computepb.ComputeServiceAttachmentConnectedEndpointsStatusEnum_value["ServiceAttachmentConnectedEndpointsStatusEnum"+string(*e)]; ok { return computepb.ComputeServiceAttachmentConnectedEndpointsStatusEnum(v) } return computepb.ComputeServiceAttachmentConnectedEndpointsStatusEnum(0) } // ServiceAttachmentConnectedEndpointsToProto converts a ServiceAttachmentConnectedEndpoints object to its proto representation. func ComputeServiceAttachmentConnectedEndpointsToProto(o *compute.ServiceAttachmentConnectedEndpoints) *computepb.ComputeServiceAttachmentConnectedEndpoints { if o == nil { return nil } p := &computepb.ComputeServiceAttachmentConnectedEndpoints{} p.SetStatus(ComputeServiceAttachmentConnectedEndpointsStatusEnumToProto(o.Status)) p.SetPscConnectionId(dcl.ValueOrEmptyInt64(o.PscConnectionId)) p.SetEndpoint(dcl.ValueOrEmptyString(o.Endpoint)) return p } // ServiceAttachmentConsumerAcceptListsToProto converts a ServiceAttachmentConsumerAcceptLists object to its proto representation. func ComputeServiceAttachmentConsumerAcceptListsToProto(o *compute.ServiceAttachmentConsumerAcceptLists) *computepb.ComputeServiceAttachmentConsumerAcceptLists { if o == nil { return nil } p := &computepb.ComputeServiceAttachmentConsumerAcceptLists{} p.SetProjectIdOrNum(dcl.ValueOrEmptyString(o.ProjectIdOrNum)) p.SetConnectionLimit(dcl.ValueOrEmptyInt64(o.ConnectionLimit)) return p } // ServiceAttachmentPscServiceAttachmentIdToProto converts a ServiceAttachmentPscServiceAttachmentId object to its proto representation. func ComputeServiceAttachmentPscServiceAttachmentIdToProto(o *compute.ServiceAttachmentPscServiceAttachmentId) *computepb.ComputeServiceAttachmentPscServiceAttachmentId { if o == nil { return nil } p := &computepb.ComputeServiceAttachmentPscServiceAttachmentId{} p.SetHigh(dcl.ValueOrEmptyInt64(o.High)) p.SetLow(dcl.ValueOrEmptyInt64(o.Low)) return p } // ServiceAttachmentToProto converts a ServiceAttachment resource to its proto representation. func ServiceAttachmentToProto(resource *compute.ServiceAttachment) *computepb.ComputeServiceAttachment { p := &computepb.ComputeServiceAttachment{} p.SetId(dcl.ValueOrEmptyInt64(resource.Id)) p.SetName(dcl.ValueOrEmptyString(resource.Name)) p.SetDescription(dcl.ValueOrEmptyString(resource.Description)) p.SetSelfLink(dcl.ValueOrEmptyString(resource.SelfLink)) p.SetRegion(dcl.ValueOrEmptyString(resource.Region)) p.SetTargetService(dcl.ValueOrEmptyString(resource.TargetService)) p.SetConnectionPreference(ComputeServiceAttachmentConnectionPreferenceEnumToProto(resource.ConnectionPreference)) p.SetEnableProxyProtocol(dcl.ValueOrEmptyBool(resource.EnableProxyProtocol)) p.SetPscServiceAttachmentId(ComputeServiceAttachmentPscServiceAttachmentIdToProto(resource.PscServiceAttachmentId)) p.SetFingerprint(dcl.ValueOrEmptyString(resource.Fingerprint)) p.SetProject(dcl.ValueOrEmptyString(resource.Project)) p.SetLocation(dcl.ValueOrEmptyString(resource.Location)) sConnectedEndpoints := make([]*computepb.ComputeServiceAttachmentConnectedEndpoints, len(resource.ConnectedEndpoints)) for i, r := range resource.ConnectedEndpoints { sConnectedEndpoints[i] = ComputeServiceAttachmentConnectedEndpointsToProto(&r) } p.SetConnectedEndpoints(sConnectedEndpoints) sNatSubnets := make([]string, len(resource.NatSubnets)) for i, r := range resource.NatSubnets { sNatSubnets[i] = r } p.SetNatSubnets(sNatSubnets) sConsumerRejectLists := make([]string, len(resource.ConsumerRejectLists)) for i, r := range resource.ConsumerRejectLists { sConsumerRejectLists[i] = r } p.SetConsumerRejectLists(sConsumerRejectLists) sConsumerAcceptLists := make([]*computepb.ComputeServiceAttachmentConsumerAcceptLists, len(resource.ConsumerAcceptLists)) for i, r := range resource.ConsumerAcceptLists { sConsumerAcceptLists[i] = ComputeServiceAttachmentConsumerAcceptListsToProto(&r) } p.SetConsumerAcceptLists(sConsumerAcceptLists) return p } // applyServiceAttachment handles the gRPC request by passing it to the underlying ServiceAttachment Apply() method. func (s *ServiceAttachmentServer) applyServiceAttachment(ctx context.Context, c *compute.Client, request *computepb.ApplyComputeServiceAttachmentRequest) (*computepb.ComputeServiceAttachment, error) { p := ProtoToServiceAttachment(request.GetResource()) res, err := c.ApplyServiceAttachment(ctx, p) if err != nil { return nil, err } r := ServiceAttachmentToProto(res) return r, nil } // applyComputeServiceAttachment handles the gRPC request by passing it to the underlying ServiceAttachment Apply() method. func (s *ServiceAttachmentServer) ApplyComputeServiceAttachment(ctx context.Context, request *computepb.ApplyComputeServiceAttachmentRequest) (*computepb.ComputeServiceAttachment, error) { cl, err := createConfigServiceAttachment(ctx, request.GetServiceAccountFile()) if err != nil { return nil, err } return s.applyServiceAttachment(ctx, cl, request) } // DeleteServiceAttachment handles the gRPC request by passing it to the underlying ServiceAttachment Delete() method. func (s *ServiceAttachmentServer) DeleteComputeServiceAttachment(ctx context.Context, request *computepb.DeleteComputeServiceAttachmentRequest) (*emptypb.Empty, error) { cl, err := createConfigServiceAttachment(ctx, request.GetServiceAccountFile()) if err != nil { return nil, err } return &emptypb.Empty{}, cl.DeleteServiceAttachment(ctx, ProtoToServiceAttachment(request.GetResource())) } // ListComputeServiceAttachment handles the gRPC request by passing it to the underlying ServiceAttachmentList() method. func (s *ServiceAttachmentServer) ListComputeServiceAttachment(ctx context.Context, request *computepb.ListComputeServiceAttachmentRequest) (*computepb.ListComputeServiceAttachmentResponse, error) { cl, err := createConfigServiceAttachment(ctx, request.GetServiceAccountFile()) if err != nil { return nil, err } resources, err := cl.ListServiceAttachment(ctx, request.GetProject(), request.GetLocation()) if err != nil { return nil, err } var protos []*computepb.ComputeServiceAttachment for _, r := range resources.Items { rp := ServiceAttachmentToProto(r) protos = append(protos, rp) } p := &computepb.ListComputeServiceAttachmentResponse{} p.SetItems(protos) return p, nil } func createConfigServiceAttachment(ctx context.Context, service_account_file string) (*compute.Client, error) { conf := dcl.NewConfig(dcl.WithUserAgent("dcl-test"), dcl.WithCredentialsFile(service_account_file)) return compute.NewClient(conf), nil }
package middleware import ( "net/http" ) type DefaultMiddleware struct { http.ServeMux middleware []func(next http.Handler) http.Handler } func (dm *DefaultMiddleware) CORS(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Access-Control-Allow-Origin", "http://localhost") w.Header().Set("Access-Control-Allow-Methods", "DELETE, POST, GET, OPTIONS") w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With, Set-Cookie") w.Header().Set("Access-Control-Allow-Credentials", "true") if r.Method == "OPTIONS" { w.Write([]byte("allowed")) return } next.ServeHTTP(w, r) }) } func (dm *DefaultMiddleware) RegisterMiddlewareDefault(next func(next http.Handler) http.Handler) { dm.middleware = append(dm.middleware, next) } func (dm *DefaultMiddleware) ServeHTTP(w http.ResponseWriter, r *http.Request) { var current http.Handler = &dm.ServeMux for _, next := range dm.middleware { current = next(current) } current.ServeHTTP(w, r) }
// Copyright 2019 Yunion // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package guestdrivers import ( "context" "fmt" "yunion.io/x/pkg/utils" api "yunion.io/x/onecloud/pkg/apis/compute" "yunion.io/x/onecloud/pkg/cloudcommon/db/taskman" "yunion.io/x/onecloud/pkg/cloudprovider" "yunion.io/x/onecloud/pkg/compute/models" "yunion.io/x/onecloud/pkg/httperrors" "yunion.io/x/onecloud/pkg/mcclient" "yunion.io/x/onecloud/pkg/util/billing" ) type SAliyunGuestDriver struct { SManagedVirtualizedGuestDriver } func init() { driver := SAliyunGuestDriver{} models.RegisterGuestDriver(&driver) } func (self *SAliyunGuestDriver) GetHypervisor() string { return models.HYPERVISOR_ALIYUN } func (self *SAliyunGuestDriver) GetDefaultSysDiskBackend() string { return models.STORAGE_CLOUD_EFFICIENCY } func (self *SAliyunGuestDriver) GetMinimalSysDiskSizeGb() int { return 20 } func (self *SAliyunGuestDriver) GetStorageTypes() []string { return []string{ models.STORAGE_CLOUD_EFFICIENCY, models.STORAGE_CLOUD_SSD, models.STORAGE_CLOUD_ESSD, models.STORAGE_PUBLIC_CLOUD, models.STORAGE_EPHEMERAL_SSD, } } func (self *SAliyunGuestDriver) ChooseHostStorage(host *models.SHost, backend string) *models.SStorage { storages := host.GetAttachedStorages("") for i := 0; i < len(storages); i += 1 { if storages[i].StorageType == backend { return &storages[i] } } for _, stype := range self.GetStorageTypes() { for i := 0; i < len(storages); i += 1 { if storages[i].StorageType == stype { return &storages[i] } } } return nil } func (self *SAliyunGuestDriver) GetDetachDiskStatus() ([]string, error) { return []string{models.VM_READY, models.VM_RUNNING}, nil } func (self *SAliyunGuestDriver) GetAttachDiskStatus() ([]string, error) { return []string{models.VM_READY, models.VM_RUNNING}, nil } func (self *SAliyunGuestDriver) GetRebuildRootStatus() ([]string, error) { return []string{models.VM_READY, models.VM_RUNNING}, nil } func (self *SAliyunGuestDriver) GetChangeConfigStatus() ([]string, error) { return []string{models.VM_READY, models.VM_RUNNING}, nil } func (self *SAliyunGuestDriver) GetDeployStatus() ([]string, error) { return []string{models.VM_READY, models.VM_RUNNING}, nil } func (self *SAliyunGuestDriver) ValidateResizeDisk(guest *models.SGuest, disk *models.SDisk, storage *models.SStorage) error { if !utils.IsInStringArray(guest.Status, []string{models.VM_READY, models.VM_RUNNING}) { return fmt.Errorf("Cannot resize disk when guest in status %s", guest.Status) } if disk.DiskType == models.DISK_TYPE_SYS { return fmt.Errorf("Cannot resize system disk") } if !utils.IsInStringArray(storage.StorageType, []string{models.STORAGE_PUBLIC_CLOUD, models.STORAGE_CLOUD_SSD, models.STORAGE_CLOUD_EFFICIENCY}) { return fmt.Errorf("Cannot resize %s disk", storage.StorageType) } return nil } func (self *SAliyunGuestDriver) RequestDetachDisk(ctx context.Context, guest *models.SGuest, task taskman.ITask) error { return guest.StartSyncTask(ctx, task.GetUserCred(), false, task.GetTaskId()) } func (self *SAliyunGuestDriver) ValidateCreateData(ctx context.Context, userCred mcclient.TokenCredential, input *api.ServerCreateInput) (*api.ServerCreateInput, error) { input, err := self.SManagedVirtualizedGuestDriver.ValidateCreateData(ctx, userCred, input) if err != nil { return nil, err } if len(input.Networks) > 2 { return nil, httperrors.NewInputParameterError("cannot support more than 1 nic") } for i, disk := range input.Disks { if i == 0 && (disk.SizeMb < 20*1024 || disk.SizeMb > 500*1024) { return nil, httperrors.NewInputParameterError("The system disk size must be in the range of 20GB ~ 500Gb") } switch disk.Backend { case models.STORAGE_CLOUD_EFFICIENCY, models.STORAGE_CLOUD_SSD, models.STORAGE_CLOUD_ESSD: if disk.SizeMb < 20*1024 || disk.SizeMb > 32768*1024 { return nil, httperrors.NewInputParameterError("The %s disk size must be in the range of 20GB ~ 32768GB", disk.Backend) } case models.STORAGE_PUBLIC_CLOUD: if disk.SizeMb < 5*1024 || disk.SizeMb > 2000*1024 { return nil, httperrors.NewInputParameterError("The %s disk size must be in the range of 5GB ~ 2000GB", disk.Backend) } case models.STORAGE_EPHEMERAL_SSD: if disk.SizeMb < 5*1024 || disk.SizeMb > 800*1024 { return nil, httperrors.NewInputParameterError("The %s disk size must be in the range of 5GB ~ 800GB", disk.Backend) } } } return input, nil } func (self *SAliyunGuestDriver) GetGuestInitialStateAfterCreate() string { return models.VM_READY } func (self *SAliyunGuestDriver) GetGuestInitialStateAfterRebuild() string { return models.VM_READY } func (self *SAliyunGuestDriver) GetLinuxDefaultAccount(desc cloudprovider.SManagedVMCreateConfig) string { userName := "root" if desc.ImageType == "system" && desc.OsType == "Windows" { userName = "Administrator" } return userName } /* func (self *SAliyunGuestDriver) RequestDeployGuestOnHost(ctx context.Context, guest *models.SGuest, host *models.SHost, task taskman.ITask) error { config, err := guest.GetDeployConfigOnHost(ctx, task.GetUserCred(), host, task.GetParams()) if err != nil { log.Errorf("GetDeployConfigOnHost error: %v", err) return err } log.Debugf("RequestDeployGuestOnHost: %s", config) desc := cloudprovider.SManagedVMCreateConfig{} if err := desc.GetConfig(config); err != nil { return err } userName := "root" if desc.ImageType == "system" && desc.OsType == "Windows" { userName = "Administrator" } action, err := config.GetString("action") if err != nil { return err } ihost, err := host.GetIHost() if err != nil { return err } if action == "create" { taskman.LocalTaskRun(task, func() (jsonutils.JSONObject, error) { iVM, createErr := ihost.CreateVM(&desc) if createErr != nil { return nil, createErr } guest.SetExternalId(task.GetUserCred(), iVM.GetGlobalId()) log.Debugf("VMcreated %s, wait status ready ...", iVM.GetGlobalId()) err = cloudprovider.WaitStatus(iVM, models.VM_READY, time.Second*5, time.Second*1800) if err != nil { return nil, err } log.Debugf("VMcreated %s, and status is ready", iVM.GetGlobalId()) iVM, err = ihost.GetIVMById(iVM.GetGlobalId()) if err != nil { log.Errorf("cannot find vm %s", err) return nil, err } data := fetchIVMinfo(desc, iVM, guest.Id, userName, desc.Password, action) return data, nil }) } else if action == "deploy" { iVM, err := ihost.GetIVMById(guest.GetExternalId()) if err != nil || iVM == nil { log.Errorf("cannot find vm %s", err) return fmt.Errorf("cannot find vm") } params := task.GetParams() log.Debugf("Deploy VM params %s", params.String()) deleteKeypair := jsonutils.QueryBoolean(params, "__delete_keypair__", false) taskman.LocalTaskRun(task, func() (jsonutils.JSONObject, error) { if len(desc.UserData) > 0 { err := iVM.UpdateUserData(desc.UserData) if err != nil { log.Errorf("update userdata fail %s", err) } } err := iVM.DeployVM(ctx, desc.Name, desc.Password, desc.PublicKey, deleteKeypair, desc.Description) if err != nil { return nil, err } data := fetchIVMinfo(desc, iVM, guest.Id, userName, desc.Password, action) return data, nil }) } else if action == "rebuild" { iVM, err := ihost.GetIVMById(guest.GetExternalId()) if err != nil || iVM == nil { log.Errorf("cannot find vm %s", err) return fmt.Errorf("cannot find vm") } taskman.LocalTaskRun(task, func() (jsonutils.JSONObject, error) { if len(desc.UserData) > 0 { err := iVM.UpdateUserData(desc.UserData) if err != nil { log.Errorf("update userdata fail %s", err) } } diskId, err := iVM.RebuildRoot(ctx, desc.ExternalImageId, desc.Password, desc.PublicKey, desc.SysDisk.SizeGB) if err != nil { return nil, err } log.Debugf("VMrebuildRoot %s new diskID %s, wait status ready ...", iVM.GetGlobalId(), diskId) err = cloudprovider.WaitStatus(iVM, models.VM_READY, time.Second*5, time.Second*1800) if err != nil { return nil, err } log.Debugf("VMrebuildRoot %s, and status is ready", iVM.GetGlobalId()) maxWaitSecs := 300 waited := 0 for { // hack, wait disk number consistent idisks, err := iVM.GetIDisks() if err != nil { log.Errorf("fail to find VM idisks %s", err) return nil, err } if len(idisks) < len(desc.DataDisks)+1 || idisks[0].GetGlobalId() != diskId { if waited > maxWaitSecs { log.Errorf("inconsistent disk number, wait timeout, must be something wrong on remote") return nil, cloudprovider.ErrTimeout } if len(idisks) < len(desc.DataDisks)+1 { log.Debugf("inconsistent disk number???? %d != %d", len(idisks), len(desc.DataDisks)+1) } if len(idisks) > 0 && idisks[0].GetGlobalId() != diskId { log.Errorf("system disk id inconsistent %s != %s", idisks[0].GetGlobalId(), diskId) } time.Sleep(time.Second * 5) waited += 5 } else { break } } data := fetchIVMinfo(desc, iVM, guest.Id, userName, desc.Password, action) return data, nil }) } else { log.Errorf("RequestDeployGuestOnHost: Action %s not supported", action) return fmt.Errorf("Action %s not supported", action) } return nil } */ func (self *SAliyunGuestDriver) AllowReconfigGuest() bool { return true } func (self *SAliyunGuestDriver) IsSupportedBillingCycle(bc billing.SBillingCycle) bool { weeks := bc.GetWeeks() if weeks >= 1 && weeks <= 4 { return true } months := bc.GetMonths() if (months >= 1 && months <= 10) || (months == 12) || (months == 24) || (months == 36) || (months == 48) || (months == 60) { return true } return false }
// Copyright (C) 2018 Storj Labs, Inc. // See LICENSE for copying information. package main import ( "os" "github.com/minio/minio/cmd" _ "storj.io/storj/pkg/miniogw" ) func main() { cmd.Main(os.Args) }
package paizaio type APIError struct { Body string } func newAPIError(body string) *APIError { return &APIError{Body: body} } func (a *APIError) Error() string { return a.Body } var _ error = &APIError{}
package loader import ( "github.com/raphael-trzpit/sandgo/model" "github.com/raphael-trzpit/sandgo/repository" ) // User is a user loader. type User struct { r repository.User } // NewUser create a new User Loader from a given repository func NewUser(r repository.User) *User { l := new(User) l.r = r return l } // RetrieveOne return a single User given a set of filters func (l User) RetrieveOne(filters map[string]string) model.User { u, _ := l.r.Find(filters) return u } // RetrieveAll return all User given a set of filters func (l User) RetrieveAll(filters map[string]string) []model.User { u, _ := l.r.FindAll(filters) return u }
package main import ( "fmt" s "strings" ) var p = fmt.Println func main() { p("Contains: ", s.Contains("test", "es")) p("Count: ", s.Count("test", "t")) // การตรวจสอบว่า test ขึ้นต้นด้วย te หรือไม่ p("HasPerfix: ", s.HasPrefix("test", "te")) // การตรวจสอบว่า test ลงท้ายด้วย e หรือไม่ p("HasSuffix: ", s.HasSuffix("test", "st")) // ค้นหาข้อมูลว่า e อยู่ตำแหน่งไหน p("Index: ", s.Index("test", "e")) // การนำ string มาต่อกัน แล้วเก็บใน [] โดยมี - คั่น p("Join : ", s.Join([]string{"a", "b"}, "-")) // ทำซ้ำ p("Repeat: ", s.Repeat("a", 5)) // แทนตำแหน่ง ตัว o เป็นเลข 0 p("Replace: ", s.Replace("foo", "o", "0", -1)) // แทนตำแหน่ง ตัว o เป็นเลข 0 แค่ 2 ตัว p("Replace: ", s.Replace("fooo", "o", "0", 2)) // การแยกช่วงของข้อมูล ระหว่าง a-b-c-d-e เป็น a b c d e แล้วเก็บใน array[] p("Spilt: ", s.Split("a-b-c-d-e", "-")) // เปลี่ยนพิมพ์เล็กเป็นพิมพ์ใหญ่ p("ToLower: ", s.ToLower("TEST")) // เปลี่ยนพิมพ์ใหญ่เป็นพิมพ์เล็ก p("ToUpper : ", s.ToUpper("test")) p("Len: ", len("Hello")) }
package ondemand import ( "fmt" "strings" ) // Quote https://www.barchart.com/ondemand/api/getQuote type Quote struct { Results []struct { Symbol string `json:"symbol"` Name string `json:"name"` DayCode string `json:"dayCode"` ServerTimestamp string `json:"serverTimestamp"` Mode string `json:"mode"` LastPrice float64 `json:"lastPrice"` TradeSize int `json:"tradeSize"` TradeTimestamp string `json:"tradeTimestamp"` NetChange float64 `json:"netChange"` PercentChange float64 `json:"percentChange"` Tick string `json:"tick"` PreviousLastPrice float64 `json:"previousLastPrice"` PreviousTimestamp string `json:"previousTimestamp"` Bid float64 `json:"bid"` BidSize int `json:"bidSize"` Ask float64 `json:"ask"` AskSize int `json:"askSize"` UnitCode string `json:"unitCode"` Open float64 `json:"open"` High float64 `json:"high"` Low float64 `json:"low"` Close float64 `json:"close"` NumTrades int `json:"numTrades"` DollarVolume float64 `json:"dollarVolume"` Flag string `json:"flag"` PreviousOpen float64 `json:"previousOpen"` PreviousHigh float64 `json:"previousHigh"` PreviousLow float64 `json:"previousLow"` PreviousClose float64 `json:"previousClose"` PreviousSettlement float64 `json:"previousSettlement"` Volume int `json:"volume"` PreviousVolume int `json:"previousVolume"` OpenInterest interface{} `json:"openInterest"` FiftyTwoWkHigh float64 `json:"fiftyTwoWkHigh"` FiftyTwoWkHighDate string `json:"fiftyTwoWkHighDate"` FiftyTwoWkLow float64 `json:"fiftyTwoWkLow"` FiftyTwoWkLowDate string `json:"fiftyTwoWkLowDate"` AvgVolume int `json:"avgVolume"` SharesOutstanding int `json:"sharesOutstanding"` DividendRateAnnual string `json:"dividendRateAnnual"` DividendYieldAnnual string `json:"dividendYieldAnnual"` ExDividendDate string `json:"exDividendDate"` ImpliedVolatility interface{} `json:"impliedVolatility"` TwentyDayAvgVol int `json:"twentyDayAvgVol"` Month interface{} `json:"month"` Year interface{} `json:"year"` ExpirationDate interface{} `json:"expirationDate"` LastTradingDay interface{} `json:"lastTradingDay"` TwelveMnthPct float64 `json:"twelveMnthPct"` AverageWeeklyVolume int `json:"averageWeeklyVolume"` AverageMonthlyVolume int `json:"averageMonthlyVolume"` AverageQuarterlyVolume int `json:"averageQuarterlyVolume"` ExchangeMargin interface{} `json:"exchangeMargin"` OneMonthHigh float64 `json:"oneMonthHigh"` OneMonthHighDate string `json:"oneMonthHighDate"` OneMonthLow float64 `json:"oneMonthLow"` OneMonthLowDate string `json:"oneMonthLowDate"` ThreeMonthHigh float64 `json:"threeMonthHigh"` ThreeMonthHighDate string `json:"threeMonthHighDate"` ThreeMonthLow float64 `json:"threeMonthLow"` ThreeMonthLowDate string `json:"threeMonthLowDate"` SixMonthHigh float64 `json:"sixMonthHigh"` SixMonthHighDate string `json:"sixMonthHighDate"` SixMonthLow float64 `json:"sixMonthLow"` SixMonthLowDate string `json:"sixMonthLowDate"` Exchange string `json:"exchange"` } `json:"results"` } // Quote https://www.barchart.com/ondemand/api/getQuote func (od *OnDemand) Quote(symbols []string, fields []string) (Quote, error) { quote := Quote{} _symbols := strings.ToUpper(strings.Join(symbols, ",")) _fields := "histVol100" if fields != nil { _fields = strings.Join(fields, ",") } _, err := od.Request("getQuote.json", fmt.Sprintf("symbols=%v&fields=%s", _symbols, _fields), &quote) return quote, err }
package libvirt // Platform stores all the global configuration that all // machinesets use. type Platform struct { // URI is the identifier for the libvirtd connection. It must be // reachable from both the host (where the installer is run) and the // cluster (where the cluster-API controller pod will be running). // Default is qemu+tcp://192.168.122.1/system // // +kubebuilder:default="qemu+tcp://192.168.122.1/system" // +optional URI string `json:"URI,omitempty"` // DefaultMachinePlatform is the default configuration used when // installing on libvirt for machine pools which do not define their // own platform configuration. // Default will set the image field to the latest RHCOS image. // // +optional DefaultMachinePlatform *MachinePool `json:"defaultMachinePlatform,omitempty"` // Network // +optional Network *Network `json:"network,omitempty"` } // Network is the configuration of the libvirt network. type Network struct { // The interface make used for the network. // Default is tt0. // // +kubebuilder:default="tt0" // +optional IfName string `json:"if,omitempty"` // DnsmasqOptions is the dnsmasq options to be used when installing on // libvirt. // // +optional DnsmasqOptions []DnsmasqOption `json:"dnsmasqOptions,omitempty"` } // DnsmasqOption contains the name and value of the option to configure in the // libvirt network. type DnsmasqOption struct { // The dnsmasq option name. A full list of options and an explanation for // each can be found in /etc/dnsmasq.conf // // +optional Name string `json:"name,omitempty"` // The value that is being set for the particular option. // // +optional Value string `json:"value,omitempty"` }
package main import ( ospaf "../" github "../../github" "encoding/json" "fmt" ) func main() { pool, err := ospaf.InitPool() if err != nil { fmt.Println(err) return } owner := "opencontainers" repo := "specs" url := fmt.Sprintf("https://api.github.com/repos/%s/%s/issues/20/comments", owner, repo) for page := 1; page != -1; { value, code, nextPage, _ := pool.ReadPage(url, page) if code != 200 { break } page = nextPage var comments []github.Comment json.Unmarshal([]byte(value), &comments) fmt.Println("There are ", len(comments), "comments") } }
package main import ( "flag" "fmt" "io" "net" "os" "runtime" log_ "log" "github.com/rs/zerolog" "github.com/rs/zerolog/log" ) type ReadWriteLogger struct { io.ReadWriter Log func() *zerolog.Event Hex bool } func (rwl ReadWriteLogger) Write(b []byte) (int, error) { n, err := rwl.ReadWriter.Write(b) if rwl.Hex { rwl.Log().Hex("data", b).Err(err).Msg("") } else { rwl.Log().Bytes("data", b).Err(err).Msg("") } return n, err } func Duplex(left io.ReadWriter, right io.ReadWriter) error { result := make(chan error) go func() { _, err := io.Copy(left, right) result <- err }() go func() { _, err := io.Copy(right, left) result <- err }() return <-result } func AcceptConnections(incoming <-chan net.Conn, remoteAddr net.Addr) (err error) { connectionCount := 0 for client := range incoming { server, err := net.Dial(remoteAddr.Network(), remoteAddr.String()) if err != nil { log.Error(). Str("clientAddr", client.RemoteAddr().String()). Err(err). Msg("connect to server failed") continue } connectionCount += 1 if Sync { HandleEstablished(client, server, connectionCount) } else { go HandleEstablished(client, server, connectionCount) } } return } func HandleEstablished(client net.Conn, server net.Conn, id int) { defer client.Close() defer server.Close() idstr := fmt.Sprintf("%s%d", Prefix, id) logger := log.With(). Str("session", idstr). Str("clientAddr", client.RemoteAddr().String()). Str("serverAddr", server.RemoteAddr().String()). Logger() logger.Log().Msg("connection established") var err error if NoLog { err = Duplex(client, server) } else { serverLog := log.With(). Str("session", idstr). Str("src", "server"). Logger() clientLog := log.With(). Str("session", idstr). Str("src", "client"). Logger() clientLogger := &ReadWriteLogger{client, serverLog.Log, Hex} serverLogger := &ReadWriteLogger{server, clientLog.Log, Hex} err = Duplex(clientLogger, serverLogger) } logger.Log().Err(err).Msg("connection closed") } func ProxyLog(listenAddr net.Addr, remoteAddr net.Addr) (err error) { listener, err := net.Listen(listenAddr.Network(), listenAddr.String()) if err != nil { log.Error().Err(err).Msg("failed to start listener") return err } defer listener.Close() var listenlog zerolog.Logger if Prefix != "" { listenlog = log.With(). Str("idPrefix", Prefix). Str("listenAddr", listener.Addr().String()). Str("remoteAddr", remoteAddr.String()). Logger() } else { listenlog = log.With(). Str("listenAddr", listener.Addr().String()). Str("remoteAddr", remoteAddr.String()). Logger() } listenlog.Info().Msg("listener started") connectionChannel := make(chan net.Conn) go AcceptConnections(connectionChannel, remoteAddr) for { client, err := listener.Accept() if err != nil { listenlog.Error(). Err(err). Msg("accept connection failed") continue } listenlog.Info(). Str("clientAddr", client.RemoteAddr().String()). Msg("connection accepted") connectionChannel <- client } } func Fatal(err ...interface{}) { if err[0] != nil { log_.Fatal(err...) } } var Sync bool = false // used in AcceptConnections var Hex bool = false // used in HandleEstablished var NoLog bool = false // used in HandleEstablished var Prefix string = "" // used in HandleEstablished func main() { log_.SetFlags(0) log_.SetPrefix("error: ") var ( Listen string Remote string Log string Append bool Color bool Time bool Verbose bool ) flag.StringVar(&Listen, "l", "", "listen/local address (required)") flag.StringVar(&Remote, "r", "", "remote/server address (required)") flag.StringVar(&Log, "o", "", "log to file instead of stdout") flag.StringVar(&Prefix, "p", "", "set session prefix") flag.BoolVar(&Append, "a", false, "append to log file") flag.BoolVar(&Sync, "s", false, "force connections to run synchronously") flag.BoolVar(&Hex, "x", false, "log bytes in hex format") flag.BoolVar(&Color, "c", false, "log with console writer") flag.BoolVar(&NoLog, "n", false, "do not log data") flag.BoolVar(&Time, "t", false, "log time in iso format") flag.BoolVar(&Verbose, "v", false, "log listener status") flag.Parse() if flag.NArg() > 0 { Fatal("unknown argument: ", flag.Arg(0)) } var logFile *os.File var err error if Listen == "" { Fatal("no listen address provided") } if Remote == "" { Fatal("no remote address provided") } if Log == "" { logFile = os.Stdout } else { if Append { logFile, err = os.OpenFile(Log, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0666) } else { logFile, err = os.OpenFile(Log, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0666) } Fatal(err) defer logFile.Close() } if Verbose { zerolog.SetGlobalLevel(zerolog.InfoLevel) } else { zerolog.SetGlobalLevel(zerolog.FatalLevel) } if Color { if runtime.GOOS == "windows" { log.Logger = log.Output(zerolog.ConsoleWriter{Out: logFile, NoColor: true}) } else { log.Logger = log.Output(zerolog.ConsoleWriter{Out: logFile, NoColor: false}) } } else { log.Logger = log.Output(logFile) } if Time { zerolog.TimeFieldFormat = "2006-01-02T15:04:05.000000Z07:00" } else { zerolog.TimeFieldFormat = zerolog.TimeFormatUnixMicro } listenAddr, err := net.ResolveTCPAddr("tcp", Listen) Fatal(err) connectAddr, err := net.ResolveTCPAddr("tcp", Remote) Fatal(err) err = ProxyLog(listenAddr, connectAddr) if err != nil { log.Fatal().Err(err).Msg("") } }
func partitionLabels(S string) []int { mapping := make(map[byte] int, 26) for i := 0; i < len(S); i++ { mapping[S[i]] = i } result := [] int {} max := 0 for i := 0; i < len(S); { max = compareMax(max, mapping[S[i]]) for j := i + 1; j <= max; j++ { max = compareMax(max, mapping[S[j]]) } result = append(result, max - i + 1) i = max + 1 } return result } func compareMax(i, j int) int { if i > j { return i } return j }
package tmpl3 func binarySearch(nums []int, target int) int { if len(nums) == 0 { return -1 } left, right := 0, len(nums)-1 for left+1 < right { // Prevent (left + right) overflow mid := left + (right-left)/2 if nums[mid] == target { return mid } else if nums[mid] < target { left = mid } else { right = mid } } // Post-processing: // End Condition: left + 1 == right if nums[left] == target { return left } if nums[right] == target { return right } return -1 }
//go:build debug // +build debug package main import ( "fmt" ) // describeCommands is a debugging function that prints out all commands. // This is normally never called, but we keep this implemented as it is useful // for debugging. func describeCommands() { handlerNames := make(map[string]string) handlerNames[fmt.Sprintf("%v", nil)] = "~" // The next few lines should ignore govet's "printf" lint because we are // intentionally printing a function instead of calling it. handlerNames[fmt.Sprintf("%v", ignoredArgHandler)] = "ignored" //nolint:govet,printf handlerNames[fmt.Sprintf("%v", volumeArgHandler)] = "volume" //nolint:govet,printf handlerNames[fmt.Sprintf("%v", filePathArgHandler)] = "file path" //nolint:govet,printf handlerNames[fmt.Sprintf("%v", outputPathArgHandler)] = "output path" //nolint:govet,printf log.Println("========== COMMAND STRUCTURE ==========") var paths []string for path := range commands { paths = append(paths, path) } sort.Strings(paths) for _, path := range paths { command := commands[path] log.Printf("%-20s %v", path, command.handler) //nolint:govet,printf var optionNames []string for optionName := range command.options { optionNames = append(optionNames, optionName) } sort.Strings(optionNames) for _, optionName := range optionNames { handler := command.options[optionName] handlerName, ok := handlerNames[fmt.Sprintf("%v", handler)] if !ok { handlerName = "<invalid handler>" } log.Printf("%20s %s", optionName, handlerName) } } log.Println("========== END COMMAND STRUCTURE ==========") }
package BinaryTreeHashMap import "Pair" var INITIAL_CAPACITY = 1 << 5 var THRESHOLD_MAX float32 = 1 var THRESHOLD_MIN float32 = 0.2 var GROW_SHIFT = 2 type BinaryTreeHashMap struct { entries []*Node Size int } type Node struct { pair Pair.Pair left *Node right *Node } func createByCapacity(capacity int) BinaryTreeHashMap { return BinaryTreeHashMap{make([]*Node, capacity), 0} } func New() BinaryTreeHashMap { return createByCapacity(INITIAL_CAPACITY) } func (hm *BinaryTreeHashMap) Put(key uint64, value int) { hm.put(key, value, true) } func (hm *BinaryTreeHashMap) put(key uint64, value int, resize bool) { bucket := key % uint64(len(hm.entries)) if hm.entries[bucket] == nil { hm.entries[bucket] = &Node{Pair.Pair{key, value}, nil, nil} hm.changeSizeBy(1, resize) } else { increment := hm.entries[bucket].putRec(Pair.Pair{key, value}) if increment { hm.changeSizeBy(1, resize) } } } func (hm *BinaryTreeHashMap) Get(key uint64) (int, bool) { bucket := key % uint64(len(hm.entries)) if hm.entries[bucket] == nil { return 0, false } node := hm.entries[bucket].getRec(key) if node != nil { return node.pair.Value, true } else { return 0, false } } func (hm *BinaryTreeHashMap) Remove(key uint64) { bucket := hm.entries[key % uint64(len(hm.entries))] if bucket == nil { return } if _, ok := hm.Get(key); ok { hm.changeSizeBy(-1, true) } hm.entries[key % uint64(len(hm.entries))] = removeRec(bucket, key) } func (hm *BinaryTreeHashMap) KeyValuePairs() []Pair.Pair { arr := make([]Pair.Pair, hm.Size) index := 0 for i := 0; i < len(hm.entries); i++ { if hm.entries[i] != nil { keyValuePairsRec(hm.entries[i], arr, &index) } } return arr } func (node *Node) putRec(pair Pair.Pair) bool { if pair.Key < node.pair.Key { if node.left == nil { node.left = &Node{pair, nil, nil} return true } else { return node.left.putRec(pair) } } else if pair.Key > node.pair.Key { if node.right == nil { node.right = &Node{pair, nil, nil} return true } else { return node.right.putRec(pair) } } else { node.pair = pair } return false } func (node *Node) getRec(key uint64) *Node { if key == node.pair.Key { return node } if key < node.pair.Key { if node.left != nil { return node.left.getRec(key) } else { return nil } } else { if node.right != nil { return node.right.getRec(key) } else { return nil } } } func removeRec(node *Node, key uint64) *Node { if node == nil { return nil } if key < node.pair.Key { node.left = removeRec(node.left, key) } else if key > node.pair.Key { node.right = removeRec(node.right, key) } else { if node.left != nil && node.right != nil { minNodeRight := minNodeRec(node.right) node.pair = minNodeRight.pair node.right = removeRec(node.right, minNodeRight.pair.Key) } else if node.left != nil { node = node.left } else if node.right != nil { node = node.right } else { node = nil } } return node } func minNodeRec(node *Node) *Node { if node.left == nil { return node } else { return minNodeRec(node.left) } } func keyValuePairsRec(node *Node, arr []Pair.Pair, index *int) { if node != nil { keyValuePairsRec(node.left, arr, index) arr[*index] = node.pair *index += 1 keyValuePairsRec(node.right, arr, index) } } func (hm *BinaryTreeHashMap) changeSizeBy(change int, resize bool) { hm.Size += change if resize { hm.resizeOnThreshold() } } func (hm *BinaryTreeHashMap) resizeOnThreshold() { newSize := 0 if hm.Size < int(float32(len(hm.entries)) * THRESHOLD_MIN) && hm.Size > INITIAL_CAPACITY { newSize = len(hm.entries) >> 1 } else if hm.Size > int(float32(len(hm.entries)) * THRESHOLD_MAX) { newSize = len(hm.entries) << GROW_SHIFT } else { return } newHashMap := createByCapacity(newSize) for _, pair := range hm.KeyValuePairs() { newHashMap.put(pair.Key, pair.Value, false) } *hm = newHashMap }
package chain import ( "testing" "github.com/stretchr/testify/assert" ) func TestSetIsIn(t *testing.T) { tests := []struct { name string setInit map[string]bool search string expected bool }{ { "should be present", map[string]bool{"work": true}, "work", true, }, { "should not be present", map[string]bool{"work": true}, "newwork", false, }, } for _, utest := range tests { t.Run(utest.name, func(t *testing.T) { set := &Set{set: utest.setInit} res := set.IsIn(utest.search) assert.Equal(t, utest.expected, res) }) } } func TestSetAddAndGetValues(t *testing.T) { tests := []struct { name string add []string expectedLen int }{ { "add one", []string{"work"}, 1, }, { "add two", []string{"work", "newwork"}, 2, }, { "add three", []string{"work", "newwork", "withoutwork"}, 3, }, } for _, utest := range tests { t.Run(utest.name, func(t *testing.T) { set := NewSet() for _, elem := range utest.add { set.Add(elem) isIn := set.IsIn(elem) assert.Equal(t, true, isIn) } assert.Equal(t, utest.expectedLen, len(set.set)) values := set.GetValues() assert.ElementsMatch(t, utest.add, values) }) } }
package test import ( "testing" "github.com/kohge4/go-rakutenapi/rakuten" "github.com/stretchr/testify/assert" ) func TestKoboGenre(t *testing.T) { params := &rakuten.KoboGenreParams{ KoboGenreID: 101912005001, } _, _, err := client.Kobo.GenreSearch(ctx, params) assert.Nil(t, err) } func TestKoboEbooks(t *testing.T) { params := &rakuten.KoboEbooksParams{ Keyword: "Go言語", } _, _, err := client.Kobo.EbooksSearch(ctx, params) assert.Nil(t, err) }
package ids_db import ( "database/sql" "fmt" _ "github.com/go-sql-driver/mysql" "github.com/rezwanul-haque/ID-Service/src/utils/helpers" "github.com/rezwanul-haque/ID-Service/src/logger" ) var ( Client *sql.DB username = helpers.GoDotEnvVariable("MYSQL_IDS_USERNAME") password = helpers.GoDotEnvVariable("MYSQL_IDS_PASSWORD") host = helpers.GoDotEnvVariable("MYSQL_IDS_HOST") port = helpers.GoDotEnvVariable("MYSQL_IDS_PORT") schema = helpers.GoDotEnvVariable("MYSQL_IDS_SCHEMA") ) func init() { dataSourceName := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8", username, password, host, port, schema, ) var err error Client, err = sql.Open("mysql", dataSourceName) if err != nil { logger.Error("connecting to database failed: ", err) panic(err) } if err = Client.Ping(); err != nil { panic(err) } logger.Info("database successfully configured") }
package order import ( "wx-gin-master/models" "wx-gin-master/models/wallet" "wx-gin-master/pkg/logging" ) type Order struct { models.Model UserId int `json:"user_id"` // 用户id //ProvinceName string `json:"province_name"` // 省份 //CityName string `json:"city_name"` // 城市 //CountyName string `json:"county_name"` // 区县 //DetailInfo string `json:"detail_info"` // 详细地址 //PostalCode string `json:"postal_code"` // 邮编 UserName string `json:"user_name"` // 收货人姓名 TelNumber string `json:"tel_number"` // 联系电话 //ExpressTitle string `json:"express_title"` // 物流公司 //ExpressCode string `json:"express_code"` // 物流编号 //ExpressNo string `json:"express_no"` // 物流单号 ExpressTime int64 `json:"express_time"` // 发货时间 Total float64 `json:"total"` // 汇总金额 SumPay float64 `json:"sum_pay"` // 结算金额 Status int `json:"status"` // 状态,0-未结算 1-已结算(待发货) 2-已发货(待收货) 3-已完成 9-异常 PushedAt int64 `json:"pushed_at"` // 推送时间 } func (Order) TableName() string { return "orders" } // Created 创建订单 func Created(order *Order) bool { if err := models.DB.Debug().Create(order).Error; err != nil { logging.Info(err) return false } return true } // Settlement 完成支付 func Settlement(userId, oid int) bool { order := QueryOrderById(oid) if wallet.CostBalance(order.SumPay, userId) { if err := models.DB.Debug().Model(order).UpdateColumn("status", 1).Error; err != nil { logging.Info(err) return false } return true } else { return false } } // Update 更新订单信息 func Update(id int, order *Order) bool { if err := models.DB.Debug().Model(Order{}).Where("id = ?", id).Update(*order).Error; err != nil { logging.Info(err) return false } return true } // Destroy 销毁订单 func Destroy(oid int) bool { if err := models.DB.Unscoped().Delete(Order{}, "id = ?", oid).Error; err != nil { logging.Info(err) return false } return true } // Done 完成订单 func Done(oid int) bool { if err := models.DB.Delete(Order{}, "id = ?", oid).Error; err != nil { logging.Info(err) return false } return true } // QueryOrderByUserId 通过用户ID查询订单信息 func QueryOrderByUserId(userId int) (order []Order) { models.DB.Debug().Model(Order{}).Where("user_id = ?", userId).Find(&order) return } // 通过ID查询订单信息 func QueryOrderById(id int) (order Order) { models.DB.Debug().Model(Order{}).Where("id = ?", id).First(&order) return } // IsOwner 判断订单ID和用户ID是否是同一个用户所拥有 func IsOwner(userId, id int) bool { var data int models.DB.Debug().Model(Order{}).Select("1").Where("id = ? AND user_id = ?", id, userId).First(&data) if data != 0 { return true } return false } /* * 导出订单 * @param $offset = 0 * @param $limit * @param $order_id * @return array */ /* func Export() { models.DB.Order("modified_on DESC").Offset(offset).array } */
package pool import ( "crawler/errors" "crawler/logger" "crawler/models" "net/http" ) var transport = &http.Transport{DisableKeepAlives: true} var client = &http.Client{Transport: transport} type ChannelPages chan *models.Page var ( Throttle = NewThrottle() Storage = NewStorage() ) func StartTask(body string) (task *models.Task) { id := Storage.NextIndex() task = models.NewTask(id, body) Storage.Set(id, task) go runTask(task) return } func FindTask(id uint64) (*models.Task, error) { task, ok := Storage.Get(id) if !ok { return task, errors.TASK_NOT_FOUND } if task.State != models.STATE_DONE { return task, errors.TASK_IN_PROGRESS } return task, nil } func DeleteTask(id uint64) (*models.Task, error) { task, ok := Storage.Get(id) if !ok { return task, errors.TASK_NOT_FOUND } if task.State != models.STATE_DONE { return task, errors.TASK_IN_PROGRESS } Storage.Delete(id) return task, nil } func runTask(task *models.Task) { counter := 0 chPages := make(ChannelPages, len(task.Links)) for _, link := range task.Links { go getPage(task.Id, link, chPages) } for counter < len(task.Links) { page := <-chPages task.Pages = append(task.Pages, page) counter++ } task.Complete() logger.Debug.Printf("[Task #%d] Completed.\n", task.Id) } func getPage(id uint64, link *models.Link, chPages ChannelPages) { if link.Error == nil { <-Throttle.Get(link.Hostname) } logger.Debug.Printf("[Task #%d] Get page: %s\n", id, link.URL) chPages <- models.GetPage(client, link) }
package package1 import "strconv" //zad 1 func Suma(a, b int) int { return a + b } //zad 2 func Concatenate(s1, s2 []int) []int { return append(s1, s2...) } //zad 3 func Is18(age int) bool { if age >= 18 { return true } else { return false } } //zad 4 func PrintDividedBy4(n int) []int { m := n s1 := []int{} for m >= 4 { if m%4 == 0 { s1 = append(s1, m) m -= 4 } else { m -= 1 } } return s1 } //zad 5 func FilterEven(age []int) []int { m := []int{} for _, v := range age { if age[v-1]%2 == 1 { m = append(m, age[v-1]) } else { continue } } return m } //zad 6 type User struct { name string lastName string age int isAdult bool } func NewUser(_name, _lastName string, _age int) *User { _User := new(User) _isAdult := Is18(_age) _User.name = _name _User.lastName = _lastName _User.age = _age _User.isAdult = _isAdult return _User } //zad 7 func (u *User) ToString() string { str := "This user has following attributes: \n" str += "Name: " + u.name + "\n" str += "Last Name: " + u.lastName + "\n" str += "Age: " + strconv.Itoa(u.age) + "\n" str += "Is an Adult: " + strconv.FormatBool(u.isAdult) return str } func (u *User) ChangeAge(newAge int) { u.age = newAge u.isAdult = Is18(newAge) }
// This file was generated for SObject FiscalYearSettings, API Version v43.0 at 2018-07-30 03:47:50.328372034 -0400 EDT m=+36.672354515 package sobjects import ( "fmt" "strings" ) type FiscalYearSettings struct { BaseSObject Description string `force:",omitempty"` EndDate string `force:",omitempty"` Id string `force:",omitempty"` IsStandardYear bool `force:",omitempty"` Name string `force:",omitempty"` PeriodId string `force:",omitempty"` PeriodLabelScheme string `force:",omitempty"` PeriodPrefix string `force:",omitempty"` QuarterLabelScheme string `force:",omitempty"` QuarterPrefix string `force:",omitempty"` StartDate string `force:",omitempty"` SystemModstamp string `force:",omitempty"` WeekLabelScheme string `force:",omitempty"` WeekStartDay int `force:",omitempty"` YearType string `force:",omitempty"` } func (t *FiscalYearSettings) ApiName() string { return "FiscalYearSettings" } func (t *FiscalYearSettings) String() string { builder := strings.Builder{} builder.WriteString(fmt.Sprintf("FiscalYearSettings #%s - %s\n", t.Id, t.Name)) builder.WriteString(fmt.Sprintf("\tDescription: %v\n", t.Description)) builder.WriteString(fmt.Sprintf("\tEndDate: %v\n", t.EndDate)) builder.WriteString(fmt.Sprintf("\tId: %v\n", t.Id)) builder.WriteString(fmt.Sprintf("\tIsStandardYear: %v\n", t.IsStandardYear)) builder.WriteString(fmt.Sprintf("\tName: %v\n", t.Name)) builder.WriteString(fmt.Sprintf("\tPeriodId: %v\n", t.PeriodId)) builder.WriteString(fmt.Sprintf("\tPeriodLabelScheme: %v\n", t.PeriodLabelScheme)) builder.WriteString(fmt.Sprintf("\tPeriodPrefix: %v\n", t.PeriodPrefix)) builder.WriteString(fmt.Sprintf("\tQuarterLabelScheme: %v\n", t.QuarterLabelScheme)) builder.WriteString(fmt.Sprintf("\tQuarterPrefix: %v\n", t.QuarterPrefix)) builder.WriteString(fmt.Sprintf("\tStartDate: %v\n", t.StartDate)) builder.WriteString(fmt.Sprintf("\tSystemModstamp: %v\n", t.SystemModstamp)) builder.WriteString(fmt.Sprintf("\tWeekLabelScheme: %v\n", t.WeekLabelScheme)) builder.WriteString(fmt.Sprintf("\tWeekStartDay: %v\n", t.WeekStartDay)) builder.WriteString(fmt.Sprintf("\tYearType: %v\n", t.YearType)) return builder.String() } type FiscalYearSettingsQueryResponse struct { BaseQuery Records []FiscalYearSettings `json:"Records" force:"records"` }
package atypes type AInt []int func (ai AInt) Len() int { return len(ai) } func (ai AInt) Less(i, j int) bool { return ai[i] < ai[j] } func (ai AInt) Swap(i, j int) { ai[i], ai[j] = ai[j], ai[i] } func (ai AInt) Get(i int) interface{} { return ai[i] } func (ai AInt) LessD(i, j interface{}) bool { return i.(int) < j.(int) } func (ai AInt) Assign(i int, d interface{}){ai[i] = d.(int)} func (ai AInt) InsertionB (i, j int){c := append(ai[:j], ai[i]);c = append(c, ai[j:i]...);c = append(c, ai[i+1:]...);ai = c} type AInt8 []int8 func (ai AInt8) Len() int { return len(ai) } func (ai AInt8) Less(i, j int) bool { return ai[i] < ai[j] } func (ai AInt8) Swap(i, j int) { ai[i], ai[j] = ai[j], ai[i] } func (ai AInt8) Get(i int) interface{} { return ai[i] } func (ai AInt8) LessD(i, j interface{}) bool { return i.(int) < j.(int) } func (ai AInt8) Assign(i int, d interface{}){ai[i] = d.(int8)} func (ai AInt8) InsertionB (i, j int){c := append(ai[:j], ai[i]);c = append(c, ai[j:i]...);c = append(c, ai[i+1:]...);ai = c} type AInt16 []int16 func (ai AInt16) Len() int { return len(ai) } func (ai AInt16) Less(i, j int) bool { return ai[i] < ai[j] } func (ai AInt16) Swap(i, j int) { ai[i], ai[j] = ai[j], ai[i] } func (ai AInt16) Get(i int) interface{} { return ai[i] } func (ai AInt16) LessD(i, j interface{}) bool { return i.(int) < j.(int) } func (ai AInt16) Assign(i int, d interface{}){ai[i] = d.(int16)} func (ai AInt16) InsertionB (i, j int){c := append(ai[:j], ai[i]);c = append(c, ai[j:i]...);c = append(c, ai[i+1:]...);ai = c} type AInt32 []int32 func (ai AInt32) Len() int { return len(ai) } func (ai AInt32) Less(i, j int) bool { return ai[i] < ai[j] } func (ai AInt32) Swap(i, j int) { ai[i], ai[j] = ai[j], ai[i] } func (ai AInt32) Get(i int) interface{} { return ai[i] } func (ai AInt32) LessD(i, j interface{}) bool { return i.(int) < j.(int) } func (ai AInt32) Assign(i int, d interface{}){ai[i] = d.(int32)} func (ai AInt32) InsertionB (i, j int){c := append(ai[:j], ai[i]);c = append(c, ai[j:i]...);c = append(c, ai[i+1:]...);ai = c} type AInt64 []int64 func (ai AInt64) Len() int { return len(ai) } func (ai AInt64) Less(i, j int) bool { return ai[i] < ai[j] } func (ai AInt64) Swap(i, j int) { ai[i], ai[j] = ai[j], ai[i] } func (ai AInt64) Get(i int) interface{} { return ai[i] } func (ai AInt64) LessD(i, j interface{}) bool { return i.(int) < j.(int) } func (ai AInt64) Assign(i int, d interface{}){ai[i] = d.(int64)} func (ai AInt64) InsertionB (i, j int){c := append(ai[:j], ai[i]);c = append(c, ai[j:i]...);c = append(c, ai[i+1:]...);ai = c} type AUInt []uint func (ai AUInt) Len() int { return len(ai) } func (ai AUInt) Less(i, j int) bool { return ai[i] < ai[j] } func (ai AUInt) Swap(i, j int) { ai[i], ai[j] = ai[j], ai[i] } func (ai AUInt) Get(i int) interface{} { return ai[i] } func (ai AUInt) LessD(i, j interface{}) bool { return i.(int) < j.(int) } func (ai AUInt) Assign(i int, d interface{}){ai[i] = d.(uint)} func (ai AUInt) InsertionB (i, j int){c := append(ai[:j], ai[i]);c = append(c, ai[j:i]...);c = append(c, ai[i+1:]...);ai = c} type AUInt8 []uint8 func (ai AUInt8) Len() int { return len(ai) } func (ai AUInt8) Less(i, j int) bool { return ai[i] < ai[j] } func (ai AUInt8) Swap(i, j int) { ai[i], ai[j] = ai[j], ai[i] } func (ai AUInt8) Get(i int) interface{} { return ai[i] } func (ai AUInt8) LessD(i, j interface{}) bool { return i.(int) < j.(int) } func (ai AUInt8) Assign(i int, d interface{}){ai[i] = d.(uint8)} func (ai AUInt8) InsertionB (i, j int){c := append(ai[:j], ai[i]);c = append(c, ai[j:i]...);c = append(c, ai[i+1:]...);ai = c} type AUInt16 []uint16 func (ai AUInt16) Len() int { return len(ai) } func (ai AUInt16) Less(i, j int) bool { return ai[i] < ai[j] } func (ai AUInt16) Swap(i, j int) { ai[i], ai[j] = ai[j], ai[i] } func (ai AUInt16) Get(i int) interface{} { return ai[i] } func (ai AUInt16) LessD(i, j interface{}) bool { return i.(int) < j.(int) } func (ai AUInt16) Assign(i int, d interface{}){ai[i] = d.(uint16)} func (ai AUInt16) InsertionB (i, j int){c := append(ai[:j], ai[i]);c = append(c, ai[j:i]...);c = append(c, ai[i+1:]...);ai = c} type AUInt32 []uint32 func (ai AUInt32) Len() int { return len(ai) } func (ai AUInt32) Less(i, j int) bool { return ai[i] < ai[j] } func (ai AUInt32) Swap(i, j int) { ai[i], ai[j] = ai[j], ai[i] } func (ai AUInt32) Get(i int) interface{} { return ai[i] } func (ai AUInt32) LessD(i, j interface{}) bool { return i.(int) < j.(int) } func (ai AUInt32) Assign(i int, d interface{}){ai[i] = d.(uint32)} func (ai AUInt32) InsertionB (i, j int){c := append(ai[:j], ai[i]);c = append(c, ai[j:i]...);c = append(c, ai[i+1:]...);ai = c} type AUInt64 []uint64 func (ai AUInt64) Len() int { return len(ai) } func (ai AUInt64) Less(i, j int) bool { return ai[i] < ai[j] } func (ai AUInt64) Swap(i, j int) { ai[i], ai[j] = ai[j], ai[i] } func (ai AUInt64) Get(i int) interface{} { return ai[i] } func (ai AUInt64) LessD(i, j interface{}) bool { return i.(int) < j.(int) } func (ai AUInt64) Assign(i int, d interface{}){ai[i] = d.(uint64)} func (ai AUInt64) InsertionB (i, j int){c := append(ai[:j], ai[i]);c = append(c, ai[j:i]...);c = append(c, ai[i+1:]...);ai = c}
package main import ( "fmt" "time" "k8s.io/apimachinery/pkg/fields" "k8s.io/client-go/tools/cache" "congwang.com/learnGo/k8s-client-go-examples/common" v1 "k8s.io/api/core/v1" "k8s.io/client-go/kubernetes" ) func main() { var ( clientset *kubernetes.Clientset err error ) // init k8s client if clientset, err = common.InitClient(); err != nil { fmt.Println(err) return } // watch for pod changes. /** Observation: when scaling in/out (delete or add a pod), AddFunc or DeleteFunc is only called once associated with 3 calls to UpdateFunc. */ watchlist := cache.NewListWatchFromClient(clientset.CoreV1().RESTClient(), "pods", v1.NamespaceDefault, fields.Everything()) _, controller := cache.NewInformer( watchlist, &v1.Pod{}, time.Second*0, cache.ResourceEventHandlerFuncs{ AddFunc: func(obj interface{}) { fmt.Printf("add: %s \n", obj.(*v1.Pod).Name) }, DeleteFunc: func(obj interface{}) { fmt.Printf("deleted: %s \n", obj.(*v1.Pod).Name) }, UpdateFunc: func(oldObj, newObj interface{}) { fmt.Printf("old: %s, new: %s \n", oldObj.(*v1.Pod).Name, newObj.(*v1.Pod).Name) }, }, ) stop := make(chan struct{}) go controller.Run(stop) for { time.Sleep(time.Second) } }
package main import ( "fmt" "math" ) func main() { fmt.Println("Circle Area Calculation") fmt.Println("Enter a Radius Value: ") var radius float64 fmt.Scanf("%f", &radius) area := math.Pi * math.Pow(radius,2) fmt.Printf("Area of a circle with a radius of %.2f = %.2f \n", radius, area) }
package orm import ( "database/sql" "errors" "reflect" ) // result is a pointer (eg. &[]struct or &[]*struct) // return affected rows func Scan(rows *sql.Rows, result interface{}) (int64, error) { if rows == nil { return 0, errors.New("rows can't be nil") } if result == nil { return 0, errors.New("result can't be nil") } out := reflect.ValueOf(result) if out.Kind() != reflect.Ptr { return 0, errors.New("result must be a pointer (eg. &[]struct or &[]*struct)") } out = out.Elem() if out.Kind() != reflect.Slice { return 0, errors.New("result must be a slice (eg. &[]struct or &[]*struct)") } outType := out.Type() outType = outType.Elem() isPtr := false // &[]struct if outType.Kind() == reflect.Ptr { isPtr = true // &[]*struct outType = outType.Elem() } columns, err := rows.Columns() if err != nil { return 0, err } size := len(columns) if size == 0 { return 0, errors.New("columns's size can't be equal than 0") } sequence, err := SqlSequence(columns, outType) if err != nil { return 0, err } if len(sequence) == 0 { return 0, errors.New("no sequence, sql rows's columns no mapping result's tag") } var affectedRows int64 = 0 for rows.Next() { attributes := make([]interface{}, size) elements := reflect.New(outType).Elem() for i, n := range columns { if j, ok := sequence[n]; ok { f := elements.Field(j) if f.IsValid() { attributes[i] = f.Addr().Interface() continue } } attributes[i] = new(interface{}) } if err := rows.Scan(attributes...); err != nil { return affectedRows, err } if isPtr { out.Set(reflect.Append(out, elements.Addr())) } else { out.Set(reflect.Append(out, elements)) } affectedRows++ } return affectedRows, nil }
// DRUNKWATER TEMPLATE(add description and prototypes) // Question Title and Description on leetcode.com // Function Declaration and Function Prototypes on leetcode.com //462. Minimum Moves to Equal Array Elements II //Given a non-empty integer array, find the minimum number of moves required to make all array elements equal, where a move is incrementing a selected element by 1 or decrementing a selected element by 1. //You may assume the array's length is at most 10,000. //Example: //Input: //[1,2,3] //Output: //2 //Explanation: //Only two moves are needed (remember each move increments or decrements one element): //[1,2,3] => [2,2,3] => [2,2,2] //func minMoves2(nums []int) int { //} // Time Is Money
package main import ( "context" "fmt" "net/http" "os" "path" "sync" "github.com/docker/docker/api/types" docker "github.com/docker/docker/client" "github.com/gorilla/websocket" "github.com/ubclaunchpad/inertia/daemon/inertiad/auth" "github.com/ubclaunchpad/inertia/daemon/inertiad/crypto" "github.com/ubclaunchpad/inertia/daemon/inertiad/project" ) var ( // daemonVersion indicates the daemon's corresponding Inertia daemonVersion daemonVersion string // deployment is the currently deployed project on this remote deployment project.Deployer // socketUpgrader specifies parameters for upgrading an HTTP connection to a WebSocket connection socketUpgrader = websocket.Upgrader{} ) var ( // specify location of SSL certificate sslDirectory = "/app/host/inertia/config/ssl/" userDatabasePath = "/app/host/inertia/data/users.db" deploymentDatabasePath = "/app/host/inertia/data/project.db" ) const ( msgNoDeployment = "No deployment is currently active on this remote - try running 'inertia $REMOTE up'" ) // run starts the daemon func run(host, port, version, keyPath, certDir, userDir string) { daemonVersion = version if keyPath != "" { auth.DaemonGithubKeyLocation = keyPath } if certDir != "" { sslDirectory = certDir } if userDir != "" { userDatabasePath = userDir } var ( daemonSSLCert = path.Join(sslDirectory, "daemon.cert") daemonSSLKey = path.Join(sslDirectory, "daemon.key") ) // Download build tools cli, err := docker.NewEnvClient() if err != nil { println(err.Error()) println("Failed to start Docker client - shutting down daemon.") return } println("Downloading build tools...") go downloadDeps(cli) // Check if the cert files are available. println("Checking for existing SSL certificates in " + sslDirectory + "...") _, err = os.Stat(daemonSSLCert) certNotPresent := os.IsNotExist(err) _, err = os.Stat(daemonSSLKey) keyNotPresent := os.IsNotExist(err) // If they are not available, generate new ones. if keyNotPresent && certNotPresent { println("No certificates found - generating new ones...") err = crypto.GenerateCertificate(daemonSSLCert, daemonSSLKey, host+":"+port, "RSA") if err != nil { println(err.Error()) return } } webPrefix := "/web/" handler, err := auth.NewPermissionsHandler( userDatabasePath, host, 120, ) if err != nil { println(err.Error()) return } defer handler.Close() // Inertia web handler.AttachPublicHandler( webPrefix, http.StripPrefix( webPrefix, http.FileServer(http.Dir("/daemon/inertia-web")), ), ) // GitHub webhook endpoint handler.AttachPublicHandlerFunc("/webhook", gitHubWebHookHandler) // CLI API endpoints handler.AttachUserRestrictedHandlerFunc("/status", statusHandler) handler.AttachUserRestrictedHandlerFunc("/logs", logHandler) handler.AttachAdminRestrictedHandlerFunc("/up", upHandler) handler.AttachAdminRestrictedHandlerFunc("/down", downHandler) handler.AttachAdminRestrictedHandlerFunc("/reset", resetHandler) handler.AttachAdminRestrictedHandlerFunc("/env", envHandler) // Root "ok" endpoint handler.AttachPublicHandlerFunc("/", func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) }) // Serve daemon on port println("Serving daemon on port " + port) fmt.Println(http.ListenAndServeTLS( ":"+port, daemonSSLCert, daemonSSLKey, handler, )) } func downloadDeps(cli *docker.Client) { var wait sync.WaitGroup wait.Add(2) go dockerPull(project.DockerComposeVersion, cli, &wait) go dockerPull(project.HerokuishVersion, cli, &wait) wait.Wait() cli.Close() } func dockerPull(image string, cli *docker.Client, wait *sync.WaitGroup) { defer wait.Done() println("Downloading " + image) _, err := cli.ImagePull(context.Background(), image, types.ImagePullOptions{}) if err != nil { println(err.Error()) } else { println(image + " download complete") } }
/* Package skipList provide an implementation of skip list. But is not thread-safe in concurrency. */ package skipList import ( "math/rand" "github.com/OneOfOne/xxhash" ) // Comes from redis's implementation. // Also you can see more detail in William Pugh's paper <Skip Lists: A Probabilistic Alternative to Balanced Trees>. // The paper is in ftp://ftp.cs.umd.edu/pub/skipLists/skiplists.pdf const ( MAX_LEVEL = 32 PROBABILITY = 0.25 ) type node struct { Index uint64 Value interface{} nextNodes []*node } func newNode(index uint64, value interface{}, level int) *node { if level <= 0 || level > MAX_LEVEL { level = MAX_LEVEL } return &node{ Index: index, Value: value, nextNodes: make([]*node, level), } } type SkipList struct { level int length int32 head *node tail *node } // NewSkipList will create and initialize a skip list with the given level. // Level must between 1 to 32. If not, the level will set as 32. // To determine the level, you can see the paper ftp://ftp.cs.umd.edu/pub/skipLists/skiplists.pdf. // A simple way to determine the level is L(N) = log(1/PROBABILITY)(N). // N is the count of the skip list which you can estimate. PROBABILITY is 0.25 in this case. // For example, if you expect the skip list contains 10000000 elements, then N = 10000000, L(N) ≈ 12. // After initialization, the head field's level equal to level parameter and point to tail field. func NewSkipList(level int) *SkipList { if level <= 0 || level > MAX_LEVEL { level = MAX_LEVEL } head := newNode(0, nil, level) var tail *node = nil for i := 0; i < len(head.nextNodes); i++ { head.nextNodes[i] = tail } return &SkipList{ level: level, length: 0, head: head, tail: tail, } } // Level will return the level of skip list. func (s *SkipList) Level() int { return s.level } // Length will return the length of skip list. func (s *SkipList) Length() int32 { return s.length } // Insert will insert a node into skip list. If skip has these this index, overwrite the value, otherwise add it. func (s *SkipList) Insert(index uint64, value interface{}) { // Ignore nil value. if value == nil { return } previousNodes, currentNode := s.doSearch(index) // If skip list contains index, update the value. // Avoid to update the head. if currentNode != s.head && currentNode.Index == index { currentNode.Value = value return } // Make a new node. pendingNode := newNode(index, value, s.randomLevel()) // Adjust pointer. Similar to update linked list. for i := len(pendingNode.nextNodes) - 1; i >= 0; i-- { // Firstly, new node point to next node. pendingNode.nextNodes[i] = previousNodes[i].nextNodes[i] // Secondly, previous nodes point to new node. previousNodes[i].nextNodes[i] = pendingNode } s.length++ } // Delete will find the index is existed or not firstly. If existed, delete it, otherwise do nothing. func (s *SkipList) Delete(index uint64) { previousNodes, currentNode := s.doSearch(index) // If skip list length is 0 or could not find node with the given index. if currentNode != s.head && currentNode.Index == index { // Adjust pointer. Similar to update linked list. for i := 0; i < len(currentNode.nextNodes); i++ { previousNodes[i].nextNodes[i] = currentNode.nextNodes[i] currentNode.nextNodes[i] = nil } s.length-- } } // Search will search the skip list with the given index. // If the index exists, return the value, otherwise return nil. func (s *SkipList) Search(index uint64) interface{} { _, result := s.doSearch(index) if result == s.head || result.Index != index { return nil } else { return result.Value } } // doSearch will search given index in skip list. // The first return value represents the previous nodes need to update when call Insert function. // The second return value represents the node with given index or the closet node whose index is larger than given index. func (s *SkipList) doSearch(index uint64) ([]*node, *node) { // Store all previous node whose index is less than index and whose next node's index is larger than index. previousNodes := make([]*node, s.level) // fmt.Printf("start doSearch:%v\n", index) currentNode := s.head // Iterate from top level to bottom level. for l := s.level - 1; l >= 0; l-- { // Iterate node util node's index is >= given index. // The max iterate count is skip list's length. So the worst O(n) is N. for currentNode.nextNodes[l] != s.tail && currentNode.nextNodes[l].Index < index { currentNode = currentNode.nextNodes[l] } // When next node's index is >= given index, add current node whose index < given index. previousNodes[l] = currentNode } // Avoid point to tail which will occur panic in Insert and Delete function. // When the next node is tail. // The index is larger than the maximum index in the skip list or skip list's length is 0. Don't point to tail. // When the next node isn't tail. // Next node's index must >= given index. Point to it. if currentNode.nextNodes[0] != s.tail { currentNode = currentNode.nextNodes[0] } // fmt.Printf("previous node:\n") // for _, n := range previousNodes { // fmt.Printf("%p\t", n) // } // fmt.Println() // fmt.Printf("end doSearch %v\n", index) return previousNodes, currentNode } // ForEach will iterate the whole skip list and do the function f for each index and value. // Function f will not modify the index and value in skip list. // Don't Insert or Delete element in ForEach function. func (s *SkipList) ForEach(f func(index uint64, value interface{}) bool) { currentNode := s.head.nextNodes[0] for currentNode != s.tail { i := currentNode.Index v := currentNode.Value if !f(i, v) { break } currentNode = currentNode.nextNodes[0] } } // randomLevel will generate and random level that level > 0 and level < skip list's level // This comes from redis's implementation. func (s *SkipList) randomLevel() int { level := 1 for rand.Float64() < PROBABILITY && level < s.level { level++ } return level } // Hash will calculate the input's hash value using xxHash algorithm. // It can be used to calculate the index of skip list. // See more detail in https://cyan4973.github.io/xxHash/ func Hash(input []byte) uint64 { h := xxhash.New64() h.Write(input) return h.Sum64() }
func longestCommonPrefix(strs []string) string { if len(strs) == 1 { return strs[0] } if len(strs) == 0 { return "" } superMap := make(map[int]map[int]string) tempStr2 := strs[0] allSingleChar := 0 for i := 0; i < len(strs); i++ { if strs[i] == "" { return "" } if tempStr2 != strs[i] { allSingleChar = -1 } tempStr2 = strs[i] aMap := make(map[int]string) tempChar := "" tempStr := "" for j := 0; j < len(strs[i]); j++ { tempChar = string(strs[i][j]) tempStr = tempStr + tempChar aMap[j] = tempStr } superMap[i] = aMap } if allSingleChar == 0 { return strs[0] } short := 0 for i := 1; i < len(strs); i++ { short = len(strs[i-1]) if short > len(strs[i]) { short = len(strs[i]) } } prefix := "" for i := 0; i < short; i++ { for j := 1; j < len(superMap); j++ { if superMap[0][i] != superMap[j][i] { return prefix } } prefix = superMap[0][i] } return prefix }
package main import ( "database/sql" "fmt" _ "github.com/lib/pq" ) var connStr = "user=postgres password=1 dbname=productdb sslmode=disable" //Phone ... type Phone struct { ID int Model string Company string Price int } func main() { db, err := sql.Open("postgres", connStr) if err != nil { panic(err) } defer db.Close() fmt.Println("OK!") //Создадим телефон и добавим в базу данных phone := Phone{Model: "IXVA -11", Company: "Sam", Price: 100} _, err = db.Exec("insert into Phones (model, company, price) VALUES ($1, $2, $3)", phone.Model, phone.Company, phone.Price) if err != nil { panic(err) } //fmt.Println(result.RowsAffected()) //Обновим объект с id = 2 - поменяем название модели _, err = db.Exec("update Phones set model=$1 where id=$2", "IXVA -12", 2) if err != nil { panic(err) } //Удалим телефон с id = 5 _, err = db.Exec("delete from Phones where id=$1", 5) if err != nil { panic(err) } //Считаем из БД все rows, err := db.Query("select * from Phones") if err != nil { panic(err) } defer rows.Close() var phones []Phone for rows.Next() { p := Phone{} err := rows.Scan(&p.ID, &p.Model, &p.Company, &p.Price) if err != nil { fmt.Println(err) continue } phones = append(phones, p) } for _, p := range phones { fmt.Println(p.ID, p.Model, p.Company, p.Price) } }
package main import ( "context" "io" "os" "github.com/PacktPublishing/Go-Programming-Cookbook-Second-Edition/chapter7/oauthstore" "golang.org/x/oauth2" "golang.org/x/oauth2/github" ) func main() { conf := oauthstore.Config{ Config: &oauth2.Config{ ClientID: os.Getenv("GITHUB_CLIENT"), ClientSecret: os.Getenv("GITHUB_SECRET"), Scopes: []string{"repo", "user"}, Endpoint: github.Endpoint, }, Storage: &oauthstore.FileStorage{Path: "token.txt"}, } ctx := context.Background() token, err := oauthstore.GetToken(ctx, conf) if err != nil { panic(err) } cli := conf.Client(ctx, token) resp, err := cli.Get("https://api.github.com/user") if err != nil { panic(err) } defer resp.Body.Close() io.Copy(os.Stdout, resp.Body) }
package main import ( "fmt" ) func main() { f := func(s string) int { return len(s) } fmt.Println(f("hello world")) fmt.Println(funcStringIntUser(f)) } func funcStringIntUser(f func(string) int) string { return fmt.Sprintf("function return value is %d", f("test")) }
package slice import ( "fmt" "testing" "time" ) func TestNew(t *testing.T) { s := New(2) s.PushBack(1) s.PushBack(2) s.PushBack(3) s.PushBack(3) s.PushBack(3) fmt.Println(s, s.len, s.cap) s.Put(3, 4) s.Put(4, 5) fmt.Println(s, s.len, s.cap) //s.Put(5, 1) } func TestCostTime(t *testing.T) { const Bench = 10000000 s := New(Bench) gs := make([]int, 0, Bench) start := time.Now() for n := 0; n < Bench; n++ { gs = append(gs, n) } fmt.Println("gosli:", time.Now().Sub(start).Nanoseconds()) start = time.Now() for n := 0; n < Bench; n++ { s.PushBack(n) } fmt.Println("slice:", time.Now().Sub(start).Nanoseconds()) } func BenchmarkSlice_PushBack(b *testing.B) { b.StopTimer() b.N = 10000000 s := New(b.N) b.StartTimer() for n := 0; n < b.N; n++ { s.PushBack(n) } s.Free() } func BenchmarkGoSlice_Append(b *testing.B) { b.StopTimer() b.N = 10000000 s := make([]int, 0, b.N) b.StartTimer() for n := 0; n < b.N; n++ { s = append(s, n) } }
package middlewares import ( "fmt" "net/http" "time" apiResponse "github.com/alexhornbake/go-crud-api/lib/api_response" sql "github.com/alexhornbake/go-crud-api/lib/datastore" log "github.com/alexhornbake/go-crud-api/lib/logging" ) func LoggingHandler(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { startTime := time.Now() next.ServeHTTP(w, r) endTime := time.Now() log.Debugf("%s %s - %d ms", r.Method, r.RequestURI, int64(endTime.Sub(startTime)/time.Millisecond)) }) } func RecoverHandler(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { defer func() { if err := recover(); err != nil { apiResponse.SendError(w, r, apiResponse.InternalServerError(fmt.Sprintf("Panic: %+v", err))) } }() next.ServeHTTP(w, r) }) } func CheckDependencies(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if !(*sql.IsReady()) { apiResponse.SendError(w, r, apiResponse.ServiceUnavailable("Database connection not ready.")) } next.ServeHTTP(w, r) }) }
// Package nutanix collects Nutanix-specific configuration. package nutanix import ( "context" "fmt" "sort" "strconv" "time" "github.com/AlecAivazis/survey/v2" nutanixclient "github.com/nutanix-cloud-native/prism-go-client" nutanixclientv3 "github.com/nutanix-cloud-native/prism-go-client/v3" "github.com/pkg/errors" "github.com/sirupsen/logrus" "github.com/openshift/installer/pkg/types/nutanix" nutanixtypes "github.com/openshift/installer/pkg/types/nutanix" "github.com/openshift/installer/pkg/validate" ) // PrismCentralClient wraps a Nutanix V3 client type PrismCentralClient struct { PrismCentral string Username string Password string Port string V3Client *nutanixclientv3.Client } // Platform collects Nutanix-specific configuration. func Platform() (*nutanix.Platform, error) { nutanixClient, err := getClients() if err != nil { return nil, err } portNum, err := strconv.Atoi(nutanixClient.Port) if err != nil { return nil, err } pc := nutanixtypes.PrismCentral{ Endpoint: nutanix.PrismEndpoint{ Address: nutanixClient.PrismCentral, Port: int32(portNum), }, Username: nutanixClient.Username, Password: nutanixClient.Password, } ctx := context.TODO() v3Client := nutanixClient.V3Client pe, err := getPrismElement(ctx, v3Client) if err != nil { return nil, err } pe.Endpoint.Port = int32(portNum) subnetUUID, err := getSubnet(ctx, v3Client, pe.UUID) if err != nil { return nil, err } apiVIP, ingressVIP, err := getVIPs() if err != nil { return nil, errors.Wrap(err, "failed to get VIPs") } platform := &nutanix.Platform{ PrismCentral: pc, PrismElements: []nutanixtypes.PrismElement{*pe}, SubnetUUIDs: []string{subnetUUID}, APIVIPs: []string{apiVIP}, IngressVIPs: []string{ingressVIP}, } return platform, nil } // getClients() surveys the user for username, password, port & prism central. // Validation on the three fields is performed by creating a client. // If creating the client fails, an error is returned. func getClients() (*PrismCentralClient, error) { var prismCentral, port, username, password string if err := survey.Ask([]*survey.Question{ { Prompt: &survey.Input{ Message: "Prism Central", Help: "The domain name or IP address of the Prism Central to be used for installation.", }, Validate: survey.ComposeValidators(survey.Required, func(ans interface{}) error { return validate.Host(ans.(string)) }), }, }, &prismCentral); err != nil { return nil, errors.Wrap(err, "failed UserInput") } if err := survey.Ask([]*survey.Question{ { Prompt: &survey.Input{ Message: "Port", Help: "The port used to login to Prism Central.", Default: "9440", }, Validate: survey.Required, }, }, &port); err != nil { return nil, errors.Wrap(err, "failed UserInput") } if err := survey.Ask([]*survey.Question{ { Prompt: &survey.Input{ Message: "Username", Help: "The username to login to the Prism Central.", }, Validate: survey.Required, }, }, &username); err != nil { return nil, errors.Wrap(err, "failed UserInput") } if err := survey.Ask([]*survey.Question{ { Prompt: &survey.Password{ Message: "Password", Help: "The password to login to Prism Central.", }, Validate: survey.Required, }, }, &password); err != nil { return nil, errors.Wrap(err, "failed UserInput") } // There is a noticeable delay when creating the client, so let the user know what's going on. logrus.Infof("Connecting to Prism Central %s", prismCentral) clientV3, err := nutanixtypes.CreateNutanixClient(context.TODO(), prismCentral, port, username, password, ) if err != nil { return nil, errors.Wrapf(err, "unable to connect to Prism Central %s. Ensure provided information is correct", prismCentral) } return &PrismCentralClient{ PrismCentral: prismCentral, Username: username, Password: password, Port: port, V3Client: clientV3, }, nil } func getPrismElement(ctx context.Context, client *nutanixclientv3.Client) (*nutanixtypes.PrismElement, error) { ctx, cancel := context.WithTimeout(ctx, 60*time.Second) defer cancel() pe := &nutanixtypes.PrismElement{} emptyFilter := "" pesAll, err := client.V3.ListAllCluster(emptyFilter) if err != nil { return nil, errors.Wrap(err, "unable to list prism element clusters") } pes := pesAll.Entities if len(pes) == 0 { return nil, errors.New("did not find any prism element clusters") } if len(pes) == 1 { pe.UUID = *pes[0].Metadata.UUID pe.Endpoint.Address = *pes[0].Spec.Resources.Network.ExternalIP logrus.Infof("Defaulting to only available prism element (cluster): %s", *pes[0].Spec.Name) return pe, nil } pesMap := make(map[string]*nutanixclientv3.ClusterIntentResponse) var peChoices []string for _, p := range pes { n := *p.Spec.Name pesMap[n] = p peChoices = append(peChoices, n) } var selectedPe string if err := survey.Ask([]*survey.Question{ { Prompt: &survey.Select{ Message: "Prism Element", Options: peChoices, Help: "The Prism Element to be used for installation.", }, Validate: survey.Required, }, }, &selectedPe); err != nil { return nil, errors.Wrap(err, "failed UserInput") } pe.UUID = *pesMap[selectedPe].Metadata.UUID pe.Endpoint.Address = *pesMap[selectedPe].Spec.Resources.Network.ExternalIP return pe, nil } func getSubnet(ctx context.Context, client *nutanixclientv3.Client, peUUID string) (string, error) { ctx, cancel := context.WithTimeout(ctx, 60*time.Second) defer cancel() emptyFilter := "" emptyClientFilters := make([]*nutanixclient.AdditionalFilter, 0) subnetsAll, err := client.V3.ListAllSubnet(emptyFilter, emptyClientFilters) if err != nil { return "", errors.Wrap(err, "unable to list subnets") } subnets := subnetsAll.Entities // API returns an error when no results, but let's leave this in to be defensive. if len(subnets) == 0 { return "", errors.New("did not find any subnets") } if len(subnets) == 1 { n := *subnets[0].Spec.Name u := *subnets[0].Metadata.UUID logrus.Infof("Defaulting to only available network: %s", n) return u, nil } subnetUUIDs := make(map[string]string) var subnetChoices []string for _, subnet := range subnets { // some subnet types (e.g. VPC overlays) do not come with a cluster reference; we don't need to check them if subnet.Spec.ClusterReference == nil || (subnet.Spec.ClusterReference.UUID != nil && *subnet.Spec.ClusterReference.UUID == peUUID) { n := *subnet.Spec.Name subnetUUIDs[n] = *subnet.Metadata.UUID subnetChoices = append(subnetChoices, n) } } if len(subnetChoices) == 0 { return "", errors.New(fmt.Sprintf("could not find any subnets linked to Prism Element with UUID %s", peUUID)) } sort.Strings(subnetChoices) var selectedSubnet string if err := survey.Ask([]*survey.Question{ { Prompt: &survey.Select{ Message: "Subnet", Options: subnetChoices, Help: "The subnet to be used for installation.", }, Validate: survey.Required, }, }, &selectedSubnet); err != nil { return "", errors.Wrap(err, "failed UserInput") } return subnetUUIDs[selectedSubnet], nil } func getVIPs() (string, string, error) { var apiVIP, ingressVIP string //TODO: Add support to specify multiple VIPs (-> dual-stack) if err := survey.Ask([]*survey.Question{ { Prompt: &survey.Input{ Message: "Virtual IP Address for API", Help: "The VIP to be used for the OpenShift API.", }, Validate: survey.ComposeValidators(survey.Required, func(ans interface{}) error { return validate.IP((ans).(string)) }), }, }, &apiVIP); err != nil { return "", "", errors.Wrap(err, "failed UserInput") } if err := survey.Ask([]*survey.Question{ { Prompt: &survey.Input{ Message: "Virtual IP Address for Ingress", Help: "The VIP to be used for ingress to the cluster.", }, Validate: survey.ComposeValidators(survey.Required, func(ans interface{}) error { if apiVIP == (ans.(string)) { return fmt.Errorf("%q should not be equal to the Virtual IP address for the API", ans.(string)) } return validate.IP((ans).(string)) }), }, }, &ingressVIP); err != nil { return "", "", errors.Wrap(err, "failed UserInput") } return apiVIP, ingressVIP, nil }
package nonblocking import ( "database/sql" "log" "sync" _ "github.com/go-sql-driver/mysql" ) type Planner struct { plannerID int connectionPool *ConnectionPool waitGroup *sync.WaitGroup chunkSize int } // NewPlanner func NewPlanner(plannerID int, connectionPool *ConnectionPool, waitGroup *sync.WaitGroup, chunkSize int) *Planner { return &Planner{ plannerID, connectionPool, waitGroup, chunkSize, } } // Execute - execute data chunk plan job func (p *Planner) Execute(trimChunkChannel chan TrimChunk, plannerLeftLimitID int, plannerRightLimitID int) { p.waitGroup.Add(1) defer p.waitGroup.Done() connection := p.connectionPool.Get() defer func() { p.connectionPool.Put(connection) }() startIntervalID := plannerLeftLimitID endIntervalID := p.getEndIntervalID(connection.driver, startIntervalID, p.chunkSize, plannerRightLimitID) for endIntervalID != 0 { // chunk planning log.Printf("[Planner #%d] Planning chunk: %d - %d", p.plannerID, startIntervalID, endIntervalID) trimChunkChannel <- TrimChunk{ startIntervalID, endIntervalID, } startIntervalID = endIntervalID + 1 endIntervalID = p.getEndIntervalID(connection.driver, startIntervalID, p.chunkSize, plannerRightLimitID) } log.Printf("[Planner #%d] Planning last chunk: %d - %d", p.plannerID, startIntervalID, endIntervalID) trimChunkChannel <- TrimChunk{ startIntervalID, plannerRightLimitID, } } // GetEndIntervalID func (p *Planner) getEndIntervalID(db *sql.DB, startIntervalID int, chunkSize int, rightLimitID int) int { var endIntervalID int err := db.QueryRow("SELECT row_id FROM catalog_product_entity WHERE row_id >= ? AND row_id <= ? ORDER BY row_id LIMIT ?,1", startIntervalID, rightLimitID, chunkSize).Scan(&endIntervalID) if err == sql.ErrNoRows { return 0 } if err != nil { panic(err.Error()) // proper error handling instead of panic in your app } return endIntervalID }
package server import ( "github.com/jchavannes/jgo/web" "github.com/jchavannes/money/app/auth" "github.com/jchavannes/money/app/chart" "net/http" ) const ( FormInputSymbol = "symbol" FormInputMarket = "market" ) var individualChartsRoute = web.Route{ Pattern: UrlIndividual, NeedsLogin: true, Handler: func(r *web.Response) { r.Render() }, } var chartGetRoute = web.Route{ Pattern: UrlChartGet, NeedsLogin: true, CsrfProtect: true, Handler: func(r *web.Response) { user, err := auth.GetSessionUser(r.Session.CookieId) if err != nil { r.Error(err, http.StatusInternalServerError) return } overallChartData, err := chart.GetOverallChartData(user.Id) if err != nil { r.Error(err, http.StatusInternalServerError) return } r.WriteJson(overallChartData, false) }, } var individualChartGetRoute = web.Route{ Pattern: UrlIndividualChartGet, CsrfProtect: true, NeedsLogin: true, Handler: func(r *web.Response) { user, err := auth.GetSessionUser(r.Session.CookieId) if err != nil { r.Error(err, http.StatusInternalServerError) return } symbol := r.Request.GetFormValue(FormInputSymbol) market := r.Request.GetFormValue(FormInputMarket) chartData, err := chart.GetIndividualChartData(user.Id, symbol, market) if err != nil { r.Error(err, http.StatusInternalServerError) return } r.WriteJson(chartData, false) }, }
package key import ( "os" "path" "testing" kyber "github.com/drand/kyber" "github.com/drand/kyber/share" "github.com/stretchr/testify/require" ) func TestKeysSaveLoad(t *testing.T) { n := 4 ps, group := BatchIdentities(n) tmp := os.TempDir() tmp = path.Join(tmp, "drand-key") os.RemoveAll(tmp) defer os.RemoveAll(tmp) store := NewFileStore(tmp).(*fileStore) require.Equal(t, tmp, store.baseFolder) // test loading saving private public key ps[0].Public.TLS = true require.NoError(t, store.SaveKeyPair(ps[0])) loadedKey, err := store.LoadKeyPair() require.NoError(t, err) require.Equal(t, loadedKey.Key.String(), ps[0].Key.String()) require.Equal(t, loadedKey.Public.Key.String(), ps[0].Public.Key.String()) require.Equal(t, loadedKey.Public.Address(), ps[0].Public.Address()) require.True(t, loadedKey.Public.IsTLS()) _, err = os.Stat(store.privateKeyFile) require.Nil(t, err) _, err = os.Stat(store.publicKeyFile) require.Nil(t, err) //require.True(t, fs.FileExists(store.privateKeyFile)) //require.True(t, fs.FileExists(store.publicKeyFile)) // test group require.Nil(t, store.SaveGroup(group)) loadedGroup, err := store.LoadGroup() require.NoError(t, err) require.Equal(t, group.Threshold, loadedGroup.Threshold) // TODO remove that ordering thing it's useless for _, lid := range loadedGroup.Identities() { var found bool for _, k := range ps { if lid.Addr != k.Public.Addr { continue } found = true require.Equal(t, k.Public.Key.String(), lid.Key.String(), "public key should hold") require.Equal(t, k.Public.IsTLS(), lid.IsTLS(), "tls property should hold") } require.True(t, found, "not found key ", lid.Addr) } // test share / dist key share := &Share{ Commits: []kyber.Point{ps[0].Public.Key, ps[1].Public.Key}, Share: &share.PriShare{V: ps[0].Key, I: 0}, } require.Nil(t, store.SaveShare(share)) loadedShare, err := store.LoadShare() require.NoError(t, err) require.Equal(t, share.Share.V, loadedShare.Share.V) require.Equal(t, share.Share.I, loadedShare.Share.I) dp := &DistPublic{[]kyber.Point{ps[0].Public.Key}} require.Nil(t, store.SaveDistPublic(dp)) loadedDp, err := store.LoadDistPublic() require.NoError(t, err) require.Equal(t, dp.Key().String(), loadedDp.Key().String()) }
package cmd import ( "bytes" "crypto/rand" "encoding/hex" "errors" "fmt" "os" ) const ( magicBytes = "\x80sabakan-cryptsetup2" maxCipherName = 106 idLength = 16 metadataSize = 2 * 1024 * 1024 ) // Pre-defined errors var ( ErrNotFound = errors.New("not found") ) // Metadata represents metadata block at the head of disk. type Metadata struct { cipher string id string kek string } // ReadMetadata read metadata from f. // If metadata does not exist, this returns ErrNotFound. func ReadMetadata(f *os.File) (*Metadata, error) { data := make([]byte, metadataSize) _, err := f.ReadAt(data, 0) if err != nil { return nil, err } if string(data[0:len(magicBytes)]) != magicBytes { return nil, ErrNotFound } keySize := int(data[20]) cnl := int(data[21]) if cnl > maxCipherName { return nil, fmt.Errorf("cipher name too long: %d", cnl) } md := &Metadata{ cipher: string(data[22:(22 + cnl)]), id: string(data[128:144]), kek: string(data[144:(144 + keySize)]), } return md, nil } // NewMetadata initializes a new Metadata. func NewMetadata(cipher string, keySize int) (*Metadata, error) { if len(cipher) > maxCipherName { return nil, errors.New("too long cipher name") } if keySize > 255 { return nil, errors.New("too large key size") } id := make([]byte, idLength) _, err := rand.Read(id) if err != nil { return nil, err } kek := make([]byte, keySize) _, err = rand.Read(kek) if err != nil { return nil, err } md := &Metadata{ cipher: cipher, id: string(id), kek: string(kek), } return md, nil } // Write writes metadata to f. func (m *Metadata) Write(f *os.File) error { if len(m.cipher) > maxCipherName { return errors.New("too long cipher name: " + m.cipher) } if len(m.id) != idLength { return errors.New("invalid id length") } data := bytes.Repeat([]byte{'\x88'}, metadataSize) copy(data, magicBytes) data[20] = byte(len(m.kek)) data[21] = byte(len(m.cipher)) copy(data[22:(22+len(m.cipher))], m.cipher) copy(data[128:144], m.id) copy(data[144:], m.kek) _, err := f.WriteAt(data, 0) if err != nil { return err } return f.Sync() } // Cipher returns cipher suite for this disk. func (m *Metadata) Cipher() string { return m.cipher } // ID returns randomly assigned ID of this disk. func (m *Metadata) ID() string { return m.id } // HexID returns hexadecimal encoded ID. func (m *Metadata) HexID() string { return hex.EncodeToString([]byte(m.id)) } // Kek returns key encryption key. func (m *Metadata) Kek() string { return m.kek } // DecryptKey decrypts encrypted key. func (m *Metadata) DecryptKey(ek []byte) ([]byte, error) { if len(ek) != len(m.kek) { return nil, fmt.Errorf("key length mismatch: expected=%d, actual=%d", len(m.kek), len(ek)) } key := make([]byte, len(ek)) for i := range ek { key[i] = m.kek[i] ^ ek[i] } return key, nil } // EncryptKey encrypts key. func (m *Metadata) EncryptKey(key []byte) ([]byte, error) { return m.DecryptKey(key) }
package logic import ( "bytes" "copyto/logic/internal/sys" "fmt" "github.com/gookit/color" "github.com/spf13/afero" "github.com/stretchr/testify/assert" "io" "os" "testing" ) type mockprn struct { w *bytes.Buffer } func (m *mockprn) String() string { return m.w.String() } func newMockPrn() *mockprn { return &mockprn{w: bytes.NewBufferString("")} } func (m *mockprn) Print(format string, a ...interface{}) { str := fmt.Sprintf(format, a...) _, _ = fmt.Fprint(m.w, str) } func (m *mockprn) W() io.Writer { return m.w } func (*mockprn) SetColor(color.Color) {} func (*mockprn) ResetColor() {} func Test_coptyfiletreeAllTargetFilesPresentInSource_AllCopied(t *testing.T) { // Arrange ass := assert.New(t) appFS := afero.NewMemMapFs() _ = appFS.MkdirAll("s/p1", 0755) _ = appFS.MkdirAll("s/p1/p2", 0755) _ = appFS.MkdirAll("t/p1", 0755) _ = appFS.MkdirAll("t/p1/p2", 0755) _ = afero.WriteFile(appFS, "s/p1/f1.txt", []byte("/s/p1/f1.txt"), 0644) _ = afero.WriteFile(appFS, "s/p1/f2.txt", []byte("/s/p1/f2.txt"), 0644) _ = afero.WriteFile(appFS, "s/p1/p2/f1.txt", []byte("/s/p1/p2/f1.txt"), 0644) _ = afero.WriteFile(appFS, "s/p1/p2/f2.txt", []byte("/s/p1/p2/f2.txt"), 0644) _ = afero.WriteFile(appFS, "t/p1/f1.txt", []byte("/t/p1/f1.txt"), 0644) _ = afero.WriteFile(appFS, "t/p1/f2.txt", []byte("/t/p1/f2.txt"), 0644) _ = afero.WriteFile(appFS, "t/p1/p2/f1.txt", []byte("/t/p1/p2/f1.txt"), 0644) _ = afero.WriteFile(appFS, "t/p1/p2/f2.txt", []byte("/t/p1/p2/f2.txt"), 0644) buf := newMockPrn() flt := NewFilter("", "") c := NewCopier(appFS, buf, false) // Act c.CopyFileTree("s", "t", flt) // Assert bytes1, _ := afero.ReadFile(appFS, "t/p1/f1.txt") bytes2, _ := afero.ReadFile(appFS, "t/p1/f2.txt") bytes3, _ := afero.ReadFile(appFS, "t/p1/p2/f1.txt") bytes4, _ := afero.ReadFile(appFS, "t/p1/p2/f2.txt") ass.Equal("/s/p1/f1.txt", string(bytes1)) ass.Equal("/s/p1/f2.txt", string(bytes2)) ass.Equal("/s/p1/p2/f1.txt", string(bytes3)) ass.Equal("/s/p1/p2/f2.txt", string(bytes4)) ass.Equal(` Total copied: 4 Copy errors: 0 Present in target but not found in source: 0 `, buf.String()) } func Test_ReadOnlyTargets_NoneCopied(t *testing.T) { // Arrange ass := assert.New(t) memfs := afero.NewMemMapFs() _ = memfs.MkdirAll("s/p1", 0755) _ = memfs.MkdirAll("s/p1/p2", 0755) _ = memfs.MkdirAll("t/p1", 0755) _ = memfs.MkdirAll("t/p1/p2", 0755) _ = afero.WriteFile(memfs, "s/p1/f1.txt", []byte("/s/p1/f1.txt"), 0644) _ = afero.WriteFile(memfs, "s/p1/f2.txt", []byte("/s/p1/f2.txt"), 0644) _ = afero.WriteFile(memfs, "s/p1/p2/f1.txt", []byte("/s/p1/p2/f1.txt"), 0644) _ = afero.WriteFile(memfs, "s/p1/p2/f2.txt", []byte("/s/p1/p2/f2.txt"), 0644) _ = afero.WriteFile(memfs, "t/p1/f1.txt", []byte("/t/p1/f1.txt"), 0644) _ = afero.WriteFile(memfs, "t/p1/f2.txt", []byte("/t/p1/f2.txt"), 0644) _ = afero.WriteFile(memfs, "t/p1/p2/f1.txt", []byte("/t/p1/p2/f1.txt"), 0644) _ = afero.WriteFile(memfs, "t/p1/p2/f2.txt", []byte("/t/p1/p2/f2.txt"), 0644) appFS := afero.NewReadOnlyFs(memfs) buf := newMockPrn() flt := NewFilter("", "") c := NewCopier(appFS, buf, false) // Act c.CopyFileTree("s", "t", flt) // Assert bytes1, _ := afero.ReadFile(appFS, "t/p1/f1.txt") bytes2, _ := afero.ReadFile(appFS, "t/p1/f2.txt") bytes3, _ := afero.ReadFile(appFS, "t/p1/p2/f1.txt") bytes4, _ := afero.ReadFile(appFS, "t/p1/p2/f2.txt") ass.Equal("/t/p1/f1.txt", string(bytes1)) ass.Equal("/t/p1/f2.txt", string(bytes2)) ass.Equal("/t/p1/p2/f1.txt", string(bytes3)) ass.Equal("/t/p1/p2/f2.txt", string(bytes4)) ass.Equal(sys.ToValidPath(`<red>Cannot copy 's\p1\f1.txt' to 't\p1\f1.txt': operation not permitted</> <red>Cannot copy 's\p1\f2.txt' to 't\p1\f2.txt': operation not permitted</> <red>Cannot copy 's\p1\p2\f1.txt' to 't\p1\p2\f1.txt': operation not permitted</> <red>Cannot copy 's\p1\p2\f2.txt' to 't\p1\p2\f2.txt': operation not permitted</> Total copied: 0 Copy errors: 4 Present in target but not found in source: 0 `), buf.String()) } func Test_copyTreeSourcesMoreThenTargets_OnlyMathesCopiedFromSources(t *testing.T) { // Arrange ass := assert.New(t) appFS := afero.NewMemMapFs() _ = appFS.MkdirAll("s/p1", 0755) _ = appFS.MkdirAll("s/p1/p2", 0755) _ = appFS.MkdirAll("t/p1", 0755) _ = afero.WriteFile(appFS, "s/p1/f1.txt", []byte("/s/p1/f1.txt"), 0644) _ = afero.WriteFile(appFS, "s/p1/f2.txt", []byte("/s/p1/f2.txt"), 0644) _ = afero.WriteFile(appFS, "s/p1/p2/f1.txt", []byte("/s/p1/p2/f1.txt"), 0644) _ = afero.WriteFile(appFS, "s/p1/p2/f2.txt", []byte("/s/p1/p2/f2.txt"), 0644) _ = afero.WriteFile(appFS, "t/p1/f1.txt", []byte("/t/p1/f1.txt"), 0644) _ = afero.WriteFile(appFS, "t/p1/f2.txt", []byte("/t/p1/f2.txt"), 0644) buf := newMockPrn() flt := NewFilter("", "") c := NewCopier(appFS, buf, false) // Act c.CopyFileTree("s", "t", flt) // Assert bytes1, _ := afero.ReadFile(appFS, "t/p1/f1.txt") bytes2, _ := afero.ReadFile(appFS, "t/p1/f2.txt") ass.Equal("/s/p1/f1.txt", string(bytes1)) ass.Equal("/s/p1/f2.txt", string(bytes2)) _, err1 := appFS.Stat("t/p1/p2/f1.txt") _, err2 := appFS.Stat("t/p1/p2/f2.txt") ass.True(os.IsNotExist(err1)) ass.True(os.IsNotExist(err2)) ass.Equal(` Total copied: 2 Copy errors: 0 Present in target but not found in source: 0 `, buf.String()) } func Test_copyTreeTargetsContainMissingSourcesElements_OnlyFoundCopiedFromSources(t *testing.T) { // Arrange ass := assert.New(t) appFS := afero.NewMemMapFs() _ = appFS.MkdirAll("s/p1", 0755) _ = appFS.MkdirAll("t/p1", 0755) _ = afero.WriteFile(appFS, "s/p1/f1.txt", []byte("/s/p1/f1.txt"), 0644) _ = afero.WriteFile(appFS, "t/p1/f1.txt", []byte("/t/p1/f1.txt"), 0644) _ = afero.WriteFile(appFS, "t/p1/f2.txt", []byte("/t/p1/f2.txt"), 0644) buf := newMockPrn() flt := NewFilter("", "") c := NewCopier(appFS, buf, false) // Act c.CopyFileTree("s", "t", flt) // Assert bytes1, _ := afero.ReadFile(appFS, "t/p1/f1.txt") bytes2, _ := afero.ReadFile(appFS, "t/p1/f2.txt") ass.Equal("/s/p1/f1.txt", string(bytes1)) ass.Equal("/t/p1/f2.txt", string(bytes2)) ass.Equal(sys.ToValidPath(` <red>Found files that present in target but missing in source:</> <gray>\p1\f2.txt</> Total copied: 1 Copy errors: 0 Present in target but not found in source: 1 `), buf.String()) } func Test_copyTreeSourcesContainsSameNameFilesButInSubfolders_OnlyExactMatchedCopiedFromSources(t *testing.T) { // Arrange ass := assert.New(t) appFS := afero.NewMemMapFs() _ = appFS.MkdirAll("s/p1", 0755) _ = appFS.MkdirAll("s/p1/p2", 0755) _ = appFS.MkdirAll("t/p1", 0755) _ = afero.WriteFile(appFS, "s/p1/f1.txt", []byte("/s/p1/f1.txt"), 0644) _ = afero.WriteFile(appFS, "s/p1/p2/f2.txt", []byte("/s/p1/p2/f2.txt"), 0644) _ = afero.WriteFile(appFS, "t/p1/f1.txt", []byte("/t/p1/f1.txt"), 0644) _ = afero.WriteFile(appFS, "t/p1/f2.txt", []byte("/t/p1/f2.txt"), 0644) buf := newMockPrn() flt := NewFilter("", "") c := NewCopier(appFS, buf, false) // Act c.CopyFileTree("s", "t", flt) // Assert bytes1, _ := afero.ReadFile(appFS, "t/p1/f1.txt") bytes2, _ := afero.ReadFile(appFS, "t/p1/f2.txt") ass.Equal("/s/p1/f1.txt", string(bytes1)) ass.Equal("/t/p1/f2.txt", string(bytes2)) } func Test_copyTreeSourcesContainsNoMatchingFiles_NothingCopied(t *testing.T) { // Arrange ass := assert.New(t) appFS := afero.NewMemMapFs() _ = appFS.MkdirAll("s/p1", 0755) _ = appFS.MkdirAll("t/p1", 0755) _ = afero.WriteFile(appFS, "s/p1/f3.txt", []byte("/s/p1/f3.txt"), 0644) _ = afero.WriteFile(appFS, "t/p1/f1.txt", []byte("/t/p1/f1.txt"), 0644) _ = afero.WriteFile(appFS, "t/p1/f2.txt", []byte("/t/p1/f2.txt"), 0644) buf := newMockPrn() flt := NewFilter("", "") c := NewCopier(appFS, buf, false) // Act c.CopyFileTree("s", "t", flt) // Assert bytes1, _ := afero.ReadFile(appFS, "t/p1/f1.txt") bytes2, _ := afero.ReadFile(appFS, "t/p1/f2.txt") ass.Equal("/t/p1/f1.txt", string(bytes1)) ass.Equal("/t/p1/f2.txt", string(bytes2)) } func Test_copyTreeEmptySources_NothingCopied(t *testing.T) { // Arrange ass := assert.New(t) appFS := afero.NewMemMapFs() _ = appFS.MkdirAll("s/p1", 0755) _ = appFS.MkdirAll("t/p1", 0755) _ = afero.WriteFile(appFS, "t/p1/f1.txt", []byte("/t/p1/f1.txt"), 0644) _ = afero.WriteFile(appFS, "t/p1/f2.txt", []byte("/t/p1/f2.txt"), 0644) buf := newMockPrn() flt := NewFilter("", "") c := NewCopier(appFS, buf, false) // Act c.CopyFileTree("s", "t", flt) // Assert bytes1, _ := afero.ReadFile(appFS, "t/p1/f1.txt") bytes2, _ := afero.ReadFile(appFS, "t/p1/f2.txt") ass.Equal("/t/p1/f1.txt", string(bytes1)) ass.Equal("/t/p1/f2.txt", string(bytes2)) } func Test_copyTreeEmptyTargets_NothingCopied(t *testing.T) { // Arrange ass := assert.New(t) appFS := afero.NewMemMapFs() _ = appFS.MkdirAll("s/p1", 0755) _ = appFS.MkdirAll("t/p1", 0755) _ = afero.WriteFile(appFS, "s/p1/f3.txt", []byte("/s/p1/f3.txt"), 0644) buf := newMockPrn() flt := NewFilter("", "") c := NewCopier(appFS, buf, false) // Act c.CopyFileTree("s", "t", flt) // Assert items, _ := afero.ReadDir(appFS, "t/p1") ass.Equal(0, len(items)) } func Test_copyTreeDifferentCase_FilesNotCopied(t *testing.T) { // Arrange ass := assert.New(t) appFS := afero.NewMemMapFs() _ = appFS.MkdirAll("s/p1", 0755) _ = appFS.MkdirAll("t/p1", 0755) srcContent := "/s/p1/f1.txt" tgtContent := "/t/p1/F1.txt" _ = afero.WriteFile(appFS, "s/p1/f1.txt", []byte(srcContent), 0644) _ = afero.WriteFile(appFS, "t/p1/F1.txt", []byte(tgtContent), 0644) buf := newMockPrn() flt := NewFilter("", "") c := NewCopier(appFS, buf, false) // Act c.CopyFileTree("s", "t", flt) // Assert bytes1, _ := afero.ReadFile(appFS, "t/p1/F1.txt") ass.Equal(tgtContent, string(bytes1)) } func Test_copyTreeVerboseTrue_EachCopiedFileOutput(t *testing.T) { // Arrange ass := assert.New(t) appFS := afero.NewMemMapFs() _ = appFS.MkdirAll("s/p1", 0755) _ = appFS.MkdirAll("t/p1", 0755) _ = afero.WriteFile(appFS, "s/p1/f1.txt", []byte("/s/p1/f1.txt"), 0644) _ = afero.WriteFile(appFS, "t/p1/f1.txt", []byte("/t/p1/F1.txt"), 0644) buf := newMockPrn() flt := NewFilter("", "") c := NewCopier(appFS, buf, true) // Act c.CopyFileTree("s", "t", flt) // Assert ass.Equal(sys.ToValidPath(` <gray>s\p1\f1.txt</> copied to <gray>t\p1\f1.txt</> Total copied: 1 Copy errors: 0 Present in target but not found in source: 0 `), buf.String()) } func Test_copyTreeUnexistTarget_NoFilesCopied(t *testing.T) { // Arrange ass := assert.New(t) appFS := afero.NewMemMapFs() _ = appFS.MkdirAll("s/p1", 0755) _ = appFS.MkdirAll("t/p1", 0755) _ = afero.WriteFile(appFS, "s/p1/f1.txt", []byte("/s/p1/f1.txt"), 0644) _ = afero.WriteFile(appFS, "t/p1/F1.txt", []byte("/t/p1/F1.txt"), 0644) buf := newMockPrn() flt := NewFilter("", "") c := NewCopier(appFS, buf, false) // Act c.CopyFileTree("s", "t1", flt) // Assert bytes1, _ := afero.ReadFile(appFS, "t/p1/F1.txt") ass.Equal("/t/p1/F1.txt", string(bytes1)) } func Test_copyFileUnexistSource_ErrReturned(t *testing.T) { // Arrange ass := assert.New(t) appFS := afero.NewMemMapFs() _ = appFS.MkdirAll("t/p1", 0755) _ = afero.WriteFile(appFS, "t/p1/F1.txt", []byte("/t/p1/F1.txt"), 0644) // Act err := sys.CopyFile("s/p1/F1.txt", "t/p1/F1.txt", appFS) // Assert ass.NotNil(err) bytes1, _ := afero.ReadFile(appFS, "t/p1/F1.txt") ass.Equal("/t/p1/F1.txt", string(bytes1)) } func Test_copyFileSourceIsDir_ErrReturned(t *testing.T) { // Arrange ass := assert.New(t) appFS := afero.NewMemMapFs() _ = appFS.MkdirAll("t/p1", 0755) _ = afero.WriteFile(appFS, "t/p1/F1.txt", []byte("/t/p1/F1.txt"), 0644) // Act err := sys.CopyFile("t/p1", "t/p1/F1.txt", appFS) // Assert ass.NotNil(err) bytes1, _ := afero.ReadFile(appFS, "t/p1/F1.txt") ass.Equal("/t/p1/F1.txt", string(bytes1)) }
// This file was generated for SObject EventLogFile, API Version v43.0 at 2018-07-30 03:47:24.579447617 -0400 EDT m=+10.922463897 package sobjects import ( "fmt" "strings" ) type EventLogFile struct { BaseSObject ApiVersion float64 `force:",omitempty"` CreatedById string `force:",omitempty"` CreatedDate string `force:",omitempty"` EventType string `force:",omitempty"` Id string `force:",omitempty"` Interval string `force:",omitempty"` IsDeleted bool `force:",omitempty"` LastModifiedById string `force:",omitempty"` LastModifiedDate string `force:",omitempty"` LogDate string `force:",omitempty"` LogFile string `force:",omitempty"` LogFileContentType string `force:",omitempty"` LogFileFieldNames string `force:",omitempty"` LogFileFieldTypes string `force:",omitempty"` LogFileLength float64 `force:",omitempty"` Sequence int `force:",omitempty"` SystemModstamp string `force:",omitempty"` } func (t *EventLogFile) ApiName() string { return "EventLogFile" } func (t *EventLogFile) String() string { builder := strings.Builder{} builder.WriteString(fmt.Sprintf("EventLogFile #%s - %s\n", t.Id, t.Name)) builder.WriteString(fmt.Sprintf("\tApiVersion: %v\n", t.ApiVersion)) builder.WriteString(fmt.Sprintf("\tCreatedById: %v\n", t.CreatedById)) builder.WriteString(fmt.Sprintf("\tCreatedDate: %v\n", t.CreatedDate)) builder.WriteString(fmt.Sprintf("\tEventType: %v\n", t.EventType)) builder.WriteString(fmt.Sprintf("\tId: %v\n", t.Id)) builder.WriteString(fmt.Sprintf("\tInterval: %v\n", t.Interval)) builder.WriteString(fmt.Sprintf("\tIsDeleted: %v\n", t.IsDeleted)) builder.WriteString(fmt.Sprintf("\tLastModifiedById: %v\n", t.LastModifiedById)) builder.WriteString(fmt.Sprintf("\tLastModifiedDate: %v\n", t.LastModifiedDate)) builder.WriteString(fmt.Sprintf("\tLogDate: %v\n", t.LogDate)) builder.WriteString(fmt.Sprintf("\tLogFile: %v\n", t.LogFile)) builder.WriteString(fmt.Sprintf("\tLogFileContentType: %v\n", t.LogFileContentType)) builder.WriteString(fmt.Sprintf("\tLogFileFieldNames: %v\n", t.LogFileFieldNames)) builder.WriteString(fmt.Sprintf("\tLogFileFieldTypes: %v\n", t.LogFileFieldTypes)) builder.WriteString(fmt.Sprintf("\tLogFileLength: %v\n", t.LogFileLength)) builder.WriteString(fmt.Sprintf("\tSequence: %v\n", t.Sequence)) builder.WriteString(fmt.Sprintf("\tSystemModstamp: %v\n", t.SystemModstamp)) return builder.String() } type EventLogFileQueryResponse struct { BaseQuery Records []EventLogFile `json:"Records" force:"records"` }
package database import ( _ "unsafe" "context" "database/sql" . "github.com/agiledragon/gomonkey" "github.com/jmoiron/sqlx" "github.com/pkg/errors" "github.com/stretchr/testify/assert" "reflect" "testing" ) // pg_sql.(*Tx).Rollback 被内联, 无法打桩, 需要对私有方法打桩 //go:linkname rollbackFn database/pg_sql.(*Tx).rollback func rollbackFn(*sql.Tx, bool) error func TestNewTransaction(t *testing.T) { var rollback, committed bool reset := func() { rollback = false committed = false } ApplyMethod(reflect.TypeOf(&sqlx.DB{}), "Beginx", func(db *sqlx.DB) (*sqlx.Tx, error) { return &sqlx.Tx{}, nil }) txType := reflect.TypeOf(&sql.Tx{}) ApplyFunc(rollbackFn, func(tx *sql.Tx, discardConn bool) error { rollback = true return nil }) ApplyMethod(txType, "Commit", func(tx *sql.Tx) error { committed = true return nil }) ctx := context.Background() t.Run("success", func(t *testing.T) { defer reset() assert.Equal(t, nil, NewTransaction(ctx, func(ctx context.Context, tx *sqlx.Tx) error { return nil })) assert.Equal(t, false, rollback) assert.Equal(t, true, committed) }) t.Run("return error", func(t *testing.T) { defer reset() returnErr := errors.New("return error") err := NewTransaction(ctx, func(ctx context.Context, tx *sqlx.Tx) error { return errors.WithStack(returnErr) }) assert.Equal(t, true, rollback) assert.Equal(t, false, committed) assert.Equal(t, returnErr, errors.Cause(err)) }) t.Run("panic error", func(t *testing.T) { defer reset() panicErr := errors.New("panic error") assert.Equal(t, panicErr, NewTransaction(ctx, func(ctx context.Context, tx *sqlx.Tx) error { panic(panicErr) })) assert.Equal(t, true, rollback) assert.Equal(t, false, committed) }) }
/****************************************************************************** Online Go Lang Compiler. Code, Compile, Run and Debug Go Lang program online. Write your code in this editor and press "Run" button to execute it. *******************************************************************************/ package main // imported package(if not used shows error) import "fmt" // if something is declared global but not used, it will not provide error var x, y, z = 123, true, "foo" // init function is called before main and executes sequencially // we can have multiple init funciton func init() { fmt.Println("hi,", "Amar") } func main() { // use of if-else if n := 25; n%2 == 0 { fmt.Println(n, "is an even number.") } else { fmt.Println(n, "is an odd number.") } // we can keep conditional statement in () if 25<23 { println("yes") } else { println("No") } for i := 0; i < 3; i++ { fmt.Println(i) } var i = 0 for ; i < 2; { fmt.Println(i) i++ } for i < 4 { fmt.Println(i) i++ } } func init() { fmt.Println("hi,", "Kumar") }
package main import ( "bufio" "fmt" "log" "os" "regexp" "strings" ) func main() { url := "" // Get and validate package URL fmt.Print("Enter the BoneTome page URL here (https://bonetome.com/h3vr/mods/id): ") reader := bufio.NewReader(os.Stdin) line, _, _ := reader.ReadLine() url = string(line) verifyUrlFormat(url) // Populate as much metadata as possible from BoneTome page. btmd := &BoneTomeMetadata{} btmd.PopulateFromUrl(url) // Add a description field to be used in the manifest. fmt.Println() fmt.Print("Please enter a short description of the package (250 characters or fewer): ") descReader := bufio.NewReader(os.Stdin) descLine, _, _ := descReader.ReadLine() btmd.ProvideDescription(string(descLine)) // Get website_url field to be used in the manifest. fmt.Println() fmt.Print("Please enter a URL to be displayed on Thunderstore. Leave blank if none. This URL is usually a link to a GitHub repository: ") webUrlReader := bufio.NewReader(os.Stdin) webUrlLine, _, _ := webUrlReader.ReadLine() webUrl := string(webUrlLine) fmt.Println() fmt.Println(fmt.Sprintf("Downloading %s from BoneTome", btmd.Asset.Name)) pullService := &PullService{} pullService.Do(btmd) fmt.Println("Repacking files") repackager := &Repackager{} repackager.Do(pullService) if repackager.ContainsDeliFiles && !repackager.ContainsLvoFiles { repackager.ContainsLvoFiles = askBooleanQuestion("Do you require OtherLoader?") } repackager.RequiresH3VRUtilities = askBooleanQuestion("Do you require H3VRUtilities?") fmt.Println() fmt.Println("Writing Thunderstore metadata files") tsm := btmd.CreateThunderstoreManifestObject(webUrl, repackager) tsm.WriteMetadataToFolder(repackager.BuildDir, btmd) correspondingNumber := inputValidNumber() fmt.Println() switch correspondingNumber { case 1: fmt.Println(fmt.Sprintf("Place an icon.png (256x256) in the %s folder", repackager.BuildDir)) fmt.Println("Once you have done this, select all files in that folder and zip them") fmt.Println("(On Windows: Select all -> Right click -> Send to -> Compressed (zipped) folder") fmt.Println() fmt.Println("When zipped, you can upload to Thunderstore.") case 2: zipName := fmt.Sprintf("%s-%s.zip", btmd.PackageName, btmd.Version) repackager.ZipBuildContents(zipName) fmt.Println(fmt.Sprintf("The zip file [%s] can be imported into a supported Thunderstore mod manager", zipName)) } fmt.Println() } func inputValidNumber() int { fmt.Println() fmt.Println("Enter the corresponding number:") fmt.Println("(1). I'm going to upload my mod to Thunderstore.") fmt.Println("(2). I want to import a mod using a mod manager.") fmt.Print("Enter number: ") numReader := bufio.NewReader(os.Stdin) numLine, _ := numReader.ReadByte() switch string(numLine) { case "1": return 1 case "2": return 2 default: fmt.Println("The number inputted was invalid. Please select a correct number.") return inputValidNumber() } } func askBooleanQuestion(question string) bool { fmt.Println() fmt.Print(fmt.Sprintf("%s (y/n): ", question)) numReader := bufio.NewReader(os.Stdin) numLine, _ := numReader.ReadByte() switch strings.ToLower(string(numLine)) { case "y": return true case "n": return false default: fmt.Println("The input was invalid. Please try again.") return askBooleanQuestion(question) } } func verifyUrlFormat(url string) { matched, _ := regexp.MatchString("^https?://bonetome\\.com/.+\\d+/?$", url) if !matched { log.Fatal("URL is not in the specified format") } }
package handler import ( "context" "fmt" "time" "github.com/jinmukeji/jiujiantang-services/service/auth" "github.com/jinmukeji/jiujiantang-services/service/mysqldb" "github.com/golang/protobuf/ptypes" proto "github.com/jinmukeji/proto/v3/gen/micro/idl/partner/xima/core/v1" ) // GetWxmpTempQrCodeUrl 得到微信临时二维码的URL func (j *JinmuHealth) GetWxmpTempQrCodeUrl(ctx context.Context, req *proto.GetWxmpTempQrCodeUrlRequest, resp *proto.GetWxmpTempQrCodeUrlResponse) error { now := time.Now() qrcode := &mysqldb.QRCode{ CreatedAt: now, UpdatedAt: now, } qrcode, errCreateQRCode := j.datastore.CreateQRCode(ctx, qrcode) if errCreateQRCode != nil { return NewError(ErrDatabase, fmt.Errorf("failed to create qr code: %s", errCreateQRCode.Error())) } wxQrCode, err := j.wechat.GetTempQrCodeUrl(qrcode.SceneID) if err != nil { return NewError(ErrGetTempQrCodeURLFaliure, err) } account, _ := auth.AccountFromContext(ctx) machineUUID, _ := auth.MachineUUIDFromContext(ctx) updateQRCode := &mysqldb.QRCode{ SceneID: qrcode.SceneID, RawURL: wxQrCode.RawURL, Account: account, MachineUUID: machineUUID, Ticket: wxQrCode.Ticket, ExpiredAt: wxQrCode.ExpiredAt, OriginID: wxQrCode.OriID, UpdatedAt: now, } errUpdateQRCode := j.datastore.UpdateQRCode(ctx, updateQRCode) if errUpdateQRCode != nil { return NewError(ErrDatabase, fmt.Errorf("failed to update qr code: %s", errUpdateQRCode.Error())) } expiredAt, _ := ptypes.TimestampProto(wxQrCode.ExpiredAt) resp.ExpiredTime = expiredAt resp.ImageUrl = wxQrCode.ImageURL resp.RawUrl = wxQrCode.RawURL resp.SceneId = wxQrCode.SceneID return nil } // ScanQRCode 扫码二维码 func (j *JinmuHealth) ScanQRCode(ctx context.Context, req *proto.ScanQRCodeRequest, resp *proto.ScanQRCodeResponse) error { createdAt, _ := ptypes.Timestamp(req.CreatedTime) record := &mysqldb.ScannedQRCodeRecord{ SceneID: req.SceneId, CreatedAt: createdAt, UpdatedAt: time.Now().UTC(), } err := j.datastore.CreateScannedQRCodeRecord(ctx, record) if err != nil { return NewError(ErrDatabase, fmt.Errorf("failed to create scanned qr record record: %s", err.Error())) } return nil }
package main const ( UNLOCK_EMAIL_SUBJECT = "Petebot unlock code" UNLOCK_EMAIL_BODY = `Dearest Petebot user, Thank you so much for donating to {charity}. Your unlock code is {code} You can unlock your account by returning to slack and typing: @petebot unlock 123456 <--- replace that with your code Happy petebotting! Matt ` )
package leetcode import "math" /*You are given K eggs, and you have access to a building with N floors from 1 to N. Each egg is identical in function, and if an egg breaks, you cannot drop it again. You know that there exists a floor F with 0 <= F <= N such that any egg dropped at a floor higher than F will break, and any egg dropped at or below floor F will not break. Each move, you may take an egg (if you have an unbroken one) and drop it from any floor X (with 1 <= X <= N). Your goal is to know with certainty what the value of F is. What is the minimum number of moves that you need to know with certainty what F is, regardless of the initial value of F? 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/super-egg-drop 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。*/ var memo map[int]int func superEggDrop(K int, N int) int { memo = make(map[int]int) return dp(K, N) } func dp(K, N int) int { if _, ok := memo[N*100+K]; !ok { ans := 0 if N == 0 { ans = 0 } else if K == 1 { ans = N } else { lo, hi := 1, N for lo+1 < hi { x := (lo + hi) / 2 t1 := dp(K-1, x-1) t2 := dp(K, N-x) if t1 < t2 { lo = x } else if t1 > t2 { hi = x } else { lo, hi = x, x } } ans = 1 + int(math.Min(math.Max(float64(dp(K-1, lo-1)), float64(dp(K, N-lo))), math.Max(float64(dp(K-1, hi-1)), float64(dp(K, N-hi))))) } memo[N*100+K] = ans } return memo[N*100+K] }
package main import ( "fmt" "github.com/xiak/k8s/pkg/ssh" ) func main() { //command := cmd.NewDefaultClusterCommand() //if err := command.Execute(); err != nil { // fmt.Fprintf(os.Stderr, "%v\n", err) // os.Exit(1) //} s, err := ssh.NewSSHTunnel("10.xx.xx.xx", "root", "password") if err != nil { fmt.Errorf("Err: %s", err.Error()) return } err = s.Dial() if err != nil { fmt.Errorf("Err: %s", err.Error()) return } outs, _, code, err := s.RunCommond("mkdir -p /xiak && pwd") if err != nil { fmt.Printf("Err Msg: (%d) %s", code, err.Error()) } fmt.Printf("%s", outs) outs, _, code, err = s.RunCommond("cd /xiak && pwd") if err != nil { fmt.Printf("Err Msg: (%d) %s", code, err.Error()) } fmt.Printf("%s", outs) outs, _, code, err = s.RunCommond("pwd") if err != nil { fmt.Printf("Err Msg: (%d) %s", code, err.Error()) } fmt.Printf("%s", outs) s.Close() }
// Copyright 2015 PingCAP, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Copyright 2013 The ql Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSES/QL-LICENSE file. package session import ( "bytes" "context" "crypto/tls" "encoding/hex" "encoding/json" stderrs "errors" "fmt" "math" "math/rand" "runtime/pprof" "strconv" "strings" "sync" "sync/atomic" "time" "github.com/ngaut/pools" "github.com/pingcap/errors" "github.com/pingcap/failpoint" "github.com/pingcap/kvproto/pkg/kvrpcpb" "github.com/pingcap/tidb/bindinfo" "github.com/pingcap/tidb/config" "github.com/pingcap/tidb/ddl" "github.com/pingcap/tidb/ddl/placement" "github.com/pingcap/tidb/domain" "github.com/pingcap/tidb/domain/infosync" "github.com/pingcap/tidb/errno" "github.com/pingcap/tidb/executor" "github.com/pingcap/tidb/expression" "github.com/pingcap/tidb/extension" "github.com/pingcap/tidb/extension/extensionimpl" "github.com/pingcap/tidb/infoschema" "github.com/pingcap/tidb/kv" "github.com/pingcap/tidb/meta" "github.com/pingcap/tidb/metrics" "github.com/pingcap/tidb/owner" "github.com/pingcap/tidb/parser" "github.com/pingcap/tidb/parser/ast" "github.com/pingcap/tidb/parser/auth" "github.com/pingcap/tidb/parser/charset" "github.com/pingcap/tidb/parser/model" "github.com/pingcap/tidb/parser/mysql" "github.com/pingcap/tidb/parser/terror" "github.com/pingcap/tidb/planner" plannercore "github.com/pingcap/tidb/planner/core" "github.com/pingcap/tidb/plugin" "github.com/pingcap/tidb/privilege" "github.com/pingcap/tidb/privilege/conn" "github.com/pingcap/tidb/privilege/privileges" session_metrics "github.com/pingcap/tidb/session/metrics" "github.com/pingcap/tidb/session/txninfo" "github.com/pingcap/tidb/sessionctx" "github.com/pingcap/tidb/sessionctx/binloginfo" "github.com/pingcap/tidb/sessionctx/sessionstates" "github.com/pingcap/tidb/sessionctx/stmtctx" "github.com/pingcap/tidb/sessionctx/variable" "github.com/pingcap/tidb/sessiontxn" "github.com/pingcap/tidb/statistics/handle" storeerr "github.com/pingcap/tidb/store/driver/error" "github.com/pingcap/tidb/store/driver/txn" "github.com/pingcap/tidb/store/helper" "github.com/pingcap/tidb/table" "github.com/pingcap/tidb/table/temptable" "github.com/pingcap/tidb/tablecodec" "github.com/pingcap/tidb/telemetry" "github.com/pingcap/tidb/ttl/ttlworker" "github.com/pingcap/tidb/util" "github.com/pingcap/tidb/util/chunk" "github.com/pingcap/tidb/util/collate" "github.com/pingcap/tidb/util/dbterror" "github.com/pingcap/tidb/util/execdetails" "github.com/pingcap/tidb/util/intest" "github.com/pingcap/tidb/util/kvcache" "github.com/pingcap/tidb/util/logutil" "github.com/pingcap/tidb/util/logutil/consistency" "github.com/pingcap/tidb/util/mathutil" "github.com/pingcap/tidb/util/memory" "github.com/pingcap/tidb/util/sem" "github.com/pingcap/tidb/util/sli" "github.com/pingcap/tidb/util/sqlexec" "github.com/pingcap/tidb/util/syncutil" "github.com/pingcap/tidb/util/tableutil" "github.com/pingcap/tidb/util/timeutil" "github.com/pingcap/tidb/util/topsql" topsqlstate "github.com/pingcap/tidb/util/topsql/state" "github.com/pingcap/tidb/util/topsql/stmtstats" "github.com/pingcap/tidb/util/tracing" "github.com/pingcap/tipb/go-binlog" tikverr "github.com/tikv/client-go/v2/error" tikvstore "github.com/tikv/client-go/v2/kv" "github.com/tikv/client-go/v2/oracle" tikvutil "github.com/tikv/client-go/v2/util" "go.uber.org/zap" ) // Session context, it is consistent with the lifecycle of a client connection. type Session interface { sessionctx.Context Status() uint16 // Flag of current status, such as autocommit. LastInsertID() uint64 // LastInsertID is the last inserted auto_increment ID. LastMessage() string // LastMessage is the info message that may be generated by last command AffectedRows() uint64 // Affected rows by latest executed stmt. // Execute is deprecated, and only used by plugins. Use ExecuteStmt() instead. Execute(context.Context, string) ([]sqlexec.RecordSet, error) // Execute a sql statement. // ExecuteStmt executes a parsed statement. ExecuteStmt(context.Context, ast.StmtNode) (sqlexec.RecordSet, error) // Parse is deprecated, use ParseWithParams() instead. Parse(ctx context.Context, sql string) ([]ast.StmtNode, error) // ExecuteInternal is a helper around ParseWithParams() and ExecuteStmt(). It is not allowed to execute multiple statements. ExecuteInternal(context.Context, string, ...interface{}) (sqlexec.RecordSet, error) String() string // String is used to debug. CommitTxn(context.Context) error RollbackTxn(context.Context) // PrepareStmt executes prepare statement in binary protocol. PrepareStmt(sql string) (stmtID uint32, paramCount int, fields []*ast.ResultField, err error) // ExecutePreparedStmt executes a prepared statement. // Deprecated: please use ExecuteStmt, this function is left for testing only. // TODO: remove ExecutePreparedStmt. ExecutePreparedStmt(ctx context.Context, stmtID uint32, param []expression.Expression) (sqlexec.RecordSet, error) DropPreparedStmt(stmtID uint32) error // SetSessionStatesHandler sets SessionStatesHandler for type stateType. SetSessionStatesHandler(stateType sessionstates.SessionStateType, handler sessionctx.SessionStatesHandler) SetClientCapability(uint32) // Set client capability flags. SetConnectionID(uint64) SetCommandValue(byte) SetProcessInfo(string, time.Time, byte, uint64) SetTLSState(*tls.ConnectionState) SetCollation(coID int) error SetSessionManager(util.SessionManager) Close() Auth(user *auth.UserIdentity, auth, salt []byte, authConn conn.AuthConn) error AuthWithoutVerification(user *auth.UserIdentity) bool AuthPluginForUser(user *auth.UserIdentity) (string, error) MatchIdentity(username, remoteHost string) (*auth.UserIdentity, error) // Return the information of the txn current running TxnInfo() *txninfo.TxnInfo // PrepareTxnCtx is exported for test. PrepareTxnCtx(context.Context) error // FieldList returns fields list of a table. FieldList(tableName string) (fields []*ast.ResultField, err error) SetPort(port string) // set cur session operations allowed when tikv disk full happens. SetDiskFullOpt(level kvrpcpb.DiskFullOpt) GetDiskFullOpt() kvrpcpb.DiskFullOpt ClearDiskFullOpt() // SetExtensions sets the `*extension.SessionExtensions` object SetExtensions(extensions *extension.SessionExtensions) } func init() { executor.CreateSession = func(ctx sessionctx.Context) (sessionctx.Context, error) { return CreateSession(ctx.GetStore()) } executor.CloseSession = func(ctx sessionctx.Context) { if se, ok := ctx.(Session); ok { se.Close() } } } var _ Session = (*session)(nil) type stmtRecord struct { st sqlexec.Statement stmtCtx *stmtctx.StatementContext } // StmtHistory holds all histories of statements in a txn. type StmtHistory struct { history []*stmtRecord } // Add appends a stmt to history list. func (h *StmtHistory) Add(st sqlexec.Statement, stmtCtx *stmtctx.StatementContext) { s := &stmtRecord{ st: st, stmtCtx: stmtCtx, } h.history = append(h.history, s) } // Count returns the count of the history. func (h *StmtHistory) Count() int { return len(h.history) } type session struct { // processInfo is used by ShowProcess(), and should be modified atomically. processInfo atomic.Value txn LazyTxn mu struct { sync.RWMutex values map[fmt.Stringer]interface{} } currentCtx context.Context // only use for runtime.trace, Please NEVER use it. currentPlan plannercore.Plan store kv.Storage sessionPlanCache sessionctx.PlanCache sessionVars *variable.SessionVars sessionManager util.SessionManager statsCollector *handle.SessionStatsCollector // ddlOwnerManager is used in `select tidb_is_ddl_owner()` statement; ddlOwnerManager owner.Manager // lockedTables use to record the table locks hold by the session. lockedTables map[int64]model.TableLockTpInfo // client shared coprocessor client per session client kv.Client mppClient kv.MPPClient // indexUsageCollector collects index usage information. idxUsageCollector *handle.SessionIndexUsageCollector functionUsageMu struct { syncutil.RWMutex builtinFunctionUsage telemetry.BuiltinFunctionsUsage } // allowed when tikv disk full happened. diskFullOpt kvrpcpb.DiskFullOpt // StmtStats is used to count various indicators of each SQL in this session // at each point in time. These data will be periodically taken away by the // background goroutine. The background goroutine will continue to aggregate // all the local data in each session, and finally report them to the remote // regularly. stmtStats *stmtstats.StatementStats // Used to encode and decode each type of session states. sessionStatesHandlers map[sessionstates.SessionStateType]sessionctx.SessionStatesHandler // Contains a list of sessions used to collect advisory locks. advisoryLocks map[string]*advisoryLock extensions *extension.SessionExtensions sandBoxMode bool } var parserPool = &sync.Pool{New: func() interface{} { return parser.New() }} // AddTableLock adds table lock to the session lock map. func (s *session) AddTableLock(locks []model.TableLockTpInfo) { for _, l := range locks { // read only lock is session unrelated, skip it when adding lock to session. if l.Tp != model.TableLockReadOnly { s.lockedTables[l.TableID] = l } } } // ReleaseTableLocks releases table lock in the session lock map. func (s *session) ReleaseTableLocks(locks []model.TableLockTpInfo) { for _, l := range locks { delete(s.lockedTables, l.TableID) } } // ReleaseTableLockByTableIDs releases table lock in the session lock map by table ID. func (s *session) ReleaseTableLockByTableIDs(tableIDs []int64) { for _, tblID := range tableIDs { delete(s.lockedTables, tblID) } } // CheckTableLocked checks the table lock. func (s *session) CheckTableLocked(tblID int64) (bool, model.TableLockType) { lt, ok := s.lockedTables[tblID] if !ok { return false, model.TableLockNone } return true, lt.Tp } // GetAllTableLocks gets all table locks table id and db id hold by the session. func (s *session) GetAllTableLocks() []model.TableLockTpInfo { lockTpInfo := make([]model.TableLockTpInfo, 0, len(s.lockedTables)) for _, tl := range s.lockedTables { lockTpInfo = append(lockTpInfo, tl) } return lockTpInfo } // HasLockedTables uses to check whether this session locked any tables. // If so, the session can only visit the table which locked by self. func (s *session) HasLockedTables() bool { b := len(s.lockedTables) > 0 return b } // ReleaseAllTableLocks releases all table locks hold by the session. func (s *session) ReleaseAllTableLocks() { s.lockedTables = make(map[int64]model.TableLockTpInfo) } // IsDDLOwner checks whether this session is DDL owner. func (s *session) IsDDLOwner() bool { return s.ddlOwnerManager.IsOwner() } func (s *session) cleanRetryInfo() { if s.sessionVars.RetryInfo.Retrying { return } retryInfo := s.sessionVars.RetryInfo defer retryInfo.Clean() if len(retryInfo.DroppedPreparedStmtIDs) == 0 { return } planCacheEnabled := s.GetSessionVars().EnablePreparedPlanCache var cacheKey kvcache.Key var err error var preparedAst *ast.Prepared var stmtText, stmtDB string if planCacheEnabled { firstStmtID := retryInfo.DroppedPreparedStmtIDs[0] if preparedPointer, ok := s.sessionVars.PreparedStmts[firstStmtID]; ok { preparedObj, ok := preparedPointer.(*plannercore.PlanCacheStmt) if ok { preparedAst = preparedObj.PreparedAst stmtText, stmtDB = preparedObj.StmtText, preparedObj.StmtDB bindSQL, _ := plannercore.GetBindSQL4PlanCache(s, preparedObj) cacheKey, err = plannercore.NewPlanCacheKey(s.sessionVars, stmtText, stmtDB, preparedAst.SchemaVersion, 0, bindSQL, expression.ExprPushDownBlackListReloadTimeStamp.Load()) if err != nil { logutil.Logger(s.currentCtx).Warn("clean cached plan failed", zap.Error(err)) return } } } } for i, stmtID := range retryInfo.DroppedPreparedStmtIDs { if planCacheEnabled { if i > 0 && preparedAst != nil { plannercore.SetPstmtIDSchemaVersion(cacheKey, stmtText, preparedAst.SchemaVersion, s.sessionVars.IsolationReadEngines) } if !s.sessionVars.IgnorePreparedCacheCloseStmt { // keep the plan in cache s.GetSessionPlanCache().Delete(cacheKey) } } s.sessionVars.RemovePreparedStmt(stmtID) } } func (s *session) Status() uint16 { return s.sessionVars.Status } func (s *session) LastInsertID() uint64 { if s.sessionVars.StmtCtx.LastInsertID > 0 { return s.sessionVars.StmtCtx.LastInsertID } return s.sessionVars.StmtCtx.InsertID } func (s *session) LastMessage() string { return s.sessionVars.StmtCtx.GetMessage() } func (s *session) AffectedRows() uint64 { return s.sessionVars.StmtCtx.AffectedRows() } func (s *session) SetClientCapability(capability uint32) { s.sessionVars.ClientCapability = capability } func (s *session) SetConnectionID(connectionID uint64) { s.sessionVars.ConnectionID = connectionID } func (s *session) SetTLSState(tlsState *tls.ConnectionState) { // If user is not connected via TLS, then tlsState == nil. if tlsState != nil { s.sessionVars.TLSConnectionState = tlsState } } func (s *session) SetCommandValue(command byte) { atomic.StoreUint32(&s.sessionVars.CommandValue, uint32(command)) } func (s *session) SetCollation(coID int) error { cs, co, err := charset.GetCharsetInfoByID(coID) if err != nil { return err } // If new collations are enabled, switch to the default // collation if this one is not supported. co = collate.SubstituteMissingCollationToDefault(co) for _, v := range variable.SetNamesVariables { terror.Log(s.sessionVars.SetSystemVarWithoutValidation(v, cs)) } return s.sessionVars.SetSystemVarWithoutValidation(variable.CollationConnection, co) } func (s *session) GetSessionPlanCache() sessionctx.PlanCache { // use the prepared plan cache if !s.GetSessionVars().EnablePreparedPlanCache && !s.GetSessionVars().EnableNonPreparedPlanCache { return nil } if s.sessionPlanCache == nil { // lazy construction s.sessionPlanCache = plannercore.NewLRUPlanCache(uint(s.GetSessionVars().SessionPlanCacheSize), variable.PreparedPlanCacheMemoryGuardRatio.Load(), plannercore.PreparedPlanCacheMaxMemory.Load(), s, false) } return s.sessionPlanCache } func (s *session) SetSessionManager(sm util.SessionManager) { s.sessionManager = sm } func (s *session) GetSessionManager() util.SessionManager { return s.sessionManager } func (s *session) UpdateColStatsUsage(predicateColumns []model.TableItemID) { if s.statsCollector == nil { return } t := time.Now() colMap := make(map[model.TableItemID]time.Time, len(predicateColumns)) for _, col := range predicateColumns { if col.IsIndex { continue } colMap[col] = t } s.statsCollector.UpdateColStatsUsage(colMap) } // StoreIndexUsage stores index usage information in idxUsageCollector. func (s *session) StoreIndexUsage(tblID int64, idxID int64, rowsSelected int64) { if s.idxUsageCollector == nil { return } s.idxUsageCollector.Update(tblID, idxID, &handle.IndexUsageInformation{QueryCount: 1, RowsSelected: rowsSelected}) } // FieldList returns fields list of a table. func (s *session) FieldList(tableName string) ([]*ast.ResultField, error) { is := s.GetInfoSchema().(infoschema.InfoSchema) dbName := model.NewCIStr(s.GetSessionVars().CurrentDB) tName := model.NewCIStr(tableName) pm := privilege.GetPrivilegeManager(s) if pm != nil && s.sessionVars.User != nil { if !pm.RequestVerification(s.sessionVars.ActiveRoles, dbName.O, tName.O, "", mysql.AllPrivMask) { user := s.sessionVars.User u := user.Username h := user.Hostname if len(user.AuthUsername) > 0 && len(user.AuthHostname) > 0 { u = user.AuthUsername h = user.AuthHostname } return nil, plannercore.ErrTableaccessDenied.GenWithStackByArgs("SELECT", u, h, tableName) } } table, err := is.TableByName(dbName, tName) if err != nil { return nil, err } cols := table.Cols() fields := make([]*ast.ResultField, 0, len(cols)) for _, col := range table.Cols() { rf := &ast.ResultField{ ColumnAsName: col.Name, TableAsName: tName, DBName: dbName, Table: table.Meta(), Column: col.ColumnInfo, } fields = append(fields, rf) } return fields, nil } // TxnInfo returns a pointer to a *copy* of the internal TxnInfo, thus is *read only* func (s *session) TxnInfo() *txninfo.TxnInfo { s.txn.mu.RLock() // Copy on read to get a snapshot, this API shouldn't be frequently called. txnInfo := s.txn.mu.TxnInfo s.txn.mu.RUnlock() if txnInfo.StartTS == 0 { return nil } processInfo := s.ShowProcess() if processInfo == nil { return nil } txnInfo.ConnectionID = processInfo.ID txnInfo.Username = processInfo.User txnInfo.CurrentDB = processInfo.DB txnInfo.RelatedTableIDs = make(map[int64]struct{}) s.GetSessionVars().GetRelatedTableForMDL().Range(func(key, value interface{}) bool { txnInfo.RelatedTableIDs[key.(int64)] = struct{}{} return true }) return &txnInfo } func (s *session) doCommit(ctx context.Context) error { if !s.txn.Valid() { return nil } // to avoid session set overlap the txn set. if s.GetDiskFullOpt() != kvrpcpb.DiskFullOpt_NotAllowedOnFull { s.txn.SetDiskFullOpt(s.GetDiskFullOpt()) } defer func() { s.txn.changeToInvalid() s.sessionVars.SetInTxn(false) s.ClearDiskFullOpt() }() // check if the transaction is read-only if s.txn.IsReadOnly() { return nil } // check if the cluster is read-only if !s.sessionVars.InRestrictedSQL && variable.RestrictedReadOnly.Load() || variable.VarTiDBSuperReadOnly.Load() { // It is not internal SQL, and the cluster has one of RestrictedReadOnly or SuperReadOnly // We need to privilege check again: a privilege check occurred during planning, but we need // to prevent the case that a long running auto-commit statement is now trying to commit. pm := privilege.GetPrivilegeManager(s) roles := s.sessionVars.ActiveRoles if pm != nil && !pm.HasExplicitlyGrantedDynamicPrivilege(roles, "RESTRICTED_REPLICA_WRITER_ADMIN", false) { s.RollbackTxn(ctx) return plannercore.ErrSQLInReadOnlyMode } } err := s.checkPlacementPolicyBeforeCommit() if err != nil { return err } // mockCommitError and mockGetTSErrorInRetry use to test PR #8743. failpoint.Inject("mockCommitError", func(val failpoint.Value) { if val.(bool) { if _, err := failpoint.Eval("tikvclient/mockCommitErrorOpt"); err == nil { failpoint.Return(kv.ErrTxnRetryable) } } }) if s.sessionVars.BinlogClient != nil { prewriteValue := binloginfo.GetPrewriteValue(s, false) if prewriteValue != nil { prewriteData, err := prewriteValue.Marshal() if err != nil { return errors.Trace(err) } info := &binloginfo.BinlogInfo{ Data: &binlog.Binlog{ Tp: binlog.BinlogType_Prewrite, PrewriteValue: prewriteData, }, Client: s.sessionVars.BinlogClient, } s.txn.SetOption(kv.BinlogInfo, info) } } sessVars := s.GetSessionVars() // Get the related table or partition IDs. relatedPhysicalTables := sessVars.TxnCtx.TableDeltaMap // Get accessed temporary tables in the transaction. temporaryTables := sessVars.TxnCtx.TemporaryTables physicalTableIDs := make([]int64, 0, len(relatedPhysicalTables)) for id := range relatedPhysicalTables { // Schema change on global temporary tables doesn't affect transactions. if _, ok := temporaryTables[id]; ok { continue } physicalTableIDs = append(physicalTableIDs, id) } needCheckSchema := true // Set this option for 2 phase commit to validate schema lease. if s.GetSessionVars().TxnCtx != nil { needCheckSchema = !s.GetSessionVars().TxnCtx.EnableMDL } s.txn.SetOption(kv.SchemaChecker, domain.NewSchemaChecker(domain.GetDomain(s), s.GetInfoSchema().SchemaMetaVersion(), physicalTableIDs, needCheckSchema)) s.txn.SetOption(kv.InfoSchema, s.sessionVars.TxnCtx.InfoSchema) s.txn.SetOption(kv.CommitHook, func(info string, _ error) { s.sessionVars.LastTxnInfo = info }) s.txn.SetOption(kv.EnableAsyncCommit, sessVars.EnableAsyncCommit) s.txn.SetOption(kv.Enable1PC, sessVars.Enable1PC) s.txn.SetOption(kv.ResourceGroupTagger, sessVars.StmtCtx.GetResourceGroupTagger()) s.txn.SetOption(kv.ExplicitRequestSourceType, sessVars.ExplicitRequestSourceType) if sessVars.StmtCtx.KvExecCounter != nil { // Bind an interceptor for client-go to count the number of SQL executions of each TiKV. s.txn.SetOption(kv.RPCInterceptor, sessVars.StmtCtx.KvExecCounter.RPCInterceptor()) } // priority of the sysvar is lower than `start transaction with causal consistency only` if val := s.txn.GetOption(kv.GuaranteeLinearizability); val == nil || val.(bool) { // We needn't ask the TiKV client to guarantee linearizability for auto-commit transactions // because the property is naturally holds: // We guarantee the commitTS of any transaction must not exceed the next timestamp from the TSO. // An auto-commit transaction fetches its startTS from the TSO so its commitTS > its startTS > the commitTS // of any previously committed transactions. s.txn.SetOption(kv.GuaranteeLinearizability, sessVars.TxnCtx.IsExplicit && sessVars.GuaranteeLinearizability) } if tables := sessVars.TxnCtx.TemporaryTables; len(tables) > 0 { s.txn.SetOption(kv.KVFilter, temporaryTableKVFilter(tables)) } var txnSource uint64 if val := s.txn.GetOption(kv.TxnSource); val != nil { txnSource, _ = val.(uint64) } // If the transaction is started by CDC, we need to set the CDCWriteSource option. if sessVars.CDCWriteSource != 0 { err := kv.SetCDCWriteSource(&txnSource, sessVars.CDCWriteSource) if err != nil { return errors.Trace(err) } s.txn.SetOption(kv.TxnSource, txnSource) } if tables := sessVars.TxnCtx.CachedTables; len(tables) > 0 { c := cachedTableRenewLease{tables: tables} now := time.Now() err := c.start(ctx) defer c.stop(ctx) sessVars.StmtCtx.WaitLockLeaseTime += time.Since(now) if err != nil { return errors.Trace(err) } s.txn.SetOption(kv.CommitTSUpperBoundCheck, c.commitTSCheck) } err = s.commitTxnWithTemporaryData(tikvutil.SetSessionID(ctx, sessVars.ConnectionID), &s.txn) if err != nil { err = s.handleAssertionFailure(ctx, err) } return err } type cachedTableRenewLease struct { tables map[int64]interface{} lease []uint64 // Lease for each visited cached tables. exit chan struct{} } func (c *cachedTableRenewLease) start(ctx context.Context) error { c.exit = make(chan struct{}) c.lease = make([]uint64, len(c.tables)) wg := make(chan error, len(c.tables)) ith := 0 for _, raw := range c.tables { tbl := raw.(table.CachedTable) go tbl.WriteLockAndKeepAlive(ctx, c.exit, &c.lease[ith], wg) ith++ } // Wait for all LockForWrite() return, this function can return. var err error for ; ith > 0; ith-- { tmp := <-wg if tmp != nil { err = tmp } } return err } func (c *cachedTableRenewLease) stop(_ context.Context) { close(c.exit) } func (c *cachedTableRenewLease) commitTSCheck(commitTS uint64) bool { for i := 0; i < len(c.lease); i++ { lease := atomic.LoadUint64(&c.lease[i]) if commitTS >= lease { // Txn fails to commit because the write lease is expired. return false } } return true } // handleAssertionFailure extracts the possible underlying assertionFailed error, // gets the corresponding MVCC history and logs it. // If it's not an assertion failure, returns the original error. func (s *session) handleAssertionFailure(ctx context.Context, err error) error { var assertionFailure *tikverr.ErrAssertionFailed if !stderrs.As(err, &assertionFailure) { return err } key := assertionFailure.Key newErr := kv.ErrAssertionFailed.GenWithStackByArgs( hex.EncodeToString(key), assertionFailure.Assertion.String(), assertionFailure.StartTs, assertionFailure.ExistingStartTs, assertionFailure.ExistingCommitTs, ) if s.GetSessionVars().EnableRedactLog { return newErr } var decodeFunc func(kv.Key, *kvrpcpb.MvccGetByKeyResponse, map[string]interface{}) // if it's a record key or an index key, decode it if infoSchema, ok := s.sessionVars.TxnCtx.InfoSchema.(infoschema.InfoSchema); ok && infoSchema != nil && (tablecodec.IsRecordKey(key) || tablecodec.IsIndexKey(key)) { tableOrPartitionID := tablecodec.DecodeTableID(key) tbl, ok := infoSchema.TableByID(tableOrPartitionID) if !ok { tbl, _, _ = infoSchema.FindTableByPartitionID(tableOrPartitionID) } if tbl == nil { logutil.Logger(ctx).Warn("cannot find table by id", zap.Int64("tableID", tableOrPartitionID), zap.String("key", hex.EncodeToString(key))) return newErr } if tablecodec.IsRecordKey(key) { decodeFunc = consistency.DecodeRowMvccData(tbl.Meta()) } else { tableInfo := tbl.Meta() _, indexID, _, e := tablecodec.DecodeIndexKey(key) if e != nil { logutil.Logger(ctx).Error("assertion failed but cannot decode index key", zap.Error(e)) return newErr } var indexInfo *model.IndexInfo for _, idx := range tableInfo.Indices { if idx.ID == indexID { indexInfo = idx break } } if indexInfo == nil { return newErr } decodeFunc = consistency.DecodeIndexMvccData(indexInfo) } } if store, ok := s.store.(helper.Storage); ok { content := consistency.GetMvccByKey(store, key, decodeFunc) logutil.Logger(ctx).Error("assertion failed", zap.String("message", newErr.Error()), zap.String("mvcc history", content)) } return newErr } func (s *session) commitTxnWithTemporaryData(ctx context.Context, txn kv.Transaction) error { sessVars := s.sessionVars txnTempTables := sessVars.TxnCtx.TemporaryTables if len(txnTempTables) == 0 { failpoint.Inject("mockSleepBeforeTxnCommit", func(v failpoint.Value) { ms := v.(int) time.Sleep(time.Millisecond * time.Duration(ms)) }) return txn.Commit(ctx) } sessionData := sessVars.TemporaryTableData var ( stage kv.StagingHandle localTempTables *infoschema.SessionTables ) if sessVars.LocalTemporaryTables != nil { localTempTables = sessVars.LocalTemporaryTables.(*infoschema.SessionTables) } else { localTempTables = new(infoschema.SessionTables) } defer func() { // stage != kv.InvalidStagingHandle means error occurs, we need to cleanup sessionData if stage != kv.InvalidStagingHandle { sessionData.Cleanup(stage) } }() for tblID, tbl := range txnTempTables { if !tbl.GetModified() { continue } if tbl.GetMeta().TempTableType != model.TempTableLocal { continue } if _, ok := localTempTables.TableByID(tblID); !ok { continue } if stage == kv.InvalidStagingHandle { stage = sessionData.Staging() } tblPrefix := tablecodec.EncodeTablePrefix(tblID) endKey := tablecodec.EncodeTablePrefix(tblID + 1) txnMemBuffer := s.txn.GetMemBuffer() iter, err := txnMemBuffer.Iter(tblPrefix, endKey) if err != nil { return err } for iter.Valid() { key := iter.Key() if !bytes.HasPrefix(key, tblPrefix) { break } value := iter.Value() if len(value) == 0 { err = sessionData.DeleteTableKey(tblID, key) } else { err = sessionData.SetTableKey(tblID, key, iter.Value()) } if err != nil { return err } err = iter.Next() if err != nil { return err } } } err := txn.Commit(ctx) if err != nil { return err } if stage != kv.InvalidStagingHandle { sessionData.Release(stage) stage = kv.InvalidStagingHandle } return nil } type temporaryTableKVFilter map[int64]tableutil.TempTable func (m temporaryTableKVFilter) IsUnnecessaryKeyValue(key, value []byte, flags tikvstore.KeyFlags) (bool, error) { tid := tablecodec.DecodeTableID(key) if _, ok := m[tid]; ok { return true, nil } // This is the default filter for all tables. defaultFilter := txn.TiDBKVFilter{} return defaultFilter.IsUnnecessaryKeyValue(key, value, flags) } // errIsNoisy is used to filter DUPLCATE KEY errors. // These can observed by users in INFORMATION_SCHEMA.CLIENT_ERRORS_SUMMARY_GLOBAL instead. // // The rationale for filtering these errors is because they are "client generated errors". i.e. // of the errors defined in kv/error.go, these look to be clearly related to a client-inflicted issue, // and the server is only responsible for handling the error correctly. It does not need to log. func errIsNoisy(err error) bool { if kv.ErrKeyExists.Equal(err) { return true } if storeerr.ErrLockAcquireFailAndNoWaitSet.Equal(err) { return true } return false } func (s *session) doCommitWithRetry(ctx context.Context) error { defer func() { s.GetSessionVars().SetTxnIsolationLevelOneShotStateForNextTxn() s.txn.changeToInvalid() s.cleanRetryInfo() sessiontxn.GetTxnManager(s).OnTxnEnd() }() if !s.txn.Valid() { // If the transaction is invalid, maybe it has already been rolled back by the client. return nil } isInternalTxn := false if internal := s.txn.GetOption(kv.RequestSourceInternal); internal != nil && internal.(bool) { isInternalTxn = true } var err error txnSize := s.txn.Size() isPessimistic := s.txn.IsPessimistic() r, ctx := tracing.StartRegionEx(ctx, "session.doCommitWithRetry") defer r.End() err = s.doCommit(ctx) if err != nil { // polish the Write Conflict error message newErr := s.tryReplaceWriteConflictError(err) if newErr != nil { err = newErr } commitRetryLimit := s.sessionVars.RetryLimit if !s.sessionVars.TxnCtx.CouldRetry { commitRetryLimit = 0 } // Don't retry in BatchInsert mode. As a counter-example, insert into t1 select * from t2, // BatchInsert already commit the first batch 1000 rows, then it commit 1000-2000 and retry the statement, // Finally t1 will have more data than t2, with no errors return to user! if s.isTxnRetryableError(err) && !s.sessionVars.BatchInsert && commitRetryLimit > 0 && !isPessimistic { logutil.Logger(ctx).Warn("sql", zap.String("label", s.GetSQLLabel()), zap.Error(err), zap.String("txn", s.txn.GoString())) // Transactions will retry 2 ~ commitRetryLimit times. // We make larger transactions retry less times to prevent cluster resource outage. txnSizeRate := float64(txnSize) / float64(kv.TxnTotalSizeLimit.Load()) maxRetryCount := commitRetryLimit - int64(float64(commitRetryLimit-1)*txnSizeRate) err = s.retry(ctx, uint(maxRetryCount)) } else if !errIsNoisy(err) { logutil.Logger(ctx).Warn("can not retry txn", zap.String("label", s.GetSQLLabel()), zap.Error(err), zap.Bool("IsBatchInsert", s.sessionVars.BatchInsert), zap.Bool("IsPessimistic", isPessimistic), zap.Bool("InRestrictedSQL", s.sessionVars.InRestrictedSQL), zap.Int64("tidb_retry_limit", s.sessionVars.RetryLimit), zap.Bool("tidb_disable_txn_auto_retry", s.sessionVars.DisableTxnAutoRetry)) } } counter := s.sessionVars.TxnCtx.StatementCount duration := time.Since(s.GetSessionVars().TxnCtx.CreateTime).Seconds() s.recordOnTransactionExecution(err, counter, duration, isInternalTxn) if err != nil { if !errIsNoisy(err) { logutil.Logger(ctx).Warn("commit failed", zap.String("finished txn", s.txn.GoString()), zap.Error(err)) } return err } s.updateStatsDeltaToCollector() return nil } // adds more information about the table in the error message // precondition: oldErr is a 9007:WriteConflict Error func (s *session) tryReplaceWriteConflictError(oldErr error) (newErr error) { if !kv.ErrWriteConflict.Equal(oldErr) { return nil } if errors.RedactLogEnabled.Load() { return nil } originErr := errors.Cause(oldErr) inErr, _ := originErr.(*errors.Error) args := inErr.Args() is := sessiontxn.GetTxnManager(s).GetTxnInfoSchema() if is == nil { return nil } newKeyTableField, ok := addTableNameInTableIDField(args[3], is) if ok { args[3] = newKeyTableField } newPrimaryKeyTableField, ok := addTableNameInTableIDField(args[5], is) if ok { args[5] = newPrimaryKeyTableField } return kv.ErrWriteConflict.FastGenByArgs(args...) } // precondition: is != nil func addTableNameInTableIDField(tableIDField interface{}, is infoschema.InfoSchema) (enhancedMsg string, done bool) { keyTableID, ok := tableIDField.(string) if !ok { return "", false } stringsInTableIDField := strings.Split(keyTableID, "=") if len(stringsInTableIDField) == 0 { return "", false } tableIDStr := stringsInTableIDField[len(stringsInTableIDField)-1] tableID, err := strconv.ParseInt(tableIDStr, 10, 64) if err != nil { return "", false } var tableName string tbl, ok := is.TableByID(tableID) if !ok { tableName = "unknown" } else { dbInfo, ok := is.SchemaByTable(tbl.Meta()) if !ok { tableName = "unknown." + tbl.Meta().Name.String() } else { tableName = dbInfo.Name.String() + "." + tbl.Meta().Name.String() } } enhancedMsg = keyTableID + ", tableName=" + tableName return enhancedMsg, true } func (s *session) updateStatsDeltaToCollector() { mapper := s.GetSessionVars().TxnCtx.TableDeltaMap if s.statsCollector != nil && mapper != nil { for _, item := range mapper { if item.TableID > 0 { s.statsCollector.Update(item.TableID, item.Delta, item.Count, &item.ColSize) } } } } func (s *session) CommitTxn(ctx context.Context) error { r, ctx := tracing.StartRegionEx(ctx, "session.CommitTxn") defer r.End() var commitDetail *tikvutil.CommitDetails ctx = context.WithValue(ctx, tikvutil.CommitDetailCtxKey, &commitDetail) err := s.doCommitWithRetry(ctx) if commitDetail != nil { s.sessionVars.StmtCtx.MergeExecDetails(nil, commitDetail) } // record the TTLInsertRows in the metric metrics.TTLInsertRowsCount.Add(float64(s.sessionVars.TxnCtx.InsertTTLRowsCount)) failpoint.Inject("keepHistory", func(val failpoint.Value) { if val.(bool) { failpoint.Return(err) } }) s.sessionVars.TxnCtx.Cleanup() s.sessionVars.CleanupTxnReadTSIfUsed() return err } func (s *session) RollbackTxn(ctx context.Context) { r, ctx := tracing.StartRegionEx(ctx, "session.RollbackTxn") defer r.End() if s.txn.Valid() { terror.Log(s.txn.Rollback()) } if ctx.Value(inCloseSession{}) == nil { s.cleanRetryInfo() } s.txn.changeToInvalid() s.sessionVars.TxnCtx.Cleanup() s.sessionVars.CleanupTxnReadTSIfUsed() s.sessionVars.SetInTxn(false) sessiontxn.GetTxnManager(s).OnTxnEnd() } func (s *session) GetClient() kv.Client { return s.client } func (s *session) GetMPPClient() kv.MPPClient { return s.mppClient } func (s *session) String() string { // TODO: how to print binded context in values appropriately? sessVars := s.sessionVars data := map[string]interface{}{ "id": sessVars.ConnectionID, "user": sessVars.User, "currDBName": sessVars.CurrentDB, "status": sessVars.Status, "strictMode": sessVars.StrictSQLMode, } if s.txn.Valid() { // if txn is committed or rolled back, txn is nil. data["txn"] = s.txn.String() } if sessVars.SnapshotTS != 0 { data["snapshotTS"] = sessVars.SnapshotTS } if sessVars.StmtCtx.LastInsertID > 0 { data["lastInsertID"] = sessVars.StmtCtx.LastInsertID } if len(sessVars.PreparedStmts) > 0 { data["preparedStmtCount"] = len(sessVars.PreparedStmts) } b, err := json.MarshalIndent(data, "", " ") terror.Log(errors.Trace(err)) return string(b) } const sqlLogMaxLen = 1024 // SchemaChangedWithoutRetry is used for testing. var SchemaChangedWithoutRetry uint32 func (s *session) GetSQLLabel() string { if s.sessionVars.InRestrictedSQL { return metrics.LblInternal } return metrics.LblGeneral } func (s *session) isInternal() bool { return s.sessionVars.InRestrictedSQL } func (*session) isTxnRetryableError(err error) bool { if atomic.LoadUint32(&SchemaChangedWithoutRetry) == 1 { return kv.IsTxnRetryableError(err) } return kv.IsTxnRetryableError(err) || domain.ErrInfoSchemaChanged.Equal(err) } func (s *session) checkTxnAborted(stmt sqlexec.Statement) error { var err error if atomic.LoadUint32(&s.GetSessionVars().TxnCtx.LockExpire) == 0 { return nil } err = kv.ErrLockExpire // If the transaction is aborted, the following statements do not need to execute, except `commit` and `rollback`, // because they are used to finish the aborted transaction. if _, ok := stmt.(*executor.ExecStmt).StmtNode.(*ast.CommitStmt); ok { return nil } if _, ok := stmt.(*executor.ExecStmt).StmtNode.(*ast.RollbackStmt); ok { return nil } return err } func (s *session) retry(ctx context.Context, maxCnt uint) (err error) { var retryCnt uint defer func() { s.sessionVars.RetryInfo.Retrying = false // retryCnt only increments on retryable error, so +1 here. if s.sessionVars.InRestrictedSQL { session_metrics.TransactionRetryInternal.Observe(float64(retryCnt + 1)) } else { session_metrics.TransactionRetryGeneral.Observe(float64(retryCnt + 1)) } s.sessionVars.SetInTxn(false) if err != nil { s.RollbackTxn(ctx) } s.txn.changeToInvalid() }() connID := s.sessionVars.ConnectionID s.sessionVars.RetryInfo.Retrying = true if atomic.LoadUint32(&s.sessionVars.TxnCtx.ForUpdate) == 1 { err = ErrForUpdateCantRetry.GenWithStackByArgs(connID) return err } nh := GetHistory(s) var schemaVersion int64 sessVars := s.GetSessionVars() orgStartTS := sessVars.TxnCtx.StartTS label := s.GetSQLLabel() for { if err = s.PrepareTxnCtx(ctx); err != nil { return err } s.sessionVars.RetryInfo.ResetOffset() for i, sr := range nh.history { st := sr.st s.sessionVars.StmtCtx = sr.stmtCtx s.sessionVars.StmtCtx.ResetForRetry() s.sessionVars.PlanCacheParams.Reset() schemaVersion, err = st.RebuildPlan(ctx) if err != nil { return err } if retryCnt == 0 { // We do not have to log the query every time. // We print the queries at the first try only. sql := sqlForLog(st.GetTextToLog(false)) if !sessVars.EnableRedactLog { sql += sessVars.PlanCacheParams.String() } logutil.Logger(ctx).Warn("retrying", zap.Int64("schemaVersion", schemaVersion), zap.Uint("retryCnt", retryCnt), zap.Int("queryNum", i), zap.String("sql", sql)) } else { logutil.Logger(ctx).Warn("retrying", zap.Int64("schemaVersion", schemaVersion), zap.Uint("retryCnt", retryCnt), zap.Int("queryNum", i)) } _, digest := s.sessionVars.StmtCtx.SQLDigest() s.txn.onStmtStart(digest.String()) if err = sessiontxn.GetTxnManager(s).OnStmtStart(ctx, st.GetStmtNode()); err == nil { _, err = st.Exec(ctx) } s.txn.onStmtEnd() if err != nil { s.StmtRollback(ctx, false) break } s.StmtCommit(ctx) } logutil.Logger(ctx).Warn("transaction association", zap.Uint64("retrying txnStartTS", s.GetSessionVars().TxnCtx.StartTS), zap.Uint64("original txnStartTS", orgStartTS)) failpoint.Inject("preCommitHook", func() { hook, ok := ctx.Value("__preCommitHook").(func()) if ok { hook() } }) if err == nil { err = s.doCommit(ctx) if err == nil { break } } if !s.isTxnRetryableError(err) { logutil.Logger(ctx).Warn("sql", zap.String("label", label), zap.Stringer("session", s), zap.Error(err)) metrics.SessionRetryErrorCounter.WithLabelValues(label, metrics.LblUnretryable).Inc() return err } retryCnt++ if retryCnt >= maxCnt { logutil.Logger(ctx).Warn("sql", zap.String("label", label), zap.Uint("retry reached max count", retryCnt)) metrics.SessionRetryErrorCounter.WithLabelValues(label, metrics.LblReachMax).Inc() return err } logutil.Logger(ctx).Warn("sql", zap.String("label", label), zap.Error(err), zap.String("txn", s.txn.GoString())) kv.BackOff(retryCnt) s.txn.changeToInvalid() s.sessionVars.SetInTxn(false) } return err } func sqlForLog(sql string) string { if len(sql) > sqlLogMaxLen { sql = sql[:sqlLogMaxLen] + fmt.Sprintf("(len:%d)", len(sql)) } return executor.QueryReplacer.Replace(sql) } type sessionPool interface { Get() (pools.Resource, error) Put(pools.Resource) } func (s *session) sysSessionPool() sessionPool { return domain.GetDomain(s).SysSessionPool() } func createSessionFunc(store kv.Storage) pools.Factory { return func() (pools.Resource, error) { se, err := createSession(store) if err != nil { return nil, err } err = se.sessionVars.SetSystemVar(variable.AutoCommit, "1") if err != nil { return nil, err } err = se.sessionVars.SetSystemVar(variable.MaxExecutionTime, "0") if err != nil { return nil, errors.Trace(err) } err = se.sessionVars.SetSystemVar(variable.MaxAllowedPacket, strconv.FormatUint(variable.DefMaxAllowedPacket, 10)) if err != nil { return nil, errors.Trace(err) } err = se.sessionVars.SetSystemVar(variable.TiDBEnableWindowFunction, variable.BoolToOnOff(variable.DefEnableWindowFunction)) if err != nil { return nil, errors.Trace(err) } err = se.sessionVars.SetSystemVar(variable.TiDBConstraintCheckInPlacePessimistic, variable.On) if err != nil { return nil, errors.Trace(err) } se.sessionVars.CommonGlobalLoaded = true se.sessionVars.InRestrictedSQL = true // Internal session uses default format to prevent memory leak problem. se.sessionVars.EnableChunkRPC = false return se, nil } } func createSessionWithDomainFunc(store kv.Storage) func(*domain.Domain) (pools.Resource, error) { return func(dom *domain.Domain) (pools.Resource, error) { se, err := CreateSessionWithDomain(store, dom) if err != nil { return nil, err } err = se.sessionVars.SetSystemVar(variable.AutoCommit, "1") if err != nil { return nil, err } err = se.sessionVars.SetSystemVar(variable.MaxExecutionTime, "0") if err != nil { return nil, errors.Trace(err) } err = se.sessionVars.SetSystemVar(variable.MaxAllowedPacket, strconv.FormatUint(variable.DefMaxAllowedPacket, 10)) if err != nil { return nil, errors.Trace(err) } err = se.sessionVars.SetSystemVar(variable.TiDBConstraintCheckInPlacePessimistic, variable.On) if err != nil { return nil, errors.Trace(err) } se.sessionVars.CommonGlobalLoaded = true se.sessionVars.InRestrictedSQL = true // Internal session uses default format to prevent memory leak problem. se.sessionVars.EnableChunkRPC = false return se, nil } } func drainRecordSet(ctx context.Context, se *session, rs sqlexec.RecordSet, alloc chunk.Allocator) ([]chunk.Row, error) { var rows []chunk.Row var req *chunk.Chunk req = rs.NewChunk(alloc) for { err := rs.Next(ctx, req) if err != nil || req.NumRows() == 0 { return rows, err } iter := chunk.NewIterator4Chunk(req) for r := iter.Begin(); r != iter.End(); r = iter.Next() { rows = append(rows, r) } req = chunk.Renew(req, se.sessionVars.MaxChunkSize) } } // getTableValue executes restricted sql and the result is one column. // It returns a string value. func (s *session) getTableValue(ctx context.Context, tblName string, varName string) (string, error) { if ctx.Value(kv.RequestSourceKey) == nil { ctx = kv.WithInternalSourceType(ctx, kv.InternalTxnSysVar) } rows, fields, err := s.ExecRestrictedSQL(ctx, nil, "SELECT VARIABLE_VALUE FROM %n.%n WHERE VARIABLE_NAME=%?", mysql.SystemDB, tblName, varName) if err != nil { return "", err } if len(rows) == 0 { return "", errResultIsEmpty } d := rows[0].GetDatum(0, &fields[0].Column.FieldType) value, err := d.ToString() if err != nil { return "", err } return value, nil } // replaceGlobalVariablesTableValue executes restricted sql updates the variable value // It will then notify the etcd channel that the value has changed. func (s *session) replaceGlobalVariablesTableValue(ctx context.Context, varName, val string, updateLocal bool) error { ctx = kv.WithInternalSourceType(ctx, kv.InternalTxnSysVar) _, _, err := s.ExecRestrictedSQL(ctx, nil, `REPLACE INTO %n.%n (variable_name, variable_value) VALUES (%?, %?)`, mysql.SystemDB, mysql.GlobalVariablesTable, varName, val) if err != nil { return err } domain.GetDomain(s).NotifyUpdateSysVarCache(updateLocal) return err } // GetGlobalSysVar implements GlobalVarAccessor.GetGlobalSysVar interface. func (s *session) GetGlobalSysVar(name string) (string, error) { if s.Value(sessionctx.Initing) != nil { // When running bootstrap or upgrade, we should not access global storage. return "", nil } sv := variable.GetSysVar(name) if sv == nil { // It might be a recently unregistered sysvar. We should return unknown // since GetSysVar is the canonical version, but we can update the cache // so the next request doesn't attempt to load this. logutil.BgLogger().Info("sysvar does not exist. sysvar cache may be stale", zap.String("name", name)) return "", variable.ErrUnknownSystemVar.GenWithStackByArgs(name) } sysVar, err := domain.GetDomain(s).GetGlobalVar(name) if err != nil { // The sysvar exists, but there is no cache entry yet. // This might be because the sysvar was only recently registered. // In which case it is safe to return the default, but we can also // update the cache for the future. logutil.BgLogger().Info("sysvar not in cache yet. sysvar cache may be stale", zap.String("name", name)) sysVar, err = s.getTableValue(context.TODO(), mysql.GlobalVariablesTable, name) if err != nil { return sv.Value, nil } } // It might have been written from an earlier TiDB version, so we should do type validation // See https://github.com/pingcap/tidb/issues/30255 for why we don't do full validation. // If validation fails, we should return the default value: // See: https://github.com/pingcap/tidb/pull/31566 sysVar, err = sv.ValidateFromType(s.GetSessionVars(), sysVar, variable.ScopeGlobal) if err != nil { return sv.Value, nil } return sysVar, nil } // SetGlobalSysVar implements GlobalVarAccessor.SetGlobalSysVar interface. // it is called (but skipped) when setting instance scope func (s *session) SetGlobalSysVar(ctx context.Context, name string, value string) (err error) { sv := variable.GetSysVar(name) if sv == nil { return variable.ErrUnknownSystemVar.GenWithStackByArgs(name) } if value, err = sv.Validate(s.sessionVars, value, variable.ScopeGlobal); err != nil { return err } if err = sv.SetGlobalFromHook(ctx, s.sessionVars, value, false); err != nil { return err } if sv.HasInstanceScope() { // skip for INSTANCE scope return nil } if sv.GlobalConfigName != "" { domain.GetDomain(s).NotifyGlobalConfigChange(sv.GlobalConfigName, variable.OnOffToTrueFalse(value)) } return s.replaceGlobalVariablesTableValue(context.TODO(), sv.Name, value, true) } // SetGlobalSysVarOnly updates the sysvar, but does not call the validation function or update aliases. // This is helpful to prevent duplicate warnings being appended from aliases, or recursion. // updateLocal indicates whether to rebuild the local SysVar Cache. This is helpful to prevent recursion. func (s *session) SetGlobalSysVarOnly(ctx context.Context, name string, value string, updateLocal bool) (err error) { sv := variable.GetSysVar(name) if sv == nil { return variable.ErrUnknownSystemVar.GenWithStackByArgs(name) } if err = sv.SetGlobalFromHook(ctx, s.sessionVars, value, true); err != nil { return err } if sv.HasInstanceScope() { // skip for INSTANCE scope return nil } return s.replaceGlobalVariablesTableValue(ctx, sv.Name, value, updateLocal) } // SetTiDBTableValue implements GlobalVarAccessor.SetTiDBTableValue interface. func (s *session) SetTiDBTableValue(name, value, comment string) error { ctx := kv.WithInternalSourceType(context.Background(), kv.InternalTxnSysVar) _, _, err := s.ExecRestrictedSQL(ctx, nil, `REPLACE INTO mysql.tidb (variable_name, variable_value, comment) VALUES (%?, %?, %?)`, name, value, comment) return err } // GetTiDBTableValue implements GlobalVarAccessor.GetTiDBTableValue interface. func (s *session) GetTiDBTableValue(name string) (string, error) { return s.getTableValue(context.TODO(), mysql.TiDBTable, name) } var _ sqlexec.SQLParser = &session{} func (s *session) ParseSQL(ctx context.Context, sql string, params ...parser.ParseParam) ([]ast.StmtNode, []error, error) { defer tracing.StartRegion(ctx, "ParseSQL").End() p := parserPool.Get().(*parser.Parser) defer parserPool.Put(p) sqlMode := s.sessionVars.SQLMode if s.isInternal() { sqlMode = mysql.DelSQLMode(sqlMode, mysql.ModeNoBackslashEscapes) } p.SetSQLMode(sqlMode) p.SetParserConfig(s.sessionVars.BuildParserConfig()) tmp, warn, err := p.ParseSQL(sql, params...) // The []ast.StmtNode is referenced by the parser, to reuse the parser, make a copy of the result. res := make([]ast.StmtNode, len(tmp)) copy(res, tmp) return res, warn, err } func (s *session) SetProcessInfo(sql string, t time.Time, command byte, maxExecutionTime uint64) { // If command == mysql.ComSleep, it means the SQL execution is finished. The processinfo is reset to SLEEP. // If the SQL finished and the session is not in transaction, the current start timestamp need to reset to 0. // Otherwise, it should be set to the transaction start timestamp. // Why not reset the transaction start timestamp to 0 when transaction committed? // Because the select statement and other statements need this timestamp to read data, // after the transaction is committed. e.g. SHOW MASTER STATUS; var curTxnStartTS uint64 var curTxnCreateTime time.Time if command != mysql.ComSleep || s.GetSessionVars().InTxn() { curTxnStartTS = s.sessionVars.TxnCtx.StartTS curTxnCreateTime = s.sessionVars.TxnCtx.CreateTime } // Set curTxnStartTS to SnapshotTS directly when the session is trying to historic read. // It will avoid the session meet GC lifetime too short error. if s.GetSessionVars().SnapshotTS != 0 { curTxnStartTS = s.GetSessionVars().SnapshotTS } p := s.currentPlan if explain, ok := p.(*plannercore.Explain); ok && explain.Analyze && explain.TargetPlan != nil { p = explain.TargetPlan } pi := util.ProcessInfo{ ID: s.sessionVars.ConnectionID, Port: s.sessionVars.Port, DB: s.sessionVars.CurrentDB, Command: command, Plan: p, PlanExplainRows: plannercore.GetExplainRowsForPlan(p), RuntimeStatsColl: s.sessionVars.StmtCtx.RuntimeStatsColl, Time: t, State: s.Status(), Info: sql, CurTxnStartTS: curTxnStartTS, CurTxnCreateTime: curTxnCreateTime, StmtCtx: s.sessionVars.StmtCtx, RefCountOfStmtCtx: &s.sessionVars.RefCountOfStmtCtx, MemTracker: s.sessionVars.MemTracker, DiskTracker: s.sessionVars.DiskTracker, StatsInfo: plannercore.GetStatsInfo, OOMAlarmVariablesInfo: s.getOomAlarmVariablesInfo(), TableIDs: s.sessionVars.StmtCtx.TableIDs, IndexNames: s.sessionVars.StmtCtx.IndexNames, MaxExecutionTime: maxExecutionTime, RedactSQL: s.sessionVars.EnableRedactLog, ResourceGroupName: s.sessionVars.ResourceGroupName, } oldPi := s.ShowProcess() if p == nil { // Store the last valid plan when the current plan is nil. // This is for `explain for connection` statement has the ability to query the last valid plan. if oldPi != nil && oldPi.Plan != nil && len(oldPi.PlanExplainRows) > 0 { pi.Plan = oldPi.Plan pi.PlanExplainRows = oldPi.PlanExplainRows pi.RuntimeStatsColl = oldPi.RuntimeStatsColl } } // We set process info before building plan, so we extended execution time. if oldPi != nil && oldPi.Info == pi.Info && oldPi.Command == pi.Command { pi.Time = oldPi.Time } if oldPi != nil && oldPi.CurTxnStartTS != 0 && oldPi.CurTxnStartTS == pi.CurTxnStartTS { // Keep the last expensive txn log time, avoid print too many expensive txn logs. pi.ExpensiveTxnLogTime = oldPi.ExpensiveTxnLogTime } _, digest := s.sessionVars.StmtCtx.SQLDigest() pi.Digest = digest.String() // DO NOT reset the currentPlan to nil until this query finishes execution, otherwise reentrant calls // of SetProcessInfo would override Plan and PlanExplainRows to nil. if command == mysql.ComSleep { s.currentPlan = nil } if s.sessionVars.User != nil { pi.User = s.sessionVars.User.Username pi.Host = s.sessionVars.User.Hostname } s.processInfo.Store(&pi) } // UpdateProcessInfo updates the session's process info for the running statement. func (s *session) UpdateProcessInfo() { pi := s.ShowProcess() if pi == nil || pi.CurTxnStartTS != 0 { return } // Update the current transaction start timestamp. pi.CurTxnStartTS = s.sessionVars.TxnCtx.StartTS pi.CurTxnCreateTime = s.sessionVars.TxnCtx.CreateTime } func (s *session) getOomAlarmVariablesInfo() util.OOMAlarmVariablesInfo { return util.OOMAlarmVariablesInfo{ SessionAnalyzeVersion: s.sessionVars.AnalyzeVersion, SessionEnabledRateLimitAction: s.sessionVars.EnabledRateLimitAction, SessionMemQuotaQuery: s.sessionVars.MemQuotaQuery, } } func (s *session) SetDiskFullOpt(level kvrpcpb.DiskFullOpt) { s.diskFullOpt = level } func (s *session) GetDiskFullOpt() kvrpcpb.DiskFullOpt { return s.diskFullOpt } func (s *session) ClearDiskFullOpt() { s.diskFullOpt = kvrpcpb.DiskFullOpt_NotAllowedOnFull } func (s *session) ExecuteInternal(ctx context.Context, sql string, args ...interface{}) (rs sqlexec.RecordSet, err error) { origin := s.sessionVars.InRestrictedSQL s.sessionVars.InRestrictedSQL = true defer func() { s.sessionVars.InRestrictedSQL = origin // Restore the goroutine label by using the original ctx after execution is finished. pprof.SetGoroutineLabels(ctx) }() r, ctx := tracing.StartRegionEx(ctx, "session.ExecuteInternal") defer r.End() logutil.Eventf(ctx, "execute: %s", sql) stmtNode, err := s.ParseWithParams(ctx, sql, args...) if err != nil { return nil, err } rs, err = s.ExecuteStmt(ctx, stmtNode) if err != nil { s.sessionVars.StmtCtx.AppendError(err) } if rs == nil { return nil, err } return rs, err } // Execute is deprecated, we can remove it as soon as plugins are migrated. func (s *session) Execute(ctx context.Context, sql string) (recordSets []sqlexec.RecordSet, err error) { r, ctx := tracing.StartRegionEx(ctx, "session.Execute") defer r.End() logutil.Eventf(ctx, "execute: %s", sql) stmtNodes, err := s.Parse(ctx, sql) if err != nil { return nil, err } if len(stmtNodes) != 1 { return nil, errors.New("Execute() API doesn't support multiple statements any more") } rs, err := s.ExecuteStmt(ctx, stmtNodes[0]) if err != nil { s.sessionVars.StmtCtx.AppendError(err) } if rs == nil { return nil, err } return []sqlexec.RecordSet{rs}, err } // Parse parses a query string to raw ast.StmtNode. func (s *session) Parse(ctx context.Context, sql string) ([]ast.StmtNode, error) { parseStartTime := time.Now() stmts, warns, err := s.ParseSQL(ctx, sql, s.sessionVars.GetParseParams()...) if err != nil { s.rollbackOnError(ctx) err = util.SyntaxError(err) // Only print log message when this SQL is from the user. // Mute the warning for internal SQLs. if !s.sessionVars.InRestrictedSQL { if s.sessionVars.EnableRedactLog { logutil.Logger(ctx).Debug("parse SQL failed", zap.Error(err), zap.String("SQL", sql)) } else { logutil.Logger(ctx).Warn("parse SQL failed", zap.Error(err), zap.String("SQL", sql)) } s.sessionVars.StmtCtx.AppendError(err) } return nil, err } durParse := time.Since(parseStartTime) s.GetSessionVars().DurationParse = durParse isInternal := s.isInternal() if isInternal { session_metrics.SessionExecuteParseDurationInternal.Observe(durParse.Seconds()) } else { session_metrics.SessionExecuteParseDurationGeneral.Observe(durParse.Seconds()) } for _, warn := range warns { s.sessionVars.StmtCtx.AppendWarning(util.SyntaxWarn(warn)) } return stmts, nil } // ParseWithParams parses a query string, with arguments, to raw ast.StmtNode. // Note that it will not do escaping if no variable arguments are passed. func (s *session) ParseWithParams(ctx context.Context, sql string, args ...interface{}) (ast.StmtNode, error) { var err error if len(args) > 0 { sql, err = sqlexec.EscapeSQL(sql, args...) if err != nil { return nil, err } } internal := s.isInternal() var stmts []ast.StmtNode var warns []error parseStartTime := time.Now() if internal { // Do no respect the settings from clients, if it is for internal usage. // Charsets from clients may give chance injections. // Refer to https://stackoverflow.com/questions/5741187/sql-injection-that-gets-around-mysql-real-escape-string/12118602. stmts, warns, err = s.ParseSQL(ctx, sql) } else { stmts, warns, err = s.ParseSQL(ctx, sql, s.sessionVars.GetParseParams()...) } if len(stmts) != 1 && err == nil { err = errors.New("run multiple statements internally is not supported") } if err != nil { s.rollbackOnError(ctx) logSQL := sql[:mathutil.Min(500, len(sql))] if s.sessionVars.EnableRedactLog { logutil.Logger(ctx).Debug("parse SQL failed", zap.Error(err), zap.String("SQL", logSQL)) } else { logutil.Logger(ctx).Warn("parse SQL failed", zap.Error(err), zap.String("SQL", logSQL)) } return nil, util.SyntaxError(err) } durParse := time.Since(parseStartTime) if internal { session_metrics.SessionExecuteParseDurationInternal.Observe(durParse.Seconds()) } else { session_metrics.SessionExecuteParseDurationGeneral.Observe(durParse.Seconds()) } for _, warn := range warns { s.sessionVars.StmtCtx.AppendWarning(util.SyntaxWarn(warn)) } if topsqlstate.TopSQLEnabled() { normalized, digest := parser.NormalizeDigest(sql) if digest != nil { // Reset the goroutine label when internal sql execute finish. // Specifically reset in ExecRestrictedStmt function. s.sessionVars.StmtCtx.IsSQLRegistered.Store(true) topsql.AttachAndRegisterSQLInfo(ctx, normalized, digest, s.sessionVars.InRestrictedSQL) } } return stmts[0], nil } // GetAdvisoryLock acquires an advisory lock of lockName. // Note that a lock can be acquired multiple times by the same session, // in which case we increment a reference count. // Each lock needs to be held in a unique session because // we need to be able to ROLLBACK in any arbitrary order // in order to release the locks. func (s *session) GetAdvisoryLock(lockName string, timeout int64) error { if lock, ok := s.advisoryLocks[lockName]; ok { lock.IncrReferences() return nil } sess, err := createSession(s.store) if err != nil { return err } infosync.StoreInternalSession(sess) lock := &advisoryLock{session: sess, ctx: context.TODO(), owner: s.ShowProcess().ID} err = lock.GetLock(lockName, timeout) if err != nil { return err } s.advisoryLocks[lockName] = lock return nil } // IsUsedAdvisoryLock checks if a lockName is already in use func (s *session) IsUsedAdvisoryLock(lockName string) uint64 { // Same session if lock, ok := s.advisoryLocks[lockName]; ok { return lock.owner } // Check for transaction on advisory_locks table sess, err := createSession(s.store) if err != nil { return 0 } lock := &advisoryLock{session: sess, ctx: context.TODO(), owner: s.ShowProcess().ID} err = lock.IsUsedLock(lockName) if err != nil { // TODO: Return actual owner pid // TODO: Check for mysql.ErrLockWaitTimeout and DeadLock return 1 } return 0 } // ReleaseAdvisoryLock releases an advisory locks held by the session. // It returns FALSE if no lock by this name was held (by this session), // and TRUE if a lock was held and "released". // Note that the lock is not actually released if there are multiple // references to the same lockName by the session, instead the reference // count is decremented. func (s *session) ReleaseAdvisoryLock(lockName string) (released bool) { if lock, ok := s.advisoryLocks[lockName]; ok { lock.DecrReferences() if lock.ReferenceCount() <= 0 { lock.Close() delete(s.advisoryLocks, lockName) infosync.DeleteInternalSession(lock.session) } return true } return false } // ReleaseAllAdvisoryLocks releases all advisory locks held by the session // and returns a count of the locks that were released. // The count is based on unique locks held, so multiple references // to the same lock do not need to be accounted for. func (s *session) ReleaseAllAdvisoryLocks() int { var count int for lockName, lock := range s.advisoryLocks { lock.Close() count += lock.ReferenceCount() delete(s.advisoryLocks, lockName) infosync.DeleteInternalSession(lock.session) } return count } // GetExtensions returns the `*extension.SessionExtensions` object func (s *session) GetExtensions() *extension.SessionExtensions { return s.extensions } // SetExtensions sets the `*extension.SessionExtensions` object func (s *session) SetExtensions(extensions *extension.SessionExtensions) { s.extensions = extensions } // InSandBoxMode indicates that this session is in sandbox mode func (s *session) InSandBoxMode() bool { return s.sandBoxMode } // EnableSandBoxMode enable the sandbox mode. func (s *session) EnableSandBoxMode() { s.sandBoxMode = true } // DisableSandBoxMode enable the sandbox mode. func (s *session) DisableSandBoxMode() { s.sandBoxMode = false } // ParseWithParams4Test wrapper (s *session) ParseWithParams for test func ParseWithParams4Test(ctx context.Context, s Session, sql string, args ...interface{}) (ast.StmtNode, error) { return s.(*session).ParseWithParams(ctx, sql, args) } var _ sqlexec.RestrictedSQLExecutor = &session{} var _ sqlexec.SQLExecutor = &session{} // ExecRestrictedStmt implements RestrictedSQLExecutor interface. func (s *session) ExecRestrictedStmt(ctx context.Context, stmtNode ast.StmtNode, opts ...sqlexec.OptionFuncAlias) ( []chunk.Row, []*ast.ResultField, error) { defer pprof.SetGoroutineLabels(ctx) execOption := sqlexec.GetExecOption(opts) var se *session var clean func() var err error if execOption.UseCurSession { se, clean, err = s.useCurrentSession(execOption) } else { se, clean, err = s.getInternalSession(execOption) } if err != nil { return nil, nil, err } defer clean() startTime := time.Now() metrics.SessionRestrictedSQLCounter.Inc() ctx = context.WithValue(ctx, execdetails.StmtExecDetailKey, &execdetails.StmtExecDetails{}) ctx = context.WithValue(ctx, tikvutil.ExecDetailsKey, &tikvutil.ExecDetails{}) rs, err := se.ExecuteStmt(ctx, stmtNode) if err != nil { se.sessionVars.StmtCtx.AppendError(err) } if rs == nil { return nil, nil, err } defer func() { if closeErr := rs.Close(); closeErr != nil { err = closeErr } }() var rows []chunk.Row rows, err = drainRecordSet(ctx, se, rs, nil) if err != nil { return nil, nil, err } vars := se.GetSessionVars() for _, dbName := range GetDBNames(vars) { metrics.QueryDurationHistogram.WithLabelValues(metrics.LblInternal, dbName, vars.ResourceGroupName).Observe(time.Since(startTime).Seconds()) } return rows, rs.Fields(), err } // ExecRestrictedStmt4Test wrapper `(s *session) ExecRestrictedStmt` for test. func ExecRestrictedStmt4Test(ctx context.Context, s Session, stmtNode ast.StmtNode, opts ...sqlexec.OptionFuncAlias) ( []chunk.Row, []*ast.ResultField, error) { ctx = kv.WithInternalSourceType(ctx, kv.InternalTxnOthers) return s.(*session).ExecRestrictedStmt(ctx, stmtNode, opts...) } // only set and clean session with execOption func (s *session) useCurrentSession(execOption sqlexec.ExecOption) (*session, func(), error) { var err error orgSnapshotInfoSchema, orgSnapshotTS := s.sessionVars.SnapshotInfoschema, s.sessionVars.SnapshotTS if execOption.SnapshotTS != 0 { if err = s.sessionVars.SetSystemVar(variable.TiDBSnapshot, strconv.FormatUint(execOption.SnapshotTS, 10)); err != nil { return nil, nil, err } s.sessionVars.SnapshotInfoschema, err = getSnapshotInfoSchema(s, execOption.SnapshotTS) if err != nil { return nil, nil, err } } prevStatsVer := s.sessionVars.AnalyzeVersion if execOption.AnalyzeVer != 0 { s.sessionVars.AnalyzeVersion = execOption.AnalyzeVer } prevAnalyzeSnapshot := s.sessionVars.EnableAnalyzeSnapshot if execOption.AnalyzeSnapshot != nil { s.sessionVars.EnableAnalyzeSnapshot = *execOption.AnalyzeSnapshot } prePruneMode := s.sessionVars.PartitionPruneMode.Load() if len(execOption.PartitionPruneMode) > 0 { s.sessionVars.PartitionPruneMode.Store(execOption.PartitionPruneMode) } prevSQL := s.sessionVars.StmtCtx.OriginalSQL prevStmtType := s.sessionVars.StmtCtx.StmtType prevTables := s.sessionVars.StmtCtx.Tables return s, func() { s.sessionVars.AnalyzeVersion = prevStatsVer s.sessionVars.EnableAnalyzeSnapshot = prevAnalyzeSnapshot if err := s.sessionVars.SetSystemVar(variable.TiDBSnapshot, ""); err != nil { logutil.BgLogger().Error("set tidbSnapshot error", zap.Error(err)) } s.sessionVars.SnapshotInfoschema = orgSnapshotInfoSchema s.sessionVars.SnapshotTS = orgSnapshotTS s.sessionVars.PartitionPruneMode.Store(prePruneMode) s.sessionVars.StmtCtx.OriginalSQL = prevSQL s.sessionVars.StmtCtx.StmtType = prevStmtType s.sessionVars.StmtCtx.Tables = prevTables s.sessionVars.MemTracker.Detach() }, nil } func (s *session) getInternalSession(execOption sqlexec.ExecOption) (*session, func(), error) { tmp, err := s.sysSessionPool().Get() if err != nil { return nil, nil, errors.Trace(err) } se := tmp.(*session) // The special session will share the `InspectionTableCache` with current session // if the current session in inspection mode. if cache := s.sessionVars.InspectionTableCache; cache != nil { se.sessionVars.InspectionTableCache = cache } if ok := s.sessionVars.OptimizerUseInvisibleIndexes; ok { se.sessionVars.OptimizerUseInvisibleIndexes = true } if execOption.SnapshotTS != 0 { if err := se.sessionVars.SetSystemVar(variable.TiDBSnapshot, strconv.FormatUint(execOption.SnapshotTS, 10)); err != nil { return nil, nil, err } se.sessionVars.SnapshotInfoschema, err = getSnapshotInfoSchema(s, execOption.SnapshotTS) if err != nil { return nil, nil, err } } prevStatsVer := se.sessionVars.AnalyzeVersion if execOption.AnalyzeVer != 0 { se.sessionVars.AnalyzeVersion = execOption.AnalyzeVer } prevAnalyzeSnapshot := se.sessionVars.EnableAnalyzeSnapshot if execOption.AnalyzeSnapshot != nil { se.sessionVars.EnableAnalyzeSnapshot = *execOption.AnalyzeSnapshot } prePruneMode := se.sessionVars.PartitionPruneMode.Load() if len(execOption.PartitionPruneMode) > 0 { se.sessionVars.PartitionPruneMode.Store(execOption.PartitionPruneMode) } return se, func() { se.sessionVars.AnalyzeVersion = prevStatsVer se.sessionVars.EnableAnalyzeSnapshot = prevAnalyzeSnapshot if err := se.sessionVars.SetSystemVar(variable.TiDBSnapshot, ""); err != nil { logutil.BgLogger().Error("set tidbSnapshot error", zap.Error(err)) } se.sessionVars.SnapshotInfoschema = nil se.sessionVars.SnapshotTS = 0 if !execOption.IgnoreWarning { if se != nil && se.GetSessionVars().StmtCtx.WarningCount() > 0 { warnings := se.GetSessionVars().StmtCtx.GetWarnings() s.GetSessionVars().StmtCtx.AppendWarnings(warnings) } } se.sessionVars.PartitionPruneMode.Store(prePruneMode) se.sessionVars.OptimizerUseInvisibleIndexes = false se.sessionVars.InspectionTableCache = nil se.sessionVars.MemTracker.Detach() s.sysSessionPool().Put(tmp) }, nil } func (s *session) withRestrictedSQLExecutor(ctx context.Context, opts []sqlexec.OptionFuncAlias, fn func(context.Context, *session) ([]chunk.Row, []*ast.ResultField, error)) ([]chunk.Row, []*ast.ResultField, error) { execOption := sqlexec.GetExecOption(opts) var se *session var clean func() var err error if execOption.UseCurSession { se, clean, err = s.useCurrentSession(execOption) } else { se, clean, err = s.getInternalSession(execOption) } if err != nil { return nil, nil, errors.Trace(err) } defer clean() if execOption.TrackSysProcID > 0 { err = execOption.TrackSysProc(execOption.TrackSysProcID, se) if err != nil { return nil, nil, errors.Trace(err) } // unTrack should be called before clean (return sys session) defer execOption.UnTrackSysProc(execOption.TrackSysProcID) } return fn(ctx, se) } func (s *session) ExecRestrictedSQL(ctx context.Context, opts []sqlexec.OptionFuncAlias, sql string, params ...interface{}) ([]chunk.Row, []*ast.ResultField, error) { return s.withRestrictedSQLExecutor(ctx, opts, func(ctx context.Context, se *session) ([]chunk.Row, []*ast.ResultField, error) { stmt, err := se.ParseWithParams(ctx, sql, params...) if err != nil { return nil, nil, errors.Trace(err) } defer pprof.SetGoroutineLabels(ctx) startTime := time.Now() metrics.SessionRestrictedSQLCounter.Inc() ctx = context.WithValue(ctx, execdetails.StmtExecDetailKey, &execdetails.StmtExecDetails{}) ctx = context.WithValue(ctx, tikvutil.ExecDetailsKey, &tikvutil.ExecDetails{}) rs, err := se.ExecuteInternalStmt(ctx, stmt) if err != nil { se.sessionVars.StmtCtx.AppendError(err) } if rs == nil { return nil, nil, err } defer func() { if closeErr := rs.Close(); closeErr != nil { err = closeErr } }() var rows []chunk.Row rows, err = drainRecordSet(ctx, se, rs, nil) if err != nil { return nil, nil, err } vars := se.GetSessionVars() for _, dbName := range GetDBNames(vars) { metrics.QueryDurationHistogram.WithLabelValues(metrics.LblInternal, dbName, vars.ResourceGroupName).Observe(time.Since(startTime).Seconds()) } return rows, rs.Fields(), err }) } // ExecuteInternalStmt execute internal stmt func (s *session) ExecuteInternalStmt(ctx context.Context, stmtNode ast.StmtNode) (sqlexec.RecordSet, error) { origin := s.sessionVars.InRestrictedSQL s.sessionVars.InRestrictedSQL = true defer func() { s.sessionVars.InRestrictedSQL = origin // Restore the goroutine label by using the original ctx after execution is finished. pprof.SetGoroutineLabels(ctx) }() return s.ExecuteStmt(ctx, stmtNode) } func (s *session) ExecuteStmt(ctx context.Context, stmtNode ast.StmtNode) (sqlexec.RecordSet, error) { r, ctx := tracing.StartRegionEx(ctx, "session.ExecuteStmt") defer r.End() if err := s.PrepareTxnCtx(ctx); err != nil { return nil, err } if err := s.loadCommonGlobalVariablesIfNeeded(); err != nil { return nil, err } sessVars := s.sessionVars sessVars.StartTime = time.Now() // Some executions are done in compile stage, so we reset them before compile. if err := executor.ResetContextOfStmt(s, stmtNode); err != nil { return nil, err } normalizedSQL, digest := s.sessionVars.StmtCtx.SQLDigest() cmdByte := byte(atomic.LoadUint32(&s.GetSessionVars().CommandValue)) if topsqlstate.TopSQLEnabled() { s.sessionVars.StmtCtx.IsSQLRegistered.Store(true) ctx = topsql.AttachAndRegisterSQLInfo(ctx, normalizedSQL, digest, s.sessionVars.InRestrictedSQL) } if sessVars.InPlanReplayer { sessVars.StmtCtx.EnableOptimizerDebugTrace = true } else if dom := domain.GetDomain(s); dom != nil && !sessVars.InRestrictedSQL { // This is the earliest place we can get the SQL digest for this execution. // If we find this digest is registered for PLAN REPLAYER CAPTURE, we need to enable optimizer debug trace no matter // the plan digest will be matched or not. if planReplayerHandle := dom.GetPlanReplayerHandle(); planReplayerHandle != nil { tasks := planReplayerHandle.GetTasks() for _, task := range tasks { if task.SQLDigest == digest.String() { sessVars.StmtCtx.EnableOptimizerDebugTrace = true } } } } if sessVars.StmtCtx.EnableOptimizerDebugTrace { plannercore.DebugTraceReceivedCommand(s, cmdByte, stmtNode) } if err := s.validateStatementInTxn(stmtNode); err != nil { return nil, err } if err := s.validateStatementReadOnlyInStaleness(stmtNode); err != nil { return nil, err } // Uncorrelated subqueries will execute once when building plan, so we reset process info before building plan. s.currentPlan = nil // reset current plan s.SetProcessInfo(stmtNode.Text(), time.Now(), cmdByte, 0) s.txn.onStmtStart(digest.String()) defer sessiontxn.GetTxnManager(s).OnStmtEnd() defer s.txn.onStmtEnd() if err := s.onTxnManagerStmtStartOrRetry(ctx, stmtNode); err != nil { return nil, err } failpoint.Inject("mockStmtSlow", func(val failpoint.Value) { if strings.Contains(stmtNode.Text(), "/* sleep */") { v, _ := val.(int) time.Sleep(time.Duration(v) * time.Millisecond) } }) var stmtLabel string if execStmt, ok := stmtNode.(*ast.ExecuteStmt); ok { prepareStmt, err := plannercore.GetPreparedStmt(execStmt, s.sessionVars) if err == nil && prepareStmt.PreparedAst != nil { stmtLabel = ast.GetStmtLabel(prepareStmt.PreparedAst.Stmt) } } if stmtLabel == "" { stmtLabel = ast.GetStmtLabel(stmtNode) } s.setRequestSource(ctx, stmtLabel, stmtNode) // Backup the original resource group name since sql hint might change it during optimization originalResourceGroup := s.GetSessionVars().ResourceGroupName // Transform abstract syntax tree to a physical plan(stored in executor.ExecStmt). compiler := executor.Compiler{Ctx: s} stmt, err := compiler.Compile(ctx, stmtNode) // session resource-group might be changed by query hint, ensure restore it back when // the execution finished. if sessVars.ResourceGroupName != originalResourceGroup { // if target resource group doesn't exist, fallback to the origin resource group. if _, ok := domain.GetDomain(s).InfoSchema().ResourceGroupByName(model.NewCIStr(sessVars.ResourceGroupName)); !ok { logutil.Logger(ctx).Warn("Unknown resource group from hint", zap.String("name", sessVars.ResourceGroupName)) sessVars.ResourceGroupName = originalResourceGroup // if we are in a txn, should also reset the txn resource group. if txn, err := s.Txn(false); err == nil && txn != nil && txn.Valid() { kv.SetTxnResourceGroup(txn, originalResourceGroup) } } else { defer func() { // Restore the resource group for the session sessVars.ResourceGroupName = originalResourceGroup }() } } if err != nil { s.rollbackOnError(ctx) // Only print log message when this SQL is from the user. // Mute the warning for internal SQLs. if !s.sessionVars.InRestrictedSQL { if !variable.ErrUnknownSystemVar.Equal(err) { sql := stmtNode.Text() if s.sessionVars.EnableRedactLog { sql = parser.Normalize(sql) } logutil.Logger(ctx).Warn("compile SQL failed", zap.Error(err), zap.String("SQL", sql)) } } return nil, err } durCompile := time.Since(s.sessionVars.StartTime) s.GetSessionVars().DurationCompile = durCompile if s.isInternal() { session_metrics.SessionExecuteCompileDurationInternal.Observe(durCompile.Seconds()) } else { session_metrics.SessionExecuteCompileDurationGeneral.Observe(durCompile.Seconds()) } s.currentPlan = stmt.Plan if execStmt, ok := stmtNode.(*ast.ExecuteStmt); ok { if execStmt.Name == "" { // for exec-stmt on bin-protocol, ignore the plan detail in `show process` to gain performance benefits. s.currentPlan = nil } } // Execute the physical plan. logStmt(stmt, s) var recordSet sqlexec.RecordSet if stmt.PsStmt != nil { // point plan short path recordSet, err = stmt.PointGet(ctx) s.txn.changeToInvalid() } else { recordSet, err = runStmt(ctx, s, stmt) } // Observe the resource group query total counter if the resource control is enabled and the // current session is attached with a resource group. resourceGroupName := s.GetSessionVars().ResourceGroupName if len(resourceGroupName) > 0 { metrics.ResourceGroupQueryTotalCounter.WithLabelValues(resourceGroupName).Inc() } if err != nil { if !errIsNoisy(err) { logutil.Logger(ctx).Warn("run statement failed", zap.Int64("schemaVersion", s.GetInfoSchema().SchemaMetaVersion()), zap.Error(err), zap.String("session", s.String())) } return recordSet, err } if !s.isInternal() && config.GetGlobalConfig().EnableTelemetry { telemetry.CurrentExecuteCount.Inc() tiFlashPushDown, tiFlashExchangePushDown := plannercore.IsTiFlashContained(stmt.Plan) if tiFlashPushDown { telemetry.CurrentTiFlashPushDownCount.Inc() } if tiFlashExchangePushDown { telemetry.CurrentTiFlashExchangePushDownCount.Inc() } } return recordSet, nil } func (s *session) onTxnManagerStmtStartOrRetry(ctx context.Context, node ast.StmtNode) error { if s.sessionVars.RetryInfo.Retrying { return sessiontxn.GetTxnManager(s).OnStmtRetry(ctx) } return sessiontxn.GetTxnManager(s).OnStmtStart(ctx, node) } func (s *session) validateStatementInTxn(stmtNode ast.StmtNode) error { vars := s.GetSessionVars() if _, ok := stmtNode.(*ast.ImportIntoStmt); ok && vars.InTxn() { return errors.New("cannot run IMPORT INTO in explicit transaction") } return nil } func (s *session) validateStatementReadOnlyInStaleness(stmtNode ast.StmtNode) error { vars := s.GetSessionVars() if !vars.TxnCtx.IsStaleness && vars.TxnReadTS.PeakTxnReadTS() == 0 && !vars.EnableExternalTSRead || vars.InRestrictedSQL { return nil } errMsg := "only support read-only statement during read-only staleness transactions" node := stmtNode.(ast.Node) switch v := node.(type) { case *ast.SplitRegionStmt: return nil case *ast.SelectStmt: // select lock statement needs start a transaction which will be conflict to stale read, // we forbid select lock statement in stale read for now. if v.LockInfo != nil { return errors.New("select lock hasn't been supported in stale read yet") } if !planner.IsReadOnly(stmtNode, vars) { return errors.New(errMsg) } return nil case *ast.ExplainStmt, *ast.DoStmt, *ast.ShowStmt, *ast.SetOprStmt, *ast.ExecuteStmt, *ast.SetOprSelectList: if !planner.IsReadOnly(stmtNode, vars) { return errors.New(errMsg) } return nil default: } // covered DeleteStmt/InsertStmt/UpdateStmt/CallStmt/LoadDataStmt if _, ok := stmtNode.(ast.DMLNode); ok { return errors.New(errMsg) } return nil } // fileTransInConnKeys contains the keys of queries that will be handled by handleFileTransInConn. var fileTransInConnKeys = []fmt.Stringer{ executor.LoadDataVarKey, executor.LoadStatsVarKey, executor.IndexAdviseVarKey, executor.PlanReplayerLoadVarKey, } func (s *session) hasFileTransInConn() bool { s.mu.RLock() defer s.mu.RUnlock() for _, k := range fileTransInConnKeys { v := s.mu.values[k] if v != nil { return true } } return false } // runStmt executes the sqlexec.Statement and commit or rollback the current transaction. func runStmt(ctx context.Context, se *session, s sqlexec.Statement) (rs sqlexec.RecordSet, err error) { failpoint.Inject("assertTxnManagerInRunStmt", func() { sessiontxn.RecordAssert(se, "assertTxnManagerInRunStmt", true) if stmt, ok := s.(*executor.ExecStmt); ok { sessiontxn.AssertTxnManagerInfoSchema(se, stmt.InfoSchema) } }) r, ctx := tracing.StartRegionEx(ctx, "session.runStmt") defer r.End() if r.Span != nil { r.Span.LogKV("sql", s.OriginText()) } se.SetValue(sessionctx.QueryString, s.OriginText()) if _, ok := s.(*executor.ExecStmt).StmtNode.(ast.DDLNode); ok { se.SetValue(sessionctx.LastExecuteDDL, true) } else { se.ClearValue(sessionctx.LastExecuteDDL) } sessVars := se.sessionVars // Record diagnostic information for DML statements if stmt, ok := s.(*executor.ExecStmt).StmtNode.(ast.DMLNode); ok { // Keep the previous queryInfo for `show session_states` because the statement needs to encode it. if showStmt, ok := stmt.(*ast.ShowStmt); !ok || showStmt.Tp != ast.ShowSessionStates { defer func() { sessVars.LastQueryInfo = sessionstates.QueryInfo{ TxnScope: sessVars.CheckAndGetTxnScope(), StartTS: sessVars.TxnCtx.StartTS, ForUpdateTS: sessVars.TxnCtx.GetForUpdateTS(), } if err != nil { sessVars.LastQueryInfo.ErrMsg = err.Error() } }() } } // Save origTxnCtx here to avoid it reset in the transaction retry. origTxnCtx := sessVars.TxnCtx err = se.checkTxnAborted(s) if err != nil { return nil, err } rs, err = s.Exec(ctx) se.updateTelemetryMetric(s.(*executor.ExecStmt)) sessVars.TxnCtx.StatementCount++ if rs != nil { if se.GetSessionVars().StmtCtx.IsExplainAnalyzeDML { if !sessVars.InTxn() { se.StmtCommit(ctx) if err := se.CommitTxn(ctx); err != nil { return nil, err } } } return &execStmtResult{ RecordSet: rs, sql: s, se: se, }, err } err = finishStmt(ctx, se, err, s) if se.hasFileTransInConn() { // The query will be handled later in handleFileTransInConn, // then should call the ExecStmt.FinishExecuteStmt to finish this statement. se.SetValue(ExecStmtVarKey, s.(*executor.ExecStmt)) } else { // If it is not a select statement or special query, we record its slow log here, // then it could include the transaction commit time. s.(*executor.ExecStmt).FinishExecuteStmt(origTxnCtx.StartTS, err, false) } return nil, err } // ExecStmtVarKeyType is a dummy type to avoid naming collision in context. type ExecStmtVarKeyType int // String defines a Stringer function for debugging and pretty printing. func (ExecStmtVarKeyType) String() string { return "exec_stmt_var_key" } // ExecStmtVarKey is a variable key for ExecStmt. const ExecStmtVarKey ExecStmtVarKeyType = 0 // execStmtResult is the return value of ExecuteStmt and it implements the sqlexec.RecordSet interface. // Why we need a struct to wrap a RecordSet and provide another RecordSet? // This is because there are so many session state related things that definitely not belongs to the original // RecordSet, so this struct exists and RecordSet.Close() is overrided handle that. type execStmtResult struct { sqlexec.RecordSet se *session sql sqlexec.Statement } func (rs *execStmtResult) Close() error { se := rs.se if err := rs.RecordSet.Close(); err != nil { return finishStmt(context.Background(), se, err, rs.sql) } return finishStmt(context.Background(), se, nil, rs.sql) } // rollbackOnError makes sure the next statement starts a new transaction with the latest InfoSchema. func (s *session) rollbackOnError(ctx context.Context) { if !s.sessionVars.InTxn() { s.RollbackTxn(ctx) } } // PrepareStmt is used for executing prepare statement in binary protocol func (s *session) PrepareStmt(sql string) (stmtID uint32, paramCount int, fields []*ast.ResultField, err error) { defer func() { if s.sessionVars.StmtCtx != nil { s.sessionVars.StmtCtx.DetachMemDiskTracker() } }() if s.sessionVars.TxnCtx.InfoSchema == nil { // We don't need to create a transaction for prepare statement, just get information schema will do. s.sessionVars.TxnCtx.InfoSchema = domain.GetDomain(s).InfoSchema() } err = s.loadCommonGlobalVariablesIfNeeded() if err != nil { return } ctx := context.Background() // NewPrepareExec may need startTS to build the executor, for example prepare statement has subquery in int. // So we have to call PrepareTxnCtx here. if err = s.PrepareTxnCtx(ctx); err != nil { return } prepareStmt := &ast.PrepareStmt{SQLText: sql} if err = s.onTxnManagerStmtStartOrRetry(ctx, prepareStmt); err != nil { return } if err = sessiontxn.GetTxnManager(s).AdviseWarmup(); err != nil { return } prepareExec := executor.NewPrepareExec(s, sql) err = prepareExec.Next(ctx, nil) // Rollback even if err is nil. s.rollbackOnError(ctx) if err != nil { return } return prepareExec.ID, prepareExec.ParamCount, prepareExec.Fields, nil } // ExecutePreparedStmt executes a prepared statement. func (s *session) ExecutePreparedStmt(ctx context.Context, stmtID uint32, params []expression.Expression) (sqlexec.RecordSet, error) { prepStmt, err := s.sessionVars.GetPreparedStmtByID(stmtID) if err != nil { err = plannercore.ErrStmtNotFound logutil.Logger(ctx).Error("prepared statement not found", zap.Uint32("stmtID", stmtID)) return nil, err } stmt, ok := prepStmt.(*plannercore.PlanCacheStmt) if !ok { return nil, errors.Errorf("invalid PlanCacheStmt type") } execStmt := &ast.ExecuteStmt{ BinaryArgs: params, PrepStmt: stmt, } return s.ExecuteStmt(ctx, execStmt) } func (s *session) DropPreparedStmt(stmtID uint32) error { vars := s.sessionVars if _, ok := vars.PreparedStmts[stmtID]; !ok { return plannercore.ErrStmtNotFound } vars.RetryInfo.DroppedPreparedStmtIDs = append(vars.RetryInfo.DroppedPreparedStmtIDs, stmtID) return nil } func (s *session) Txn(active bool) (kv.Transaction, error) { if !active { return &s.txn, nil } _, err := sessiontxn.GetTxnManager(s).ActivateTxn() s.SetMemoryFootprintChangeHook() return &s.txn, err } func (s *session) SetValue(key fmt.Stringer, value interface{}) { s.mu.Lock() s.mu.values[key] = value s.mu.Unlock() } func (s *session) Value(key fmt.Stringer) interface{} { s.mu.RLock() value := s.mu.values[key] s.mu.RUnlock() return value } func (s *session) ClearValue(key fmt.Stringer) { s.mu.Lock() delete(s.mu.values, key) s.mu.Unlock() } type inCloseSession struct{} // Close function does some clean work when session end. // Close should release the table locks which hold by the session. func (s *session) Close() { // TODO: do clean table locks when session exited without execute Close. // TODO: do clean table locks when tidb-server was `kill -9`. if s.HasLockedTables() && config.TableLockEnabled() { if ds := config.TableLockDelayClean(); ds > 0 { time.Sleep(time.Duration(ds) * time.Millisecond) } lockedTables := s.GetAllTableLocks() err := domain.GetDomain(s).DDL().UnlockTables(s, lockedTables) if err != nil { logutil.BgLogger().Error("release table lock failed", zap.Uint64("conn", s.sessionVars.ConnectionID)) } } s.ReleaseAllAdvisoryLocks() if s.statsCollector != nil { s.statsCollector.Delete() } if s.idxUsageCollector != nil { s.idxUsageCollector.Delete() } telemetry.GlobalBuiltinFunctionsUsage.Collect(s.GetBuiltinFunctionUsage()) bindValue := s.Value(bindinfo.SessionBindInfoKeyType) if bindValue != nil { bindValue.(*bindinfo.SessionHandle).Close() } ctx := context.WithValue(context.TODO(), inCloseSession{}, struct{}{}) s.RollbackTxn(ctx) if s.sessionVars != nil { s.sessionVars.WithdrawAllPreparedStmt() } if s.stmtStats != nil { s.stmtStats.SetFinished() } s.ClearDiskFullOpt() if s.sessionPlanCache != nil { s.sessionPlanCache.Close() } } // GetSessionVars implements the context.Context interface. func (s *session) GetSessionVars() *variable.SessionVars { return s.sessionVars } func (s *session) AuthPluginForUser(user *auth.UserIdentity) (string, error) { pm := privilege.GetPrivilegeManager(s) authplugin, err := pm.GetAuthPluginForConnection(user.Username, user.Hostname) if err != nil { return "", err } return authplugin, nil } // Auth validates a user using an authentication string and salt. // If the password fails, it will keep trying other users until exhausted. // This means it can not be refactored to use MatchIdentity yet. func (s *session) Auth(user *auth.UserIdentity, authentication, salt []byte, authConn conn.AuthConn) error { hasPassword := "YES" if len(authentication) == 0 { hasPassword = "NO" } pm := privilege.GetPrivilegeManager(s) authUser, err := s.MatchIdentity(user.Username, user.Hostname) if err != nil { return privileges.ErrAccessDenied.FastGenByArgs(user.Username, user.Hostname, hasPassword) } // Check whether continuous login failure is enabled to lock the account. // If enabled, determine whether to unlock the account and notify TiDB to update the cache. enableAutoLock := pm.IsAccountAutoLockEnabled(authUser.Username, authUser.Hostname) if enableAutoLock { err = failedLoginTrackingBegin(s) if err != nil { return err } lockStatusChanged, err := verifyAccountAutoLock(s, authUser.Username, authUser.Hostname) if err != nil { rollbackErr := failedLoginTrackingRollback(s) if rollbackErr != nil { return rollbackErr } return err } err = failedLoginTrackingCommit(s) if err != nil { rollbackErr := failedLoginTrackingRollback(s) if rollbackErr != nil { return rollbackErr } return err } if lockStatusChanged { // Notification auto unlock. err = domain.GetDomain(s).NotifyUpdatePrivilege() if err != nil { return err } } } info, err := pm.ConnectionVerification(user, authUser.Username, authUser.Hostname, authentication, salt, s.sessionVars, authConn) if err != nil { if info.FailedDueToWrongPassword { // when user enables the account locking function for consecutive login failures, // the system updates the login failure count and determines whether to lock the account when authentication fails. if enableAutoLock { err := failedLoginTrackingBegin(s) if err != nil { return err } lockStatusChanged, passwordLocking, trackingErr := authFailedTracking(s, authUser.Username, authUser.Hostname) if trackingErr != nil { if rollBackErr := failedLoginTrackingRollback(s); rollBackErr != nil { return rollBackErr } return trackingErr } if err := failedLoginTrackingCommit(s); err != nil { if rollBackErr := failedLoginTrackingRollback(s); rollBackErr != nil { return rollBackErr } return err } if lockStatusChanged { // Notification auto lock. err := autolockAction(s, passwordLocking, authUser.Username, authUser.Hostname) if err != nil { return err } } } } return err } if variable.EnableResourceControl.Load() && info.ResourceGroupName != "" { s.sessionVars.ResourceGroupName = strings.ToLower(info.ResourceGroupName) } if info.InSandBoxMode { // Enter sandbox mode, only execute statement for resetting password. s.EnableSandBoxMode() } if enableAutoLock { err := failedLoginTrackingBegin(s) if err != nil { return err } // The password is correct. If the account is not locked, the number of login failure statistics will be cleared. err = authSuccessClearCount(s, authUser.Username, authUser.Hostname) if err != nil { if rollBackErr := failedLoginTrackingRollback(s); rollBackErr != nil { return rollBackErr } return err } err = failedLoginTrackingCommit(s) if err != nil { if rollBackErr := failedLoginTrackingRollback(s); rollBackErr != nil { return rollBackErr } return err } } pm.AuthSuccess(authUser.Username, authUser.Hostname) user.AuthUsername = authUser.Username user.AuthHostname = authUser.Hostname s.sessionVars.User = user s.sessionVars.ActiveRoles = pm.GetDefaultRoles(user.AuthUsername, user.AuthHostname) return nil } func authSuccessClearCount(s *session, user string, host string) error { // Obtain accurate lock status and failure count information. passwordLocking, err := getFailedLoginUserAttributes(s, user, host) if err != nil { return err } // If the account is locked, it may be caused by the untimely update of the cache, // directly report the account lock. if passwordLocking.AutoAccountLocked { if passwordLocking.PasswordLockTimeDays == -1 { return privileges.GenerateAccountAutoLockErr(passwordLocking.FailedLoginAttempts, user, host, "unlimited", "unlimited") } lds := strconv.FormatInt(passwordLocking.PasswordLockTimeDays, 10) return privileges.GenerateAccountAutoLockErr(passwordLocking.FailedLoginAttempts, user, host, lds, lds) } if passwordLocking.FailedLoginCount != 0 { // If the number of account login failures is not zero, it will be updated to 0. passwordLockingJSON := privileges.BuildSuccessPasswordLockingJSON(passwordLocking.FailedLoginAttempts, passwordLocking.PasswordLockTimeDays) if passwordLockingJSON != "" { if err := s.passwordLocking(user, host, passwordLockingJSON); err != nil { return err } } } return nil } func verifyAccountAutoLock(s *session, user, host string) (bool, error) { pm := privilege.GetPrivilegeManager(s) // Use the cache to determine whether to unlock the account. // If the account needs to be unlocked, read the database information to determine whether // the account needs to be unlocked. Otherwise, an error message is displayed. lockStatusInMemory, err := pm.VerifyAccountAutoLockInMemory(user, host) if err != nil { return false, err } // If the lock status in the cache is Unlock, the automatic unlock is skipped. // If memory synchronization is slow and there is a lock in the database, it will be processed upon successful login. if !lockStatusInMemory { return false, nil } lockStatusChanged := false var plJSON string // After checking the cache, obtain the latest data from the database and determine // whether to automatically unlock the database to prevent repeated unlock errors. pl, err := getFailedLoginUserAttributes(s, user, host) if err != nil { return false, err } if pl.AutoAccountLocked { // If it is locked, need to check whether it can be automatically unlocked. lockTimeDay := pl.PasswordLockTimeDays if lockTimeDay == -1 { return false, privileges.GenerateAccountAutoLockErr(pl.FailedLoginAttempts, user, host, "unlimited", "unlimited") } lastChanged := pl.AutoLockedLastChanged d := time.Now().Unix() - lastChanged if d <= lockTimeDay*24*60*60 { lds := strconv.FormatInt(lockTimeDay, 10) rds := strconv.FormatInt(int64(math.Ceil(float64(lockTimeDay)-float64(d)/(24*60*60))), 10) return false, privileges.GenerateAccountAutoLockErr(pl.FailedLoginAttempts, user, host, lds, rds) } // Generate unlock json string. plJSON = privileges.BuildPasswordLockingJSON(pl.FailedLoginAttempts, pl.PasswordLockTimeDays, "N", 0, time.Now().Format(time.UnixDate)) } if plJSON != "" { lockStatusChanged = true if err = s.passwordLocking(user, host, plJSON); err != nil { return false, err } } return lockStatusChanged, nil } func authFailedTracking(s *session, user string, host string) (bool, *privileges.PasswordLocking, error) { // Obtain the number of consecutive password login failures. passwordLocking, err := getFailedLoginUserAttributes(s, user, host) if err != nil { return false, nil, err } // Consecutive wrong password login failure times +1, // If the lock condition is satisfied, the lock status is updated and the update cache is notified. lockStatusChanged, err := userAutoAccountLocked(s, user, host, passwordLocking) if err != nil { return false, nil, err } return lockStatusChanged, passwordLocking, nil } func autolockAction(s *session, passwordLocking *privileges.PasswordLocking, user, host string) error { // Don't want to update the cache frequently, and only trigger the update cache when the lock status is updated. err := domain.GetDomain(s).NotifyUpdatePrivilege() if err != nil { return err } // The number of failed login attempts reaches FAILED_LOGIN_ATTEMPTS. // An error message is displayed indicating permission denial and account lock. if passwordLocking.PasswordLockTimeDays == -1 { return privileges.GenerateAccountAutoLockErr(passwordLocking.FailedLoginAttempts, user, host, "unlimited", "unlimited") } lds := strconv.FormatInt(passwordLocking.PasswordLockTimeDays, 10) return privileges.GenerateAccountAutoLockErr(passwordLocking.FailedLoginAttempts, user, host, lds, lds) } func (s *session) passwordLocking(user string, host string, newAttributesStr string) error { sql := new(strings.Builder) sqlexec.MustFormatSQL(sql, "UPDATE %n.%n SET ", mysql.SystemDB, mysql.UserTable) sqlexec.MustFormatSQL(sql, "user_attributes=json_merge_patch(coalesce(user_attributes, '{}'), %?)", newAttributesStr) sqlexec.MustFormatSQL(sql, " WHERE Host=%? and User=%?;", host, user) ctx := kv.WithInternalSourceType(context.Background(), kv.InternalTxnPrivilege) _, err := s.ExecuteInternal(ctx, sql.String()) return err } func failedLoginTrackingBegin(s *session) error { ctx := kv.WithInternalSourceType(context.Background(), kv.InternalTxnPrivilege) _, err := s.ExecuteInternal(ctx, "BEGIN PESSIMISTIC") return err } func failedLoginTrackingCommit(s *session) error { ctx := kv.WithInternalSourceType(context.Background(), kv.InternalTxnPrivilege) _, err := s.ExecuteInternal(ctx, "COMMIT") if err != nil { _, rollBackErr := s.ExecuteInternal(ctx, "ROLLBACK") if rollBackErr != nil { return rollBackErr } } return err } func failedLoginTrackingRollback(s *session) error { ctx := kv.WithInternalSourceType(context.Background(), kv.InternalTxnPrivilege) _, err := s.ExecuteInternal(ctx, "ROLLBACK") return err } // getFailedLoginUserAttributes queries the exact number of consecutive password login failures (concurrency is not allowed). func getFailedLoginUserAttributes(s *session, user string, host string) (*privileges.PasswordLocking, error) { passwordLocking := &privileges.PasswordLocking{} ctx := kv.WithInternalSourceType(context.Background(), kv.InternalTxnPrivilege) rs, err := s.ExecuteInternal(ctx, `SELECT user_attributes from mysql.user WHERE USER = %? AND HOST = %? for update`, user, host) if err != nil { return passwordLocking, err } defer func() { if closeErr := rs.Close(); closeErr != nil { err = closeErr } }() req := rs.NewChunk(nil) iter := chunk.NewIterator4Chunk(req) err = rs.Next(ctx, req) if err != nil { return passwordLocking, err } if req.NumRows() == 0 { return passwordLocking, fmt.Errorf("user_attributes by `%s`@`%s` not found", user, host) } row := iter.Begin() if !row.IsNull(0) { passwordLockingJSON := row.GetJSON(0) return passwordLocking, passwordLocking.ParseJSON(passwordLockingJSON) } return passwordLocking, fmt.Errorf("user_attributes by `%s`@`%s` not found", user, host) } func userAutoAccountLocked(s *session, user string, host string, pl *privileges.PasswordLocking) (bool, error) { // Indicates whether the user needs to update the lock status change. lockStatusChanged := false // The number of consecutive login failures is stored in the database. // If the current login fails, one is added to the number of consecutive login failures // stored in the database to determine whether the user needs to be locked and the number of update failures. failedLoginCount := pl.FailedLoginCount + 1 // If the cache is not updated, but it is already locked, it will report that the account is locked. if pl.AutoAccountLocked { if pl.PasswordLockTimeDays == -1 { return false, privileges.GenerateAccountAutoLockErr(pl.FailedLoginAttempts, user, host, "unlimited", "unlimited") } lds := strconv.FormatInt(pl.PasswordLockTimeDays, 10) return false, privileges.GenerateAccountAutoLockErr(pl.FailedLoginAttempts, user, host, lds, lds) } autoAccountLocked := "N" autoLockedLastChanged := "" if pl.FailedLoginAttempts == 0 || pl.PasswordLockTimeDays == 0 { return false, nil } if failedLoginCount >= pl.FailedLoginAttempts { autoLockedLastChanged = time.Now().Format(time.UnixDate) autoAccountLocked = "Y" lockStatusChanged = true } newAttributesStr := privileges.BuildPasswordLockingJSON(pl.FailedLoginAttempts, pl.PasswordLockTimeDays, autoAccountLocked, failedLoginCount, autoLockedLastChanged) if newAttributesStr != "" { return lockStatusChanged, s.passwordLocking(user, host, newAttributesStr) } return lockStatusChanged, nil } // MatchIdentity finds the matching username + password in the MySQL privilege tables // for a username + hostname, since MySQL can have wildcards. func (s *session) MatchIdentity(username, remoteHost string) (*auth.UserIdentity, error) { pm := privilege.GetPrivilegeManager(s) var success bool var skipNameResolve bool var user = &auth.UserIdentity{} varVal, err := s.GetSessionVars().GlobalVarsAccessor.GetGlobalSysVar(variable.SkipNameResolve) if err == nil && variable.TiDBOptOn(varVal) { skipNameResolve = true } user.Username, user.Hostname, success = pm.MatchIdentity(username, remoteHost, skipNameResolve) if success { return user, nil } // This error will not be returned to the user, access denied will be instead return nil, fmt.Errorf("could not find matching user in MatchIdentity: %s, %s", username, remoteHost) } // AuthWithoutVerification is required by the ResetConnection RPC func (s *session) AuthWithoutVerification(user *auth.UserIdentity) bool { pm := privilege.GetPrivilegeManager(s) authUser, err := s.MatchIdentity(user.Username, user.Hostname) if err != nil { return false } if pm.GetAuthWithoutVerification(authUser.Username, authUser.Hostname) { user.AuthUsername = authUser.Username user.AuthHostname = authUser.Hostname s.sessionVars.User = user s.sessionVars.ActiveRoles = pm.GetDefaultRoles(user.AuthUsername, user.AuthHostname) return true } return false } // RefreshVars implements the sessionctx.Context interface. func (s *session) RefreshVars(_ context.Context) error { pruneMode, err := s.GetSessionVars().GlobalVarsAccessor.GetGlobalSysVar(variable.TiDBPartitionPruneMode) if err != nil { return err } s.sessionVars.PartitionPruneMode.Store(pruneMode) return nil } // SetSessionStatesHandler implements the Session.SetSessionStatesHandler interface. func (s *session) SetSessionStatesHandler(stateType sessionstates.SessionStateType, handler sessionctx.SessionStatesHandler) { s.sessionStatesHandlers[stateType] = handler } // CreateSession4Test creates a new session environment for test. func CreateSession4Test(store kv.Storage) (Session, error) { se, err := CreateSession4TestWithOpt(store, nil) if err == nil { // Cover both chunk rpc encoding and default encoding. // nolint:gosec if rand.Intn(2) == 0 { se.GetSessionVars().EnableChunkRPC = false } else { se.GetSessionVars().EnableChunkRPC = true } } return se, err } // Opt describes the option for creating session type Opt struct { PreparedPlanCache sessionctx.PlanCache } // CreateSession4TestWithOpt creates a new session environment for test. func CreateSession4TestWithOpt(store kv.Storage, opt *Opt) (Session, error) { s, err := CreateSessionWithOpt(store, opt) if err == nil { // initialize session variables for test. s.GetSessionVars().InitChunkSize = 2 s.GetSessionVars().MaxChunkSize = 32 s.GetSessionVars().MinPagingSize = variable.DefMinPagingSize s.GetSessionVars().EnablePaging = variable.DefTiDBEnablePaging err = s.GetSessionVars().SetSystemVarWithoutValidation(variable.CharacterSetConnection, "utf8mb4") } return s, err } // CreateSession creates a new session environment. func CreateSession(store kv.Storage) (Session, error) { return CreateSessionWithOpt(store, nil) } // CreateSessionWithOpt creates a new session environment with option. // Use default option if opt is nil. func CreateSessionWithOpt(store kv.Storage, opt *Opt) (Session, error) { s, err := createSessionWithOpt(store, opt) if err != nil { return nil, err } // Add auth here. do, err := domap.Get(store) if err != nil { return nil, err } extensions, err := extension.GetExtensions() if err != nil { return nil, err } pm := privileges.NewUserPrivileges(do.PrivilegeHandle(), extensions) privilege.BindPrivilegeManager(s, pm) // Add stats collector, and it will be freed by background stats worker // which periodically updates stats using the collected data. if do.StatsHandle() != nil && do.StatsUpdating() { s.statsCollector = do.StatsHandle().NewSessionStatsCollector() if GetIndexUsageSyncLease() > 0 { s.idxUsageCollector = do.StatsHandle().NewSessionIndexUsageCollector() } } return s, nil } // loadCollationParameter loads collation parameter from mysql.tidb func loadCollationParameter(ctx context.Context, se *session) (bool, error) { para, err := se.getTableValue(ctx, mysql.TiDBTable, tidbNewCollationEnabled) if err != nil { return false, err } if para == varTrue { return true, nil } else if para == varFalse { return false, nil } logutil.BgLogger().Warn( "Unexpected value of 'new_collation_enabled' in 'mysql.tidb', use 'False' instead", zap.String("value", para)) return false, nil } type tableBasicInfo struct { SQL string id int64 } var ( errResultIsEmpty = dbterror.ClassExecutor.NewStd(errno.ErrResultIsEmpty) // DDLJobTables is a list of tables definitions used in concurrent DDL. DDLJobTables = []tableBasicInfo{ {ddl.JobTableSQL, ddl.JobTableID}, {ddl.ReorgTableSQL, ddl.ReorgTableID}, {ddl.HistoryTableSQL, ddl.HistoryTableID}, } // BackfillTables is a list of tables definitions used in dist reorg DDL. BackfillTables = []tableBasicInfo{ {ddl.BackgroundSubtaskTableSQL, ddl.BackgroundSubtaskTableID}, {ddl.BackgroundSubtaskHistoryTableSQL, ddl.BackgroundSubtaskHistoryTableID}, } mdlTable = "create table mysql.tidb_mdl_info(job_id BIGINT NOT NULL PRIMARY KEY, version BIGINT NOT NULL, table_ids text(65535));" ) func splitAndScatterTable(store kv.Storage, tableIDs []int64) { if s, ok := store.(kv.SplittableStore); ok && atomic.LoadUint32(&ddl.EnableSplitTableRegion) == 1 { ctxWithTimeout, cancel := context.WithTimeout(context.Background(), variable.DefWaitSplitRegionTimeout*time.Second) var regionIDs []uint64 for _, id := range tableIDs { regionIDs = append(regionIDs, ddl.SplitRecordRegion(ctxWithTimeout, s, id, id, variable.DefTiDBScatterRegion)) } if variable.DefTiDBScatterRegion { ddl.WaitScatterRegionFinish(ctxWithTimeout, s, regionIDs...) } cancel() } } // InitDDLJobTables is to create tidb_ddl_job, tidb_ddl_reorg and tidb_ddl_history, or tidb_background_subtask and tidb_background_subtask_history. func InitDDLJobTables(store kv.Storage, targetVer meta.DDLTableVersion) error { targetTables := DDLJobTables if targetVer == meta.BackfillTableVersion { targetTables = BackfillTables } return kv.RunInNewTxn(kv.WithInternalSourceType(context.Background(), kv.InternalTxnDDL), store, true, func(ctx context.Context, txn kv.Transaction) error { t := meta.NewMeta(txn) tableVer, err := t.CheckDDLTableVersion() if err != nil || tableVer >= targetVer { return errors.Trace(err) } dbID, err := t.CreateMySQLDatabaseIfNotExists() if err != nil { return err } if err = createAndSplitTables(store, t, dbID, targetTables); err != nil { return err } return t.SetDDLTables(targetVer) }) } func createAndSplitTables(store kv.Storage, t *meta.Meta, dbID int64, tables []tableBasicInfo) error { tableIDs := make([]int64, 0, len(tables)) for _, tbl := range tables { tableIDs = append(tableIDs, tbl.id) } splitAndScatterTable(store, tableIDs) p := parser.New() for _, tbl := range tables { stmt, err := p.ParseOneStmt(tbl.SQL, "", "") if err != nil { return errors.Trace(err) } tblInfo, err := ddl.BuildTableInfoFromAST(stmt.(*ast.CreateTableStmt)) if err != nil { return errors.Trace(err) } tblInfo.State = model.StatePublic tblInfo.ID = tbl.id tblInfo.UpdateTS = t.StartTS err = t.CreateTableOrView(dbID, tblInfo) if err != nil { return errors.Trace(err) } } return nil } // InitMDLTable is to create tidb_mdl_info, which is used for metadata lock. func InitMDLTable(store kv.Storage) error { return kv.RunInNewTxn(kv.WithInternalSourceType(context.Background(), kv.InternalTxnDDL), store, true, func(ctx context.Context, txn kv.Transaction) error { t := meta.NewMeta(txn) ver, err := t.CheckDDLTableVersion() if err != nil || ver >= meta.MDLTableVersion { return errors.Trace(err) } dbID, err := t.CreateMySQLDatabaseIfNotExists() if err != nil { return err } splitAndScatterTable(store, []int64{ddl.MDLTableID}) p := parser.New() stmt, err := p.ParseOneStmt(mdlTable, "", "") if err != nil { return errors.Trace(err) } tblInfo, err := ddl.BuildTableInfoFromAST(stmt.(*ast.CreateTableStmt)) if err != nil { return errors.Trace(err) } tblInfo.State = model.StatePublic tblInfo.ID = ddl.MDLTableID tblInfo.UpdateTS = t.StartTS err = t.CreateTableOrView(dbID, tblInfo) if err != nil { return errors.Trace(err) } return t.SetDDLTables(meta.MDLTableVersion) }) } // InitMDLVariableForBootstrap initializes the metadata lock variable. func InitMDLVariableForBootstrap(store kv.Storage) error { err := kv.RunInNewTxn(kv.WithInternalSourceType(context.Background(), kv.InternalTxnDDL), store, true, func(ctx context.Context, txn kv.Transaction) error { t := meta.NewMeta(txn) return t.SetMetadataLock(true) }) if err != nil { return err } variable.EnableMDL.Store(true) return nil } // InitMDLVariableForUpgrade initializes the metadata lock variable. func InitMDLVariableForUpgrade(store kv.Storage) (bool, error) { isNull := false enable := false var err error err = kv.RunInNewTxn(kv.WithInternalSourceType(context.Background(), kv.InternalTxnDDL), store, true, func(ctx context.Context, txn kv.Transaction) error { t := meta.NewMeta(txn) enable, isNull, err = t.GetMetadataLock() if err != nil { return err } return nil }) if isNull || !enable { variable.EnableMDL.Store(false) } else { variable.EnableMDL.Store(true) } return isNull, err } // InitMDLVariable initializes the metadata lock variable. func InitMDLVariable(store kv.Storage) error { isNull := false enable := false var err error err = kv.RunInNewTxn(kv.WithInternalSourceType(context.Background(), kv.InternalTxnDDL), store, true, func(ctx context.Context, txn kv.Transaction) error { t := meta.NewMeta(txn) enable, isNull, err = t.GetMetadataLock() if err != nil { return err } if isNull { // Workaround for version: nightly-2022-11-07 to nightly-2022-11-17. enable = true logutil.BgLogger().Warn("metadata lock is null") err = t.SetMetadataLock(true) if err != nil { return err } } return nil }) variable.EnableMDL.Store(enable) return err } // BootstrapSession bootstrap session and domain. func BootstrapSession(store kv.Storage) (*domain.Domain, error) { return bootstrapSessionImpl(store, createSessions) } // BootstrapSession4DistExecution bootstrap session and dom for Distributed execution test, only for unit testing. func BootstrapSession4DistExecution(store kv.Storage) (*domain.Domain, error) { return bootstrapSessionImpl(store, createSessions4DistExecution) } func bootstrapSessionImpl(store kv.Storage, createSessionsImpl func(store kv.Storage, cnt int) ([]*session, error)) (*domain.Domain, error) { ctx := kv.WithInternalSourceType(context.Background(), kv.InternalTxnBootstrap) cfg := config.GetGlobalConfig() if len(cfg.Instance.PluginLoad) > 0 { err := plugin.Load(context.Background(), plugin.Config{ Plugins: strings.Split(cfg.Instance.PluginLoad, ","), PluginDir: cfg.Instance.PluginDir, }) if err != nil { return nil, err } } err := InitDDLJobTables(store, meta.BaseDDLTableVersion) if err != nil { return nil, err } err = InitMDLTable(store) if err != nil { return nil, err } err = InitDDLJobTables(store, meta.BackfillTableVersion) if err != nil { return nil, err } ver := getStoreBootstrapVersion(store) if ver == notBootstrapped { runInBootstrapSession(store, bootstrap) } else if ver < currentBootstrapVersion { runInBootstrapSession(store, upgrade) } else { err = InitMDLVariable(store) if err != nil { return nil, err } } analyzeConcurrencyQuota := int(config.GetGlobalConfig().Performance.AnalyzePartitionConcurrencyQuota) concurrency := int(config.GetGlobalConfig().Performance.StatsLoadConcurrency) ses, err := createSessionsImpl(store, 10) if err != nil { return nil, err } ses[0].GetSessionVars().InRestrictedSQL = true // get system tz from mysql.tidb tz, err := ses[0].getTableValue(ctx, mysql.TiDBTable, tidbSystemTZ) if err != nil { return nil, err } timeutil.SetSystemTZ(tz) // get the flag from `mysql`.`tidb` which indicating if new collations are enabled. newCollationEnabled, err := loadCollationParameter(ctx, ses[0]) if err != nil { return nil, err } collate.SetNewCollationEnabledForTest(newCollationEnabled) // To deal with the location partition failure caused by inconsistent NewCollationEnabled values(see issue #32416). rebuildAllPartitionValueMapAndSorted(ses[0]) dom := domain.GetDomain(ses[0]) // We should make the load bind-info loop before other loops which has internal SQL. // Because the internal SQL may access the global bind-info handler. As the result, the data race occurs here as the // LoadBindInfoLoop inits global bind-info handler. err = dom.LoadBindInfoLoop(ses[1], ses[2]) if err != nil { return nil, err } if !config.GetGlobalConfig().Security.SkipGrantTable { err = dom.LoadPrivilegeLoop(ses[3]) if err != nil { return nil, err } } // Rebuild sysvar cache in a loop err = dom.LoadSysVarCacheLoop(ses[4]) if err != nil { return nil, err } if config.GetGlobalConfig().DisaggregatedTiFlash && !config.GetGlobalConfig().UseAutoScaler { // Invalid client-go tiflash_compute store cache if necessary. err = dom.WatchTiFlashComputeNodeChange() if err != nil { return nil, err } } if err = extensionimpl.Bootstrap(context.Background(), dom); err != nil { return nil, err } if len(cfg.Instance.PluginLoad) > 0 { err := plugin.Init(context.Background(), plugin.Config{EtcdClient: dom.GetEtcdClient()}) if err != nil { return nil, err } } err = executor.LoadExprPushdownBlacklist(ses[5]) if err != nil { return nil, err } err = executor.LoadOptRuleBlacklist(ctx, ses[5]) if err != nil { return nil, err } if dom.GetEtcdClient() != nil { // We only want telemetry data in production-like clusters. When TiDB is deployed over other engines, // for example, unistore engine (used for local tests), we just skip it. Its etcd client is nil. if config.GetGlobalConfig().EnableTelemetry { // There is no way to turn telemetry on with global variable `tidb_enable_telemetry` // when it is disabled in config. See IsTelemetryEnabled function in telemetry/telemetry.go go func() { dom.TelemetryReportLoop(ses[5]) dom.TelemetryRotateSubWindowLoop(ses[5]) }() } } planReplayerWorkerCnt := config.GetGlobalConfig().Performance.PlanReplayerDumpWorkerConcurrency planReplayerWorkersSctx := make([]sessionctx.Context, planReplayerWorkerCnt) pworkerSes, err := createSessions(store, int(planReplayerWorkerCnt)) if err != nil { return nil, err } for i := 0; i < int(planReplayerWorkerCnt); i++ { planReplayerWorkersSctx[i] = pworkerSes[i] } // setup plan replayer handle dom.SetupPlanReplayerHandle(ses[6], planReplayerWorkersSctx) dom.StartPlanReplayerHandle() // setup dumpFileGcChecker dom.SetupDumpFileGCChecker(ses[7]) dom.DumpFileGcCheckerLoop() // setup historical stats worker dom.SetupHistoricalStatsWorker(ses[8]) dom.StartHistoricalStatsWorker() failToLoadOrParseSQLFile := false // only used for unit test if runBootstrapSQLFile { pm := &privileges.UserPrivileges{ Handle: dom.PrivilegeHandle(), } privilege.BindPrivilegeManager(ses[9], pm) if err := doBootstrapSQLFile(ses[9]); err != nil { failToLoadOrParseSQLFile = true } } // A sub context for update table stats, and other contexts for concurrent stats loading. cnt := 1 + concurrency syncStatsCtxs, err := createSessions(store, cnt) if err != nil { return nil, err } subCtxs := make([]sessionctx.Context, cnt) for i := 0; i < cnt; i++ { subCtxs[i] = sessionctx.Context(syncStatsCtxs[i]) } // setup extract Handle extractWorkers := 1 sctxs, err := createSessions(store, extractWorkers) if err != nil { return nil, err } extractWorkerSctxs := make([]sessionctx.Context, 0) for _, sctx := range sctxs { extractWorkerSctxs = append(extractWorkerSctxs, sctx) } dom.SetupExtractHandle(extractWorkerSctxs) // setup init stats loader initStatsCtx, err := createSession(store) if err != nil { return nil, err } if err = dom.LoadAndUpdateStatsLoop(subCtxs, initStatsCtx); err != nil { return nil, err } // start TTL job manager after setup stats collector // because TTL could modify a lot of columns, and need to trigger auto analyze ttlworker.AttachStatsCollector = func(s sqlexec.SQLExecutor) sqlexec.SQLExecutor { if s, ok := s.(*session); ok { return attachStatsCollector(s, dom) } return s } ttlworker.DetachStatsCollector = func(s sqlexec.SQLExecutor) sqlexec.SQLExecutor { if s, ok := s.(*session); ok { return detachStatsCollector(s) } return s } dom.StartTTLJobManager() analyzeCtxs, err := createSessions(store, analyzeConcurrencyQuota) if err != nil { return nil, err } subCtxs2 := make([]sessionctx.Context, analyzeConcurrencyQuota) for i := 0; i < analyzeConcurrencyQuota; i++ { subCtxs2[i] = analyzeCtxs[i] } dom.SetupAnalyzeExec(subCtxs2) dom.LoadSigningCertLoop(cfg.Security.SessionTokenSigningCert, cfg.Security.SessionTokenSigningKey) if raw, ok := store.(kv.EtcdBackend); ok { err = raw.StartGCWorker() if err != nil { return nil, err } } // This only happens in testing, since the failure of loading or parsing sql file // would panic the bootstrapping. if failToLoadOrParseSQLFile { dom.Close() return nil, err } err = dom.InitDistTaskLoop(ctx) if err != nil { return nil, err } return dom, err } // GetDomain gets the associated domain for store. func GetDomain(store kv.Storage) (*domain.Domain, error) { return domap.Get(store) } // runInBootstrapSession create a special session for bootstrap to run. // If no bootstrap and storage is remote, we must use a little lease time to // bootstrap quickly, after bootstrapped, we will reset the lease time. // TODO: Using a bootstrap tool for doing this may be better later. func runInBootstrapSession(store kv.Storage, bootstrap func(Session)) { s, err := createSession(store) if err != nil { // Bootstrap fail will cause program exit. logutil.BgLogger().Fatal("createSession error", zap.Error(err)) } // For the bootstrap SQLs, the following variables should be compatible with old TiDB versions. s.sessionVars.EnableClusteredIndex = variable.ClusteredIndexDefModeIntOnly s.SetValue(sessionctx.Initing, true) bootstrap(s) finishBootstrap(store) s.ClearValue(sessionctx.Initing) dom := domain.GetDomain(s) dom.Close() if intest.InTest { infosync.MockGlobalServerInfoManagerEntry.Close() } domap.Delete(store) } func createSessions(store kv.Storage, cnt int) ([]*session, error) { return createSessionsImpl(store, cnt, createSession) } func createSessions4DistExecution(store kv.Storage, cnt int) ([]*session, error) { domap.Delete(store) return createSessionsImpl(store, cnt, createSession4DistExecution) } func createSessionsImpl(store kv.Storage, cnt int, createSessionImpl func(kv.Storage) (*session, error)) ([]*session, error) { // Then we can create new dom ses := make([]*session, cnt) for i := 0; i < cnt; i++ { se, err := createSessionImpl(store) if err != nil { return nil, err } ses[i] = se } return ses, nil } // createSession creates a new session. // Please note that such a session is not tracked by the internal session list. // This means the min ts reporter is not aware of it and may report a wrong min start ts. // In most cases you should use a session pool in domain instead. func createSession(store kv.Storage) (*session, error) { return createSessionWithOpt(store, nil) } func createSession4DistExecution(store kv.Storage) (*session, error) { return createSessionWithOpt(store, nil) } func createSessionWithOpt(store kv.Storage, opt *Opt) (*session, error) { dom, err := domap.Get(store) if err != nil { return nil, err } s := &session{ store: store, ddlOwnerManager: dom.DDL().OwnerManager(), client: store.GetClient(), mppClient: store.GetMPPClient(), stmtStats: stmtstats.CreateStatementStats(), sessionStatesHandlers: make(map[sessionstates.SessionStateType]sessionctx.SessionStatesHandler), } s.sessionVars = variable.NewSessionVars(s) s.functionUsageMu.builtinFunctionUsage = make(telemetry.BuiltinFunctionsUsage) if opt != nil && opt.PreparedPlanCache != nil { s.sessionPlanCache = opt.PreparedPlanCache } s.mu.values = make(map[fmt.Stringer]interface{}) s.lockedTables = make(map[int64]model.TableLockTpInfo) s.advisoryLocks = make(map[string]*advisoryLock) domain.BindDomain(s, dom) // session implements variable.GlobalVarAccessor. Bind it to ctx. s.sessionVars.GlobalVarsAccessor = s s.sessionVars.BinlogClient = binloginfo.GetPumpsClient() s.txn.init() sessionBindHandle := bindinfo.NewSessionBindHandle() s.SetValue(bindinfo.SessionBindInfoKeyType, sessionBindHandle) s.SetSessionStatesHandler(sessionstates.StateBinding, sessionBindHandle) return s, nil } // attachStatsCollector attaches the stats collector in the dom for the session func attachStatsCollector(s *session, dom *domain.Domain) *session { if dom.StatsHandle() != nil && dom.StatsUpdating() { if s.statsCollector == nil { s.statsCollector = dom.StatsHandle().NewSessionStatsCollector() } if s.idxUsageCollector == nil && GetIndexUsageSyncLease() > 0 { s.idxUsageCollector = dom.StatsHandle().NewSessionIndexUsageCollector() } } return s } // detachStatsCollector removes the stats collector in the session func detachStatsCollector(s *session) *session { if s.statsCollector != nil { s.statsCollector.Delete() s.statsCollector = nil } if s.idxUsageCollector != nil { s.idxUsageCollector.Delete() s.idxUsageCollector = nil } return s } // CreateSessionWithDomain creates a new Session and binds it with a Domain. // We need this because when we start DDL in Domain, the DDL need a session // to change some system tables. But at that time, we have been already in // a lock context, which cause we can't call createSession directly. func CreateSessionWithDomain(store kv.Storage, dom *domain.Domain) (*session, error) { s := &session{ store: store, sessionVars: variable.NewSessionVars(nil), client: store.GetClient(), mppClient: store.GetMPPClient(), stmtStats: stmtstats.CreateStatementStats(), sessionStatesHandlers: make(map[sessionstates.SessionStateType]sessionctx.SessionStatesHandler), } s.functionUsageMu.builtinFunctionUsage = make(telemetry.BuiltinFunctionsUsage) s.mu.values = make(map[fmt.Stringer]interface{}) s.lockedTables = make(map[int64]model.TableLockTpInfo) domain.BindDomain(s, dom) // session implements variable.GlobalVarAccessor. Bind it to ctx. s.sessionVars.GlobalVarsAccessor = s s.txn.init() return s, nil } const ( notBootstrapped = 0 ) func getStoreBootstrapVersion(store kv.Storage) int64 { storeBootstrappedLock.Lock() defer storeBootstrappedLock.Unlock() // check in memory _, ok := storeBootstrapped[store.UUID()] if ok { return currentBootstrapVersion } var ver int64 // check in kv store ctx := kv.WithInternalSourceType(context.Background(), kv.InternalTxnBootstrap) err := kv.RunInNewTxn(ctx, store, false, func(ctx context.Context, txn kv.Transaction) error { var err error t := meta.NewMeta(txn) ver, err = t.GetBootstrapVersion() return err }) if err != nil { logutil.BgLogger().Fatal("check bootstrapped failed", zap.Error(err)) } if ver > notBootstrapped { // here mean memory is not ok, but other server has already finished it storeBootstrapped[store.UUID()] = true } return modifyBootstrapVersionForTest(store, ver) } func finishBootstrap(store kv.Storage) { setStoreBootstrapped(store.UUID()) ctx := kv.WithInternalSourceType(context.Background(), kv.InternalTxnBootstrap) err := kv.RunInNewTxn(ctx, store, true, func(ctx context.Context, txn kv.Transaction) error { t := meta.NewMeta(txn) err := t.FinishBootstrap(currentBootstrapVersion) return err }) if err != nil { logutil.BgLogger().Fatal("finish bootstrap failed", zap.Error(err)) } } const quoteCommaQuote = "', '" // loadCommonGlobalVariablesIfNeeded loads and applies commonly used global variables for the session. func (s *session) loadCommonGlobalVariablesIfNeeded() error { vars := s.sessionVars if vars.CommonGlobalLoaded { return nil } if s.Value(sessionctx.Initing) != nil { // When running bootstrap or upgrade, we should not access global storage. return nil } vars.CommonGlobalLoaded = true // Deep copy sessionvar cache sessionCache, err := domain.GetDomain(s).GetSessionCache() if err != nil { return err } for varName, varVal := range sessionCache { if _, ok := vars.GetSystemVar(varName); !ok { err = vars.SetSystemVarWithRelaxedValidation(varName, varVal) if err != nil { if variable.ErrUnknownSystemVar.Equal(err) { continue // sessionCache is stale; sysvar has likely been unregistered } return err } } } // when client set Capability Flags CLIENT_INTERACTIVE, init wait_timeout with interactive_timeout if vars.ClientCapability&mysql.ClientInteractive > 0 { if varVal, ok := vars.GetSystemVar(variable.InteractiveTimeout); ok { if err := vars.SetSystemVar(variable.WaitTimeout, varVal); err != nil { return err } } } return nil } // PrepareTxnCtx begins a transaction, and creates a new transaction context. // It is called before we execute a sql query. func (s *session) PrepareTxnCtx(ctx context.Context) error { s.currentCtx = ctx if s.txn.validOrPending() { return nil } txnMode := ast.Optimistic if !s.sessionVars.IsAutocommit() || config.GetGlobalConfig().PessimisticTxn.PessimisticAutoCommit.Load() { if s.sessionVars.TxnMode == ast.Pessimistic { txnMode = ast.Pessimistic } } if s.sessionVars.RetryInfo.Retrying { txnMode = ast.Pessimistic } return sessiontxn.GetTxnManager(s).EnterNewTxn(ctx, &sessiontxn.EnterNewTxnRequest{ Type: sessiontxn.EnterNewTxnBeforeStmt, TxnMode: txnMode, }) } // PrepareTSFuture uses to try to get ts future. func (s *session) PrepareTSFuture(ctx context.Context, future oracle.Future, scope string) error { if s.txn.Valid() { return errors.New("cannot prepare ts future when txn is valid") } failpoint.Inject("assertTSONotRequest", func() { if _, ok := future.(sessiontxn.ConstantFuture); !ok && !s.isInternal() { panic("tso shouldn't be requested") } }) failpoint.InjectContext(ctx, "mockGetTSFail", func() { future = txnFailFuture{} }) s.txn.changeToPending(&txnFuture{ future: future, store: s.store, txnScope: scope, }) return nil } // GetPreparedTxnFuture returns the TxnFuture if it is valid or pending. // It returns nil otherwise. func (s *session) GetPreparedTxnFuture() sessionctx.TxnFuture { if !s.txn.validOrPending() { return nil } return &s.txn } // RefreshTxnCtx implements context.RefreshTxnCtx interface. func (s *session) RefreshTxnCtx(ctx context.Context) error { var commitDetail *tikvutil.CommitDetails ctx = context.WithValue(ctx, tikvutil.CommitDetailCtxKey, &commitDetail) err := s.doCommit(ctx) if commitDetail != nil { s.GetSessionVars().StmtCtx.MergeExecDetails(nil, commitDetail) } if err != nil { return err } s.updateStatsDeltaToCollector() return sessiontxn.NewTxn(ctx, s) } // GetStore gets the store of session. func (s *session) GetStore() kv.Storage { return s.store } func (s *session) ShowProcess() *util.ProcessInfo { var pi *util.ProcessInfo tmp := s.processInfo.Load() if tmp != nil { pi = tmp.(*util.ProcessInfo) } return pi } // GetStartTSFromSession returns the startTS in the session `se` func GetStartTSFromSession(se interface{}) (startTS, processInfoID uint64) { tmp, ok := se.(*session) if !ok { logutil.BgLogger().Error("GetStartTSFromSession failed, can't transform to session struct") return 0, 0 } txnInfo := tmp.TxnInfo() if txnInfo != nil { startTS = txnInfo.StartTS processInfoID = txnInfo.ConnectionID } logutil.BgLogger().Debug( "GetStartTSFromSession getting startTS of internal session", zap.Uint64("startTS", startTS), zap.Time("start time", oracle.GetTimeFromTS(startTS))) return startTS, processInfoID } // logStmt logs some crucial SQL including: CREATE USER/GRANT PRIVILEGE/CHANGE PASSWORD/DDL etc and normal SQL // if variable.ProcessGeneralLog is set. func logStmt(execStmt *executor.ExecStmt, s *session) { vars := s.GetSessionVars() isCrucial := false switch stmt := execStmt.StmtNode.(type) { case *ast.DropIndexStmt: isCrucial = true if stmt.IsHypo { isCrucial = false } case *ast.CreateIndexStmt: isCrucial = true if stmt.IndexOption != nil && stmt.IndexOption.Tp == model.IndexTypeHypo { isCrucial = false } case *ast.CreateUserStmt, *ast.DropUserStmt, *ast.AlterUserStmt, *ast.SetPwdStmt, *ast.GrantStmt, *ast.RevokeStmt, *ast.AlterTableStmt, *ast.CreateDatabaseStmt, *ast.CreateTableStmt, *ast.DropDatabaseStmt, *ast.DropTableStmt, *ast.RenameTableStmt, *ast.TruncateTableStmt, *ast.RenameUserStmt: isCrucial = true } if isCrucial { user := vars.User schemaVersion := s.GetInfoSchema().SchemaMetaVersion() if ss, ok := execStmt.StmtNode.(ast.SensitiveStmtNode); ok { logutil.BgLogger().Info("CRUCIAL OPERATION", zap.Uint64("conn", vars.ConnectionID), zap.Int64("schemaVersion", schemaVersion), zap.String("secure text", ss.SecureText()), zap.Stringer("user", user)) } else { logutil.BgLogger().Info("CRUCIAL OPERATION", zap.Uint64("conn", vars.ConnectionID), zap.Int64("schemaVersion", schemaVersion), zap.String("cur_db", vars.CurrentDB), zap.String("sql", execStmt.StmtNode.Text()), zap.Stringer("user", user)) } } else { logGeneralQuery(execStmt, s, false) } } func logGeneralQuery(execStmt *executor.ExecStmt, s *session, isPrepared bool) { vars := s.GetSessionVars() if variable.ProcessGeneralLog.Load() && !vars.InRestrictedSQL { var query string if isPrepared { query = execStmt.OriginText() } else { query = execStmt.GetTextToLog(false) } query = executor.QueryReplacer.Replace(query) if !vars.EnableRedactLog { query += vars.PlanCacheParams.String() } logutil.BgLogger().Info("GENERAL_LOG", zap.Uint64("conn", vars.ConnectionID), zap.String("session_alias", vars.SessionAlias), zap.String("user", vars.User.LoginString()), zap.Int64("schemaVersion", s.GetInfoSchema().SchemaMetaVersion()), zap.Uint64("txnStartTS", vars.TxnCtx.StartTS), zap.Uint64("forUpdateTS", vars.TxnCtx.GetForUpdateTS()), zap.Bool("isReadConsistency", vars.IsIsolation(ast.ReadCommitted)), zap.String("currentDB", vars.CurrentDB), zap.Bool("isPessimistic", vars.TxnCtx.IsPessimistic), zap.String("sessionTxnMode", vars.GetReadableTxnMode()), zap.String("sql", query)) } } func (s *session) recordOnTransactionExecution(err error, counter int, duration float64, isInternal bool) { if s.sessionVars.TxnCtx.IsPessimistic { if err != nil { if isInternal { session_metrics.TransactionDurationPessimisticAbortInternal.Observe(duration) session_metrics.StatementPerTransactionPessimisticErrorInternal.Observe(float64(counter)) } else { session_metrics.TransactionDurationPessimisticAbortGeneral.Observe(duration) session_metrics.StatementPerTransactionPessimisticErrorGeneral.Observe(float64(counter)) } } else { if isInternal { session_metrics.TransactionDurationPessimisticCommitInternal.Observe(duration) session_metrics.StatementPerTransactionPessimisticOKInternal.Observe(float64(counter)) } else { session_metrics.TransactionDurationPessimisticCommitGeneral.Observe(duration) session_metrics.StatementPerTransactionPessimisticOKGeneral.Observe(float64(counter)) } } } else { if err != nil { if isInternal { session_metrics.TransactionDurationOptimisticAbortInternal.Observe(duration) session_metrics.StatementPerTransactionOptimisticErrorInternal.Observe(float64(counter)) } else { session_metrics.TransactionDurationOptimisticAbortGeneral.Observe(duration) session_metrics.StatementPerTransactionOptimisticErrorGeneral.Observe(float64(counter)) } } else { if isInternal { session_metrics.TransactionDurationOptimisticCommitInternal.Observe(duration) session_metrics.StatementPerTransactionOptimisticOKInternal.Observe(float64(counter)) } else { session_metrics.TransactionDurationOptimisticCommitGeneral.Observe(duration) session_metrics.StatementPerTransactionOptimisticOKGeneral.Observe(float64(counter)) } } } } func (s *session) checkPlacementPolicyBeforeCommit() error { var err error // Get the txnScope of the transaction we're going to commit. txnScope := s.GetSessionVars().TxnCtx.TxnScope if txnScope == "" { txnScope = kv.GlobalTxnScope } if txnScope != kv.GlobalTxnScope { is := s.GetInfoSchema().(infoschema.InfoSchema) deltaMap := s.GetSessionVars().TxnCtx.TableDeltaMap for physicalTableID := range deltaMap { var tableName string var partitionName string tblInfo, _, partInfo := is.FindTableByPartitionID(physicalTableID) if tblInfo != nil && partInfo != nil { tableName = tblInfo.Meta().Name.String() partitionName = partInfo.Name.String() } else { tblInfo, _ := is.TableByID(physicalTableID) tableName = tblInfo.Meta().Name.String() } bundle, ok := is.PlacementBundleByPhysicalTableID(physicalTableID) if !ok { errMsg := fmt.Sprintf("table %v doesn't have placement policies with txn_scope %v", tableName, txnScope) if len(partitionName) > 0 { errMsg = fmt.Sprintf("table %v's partition %v doesn't have placement policies with txn_scope %v", tableName, partitionName, txnScope) } err = dbterror.ErrInvalidPlacementPolicyCheck.GenWithStackByArgs(errMsg) break } dcLocation, ok := bundle.GetLeaderDC(placement.DCLabelKey) if !ok { errMsg := fmt.Sprintf("table %v's leader placement policy is not defined", tableName) if len(partitionName) > 0 { errMsg = fmt.Sprintf("table %v's partition %v's leader placement policy is not defined", tableName, partitionName) } err = dbterror.ErrInvalidPlacementPolicyCheck.GenWithStackByArgs(errMsg) break } if dcLocation != txnScope { errMsg := fmt.Sprintf("table %v's leader location %v is out of txn_scope %v", tableName, dcLocation, txnScope) if len(partitionName) > 0 { errMsg = fmt.Sprintf("table %v's partition %v's leader location %v is out of txn_scope %v", tableName, partitionName, dcLocation, txnScope) } err = dbterror.ErrInvalidPlacementPolicyCheck.GenWithStackByArgs(errMsg) break } // FIXME: currently we assume the physicalTableID is the partition ID. In future, we should consider the situation // if the physicalTableID belongs to a Table. partitionID := physicalTableID tbl, _, partitionDefInfo := is.FindTableByPartitionID(partitionID) if tbl != nil { tblInfo := tbl.Meta() state := tblInfo.Partition.GetStateByID(partitionID) if state == model.StateGlobalTxnOnly { err = dbterror.ErrInvalidPlacementPolicyCheck.GenWithStackByArgs( fmt.Sprintf("partition %s of table %s can not be written by local transactions when its placement policy is being altered", tblInfo.Name, partitionDefInfo.Name)) break } } } } return err } func (s *session) SetPort(port string) { s.sessionVars.Port = port } // GetTxnWriteThroughputSLI implements the Context interface. func (s *session) GetTxnWriteThroughputSLI() *sli.TxnWriteThroughputSLI { return &s.txn.writeSLI } // GetInfoSchema returns snapshotInfoSchema if snapshot schema is set. // Transaction infoschema is returned if inside an explicit txn. // Otherwise the latest infoschema is returned. func (s *session) GetInfoSchema() sessionctx.InfoschemaMetaVersion { vars := s.GetSessionVars() var is infoschema.InfoSchema if snap, ok := vars.SnapshotInfoschema.(infoschema.InfoSchema); ok { logutil.BgLogger().Info("use snapshot schema", zap.Uint64("conn", vars.ConnectionID), zap.Int64("schemaVersion", snap.SchemaMetaVersion())) is = snap } else { vars.TxnCtxMu.Lock() if vars.TxnCtx != nil { if tmp, ok := vars.TxnCtx.InfoSchema.(infoschema.InfoSchema); ok { is = tmp } } vars.TxnCtxMu.Unlock() } if is == nil { is = domain.GetDomain(s).InfoSchema() } // Override the infoschema if the session has temporary table. return temptable.AttachLocalTemporaryTableInfoSchema(s, is) } func (s *session) GetDomainInfoSchema() sessionctx.InfoschemaMetaVersion { is := domain.GetDomain(s).InfoSchema() extIs := &infoschema.SessionExtendedInfoSchema{InfoSchema: is} return temptable.AttachLocalTemporaryTableInfoSchema(s, extIs) } func getSnapshotInfoSchema(s sessionctx.Context, snapshotTS uint64) (infoschema.InfoSchema, error) { is, err := domain.GetDomain(s).GetSnapshotInfoSchema(snapshotTS) if err != nil { return nil, err } // Set snapshot does not affect the witness of the local temporary table. // The session always see the latest temporary tables. return temptable.AttachLocalTemporaryTableInfoSchema(s, is), nil } func (s *session) updateTelemetryMetric(es *executor.ExecStmt) { if es.Ti == nil { return } if s.isInternal() { return } ti := es.Ti if ti.UseRecursive { session_metrics.TelemetryCTEUsageRecurCTE.Inc() } else if ti.UseNonRecursive { session_metrics.TelemetryCTEUsageNonRecurCTE.Inc() } else { session_metrics.TelemetryCTEUsageNotCTE.Inc() } if ti.UseIndexMerge { session_metrics.TelemetryIndexMerge.Inc() } if ti.UseMultiSchemaChange { session_metrics.TelemetryMultiSchemaChangeUsage.Inc() } if ti.UseFlashbackToCluster { session_metrics.TelemetryFlashbackClusterUsage.Inc() } if ti.UseExchangePartition { session_metrics.TelemetryExchangePartitionUsage.Inc() } if ti.PartitionTelemetry != nil { if ti.PartitionTelemetry.UseTablePartition { session_metrics.TelemetryTablePartitionUsage.Inc() session_metrics.TelemetryTablePartitionMaxPartitionsUsage.Add(float64(ti.PartitionTelemetry.TablePartitionMaxPartitionsNum)) } if ti.PartitionTelemetry.UseTablePartitionList { session_metrics.TelemetryTablePartitionListUsage.Inc() } if ti.PartitionTelemetry.UseTablePartitionRange { session_metrics.TelemetryTablePartitionRangeUsage.Inc() } if ti.PartitionTelemetry.UseTablePartitionHash { session_metrics.TelemetryTablePartitionHashUsage.Inc() } if ti.PartitionTelemetry.UseTablePartitionRangeColumns { session_metrics.TelemetryTablePartitionRangeColumnsUsage.Inc() } if ti.PartitionTelemetry.UseTablePartitionRangeColumnsGt1 { session_metrics.TelemetryTablePartitionRangeColumnsGt1Usage.Inc() } if ti.PartitionTelemetry.UseTablePartitionRangeColumnsGt2 { session_metrics.TelemetryTablePartitionRangeColumnsGt2Usage.Inc() } if ti.PartitionTelemetry.UseTablePartitionRangeColumnsGt3 { session_metrics.TelemetryTablePartitionRangeColumnsGt3Usage.Inc() } if ti.PartitionTelemetry.UseTablePartitionListColumns { session_metrics.TelemetryTablePartitionListColumnsUsage.Inc() } if ti.PartitionTelemetry.UseCreateIntervalPartition { session_metrics.TelemetryTablePartitionCreateIntervalUsage.Inc() } if ti.PartitionTelemetry.UseAddIntervalPartition { session_metrics.TelemetryTablePartitionAddIntervalUsage.Inc() } if ti.PartitionTelemetry.UseDropIntervalPartition { session_metrics.TelemetryTablePartitionDropIntervalUsage.Inc() } if ti.PartitionTelemetry.UseCompactTablePartition { session_metrics.TelemetryTableCompactPartitionUsage.Inc() } if ti.PartitionTelemetry.UseReorganizePartition { session_metrics.TelemetryReorganizePartitionUsage.Inc() } } if ti.AccountLockTelemetry != nil { session_metrics.TelemetryLockUserUsage.Add(float64(ti.AccountLockTelemetry.LockUser)) session_metrics.TelemetryUnlockUserUsage.Add(float64(ti.AccountLockTelemetry.UnlockUser)) session_metrics.TelemetryCreateOrAlterUserUsage.Add(float64(ti.AccountLockTelemetry.CreateOrAlterUser)) } if ti.UseTableLookUp.Load() && s.sessionVars.StoreBatchSize > 0 { session_metrics.TelemetryStoreBatchedUsage.Inc() } } // GetBuiltinFunctionUsage returns the replica of counting of builtin function usage func (s *session) GetBuiltinFunctionUsage() map[string]uint32 { replica := make(map[string]uint32) s.functionUsageMu.RLock() defer s.functionUsageMu.RUnlock() for key, value := range s.functionUsageMu.builtinFunctionUsage { replica[key] = value } return replica } // BuiltinFunctionUsageInc increase the counting of the builtin function usage func (s *session) BuiltinFunctionUsageInc(scalarFuncSigName string) { s.functionUsageMu.Lock() defer s.functionUsageMu.Unlock() s.functionUsageMu.builtinFunctionUsage.Inc(scalarFuncSigName) } func (s *session) GetStmtStats() *stmtstats.StatementStats { return s.stmtStats } // SetMemoryFootprintChangeHook sets the hook that is called when the memdb changes its size. // Call this after s.txn becomes valid, since TxnInfo is initialized when the txn becomes valid. func (s *session) SetMemoryFootprintChangeHook() { if config.GetGlobalConfig().Performance.TxnTotalSizeLimit != config.DefTxnTotalSizeLimit { // if the user manually specifies the config, don't involve the new memory tracker mechanism, let the old config // work as before. return } hook := func(mem uint64) { if s.sessionVars.MemDBFootprint == nil { tracker := memory.NewTracker(memory.LabelForMemDB, -1) tracker.AttachTo(s.sessionVars.MemTracker) s.sessionVars.MemDBFootprint = tracker } s.sessionVars.MemDBFootprint.ReplaceBytesUsed(int64(mem)) } s.txn.SetMemoryFootprintChangeHook(hook) } // EncodeSessionStates implements SessionStatesHandler.EncodeSessionStates interface. func (s *session) EncodeSessionStates(ctx context.Context, _ sessionctx.Context, sessionStates *sessionstates.SessionStates) error { // Transaction status is hard to encode, so we do not support it. s.txn.mu.Lock() valid := s.txn.Valid() s.txn.mu.Unlock() if valid { return sessionstates.ErrCannotMigrateSession.GenWithStackByArgs("session has an active transaction") } // Data in local temporary tables is hard to encode, so we do not support it. // Check temporary tables here to avoid circle dependency. if s.sessionVars.LocalTemporaryTables != nil { localTempTables := s.sessionVars.LocalTemporaryTables.(*infoschema.SessionTables) if localTempTables.Count() > 0 { return sessionstates.ErrCannotMigrateSession.GenWithStackByArgs("session has local temporary tables") } } // The advisory locks will be released when the session is closed. if len(s.advisoryLocks) > 0 { return sessionstates.ErrCannotMigrateSession.GenWithStackByArgs("session has advisory locks") } // The TableInfo stores session ID and server ID, so the session cannot be migrated. if len(s.lockedTables) > 0 { return sessionstates.ErrCannotMigrateSession.GenWithStackByArgs("session has locked tables") } // It's insecure to migrate sandBoxMode because users can fake it. if s.InSandBoxMode() { return sessionstates.ErrCannotMigrateSession.GenWithStackByArgs("session is in sandbox mode") } if err := s.sessionVars.EncodeSessionStates(ctx, sessionStates); err != nil { return err } // Encode session variables. We put it here instead of SessionVars to avoid cycle import. sessionStates.SystemVars = make(map[string]string) for _, sv := range variable.GetSysVars() { switch { case sv.HasNoneScope(), sv.HasInstanceScope(), !sv.HasSessionScope(): // Hidden attribute is deprecated. // None-scoped variables cannot be modified. // Instance-scoped variables don't need to be encoded. // Noop variables should also be migrated even if they are noop. continue case sv.ReadOnly: // Skip read-only variables here. We encode them into SessionStates manually. continue case sem.IsEnabled() && sem.IsInvisibleSysVar(sv.Name): // If they are shown, there will be a security issue. continue } // Get all session variables because the default values may change between versions. if val, keep, err := s.sessionVars.GetSessionStatesSystemVar(sv.Name); err != nil { return err } else if keep { sessionStates.SystemVars[sv.Name] = val } } // Encode prepared statements and sql bindings. for _, handler := range s.sessionStatesHandlers { if err := handler.EncodeSessionStates(ctx, s, sessionStates); err != nil { return err } } return nil } // DecodeSessionStates implements SessionStatesHandler.DecodeSessionStates interface. func (s *session) DecodeSessionStates(ctx context.Context, _ sessionctx.Context, sessionStates *sessionstates.SessionStates) error { // Decode prepared statements and sql bindings. for _, handler := range s.sessionStatesHandlers { if err := handler.DecodeSessionStates(ctx, s, sessionStates); err != nil { return err } } // Decode session variables. names := variable.OrderByDependency(sessionStates.SystemVars) // Some variables must be set before others, e.g. tidb_enable_noop_functions should be before noop variables. for _, name := range names { val := sessionStates.SystemVars[name] // Experimental system variables may change scope, data types, or even be removed. // We just ignore the errors and continue. if err := s.sessionVars.SetSystemVar(name, val); err != nil { logutil.Logger(ctx).Warn("set session variable during decoding session states error", zap.String("name", name), zap.String("value", val), zap.Error(err)) } } // Decoding session vars / prepared statements may override stmt ctx, such as warnings, // so we decode stmt ctx at last. return s.sessionVars.DecodeSessionStates(ctx, sessionStates) } func (s *session) setRequestSource(ctx context.Context, stmtLabel string, stmtNode ast.StmtNode) { if !s.isInternal() { if txn, _ := s.Txn(false); txn != nil && txn.Valid() { txn.SetOption(kv.RequestSourceType, stmtLabel) } else { s.sessionVars.RequestSourceType = stmtLabel } return } if source := ctx.Value(kv.RequestSourceKey); source != nil { requestSource := source.(kv.RequestSource) if requestSource.RequestSourceType != "" { s.sessionVars.RequestSourceType = requestSource.RequestSourceType return } } // panic in test mode in case there are requests without source in the future. // log warnings in production mode. if intest.InTest { panic("unexpected no source type context, if you see this error, " + "the `RequestSourceTypeKey` is missing in your context") } else { logutil.Logger(ctx).Warn("unexpected no source type context, if you see this warning, "+ "the `RequestSourceTypeKey` is missing in the context", zap.Bool("internal", s.isInternal()), zap.String("sql", stmtNode.Text())) } } // RemoveLockDDLJobs removes the DDL jobs which doesn't get the metadata lock from job2ver. func RemoveLockDDLJobs(s Session, job2ver map[int64]int64, job2ids map[int64]string, printLog bool) { sv := s.GetSessionVars() if sv.InRestrictedSQL { return } sv.TxnCtxMu.Lock() defer sv.TxnCtxMu.Unlock() if sv.TxnCtx == nil { return } sv.GetRelatedTableForMDL().Range(func(tblID, value any) bool { for jobID, ver := range job2ver { ids := util.Str2Int64Map(job2ids[jobID]) if _, ok := ids[tblID.(int64)]; ok && value.(int64) < ver { delete(job2ver, jobID) elapsedTime := time.Since(oracle.GetTimeFromTS(sv.TxnCtx.StartTS)) if elapsedTime > time.Minute && printLog { logutil.BgLogger().Info("old running transaction block DDL", zap.Int64("table ID", tblID.(int64)), zap.Int64("jobID", jobID), zap.Uint64("connection ID", sv.ConnectionID), zap.Duration("elapsed time", elapsedTime)) } else { logutil.BgLogger().Debug("old running transaction block DDL", zap.Int64("table ID", tblID.(int64)), zap.Int64("jobID", jobID), zap.Uint64("connection ID", sv.ConnectionID), zap.Duration("elapsed time", elapsedTime)) } } } return true }) } // GetDBNames gets the sql layer database names from the session. func GetDBNames(seVar *variable.SessionVars) []string { dbNames := make(map[string]struct{}) if seVar == nil || !config.GetGlobalConfig().Status.RecordDBLabel { return []string{""} } if seVar.StmtCtx != nil { for _, t := range seVar.StmtCtx.Tables { dbNames[t.DB] = struct{}{} } } if len(dbNames) == 0 { dbNames[seVar.CurrentDB] = struct{}{} } ns := make([]string, 0, len(dbNames)) for n := range dbNames { ns = append(ns, n) } return ns }
package workerpool import "sync" type WorkerPool struct { maxWorkerNumber int workers []*Worker objectPool *sync.Pool } type Worker struct { }
package index import "github.com/Mintegral-official/juno/document" type StorageIndex interface { Get(filedName string, id document.DocId) interface{} }
package merchant import ( "context" "tpay_backend/adminapi/internal/common" "tpay_backend/model" "tpay_backend/adminapi/internal/svc" "tpay_backend/adminapi/internal/types" "github.com/tal-tech/go-zero/core/logx" ) type GetMerchantBankCardListLogic struct { logx.Logger ctx context.Context svcCtx *svc.ServiceContext } func NewGetMerchantBankCardListLogic(ctx context.Context, svcCtx *svc.ServiceContext) GetMerchantBankCardListLogic { return GetMerchantBankCardListLogic{ Logger: logx.WithContext(ctx), ctx: ctx, svcCtx: svcCtx, } } func (l *GetMerchantBankCardListLogic) GetMerchantBankCardList(req types.GetMerchantBankCardListRequest) (*types.GetMerchantBankCardListResponse, error) { f := model.FindMerchantBankCardList{ Search: req.Search, Page: req.Page, PageSize: req.PageSize, } list, total, err := model.NewMerchantBankCardModel(l.svcCtx.DbEngine).FindList(f) if err != nil { l.Errorf("查询商户银行卡列表失败, err=%v", err) return nil, common.NewCodeError(common.SysDBGet) } var cardList []types.MerchantBankCard for _, v := range list { cardList = append(cardList, types.MerchantBankCard{ CardId: v.Id, Username: v.MerchantUsername, BankName: v.BankName, AccountName: v.AccountName, CardNumber: v.CardNumber, BranchName: v.BranchName, Currency: v.Currency, Remark: v.Remark, CreateTime: v.CreateTime, UpdateTime: v.UpdateTime, }) } return &types.GetMerchantBankCardListResponse{ Total: total, List: cardList, }, nil }
package server import ("strings" "fmt" "io/ioutil" "encoding/json" "net/http" "strconv" ) /* This structure will be used by JSON data returned from yahoo finance API */ type Jsonresponse struct { List struct { Resources []struct { Resource struct { Fields struct { Name string Price string Symbol string } } } } } var noOfShares map[string]int // This map will save share as key, and no of shares purchased by the user as Values var url = "http://finance.yahoo.com/webservice/v1/symbols/" /* This function will create Yahoo finance API URL from user input */ func makeUrl(stocksWithPercentage []string) (map[string]string, string){ stocksData := make(map[string]string) var symbolStr string for data := range stocksWithPercentage { singleStock := strings.Split(stocksWithPercentage[data],":") percentage := strings.Split(singleStock[1],"%") stocksData[singleStock[0]] = percentage[0] } for symbol := range stocksData { symbolStr += symbol + "," } symbolStr = symbolStr[:len(symbolStr)-1] urlCreated := url+symbolStr+"/quote?format=json&view=‌detail" fmt.Println("url: ",urlCreated) return stocksData, urlCreated } /* This function will call get on yahoo finance api to fetch JSON data, and populate Jsonresponse structure */ func DataFromYahoo(url string) { resp, err := http.Get(url) if err!=nil { fmt.Println("Error from DataFromYahoo function: ",err) } else { defer resp.Body.Close() jsonDataFromHttp, err := ioutil.ReadAll(resp.Body) if err != nil { panic(err) } err = json.Unmarshal([]byte(jsonDataFromHttp), &DataPopulated) if err != nil { fmt.Println("error: ",err) panic(err) } } } /* This map will have mapping of shares requestes by the user to buy, to its current market price. */ func makeStockWithCurrentPriceMap(data Jsonresponse) map[string]float64{ stocksPrice := make(map[string]float64) for _, resourceList := range DataPopulated.List.Resources { price, err := strconv.ParseFloat(resourceList.Resource.Fields.Price,64) if err!= nil { fmt.Println(err) } else { stocksPrice[resourceList.Resource.Fields.Symbol] = price } } return stocksPrice } /* This function will calculate budget for each share requested by the user, no of shares bought in that budget allocated for the particular share uninvestedAmount that remains with the user. Finally, this function will populate Reply structure that will be returned to the user */ func stocksPurchased(budget float32,stocksData map[string]string, stockPrice map[string]float64, reply *Reply) { var uninvestedAmount float64 uninvestedAmount = float64(budget) noOfShares = make(map[string]int) for share, percentage := range stocksData { percentage, err := strconv.ParseFloat(percentage,64) if err == nil { budgetForShare := (float64(budget) * (percentage/100)) uninvestedAmount = float64(uninvestedAmount) - budgetForShare sharesCount := budgetForShare /stockPrice[share] noOfShares[share] = int(sharesCount) uninvestedAmount += budgetForShare - float64(int(sharesCount))*stockPrice[share] } } var stocks string for share, count := range noOfShares { stocks+=string(share)+":"+ strconv.Itoa(count) +":$" + strconv.FormatFloat(stockPrice[share], 'G', -1, 64) + "," } stocks = stocks[:len(stocks)-1] reply.UnivestedAmount = float32(uninvestedAmount) reply.Stocks = stocks tradeId = tradeId+1 reply.TradeId = tradeId tradeIdWithSharesMap[reply.TradeId] = noOfShares tradeIdWithUninvestedAmount[reply.TradeId] = uninvestedAmount } /* This function will populate PortFolioReply strucure that will be returend to the user, when user request portfolio view request. */ func FetchPortFolioRecords(tradeId int,reply *PortFolioReply) { var symbolStr string var stocks string var marketValue float64 if len(tradeIdWithSharesMap[tradeId]) == 0 { reply.ErrorMessage = "No portfolio available for TradeId "+strconv.Itoa(tradeId)+". Please buy some shares first" return } sharesWithNo := tradeIdWithSharesMap[tradeId] for share, _ := range sharesWithNo { symbolStr +=share+"," } symbolStr = symbolStr[:len(symbolStr)-1] urlCreated := url+symbolStr+"/quote?format=json&view=‌detail" DataFromYahoo(urlCreated) stocksPrice := makeStockWithCurrentPriceMap(DataPopulated) for share, count := range sharesWithNo { stocks += share+":"+ strconv.Itoa(count)+":$"+ strconv.FormatFloat(stocksPrice[share], 'G', -1, 64)+"," marketValue += stocksPrice[share]*float64(count) } reply.Stocks = stocks[:len(stocks)-1] reply.CurrentMarketValue = float32(marketValue) reply.UnivestedAmount = float32(tradeIdWithUninvestedAmount[tradeId]) }
package io import "time" type TimeBuilder func() time.Time func NowBuilder() TimeBuilder { return func() time.Time { return time.Now() } } func FixedTimeBuilder(t time.Time) TimeBuilder { return func() time.Time { return t } } func FixedUnixTimeBuilder(sec int64) TimeBuilder { return func() time.Time { return time.Unix(sec, 0) } }
package crud_interface import ( "net/http" ) type Database interface { CreateCustomer(w http.ResponseWriter,r *http.Request) GetId(w http.ResponseWriter,r *http.Request) GetAll(w http.ResponseWriter,r *http.Request) CustomerCtx(next http.Handler) http.Handler }
package data import ( "github.com/flynn/flynn/controller/schema" ct "github.com/flynn/flynn/controller/types" "github.com/flynn/flynn/pkg/postgres" routerc "github.com/flynn/flynn/router/client" "github.com/flynn/flynn/router/types" ) func routeParentRef(appID string) string { return ct.RouteParentRefPrefix + appID } func CreateRoute(db *postgres.DB, rc routerc.Client, appID string, route *router.Route) error { route.ParentRef = routeParentRef(appID) if err := schema.Validate(route); err != nil { return err } return rc.CreateRoute(route) }
package nougat import ( "net/url" "reflect" "testing" ) func TestAddHeader(t *testing.T) { cases := []struct { Nougat *Nougat expectedHeader map[string][]string }{ {New().Add("authorization", "OAuth key=\"value\""), map[string][]string{"Authorization": []string{"OAuth key=\"value\""}}}, // header keys should be canonicalized {New().Add("content-tYPE", "application/json").Add("User-AGENT", "Nougat"), map[string][]string{"Content-Type": []string{"application/json"}, "User-Agent": []string{"Nougat"}}}, // values for existing keys should be appended {New().Add("A", "B").Add("a", "c"), map[string][]string{"A": []string{"B", "c"}}}, // Add should add to values for keys added by parent Nougats {New().Add("A", "B").Add("a", "c").New(), map[string][]string{"A": []string{"B", "c"}}}, {New().Add("A", "B").New().Add("a", "c"), map[string][]string{"A": []string{"B", "c"}}}, } for _, c := range cases { // type conversion from header to alias'd map for deep equality comparison headerMap := map[string][]string(c.Nougat.header) if !reflect.DeepEqual(c.expectedHeader, headerMap) { t.Errorf("not DeepEqual: expected %v, got %v", c.expectedHeader, headerMap) } } } func TestSetHeader(t *testing.T) { cases := []struct { Nougat *Nougat expectedHeader map[string][]string }{ // should replace existing values associated with key {New().Add("A", "B").Set("a", "c"), map[string][]string{"A": []string{"c"}}}, {New().Set("content-type", "A").Set("Content-Type", "B"), map[string][]string{"Content-Type": []string{"B"}}}, // Set should replace values received by copying parent Nougats {New().Set("A", "B").Add("a", "c").New(), map[string][]string{"A": []string{"B", "c"}}}, {New().Add("A", "B").New().Set("a", "c"), map[string][]string{"A": []string{"c"}}}, } for _, c := range cases { // type conversion from Header to alias'd map for deep equality comparison headerMap := map[string][]string(c.Nougat.header) if !reflect.DeepEqual(c.expectedHeader, headerMap) { t.Errorf("not DeepEqual: expected %v, got %v", c.expectedHeader, headerMap) } } } func TestBasicAuth(t *testing.T) { cases := []struct { Nougat *Nougat expectedAuth []string }{ // basic auth: username & password {New().SetBasicAuth("Aladdin", "open sesame"), []string{"Aladdin", "open sesame"}}, // empty username {New().SetBasicAuth("", "secret"), []string{"", "secret"}}, // empty password {New().SetBasicAuth("admin", ""), []string{"admin", ""}}, } for _, c := range cases { req, err := c.Nougat.Request() if err != nil { t.Errorf("unexpected error when building Request with .SetBasicAuth()") } username, password, ok := req.BasicAuth() if !ok { t.Errorf("basic auth missing when expected") } auth := []string{username, password} if !reflect.DeepEqual(c.expectedAuth, auth) { t.Errorf("not DeepEqual: expected %v, got %v", c.expectedAuth, auth) } } } func TestAddQueryStructs(t *testing.T) { cases := []struct { rawurl string queryStructs []interface{} expected string }{ {"http://a.io", []interface{}{}, "http://a.io"}, {"http://a.io", []interface{}{paramsA}, "http://a.io?limit=30"}, {"http://a.io", []interface{}{paramsA, paramsA}, "http://a.io?limit=30&limit=30"}, {"http://a.io", []interface{}{paramsA, paramsB}, "http://a.io?count=25&kind_name=recent&limit=30"}, // don't blow away query values on the rawURL (parsed into RawQuery) {"http://a.io?initial=7", []interface{}{paramsA}, "http://a.io?initial=7&limit=30"}, } for _, c := range cases { reqURL, _ := url.Parse(c.rawurl) addQueryStructs(reqURL, c.queryStructs) if reqURL.String() != c.expected { t.Errorf("expected %s, got %s", c.expected, reqURL.String()) } } } func TestRequest_headers(t *testing.T) { cases := []struct { Nougat *Nougat expectedHeader map[string][]string }{ {New().Add("authorization", "OAuth key=\"value\""), map[string][]string{"Authorization": []string{"OAuth key=\"value\""}}}, // header keys should be canonicalized {New().Add("content-tYPE", "application/json").Add("User-AGENT", "Nougat"), map[string][]string{"Content-Type": []string{"application/json"}, "User-Agent": []string{"Nougat"}}}, // values for existing keys should be appended {New().Add("A", "B").Add("a", "c"), map[string][]string{"A": []string{"B", "c"}}}, // Add should add to values for keys added by parent Nougats {New().Add("A", "B").Add("a", "c").New(), map[string][]string{"A": []string{"B", "c"}}}, {New().Add("A", "B").New().Add("a", "c"), map[string][]string{"A": []string{"B", "c"}}}, // Add and Set {New().Add("A", "B").Set("a", "c"), map[string][]string{"A": []string{"c"}}}, {New().Set("content-type", "A").Set("Content-Type", "B"), map[string][]string{"Content-Type": []string{"B"}}}, // Set should replace values received by copying parent Nougats {New().Set("A", "B").Add("a", "c").New(), map[string][]string{"A": []string{"B", "c"}}}, {New().Add("A", "B").New().Set("a", "c"), map[string][]string{"A": []string{"c"}}}, } for _, c := range cases { req, _ := c.Nougat.Request() // type conversion from Header to alias'd map for deep equality comparison headerMap := map[string][]string(req.Header) if !reflect.DeepEqual(c.expectedHeader, headerMap) { t.Errorf("not DeepEqual: expected %v, got %v", c.expectedHeader, headerMap) } } }
package main import ( "flag" "fmt" "github.com/jkomoros/sudoku/cmd/dokugen-analysis/internal/wekaparser" "io/ioutil" "log" "os" "os/exec" ) const temporaryArff = "solves.arff" var wekaJar string type appOptions struct { inFile string outFile string help bool flagSet *flag.FlagSet } func init() { //Check for various installed versions of Weka //TODO: make this WAY more resilient to different versions possibleJarLocations := []string{ "/Applications/weka-3-6-11-oracle-jvm.app/Contents/Java/weka.jar", "/Applications/weka-3-6-12-oracle-jvm.app/Contents/Java/weka.jar", } for _, path := range possibleJarLocations { if _, err := os.Stat(path); !os.IsNotExist(err) { //Found it! wekaJar = path continue } } if wekaJar == "" { log.Fatalln("Could not find Weka") } } func (a *appOptions) defineFlags() { if a.flagSet == nil { return } a.flagSet.StringVar(&a.inFile, "i", "solves.csv", "Which file to read from") a.flagSet.StringVar(&a.outFile, "o", "analysis.txt", "Which file to output analysis to") a.flagSet.BoolVar(&a.help, "h", false, "If provided, will print help and exit.") } func (a *appOptions) parse(args []string) { a.flagSet.Parse(args) } func newAppOptions(flagSet *flag.FlagSet) *appOptions { a := &appOptions{ flagSet: flagSet, } a.defineFlags() return a } func main() { options := newAppOptions(flag.CommandLine) options.parse(os.Args[1:]) if options.help { options.flagSet.PrintDefaults() return } //TODO: allow configuring just a relativedifficulties file and run the whole pipeline //First, convert the file to arff. cmd := execJavaCommand("weka.core.converters.CSVLoader", options.inFile) out, err := os.Create(temporaryArff) if err != nil { log.Println(err) return } cmd.Stdout = out //TODO: really we should pipe the output to stderr, but Weka complains //about some stupid unnecessary database JARs every time, so it's //generally annoying. //cmd.Stderr = os.Stderr err = cmd.Run() if err != nil { log.Println(err) return } //Do the training trainCmd := execJavaCommand("weka.classifiers.functions.SMOreg", "-C", "1.0", "-N", "2", "-I", `weka.classifiers.functions.supportVector.RegSMOImproved -L 0.001 -W 1 -P 1.0E-12 -T 0.001 -V`, "-K", `weka.classifiers.functions.supportVector.PolyKernel -C 250007 -E 1.0`, "-c", "first", "-i", "-t", "solves.arff") trainCmd.Stderr = os.Stderr output, err := trainCmd.Output() if err != nil { log.Println(err) return } r2, _ := wekaparser.ParseR2(string(output)) fmt.Println("R2 =", r2) ioutil.WriteFile(options.outFile, output, 0644) //Remove the temporary arff file. os.Remove(temporaryArff) } func execJavaCommand(input ...string) *exec.Cmd { var args []string args = append(args, "-cp") args = append(args, wekaJar) args = append(args, input...) return exec.Command("java", args...) }
package domain // Return a list of all the articles func getAllArticles() []article { return []article{} }
package main import ( "fmt" "sync" "time" ) func main() { var wg sync.WaitGroup fmt.Println("Starting") wg.Add(1) go func() { PAUSE := time.Duration(2 * time.Second) fmt.Println("........") time.Sleep(PAUSE) wg.Done() }() wg.Wait() fmt.Println("Finished") }
package bt import ( "strings" "github.com/neoql/btlet/bencode" ) // RawMeta is raw metadata type RawMeta bencode.RawMessage // Meta is meta type Meta struct { Name string `bencode:"name"` Length *uint64 `bencode:"length,omitempty"` PieceLength uint `bencode:"piece length"` Pieces []byte `bencode:"pieces"` Files []struct { Path []string `bencode:"path"` Length uint64 `bencode:"length"` } `bencode:"files,omitempty"` } // MetaOutline is outline of metadata type MetaOutline interface { SetName(string) AddFile(string, uint64) } // FillOutline can fill MetaOutline func (rm RawMeta) FillOutline(mo MetaOutline) error { var meta Meta err := bencode.Unmarshal(rm, &meta) if err != nil { return err } mo.SetName(meta.Name) if meta.Files == nil { mo.AddFile(meta.Name, *meta.Length) } for _, f := range meta.Files { mo.AddFile(strings.Join(f.Path, "/"), f.Length) } return nil }
package main import ( "github.com/spf13/cobra" "github.com/alejandroEsc/maas-cli/pkg/cli" ) func machineCmd() *cobra.Command { mo := &cli.MachineOptions{} cmd := &cobra.Command{ Use: "machine", Short: "Run a few simple machine commands", Long: "", Run: func(cmd *cobra.Command, args []string) { cmd.Usage() }, } fs := cmd.Flags() bindCommonMAASFlags(&mo.MAASOptions, fs) cmd.AddCommand(machineStatusCmd()) cmd.AddCommand(machineReleaseCmd()) cmd.AddCommand(machineDeployCmd()) cmd.AddCommand(machineCommissionCmd()) return cmd }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. package common type ContainerdConfig struct { OomScore int `toml:"oom_score,omitempty"` Root string `toml:"root,omitempty"` Version int `toml:"version,omitempty"` Plugins Plugins `toml:"plugins,omitempty"` } type ContainerdCNIPlugin struct { ConfTemplate string `toml:"conf_template,omitempty"` } type ContainerdRuntime struct { RuntimeType string `toml:"runtime_type,omitempty"` } type ContainerdPlugin struct { DefaultRuntimeName string `toml:"default_runtime_name,omitempty"` Runtimes map[string]ContainerdRuntime `toml:"runtimes,omitempty"` } type IoContainerdGrpcV1Cri struct { SandboxImage string `toml:"sandbox_image,omitempty"` CNI ContainerdCNIPlugin `toml:"cni,omitempty"` Containerd ContainerdPlugin `toml:"containerd,omitempty"` } type Plugins struct { IoContainerdGrpcV1Cri IoContainerdGrpcV1Cri `toml:"io.containerd.grpc.v1.cri,omitempty"` } type DockerConfig struct { ExecOpts []string `json:"exec-opts,omitempty"` DataRoot string `json:"data-root,omitempty"` LiveRestore bool `json:"live-restore,omitempty"` LogDriver string `json:"log-driver,omitempty"` LogOpts LogOpts `json:"log-opts,omitempty"` DefaultRuntime string `json:"default-runtime,omitempty"` DockerDaemonRuntimes map[string]DockerDaemonRuntime `json:"runtimes,omitempty"` } type LogOpts struct { MaxSize string `json:"max-size,omitempty"` MaxFile string `json:"max-file,omitempty"` } type DockerDaemonRuntime struct { Path string `json:"path,omitempty"` RuntimeArgs []string `json:"runtimeArgs"` }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. package armhelpers import "context" // ListResourceSkus lists Microsoft.Compute SKUs available for a subscription func (az *AzureClient) ListResourceSkus(ctx context.Context, filter string) (ResourceSkusResultPage, error) { page, err := az.resourceSkusClient.List(ctx, filter) if err != nil { return nil, err } return &page, nil }
package main import ( "bufio" "fmt" "io" "os" "github.com/libp2p/go-libp2p-core/network" ) const protocol = "/libp2p/chat/1.0.0" func chatHandler(s network.Stream) { var ( err error chunk []byte line string ) r := bufio.NewReader(s) for { prefix := true for prefix { chunk, prefix, err = r.ReadLine() switch err { case io.EOF: return default: fmt.Fprintln(os.Stderr, err) } line += string(chunk) } fmt.Println(line) line = "" } } func send(msg string, s network.Stream) error { w := bufio.NewWriter(s) n, err := w.WriteString(msg) if n != len(msg) { return fmt.Errorf("expected to write %d bytes, wrote %d", len(msg), n) } return err }
package el import ( "testing" ) func a() error { return Wrap(nil, "a") } func b() error { return Wrap(a(), "b") } type X struct { } func (x *X) Foo() error { return Wrap(a(), nil) } func (x X) Bar() error { return Wrap(a(), nil) } func TestWrap(t *testing.T) { t.Log("here") e0 := Wrap(nil, "the original error\nbreak") e1 := Wrap(e0, "something wrong") e2 := Wrap(e1, "start") t.Log("\n" + e2.Error()) e3 := Wrap(e2, "") t.Log("\n" + e3.Error()) t.Log("\n" + Wrap(ErrNil, "test").Error()) } func TestWrapFn(t *testing.T) { t.Log("\n" + b().Error()) x := &X{} t.Log("\n" + x.Foo().Error()) t.Log("\n" + x.Bar().Error()) t.Log("\n" + (func() error { return WrapFn(a(), "hello", "info") }()).Error()) }
package main import ( "context" "fmt" "google.golang.org/grpc" "github.com/bai615/Go-000/Week04/grpc_test/proto" ) func main() { //stream conn, err := grpc.Dial("127.0.0.1:8088", grpc.WithInsecure()) if err != nil { panic(err) } defer conn.Close() c := proto.NewGreeterClient(conn) r, err := c.SayHello(context.Background(), &proto.HelloRequest{Name: "world"}) if err != nil { panic(err) } fmt.Println(r.Message) }
package main import ( "bufio" "log" "os" "github.com/luizbranco/pilgrims/cli" ) func main() { c, err := cli.NewClient() if err != nil { log.Fatal(err) } r := bufio.NewReader(os.Stdin) for { txt, err := r.ReadSlice('\n') if err != nil { log.Fatal(err) } c.Message(txt) } }
package main import "fmt" //定义一个 函数 func swap(a, b string) (string, string) { return b, a } func main() { m, n := swap("111", "222") fmt.Println(m, n) }
package server import ( "github.com/gorilla/websocket" "github.com/go-redis/redis" "fmt" "encoding/json" ) const max_room_num = 2 //每个房间的最大人数 var ( ActiveClients = make(map[string]ClientConn) //在线的用户的信息 User = make(map[string]string) ) type UserMsg struct { Room string `json:"room"` //房间名字 Cmd string `json:"cmd"` //登录,初始化 准备 退出 等相关的命令 User string `json:"user"` //用户的信息 AvatarUrl string `json:"avatar_url"` //用户的头像信息 Content string `json:"content"` //用户的发送的内容 Uuid string `json:"uuid"` //创建用户的唯一识别码 Gameid string `json:"gameid"` //当前的游戏 } type ClientConn struct { websocket *websocket.Conn } type UserInfo struct { User string `json:"user"` //玩家的用户信息 AvatarUrl string `json:"avatar_url"` //头像 Uuid string `json:"uuid"` //用户ID Gameid string `json:"gameid"` //游戏ID } type ReplyMsg struct { Room string `json:"room"` //玩家的放假 Cmd string `json:"cmd"` //玩家执行的命令 Data string `json:"data"` //传递的数据 Gameid string `json:"gameid"` //当前的游戏id } type DatBase struct { Room string `json:"room"` // 房间号 Command string `json:"command"` // 执行访问命令 Content string `json:"content"` // 传递数据信息 } type Clients struct { Clients UserMsg //保存用户的信息 } type GameClient interface{ Connect(conn *websocket.Conn) } var RedisClient *redis.Client func init(){ RedisClient = redis.NewClient(&redis.Options{ Addr: "192.168.1.246:6379", Password: "", // 设置Redis的链接的链接方法 DB: 0, // use default DB }) } func WsConnect(conn *websocket.Conn,dat *UserMsg){ sockCli := ClientConn{conn} RedisClient.Ping() // room := fmt.Sprintf("ROOM:%s", dat.Room) //读取房间信息 command := dat.Cmd //获取房间信息 println(room,command) switch command { case "reday": println("游戏退出当前登录") RedisClient.Set("READY:"+dat.Uuid,"ready",0) //从redis取房间内的所有用户uuid roomSlice := RedisClient.SMembers("ROOM:"+dat.Room) //更新当前的用户的状态为 //用户uuid保存到一个go切片online online := roomSlice.Val() i := 0 //循环取在线用户个人信息 if len(online) != 0 { for _, na := range online { if na != "" { userJson := RedisClient.Get("READY:"+na) userJson2 := userJson.Val() if userJson2 == "ready" { i++ } } } } if i == len(online) && i == max_room_num { var rm ReplyMsg rm.Room = dat.Room rm.Cmd = "start" rm.Data = "" rm.Gameid = dat.Gameid broadcast(RedisClient,dat,rm) } case "login": println("游戏进入转呗状态") checkNumTmp := RedisClient.SCard(room) checkNum := checkNumTmp.Val() println("房间中的人数:",checkNum) println(dat.Uuid) if(checkNum <= max_room_num) { fmt.Println("checkNum success") //socket用户列表新增当前用户websocket连接 ActiveClients[dat.Uuid] = sockCli //用户uuid保存到redis房间set集合内 RedisClient.SAdd(room, dat.Uuid) var userinfo UserInfo userinfo.User = dat.User userinfo.AvatarUrl = dat.AvatarUrl userinfo.Uuid = dat.Uuid userinfo.Gameid = dat.Gameid //生成用户信息json串 b, err := json.Marshal(userinfo) //格式化当前的数据信息 if err != nil { fmt.Println("Encoding User Faild") } else { //保存用户信息到redis RedisClient.Set("USER:"+userinfo.Uuid, b, 0) println("保存用户信息到Redis--》") //初始化用户 initOnlineMsg(RedisClient,dat) } }else { var rm ReplyMsg rm.Room = dat.Room rm.Cmd = "loginFailed" rm.Data = "登录失败,人数已满" sendMsg,err2 := json.Marshal(rm) sendMsgStr := string(sendMsg) fmt.Println(sendMsgStr) if err2 != nil { println("data type channge error",err2.Error()) } else { if err := conn.WriteMessage(websocket.TextMessage,[]byte(sendMsgStr)); err != nil { println("Could not send UsersList to ", dat.User, err.Error()) } } } case "logout": delete(ActiveClients,dat.Uuid) //删除当前用户 println("退出当前的服务") RedisClient.SRem("ROOM:"+dat.Room,dat.Uuid) //初始化用户 initOnlineMsg(RedisClient,dat) case "sendmess": println("发送数据") var rm ReplyMsg rm.Room = dat.Room rm.Cmd = "start" rm.Data = dat.Content rm.Gameid = dat.Gameid broadcast(RedisClient,dat,rm) //广播当前的游戏的信息 } } //房间成员初始化,有人加入或者退出都要重新初始化,相当于聊天室的在线用户列表的维护 func initOnlineMsg(redisClient *redis.Client,userMsg *UserMsg) { var err error //从redis取房间内的所有用户uuid roomSlice := redisClient.SMembers("ROOM:"+userMsg.Room) //用户uuid保存到一个go切片online online := roomSlice.Val() // var onlineList []string //循环取在线用户个人信息 if len(online) != 0 { for _, na := range online { if na != "" { userJson := redisClient.Get("USER:"+na) userJson2 := userJson.Val() onlineList = append(onlineList,userJson2) //获取获取房钱房间的用户的信息 } } } //生成在线用户信息json在线的用户新书数据 //c, err := json.Marshal(onlineList) onlineListStr,err2 := json.Marshal(onlineList) if err2 != nil{ return } //数据展示的过程 var rm ReplyMsg rm.Room = userMsg.Room rm.Cmd = "init" rm.Data = string(onlineListStr) //给所有用户发初始化消息 if len(online) != 0 { for _, na := range online { if na != "" { ws := ActiveClients[userMsg.Uuid] if err = ws.websocket.WriteJSON(rm); err != nil { println("Could not send UsersList to ", "", err.Error()) } } } } //若房间人数满,发送就绪消息 if len(online) >= max_room_num { fmt.Println("full") var rm ReplyMsg rm.Room = userMsg.Room rm.Cmd = "full" rm.Data = "the game is full" for _, na := range online { if na != "" { ws := ActiveClients[userMsg.Uuid] if err = ws.websocket.WriteJSON(rm); err != nil { println("Could not send UsersList to ", "", err.Error()) } } } } } //给房间内的所有用户发送相关的数据 func broadcast(redisClient *redis.Client,userMsg *UserMsg,rm ReplyMsg) { var err error //从redis取房间内的所有用户uuid roomSlice := redisClient.SMembers("ROOM:"+userMsg.Room) //用户uuid保存到一个go切片online online := roomSlice.Val() sendMsg,err2 := json.Marshal(rm) fmt.Println("broadcast") if err2 != nil { } else { //给所有用户发消息 if len(online) != 0 { for _, na := range online { if na != "" { if err = ActiveClients[na].websocket.WriteMessage(websocket.TextMessage,sendMsg); err != nil { println("Could not send UsersList to ", "", err.Error()) } } } } } } func NewUm() *UserMsg{ return &UserMsg{} }
package Problem0380 import ( "testing" "github.com/stretchr/testify/assert" ) func Test_Problem0380(t *testing.T) { ast := assert.New(t) rs := Constructor() ast.True(rs.Insert(1), "插入1") ast.False(rs.Remove(2), "删除2") ast.True(rs.Insert(2), "插入2") ast.Contains([]int{1, 2}, rs.GetRandom(), "返回1或2") ast.True(rs.Remove(1), "删除1") ast.False(rs.Insert(2), "再一次插入2") ast.Equal(2, rs.GetRandom(), "从只有2的集合中随机取出2") length := 100 result := make([]int, length) for i := 0; i < 100; i++ { rs.Insert(i) result[i] = i } ast.Contains(result, rs.GetRandom(), "随机获取0~100之间的数") }
package ciolite // Api functions that support: users/email_accounts import ( "fmt" "strings" "github.com/pkg/errors" ) // GetUserEmailAccountsParams query values data struct. // Optional: Status, StatusOK type GetUserEmailAccountsParams struct { // Optional: Status string `json:"status,omitempty"` StatusOK string `json:"status_ok,omitempty"` } // GetUsersEmailAccountsResponse data struct type GetUsersEmailAccountsResponse struct { Status string `json:"status,omitempty"` ResourceURL string `json:"resource_url,omitempty"` Type string `json:"type,omitempty"` AuthenticationType string `json:"authentication_type,omitempty"` Server string `json:"server,omitempty"` Label string `json:"label,omitempty"` Username string `json:"username,omitempty"` MailServiceAccountID string `json:"mailservice_account_id,omitempty"` UseSSL bool `json:"use_ssl,omitempty"` Port int `json:"port,omitempty"` } // CreateEmailAccountResponse data struct type CreateEmailAccountResponse struct { Status string `json:"status,omitempty"` Label string `json:"label,omitempty"` ResourceURL string `json:"resource_url,omitempty"` MailServiceAccountID string `json:"mailservice_account_id,omitempty"` } // ModifyUserEmailAccountParams form values data struct. // formValues optionally may contain Status, ForceStatusCheck, Password, // ProviderRefreshToken, ProviderConsumerKey, StatusCallbackURL type ModifyUserEmailAccountParams struct { // Optional: Status string `json:"status,omitempty"` Password string `json:"password,omitempty"` ProviderRefreshToken string `json:"provider_refresh_token,omitempty"` ProviderConsumerKey string `json:"provider_consumer_key,omitempty"` StatusCallbackURL string `json:"status_callback_url,omitempty"` ForceStatusCheck bool `json:"force_status_check,omitempty"` } // ModifyEmailAccountResponse data struct type ModifyEmailAccountResponse struct { Success bool `json:"success,omitempty"` ResourceURL string `json:"resource_url,omitempty"` FeedbackCode string `json:"feedback_code,omitempty"` ConnectionLog string `json:"connection_log,omitempty"` } // DeleteEmailAccountResponse data struct type DeleteEmailAccountResponse struct { Success bool `json:"success,omitempty"` ResourceURL string `json:"resource_url,omitempty"` FeedbackCode string `json:"feedback_code,omitempty"` } // StatusCallback data struct that will be received from CIO when a user's status changes type StatusCallback struct { AccountID string `json:"account_id,omitempty"` UserID string `json:"user_id,omitempty"` ServerLabel string `json:"server_label,omitempty"` EmailAccount string `json:"email_account,omitempty"` Failure string `json:"failure,omitempty"` FailureMessage string `json:"failure_message,omitempty"` Token string `json:"token,omitempty" valid:"required"` Signature string `json:"signature,omitempty" valid:"required"` Timestamp int `json:"timestamp,omitempty" valid:"required"` } // GetUserEmailAccounts gets a list of email accounts assigned to a user. // queryValues may optionally contain Status, StatusOK func (cioLite CioLite) GetUserEmailAccounts(userID string, queryValues GetUserEmailAccountsParams) ([]GetUsersEmailAccountsResponse, error) { // Make request request := clientRequest{ Method: "GET", Path: fmt.Sprintf("/lite/users/%s/email_accounts", userID), QueryValues: queryValues, UserID: userID, } // Make response var response []GetUsersEmailAccountsResponse // Request err := cioLite.doFormRequest(request, &response) return response, err } // GetUserEmailAccount gets the parameters and status for an email account. // Status can be one of: OK, CONNECTION_IMPOSSIBLE, INVALID_CREDENTIALS, TEMP_DISABLED, DISABLED func (cioLite CioLite) GetUserEmailAccount(userID string, label string) (GetUsersEmailAccountsResponse, error) { // Make request request := clientRequest{ Method: "GET", Path: fmt.Sprintf("/lite/users/%s/email_accounts/%s", userID, label), UserID: userID, AccountLabel: label, } // Make response var response GetUsersEmailAccountsResponse // Request err := cioLite.doFormRequest(request, &response) return response, err } // CreateUserEmailAccount adds a mailbox to a given user. // formValues requires Email, Server, Username, UseSSL, Port, Type, // and (if OAUTH) ProviderRefreshToken and ProviderConsumerKey, // and (if not OAUTH) Password, // and may optionally contain StatusCallbackURL func (cioLite CioLite) CreateUserEmailAccount(userID string, formValues CreateUserParams) (CreateEmailAccountResponse, error) { // Make request request := clientRequest{ Method: "POST", Path: fmt.Sprintf("/lite/users/%s/email_accounts", userID), FormValues: formValues, UserID: userID, } // Make response var response CreateEmailAccountResponse // Request err := cioLite.doFormRequest(request, &response) return response, err } // ModifyUserEmailAccount modifies an email account on a given user. // formValues optionally may contain Status, ForceStatusCheck, Password, // ProviderRefreshToken, ProviderConsumerKey, StatusCallbackURL func (cioLite CioLite) ModifyUserEmailAccount(userID string, label string, formValues ModifyUserEmailAccountParams) (ModifyEmailAccountResponse, error) { // Make request request := clientRequest{ Method: "POST", Path: fmt.Sprintf("/lite/users/%s/email_accounts/%s", userID, label), FormValues: formValues, UserID: userID, AccountLabel: label, } // Make response var response ModifyEmailAccountResponse // Request err := cioLite.doFormRequest(request, &response) return response, err } // DeleteUserEmailAccount deletes an email account of a user. func (cioLite CioLite) DeleteUserEmailAccount(userID string, label string) (DeleteEmailAccountResponse, error) { // Make request request := clientRequest{ Method: "DELETE", Path: fmt.Sprintf("/lite/users/%s/email_accounts/%s", userID, label), UserID: userID, AccountLabel: label, } // Make response var response DeleteEmailAccountResponse // Request err := cioLite.doFormRequest(request, &response) return response, err } // FindEmailAccountMatching searches an array of GetUsersEmailAccountsResponse's // for the one that matches the provided email address, and returns it. func FindEmailAccountMatching(emailAccounts []GetUsersEmailAccountsResponse, email string) (GetUsersEmailAccountsResponse, error) { if emailAccounts != nil { // Try to match against the username for _, emailAccount := range emailAccounts { if strings.ToLower(email) == strings.ToLower(emailAccount.Username) { return emailAccount, nil } } // Try to match the local part against the username or label localPart := strings.ToLower(upToSeparator(email, "@")) for _, emailAccount := range emailAccounts { if localPart == strings.ToLower(upToSeparator(emailAccount.Username, "@")) || localPart == strings.ToLower(upToSeparator(emailAccount.Label, ":")) { return emailAccount, nil } } } return GetUsersEmailAccountsResponse{}, errors.Errorf("No email accounts match %s in %v", email, emailAccounts) } // upToSeparator returns a string up to the separator, or the whole string // if the separator is not contained in the string func upToSeparator(s string, sep string) string { idx := strings.Index(s, sep) if idx >= 0 { return s[:idx] } return s }
package backtracking // 下标表示行, 值表示 queen 存储在哪一列 var result = [8]int{} func Cal8Queens(row int) { if row == 8 { // 8 个棋子都放置好了,打印结果 printQueens(result) return } // 每一行都有 8 种放法 for column := 0; column < 8; column++ { // 有些放法不满足要求 if isOk(row, column) { // 第 row 行的棋子放到了 column 列 result[row] = column // 考察下一行 Cal8Queens(row + 1) } } } // 判断坐标为 (row, column) 的位置放置棋子是否合适 // 由于是从上往下放置棋子,故只需判断当前坐标的上方(正上方、左上、右上对角线) func isOk(row, column int) bool { leftup, rightup := column-1, column+1 // 逐行往上考察每一行 for i := row - 1; i >= 0; i-- { // 当前坐标正上方 (row-1, column) 是否有棋子 if result[i] == column { return false } // 当前坐标左上对角线 (row-1, column-1) 是否有棋子 if leftup >= 0 { if result[i] == leftup { return false } } // 当前坐标右上对角线 (row-1, column-1) 是否有棋子 if rightup < 8 { if result[i] == rightup { return false } } // 继续向左、右上对角线移动判断 leftup-- rightup++ } return true } // 打印出一个二维矩阵 func printQueens(result [8]int) { for row := 0; row < 8; row++ { for column := 0; column < 8; column++ { if result[row] == column { print("Q ") } else { print("* ") } } println() } println() }
package gonba import ( "strconv" ) const endpointPlayByPlay = "playbyplayv2" // first period is startPeriod, second period is endPeriod func (c *Client) GetPlayByPlay(gameId int, periods ...int) { params := make(map[string]string) if len(periods) > 0 { params["StartPeriod"] = strconv.Itoa(periods[0]) if len(periods) > 1 { params["EndPeriod"] = strconv.Itoa(periods[1]) } } params["GameID"] = FormatGameIdString(gameId) c.makeRequestWithoutJson(endpointPlayByPlay, params) }
package logger import ( "testing" ) func TestDebugf(t *testing.T) { Debugf("Test debug") } func TestInfof(t *testing.T) { Infof("Test info") } func TestWarnf(t *testing.T) { Warnf("Test warn") } func TestErrorf(t *testing.T) { Errorf("Test error") } func init() { Setup(&LoggerConfig{ Facility: "Logger test", Level: "debug", Colors: true, Caller: true, DeepStack: 2, Timestamp: true, }) }
package atypes type AInterface interface { Len() int Less(i, j int) bool Swap(i, j int) Assign(i int, d interface{}) Get(i int) interface{} LessD(i, j interface{}) bool InsertionB(i, j int) }
package day12 var directions map[int]rune = map[int]rune{ 0: 'E', 90: 'S', 180: 'W', 270: 'N', } type WaypointShip struct { x int y int WaypointX int WaypointY int } func (ship WaypointShip) turn(direction rune, degrees int) WaypointShip { turns := degrees / 90 if direction == 'L' { var i int for i < turns { ship.WaypointX, ship.WaypointY = ship.WaypointY*-1, ship.WaypointX i++ } return ship } var i int for i < turns { ship.WaypointX, ship.WaypointY = ship.WaypointY, ship.WaypointX*-1 i++ } return ship } func (ship WaypointShip) MoveWaypoint(direction rune, distance int) WaypointShip { switch direction { case 'E': ship.WaypointX += distance case 'W': ship.WaypointX -= distance case 'N': ship.WaypointY += distance case 'S': ship.WaypointY -= distance } return ship } func (ship WaypointShip) Move(direction rune, distance int) WaypointShip { yDistance := ship.WaypointY * distance ship.y += yDistance xDistance := ship.WaypointX * distance ship.x += xDistance return ship }
package controllers import ( "net/http" apiRequest "github.com/alexhornbake/go-crud-api/lib/api_request" apiResponse "github.com/alexhornbake/go-crud-api/lib/api_response" models "github.com/alexhornbake/go-crud-api/models" schemas "github.com/alexhornbake/go-crud-api/schemas" ) func showPost(w http.ResponseWriter, r *http.Request) { params := r.URL.Query() userId := params.Get(":user") id := params.Get(":post") post, err := models.FindPost(userId, id) if err != nil { apiResponse.SendError(w, r, err) return } apiResponse.SendOK(w, r, post) } var ShowPost = http.HandlerFunc(showPost) func indexPosts(w http.ResponseWriter, r *http.Request) { params := r.URL.Query() userId := params.Get(":user") posts, err := models.FindAllPosts(userId) if err != nil { apiResponse.SendError(w, r, err) return } apiResponse.SendOK(w, r, posts) } var IndexPosts = http.HandlerFunc(indexPosts) func createPost(w http.ResponseWriter, r *http.Request) { //parse the request var err error var apiError *apiResponse.ErrorResponse var body *map[string]interface{} params := r.URL.Query() userId := params.Get(":user") body, err = apiRequest.ParseRequest(r) if err != nil { apiResponse.SendError(w, r, apiResponse.RequestParseError(err)) return } //validate the body against schema err = schemas.ValidateCreation("post", body) if err != nil { apiResponse.SendError(w, r, apiResponse.BadRequest(err)) return } //create a post with the body values post := models.NewPost(userId, body) if apiError != nil { apiResponse.SendError(w, r, apiError) return } post, apiError = post.InitialSave() if apiError != nil { apiResponse.SendError(w, r, apiError) return } apiResponse.SendOK(w, r, post) } var CreatePost = http.HandlerFunc(createPost) func updatePost(w http.ResponseWriter, r *http.Request) { //parse the request var err error var apiError *apiResponse.ErrorResponse var body *map[string]interface{} body, err = apiRequest.ParseRequest(r) if err != nil { apiResponse.SendError(w, r, apiResponse.RequestParseError(err)) return } //validate the body against schema err = schemas.ValidateUpdate("post", body) if err != nil { apiResponse.SendError(w, r, apiResponse.BadRequest(err)) return } params := r.URL.Query() userId := params.Get(":user") id := params.Get(":post") post, apiErr := models.FindPost(userId, id) if apiErr != nil { apiResponse.SendError(w, r, apiError) return } post.ApplyChanges(body) post, apiError = post.Save() if apiError != nil { apiResponse.SendError(w, r, apiError) return } apiResponse.SendOK(w, r, post) } var UpdatePost = http.HandlerFunc(updatePost) func deletePost(w http.ResponseWriter, r *http.Request) { var apiError *apiResponse.ErrorResponse params := r.URL.Query() userId := params.Get(":user") id := params.Get(":post") post, apiErr := models.FindPost(userId, id) if apiErr != nil { apiResponse.SendError(w, r, apiError) return } post, apiError = post.Delete() if apiError != nil { apiResponse.SendError(w, r, apiError) return } apiResponse.SendOK(w, r, post) } var DeletePost = http.HandlerFunc(deletePost)
package jwtauth import ( "crypto/md5" "encoding/hex" "encoding/json" "net/http" "os" jwt "github.com/dgrijalva/jwt-go" "github.com/gorilla/handlers" "github.com/gorilla/mux" ) type authInfo struct { Login string `json:"login"` Pass string `json:"password"` } type User struct { Login string Password string Role string } var ( db = []User{ User{ Login: "leonid_kit@mail.ru", Password: "d8578edf8458ce06fbc5bb76a58c5ca4", Role: "admin", }, User{ Login: "andrcop@gmail.ru", Password: "d8578edf8458ce06fbc5bb76a58c5ca4", Role: "user", }, } secretKey = "yd0jWLynmm" ) type AuthServer struct { Handler http.Handler } func JSONError(w http.ResponseWriter, resp interface{}, code int) { w.WriteHeader(code) err := json.NewEncoder(w).Encode(resp) if err != nil { w.WriteHeader(http.StatusInternalServerError) w.Write([]byte(err.Error())) } } func (as *AuthServer) Auth(w http.ResponseWriter, r *http.Request) { h := md5.New() ai := authInfo{} err := json.NewDecoder(r.Body).Decode(&ai) if err != nil { resp := map[string]string{ "error": "unmarshaling input json error: " + err.Error(), } JSONError(w, resp, http.StatusInternalServerError) return } defer r.Body.Close() for _, u := range db { _, err := h.Write([]byte(ai.Pass)) if err != nil { resp := map[string]string{ "error": err.Error(), } JSONError(w, resp, http.StatusInternalServerError) return } pass := hex.EncodeToString(h.Sum(nil)) if u.Login == ai.Login { if u.Password != pass { resp := map[string]string{ "error": "incorrect username or password", } JSONError(w, resp, http.StatusBadRequest) return } token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{ "role": u.Role, }) tokenString, err := token.SignedString([]byte(secretKey)) if err != nil { w.WriteHeader(http.StatusInternalServerError) w.Write([]byte(err.Error())) } resp := map[string]string{ "token": tokenString, } err = json.NewEncoder(w).Encode(resp) if err != nil { w.WriteHeader(http.StatusInternalServerError) w.Write([]byte(err.Error())) } return } } resp := map[string]string{ "error": "user not found", } JSONError(w, resp, http.StatusNotFound) return } func (as *AuthServer) Endpoints() { router := mux.NewRouter() router.HandleFunc("/auth", as.Auth).Methods(http.MethodPost) as.Handler = handlers.LoggingHandler(os.Stdout, router) }
package testutil import ( "bufio" "context" "fmt" "io" "testing" "github.com/minio/minio-go/v7" "github.com/minio/minio-go/v7/pkg/credentials" "github.com/ory/dockertest/v3" "github.com/ory/dockertest/v3/docker" ) // WithTestMinIO starts a test MinIO server func WithTestMinIO(t *testing.T, bucket string, handler func(endpoint string) error) error { t.Helper() ctx, clearTimeout := context.WithTimeout(context.Background(), maxWait) defer clearTimeout() // uses a sensible default on windows (tcp/http) and linux/osx (socket) pool, err := dockertest.NewPool("") if err != nil { return err } resource, err := pool.RunWithOptions(&dockertest.RunOptions{ Repository: "quay.io/minio/minio", Tag: "RELEASE.2022-12-02T19-19-22Z", Env: []string{"MINIO_ROOT_USER=pomerium", "MINIO_ROOT_PASSWORD=pomerium"}, Cmd: []string{"server", "/data"}, }) if err != nil { return err } _ = resource.Expire(uint(maxWait.Seconds())) go tailLogs(ctx, t, pool, resource) endpoint := fmt.Sprintf("localhost:%s", resource.GetPort("9000/tcp")) if err := pool.Retry(func() error { client, err := minio.New(endpoint, &minio.Options{ Creds: credentials.NewStaticV4("pomerium", "pomerium", ""), }) if err != nil { t.Logf("minio: %s", err) return err } err = client.MakeBucket(ctx, bucket, minio.MakeBucketOptions{}) if err != nil { t.Logf("minio: %s", err) return err } return nil }); err != nil { _ = pool.Purge(resource) return err } t.Setenv("MINIO_ROOT_USER", "pomerium") t.Setenv("MINIO_ROOT_PASSWORD", "pomerium") t.Setenv("AWS_ACCESS_KEY_ID", "pomerium") t.Setenv("AWS_SECRET_ACCESS_KEY", "pomerium") e := handler(endpoint) if err := pool.Purge(resource); err != nil { return err } return e } func tailLogs(ctx context.Context, t *testing.T, pool *dockertest.Pool, resource *dockertest.Resource) { t.Helper() pr, pw := io.Pipe() go func() { s := bufio.NewScanner(pr) for s.Scan() { t.Logf("%s: %s", resource.Container.Config.Image, s.Text()) } }() defer pw.Close() opts := docker.LogsOptions{ Context: ctx, Stderr: true, Stdout: true, Follow: true, Timestamps: true, RawTerminal: true, Container: resource.Container.ID, OutputStream: pw, } _ = pool.Client.Logs(opts) }