text
stringlengths
11
4.05M
// Package logr defines abstract interfaces for logging. Packages can depend on // these interfaces and callers can implement logging in whatever way is // appropriate. // // This design derives from Dave Cheney's blog: // http://dave.cheney.net/2015/11/05/lets-talk-about-logging // // This is a BETA grade API. Until there is a significant 2nd implementation, // I don't really know how it will change. <<<<<<< HEAD <<<<<<< HEAD ======= // // The logging specifically makes it non-trivial to use format strings, to encourage // attaching structured information instead of unstructured format strings. // // Usage // // Logging is done using a Logger. Loggers can have name prefixes and tags attached, // so that all log messages logged with that Logger have some base context associated. // // For instance, suppose we're trying to reconcile the state of an object, and we want // to log that we've made some decision. // // With the traditional log package, we might write // log.Printf( // "decided to set field foo to value %q for object %s/%s", // targetValue, object.Namespace, object.Name) // // With logr's structured logging, we'd write // // elsewhere in the file, set up the logger to log with the prefix of "reconcilers", // // and the tag target-type=Foo, for extra context. // log := mainLogger.WithName("reconcilers").WithTag("target-type", "Foo") // // // later on... // log.Info("setting field foo on object", "value", targetValue, "object", object) // // Depending on our logging implementation, we could then make logging decisions based on field values // (like only logging such events for objects in a certain namespace), or copy the structured // information into a structured log store. // // For logging errors, Logger has a convinience method called Error. Suppose we wanted to log an // error while reconciling. With the traditional log package, we might write // log.Errorf("unable to reconcile object %s/%s: %v", object.Namespace, object.Name, err) // // With logr, we'd instead write // // assuming the above setup for log // log.Error(err, "unable to reconcile object", "object", object) // // This is mostly identical to // log.Info("unable to reconcile object", "error", err, "object", object) // // However, it's more convinient, and certain logging libraries may choose to attach additional // information (such as stack traces) on calls to Error, so it's preferred to use Error to log errors. // // Parts of a log line // // Each log message from a Logger has four types of context: // logger name, log verbosity, log message, and key-value pairs. // // The Logger name is constists of a series of name "segments" added by successive calls to WithName. // These name segments may contain anything but periods. Exactly how these are represented in the // output is implementation-dependent. A common format for implementations is to prefix log messages // with the name segments, separated by periods. // // Log verbosity represents how little a log matters. Level zero, the default, matters most. // Increasing levels matter less and less. Try to avoid lots of different verbosity levels, // and instead provide useful keys, logger names, and log messages instead for users to filter on // instead. // // The log message consists of a constant message attached to the the log line. This // should generally be a simple description of what's occuring, and should never be a format string. // // Variable information can then be attached using key/value pairs. Keys are arbitrary strings, // and values may be any Go object. >>>>>>> parent of b8c64da... fixup! Structured Logging ======= >>>>>>> parent of c62468b... Structured Logging package logr // TODO: consider structured logging, a la uber-go/zap // TODO: consider other bits of glog functionality like Flush, InfoDepth, OutputStats // InfoLogger represents the ability to log non-error messages. type InfoLogger interface { // Info logs a non-error message. This is behaviorally akin to fmt.Print. Info(args ...interface{}) // Infof logs a formatted non-error message. Infof(format string, args ...interface{}) // Enabled test whether this InfoLogger is enabled. For example, // commandline flags might be used to set the logging verbosity and disable // some info logs. Enabled() bool } // Logger represents the ability to log messages, both errors and not. type Logger interface { // All Loggers implement InfoLogger. Calling InfoLogger methods directly on // a Logger value is equivalent to calling them on a V(0) InfoLogger. For // example, logger.Info() produces the same result as logger.V(0).Info. InfoLogger <<<<<<< HEAD <<<<<<< HEAD ======= >>>>>>> parent of c62468b... Structured Logging // Error logs a error message. This is behaviorally akin to fmt.Print. Error(args ...interface{}) // Errorf logs a formatted error message. Errorf(format string, args ...interface{}) <<<<<<< HEAD ======= // Error logs an error, with the given message and key/value pairs as context. // It functions as a convinience wrapper around Info, and generally behaves // equivalently to calling Info with the error attached as the "error" key, // but this method should be preferred for logging errors (see the package // documentations for more information). // // The msg field should be used to add context to any underlying error, // while the err field should be used to attach the actual error that // triggered this log line, if present. Error(err error, msg string, keysAndValues ...interface{}) >>>>>>> parent of b8c64da... fixup! Structured Logging ======= >>>>>>> parent of c62468b... Structured Logging // V returns an InfoLogger value for a specific verbosity level. A higher // verbosity level means a log message is less important. V(level int) InfoLogger <<<<<<< HEAD <<<<<<< HEAD // NewWithPrefix returns a Logger which prefixes all messages. NewWithPrefix(prefix string) Logger ======= // WithTags adds some key-value pairs of context to a logger. // See Info for documentation on how key/value pairs work. WithTags(keysAndValues ...interface{}) Logger // WithName adds a new suffix to the logger's name. // Successive calls with WithName continue to append // suffixes to the logger's name. Name segments should // not contain periods, but are otherwise freeform. WithName(name string) Logger >>>>>>> parent of b8c64da... fixup! Structured Logging ======= // NewWithPrefix returns a Logger which prefixes all messages. NewWithPrefix(prefix string) Logger >>>>>>> parent of c62468b... Structured Logging }
package transfer import ( "context" "errors" "github.com/juntaki/transparent" "github.com/juntaki/transparent/simple" pb "github.com/juntaki/transparent/transfer/pb" "google.golang.org/grpc" ) type transmitter struct { converter client pb.TransferClient serverAddr string conn *grpc.ClientConn } // NewSimpleLayerTransmitter returns simple Transmitter layer func NewSimpleLayerTransmitter(serverAddr string) transparent.Layer { a1 := NewSimpleTransmitter(serverAddr) return transparent.NewLayerTransmitter(a1) } // NewSimpleTransmitter returns simple Transmitter func NewSimpleTransmitter(serverAddr string) transparent.BackendTransmitter { return &transmitter{ converter: converter{}, serverAddr: serverAddr, } } func (t *transmitter) Request(m *transparent.Message) (*transparent.Message, error) { message, err := t.convertSendMessage(m) if err != nil { return nil, err } r, err := t.client.Request(context.Background(), message) response, err := t.convertReceiveMessage(r) if err != nil { return nil, err } return response, nil } func (t *transmitter) Start() error { conn, err := grpc.Dial(t.serverAddr, grpc.WithInsecure()) t.conn = conn if err != nil { return err } t.client = pb.NewTransferClient(t.conn) return nil } func (t *transmitter) Stop() error { t.conn.Close() return nil } func (t *transmitter) SetCallback(m func(*transparent.Message) (*transparent.Message, error)) error { return nil } type converter struct { simple.Validator } func (t *converter) convertSendMessage(m *transparent.Message) (*pb.Message, error) { var converted pb.Message if m.Key != nil { keyStr, err := t.ValidateKey(m.Key) if err != nil { return nil, err } converted.Key = keyStr } if m.Value != nil { valueBytes, err := t.ValidateValue(m.Value) if err != nil { return nil, err } converted.Value = valueBytes } switch m.Message { case transparent.MessageSet: converted.MessageType = pb.MessageType_Set case transparent.MessageGet: converted.MessageType = pb.MessageType_Get case transparent.MessageRemove: converted.MessageType = pb.MessageType_Remove case transparent.MessageSync: converted.MessageType = pb.MessageType_Sync default: return nil, errors.New("Unknown type") } return &converted, nil } func (t *converter) convertReceiveMessage(m *pb.Message) (*transparent.Message, error) { if m == nil { return nil, errors.New("nil") } var converted transparent.Message converted.Key = m.Key converted.Value = m.Value switch m.MessageType { case pb.MessageType_Set: converted.Message = transparent.MessageSet case pb.MessageType_Get: converted.Message = transparent.MessageGet case pb.MessageType_Remove: converted.Message = transparent.MessageRemove case pb.MessageType_Sync: converted.Message = transparent.MessageSync default: return nil, errors.New("Unknown type") } return &converted, nil }
// 18 august 2014 package ui type windowDialog interface { openFile(f func(filename string)) } // OpenFile opens a dialog box that asks the user to choose a file. // The dialog box is modal to win, which mut not be nil. // Some time after the dialog box is closed, OpenFile runs f on the main thread, passing filename. // filename is the selected filename, or an empty string if no file was chosen. // OpenFile does not ensure that f remains alive; the programmer is responsible for this. // If possible on a given system, OpenFile() will not dereference links; it will return the link file itself. // Hidden files will not be hidden by OpenFile(). func OpenFile(win Window, f func(filename string)) { if win == nil { panic("Window passed to OpenFile() cannot be nil") } win.openFile(f) }
package main import ( "bytes" "encoding/json" "fmt" "io/ioutil" "net/http" "net/http/httptest" "testing" ) // PotentialGuest is a struct to capture a guest from request before he added to guest list type PotentialGuest struct { Table int `json:"table"` AccompaniyingGuests int `json:"accompanying_guests"` } // Constants of a guest to add him to the guest list const ( ACCOMPANYING_GUESTS = 3 NAME = "john" TABLE = 2 ) // TestReturnGuestlist test that verifies that ReturnGuestlist request // utilizes the right request method, route and checks if response is correct func TestReturnGuestlist(t *testing.T) { ts := getReturnGuestlistTestServer(t) err := makeReturnGuestlistRequest(ts.URL, t) if err != nil { t.Errorf("makeReturnGuestlistRequest() returned an error: %s", err) } defer ts.Close() } // TestAddGuestToGuestlist test that verifies that AddGuestToGuestlist request // utilizes the right request method, route and checks if response is correct func TestAddGuestToGuestlist(t *testing.T) { ts := getAddGuestToGuestlistTestServer(t) err := makeAddToGuestBookRequest(ts.URL, t) if err != nil { t.Errorf("makeAddToGuestBookRequest() returned an error: %s", err) } defer ts.Close() } // TestGetArrivedGuests test that verifies that GetArrivedGuests request // utilizes the right request method, route and checks if response is correct func TestGetArrivedGuests(t *testing.T) { ts := getGetArrivedGuestsTestServer(t) err := makeGetArrivedGuestsRequest(ts.URL, t) if err != nil { t.Errorf("makeGetArrivedGuestsRequest() returned an error: %s", err) } defer ts.Close() } // getReturnGuestlistTestServer establishes a test http server with its predefined response func getReturnGuestlistTestServer(t *testing.T) *httptest.Server { ts := httptest.NewServer(http.HandlerFunc( func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) if r.Method != "GET" { t.Errorf(`Expected GET request, got ‘%s’`, r.Method) } if r.URL.EscapedPath() != "/guest_list" { t.Errorf(`Expected request to ‘/guest_list, got ‘%s’`, r.URL.EscapedPath()) } guestlist := GuestList{ []Guest{ {Name: "john", AccompaniyingGuests: 3, Table: 1}, {Name: "mike", AccompaniyingGuests: 2, Table: 1}, {Name: "johana", AccompaniyingGuests: 4, Table: 2}, {Name: "greg", AccompaniyingGuests: 2, Table: 3}, }, } json.NewEncoder(w).Encode(guestlist) }, )) return ts } // getAddGuestToGuestlistTestServer establishes a test http server with its predefined response func getAddGuestToGuestlistTestServer(t *testing.T) *httptest.Server { ts := httptest.NewServer(http.HandlerFunc( func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) if r.Method != "POST" { t.Errorf(`Expected POST request, got ‘%s’`, r.Method) } if r.URL.EscapedPath() != fmt.Sprintf("/guest_list/%s", NAME) { t.Errorf(`Expected request to ‘/guest_list/%s, got ‘%s’`, r.URL.EscapedPath(), NAME) } reqBody, _ := ioutil.ReadAll(r.Body) var guest PotentialGuest json.Unmarshal(reqBody, &guest) if guest.AccompaniyingGuests < 0 { t.Errorf(`Expected 'accompanying guests' be > 0, got ‘%v’`, guest.AccompaniyingGuests) } if guest.Table < 0 { t.Errorf(`Expected 'table' be > 0, got ‘%v’`, guest.Table) } person := Person{Name: NAME} json.NewEncoder(w).Encode(person) }, )) return ts } // makeReturnGuestlistRequest simulates a request to hit ReturnGuestlist endpoint func makeReturnGuestlistRequest(testUrl string, t *testing.T) error { url := fmt.Sprintf("%s/guest_list", testUrl) resp, err := http.Get(url) if err != nil { return err } if resp.StatusCode != http.StatusOK { return fmt.Errorf(`guestbook didn’t respond 200 OK: %s`, resp.Status) } body, _ := ioutil.ReadAll(resp.Body) var list GuestList json.Unmarshal(body, &list) if guest_size := len(list.Guests); guest_size != 4 { t.Errorf("Expected request to return 4 guests, got: ‘%v’", guest_size) } return nil } // makeAddToGuestBookRequest simulates a request to hit AddToGuestBook endpoint func makeAddToGuestBookRequest(testUrl string, t *testing.T) error { url := fmt.Sprintf("%s/guest_list/%s", testUrl, NAME) guest := PotentialGuest{ Table: TABLE, AccompaniyingGuests: ACCOMPANYING_GUESTS, } json_data, err := json.Marshal(guest) resp, err := http.Post(url, "application/json", bytes.NewBuffer(json_data)) if err != nil { return err } if resp.StatusCode != http.StatusOK { return fmt.Errorf("guestbook didn’t respond 200 OK: %s", resp.Status) } body, _ := ioutil.ReadAll(resp.Body) var person Person json.Unmarshal(body, &person) if person.Name != NAME { t.Errorf("Expected request to return %s, got: ‘%s’", NAME, person.Name) } return nil } // getGetArrivedGuestsTestServer establishes a test http server with its predefined response func getGetArrivedGuestsTestServer(t *testing.T) *httptest.Server { ts := httptest.NewServer(http.HandlerFunc( func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) if r.Method != "GET" { t.Errorf(`Expected GET request, got ‘%s’`, r.Method) } if r.URL.EscapedPath() != "/guests" { t.Errorf(`Expected request to ‘/guests, got ‘%s’`, r.URL.EscapedPath()) } arrivedGuestlist := ArrivedGuestList{ []ArrivedGuest{ {Name: "john", AccompaniyingGuests: 3, TimeArrived: "2021-05-20 16:32:32"}, {Name: "mike", AccompaniyingGuests: 2, TimeArrived: "2021-05-20 16:33:33"}, {Name: "johana", AccompaniyingGuests: 4, TimeArrived: "2021-05-20 16:39:00"}, {Name: "greg", AccompaniyingGuests: 2, TimeArrived: "2021-05-20 14:23:23"}, }, } json.NewEncoder(w).Encode(arrivedGuestlist) }, )) return ts } // makeGetArrivedGuestsRequest simulates a request to hit GetArrivedGuests endpoint func makeGetArrivedGuestsRequest(testUrl string, t *testing.T) error { url := fmt.Sprintf("%s/guests", testUrl) resp, err := http.Get(url) if err != nil { return err } if resp.StatusCode != http.StatusOK { return fmt.Errorf(`guestbook didn’t respond 200 OK: %s`, resp.Status) } body, _ := ioutil.ReadAll(resp.Body) var list ArrivedGuestList json.Unmarshal(body, &list) if guest_size := len(list.Guests); guest_size != 4 { t.Errorf("Expected request to return 4 guests, got: ‘%v’", guest_size) } return nil }
package proc import ( "context" "encoding/json" "github.com/aberic/gnomon" "github.com/aberic/gnomon/log" "github.com/aberic/proc/protos" "google.golang.org/grpc" "io/ioutil" "time" ) var ( proc *Proc host string scheduled *time.Timer // 超时检查对象 delay time.Duration stop chan struct{} // 释放当前角色chan ) func init() { proc = &Proc{} timeDistance := gnomon.EnvGetInt64D(timeDistanceEnv, 1500) delay = time.Millisecond * time.Duration(timeDistance) host = gnomon.EnvGet(hostname) scheduled = time.NewTimer(delay) stop = make(chan struct{}, 1) } // ListenStart 开启监听发送 func ListenStart(remote string, useHTTP bool) { log.Debug("listener start", log.Server("proc"), log.Field("remote", remote)) if gnomon.StringIsNotEmpty(remote) { go send(remote, useHTTP) } } // remote swarm:20219 func send(remote string, useHTTP bool) { scheduled.Reset(time.Millisecond * time.Duration(5)) for { select { case <-scheduled.C: if err := proc.run(); nil == err { if useHTTP { if _, err := gnomon.HTTPPostJSON(remote, proc); nil != err { log.Error("send http", log.Err(err)) } else { log.Debug("send http", log.Server("proc"), log.Field("proc", proc)) } } else { var ( procBytes []byte err error ) if procBytes, err = json.Marshal(proc); nil != err { log.Error("send grpc", log.Err(err)) } else { if _, err := gnomon.GRPCRequestSingleConn(remote, func(conn *grpc.ClientConn) (i interface{}, err error) { // 创建grpc客户端 cli := protos.NewProcClient(conn) // 客户端向grpc服务端发起请求 return cli.Info(context.Background(), &protos.Request{Proc: procBytes}) }); nil != err { log.Error("send grpc", log.Err(err)) } else { log.Debug("send grpc", log.Server("proc"), log.Field("proc", proc)) } } } } else { log.Error("send", log.Err(err)) } scheduled.Reset(delay) case <-stop: return } } } // Proc 监听发送完整对象 type Proc struct { Hostname string CPUGroup *CPUGroup MemInfo *MemInfo LoadAvg *LoadAvg //Swaps *Swaps Version *Version Stat *Stat //CGroup *CGroup UsageCPU float64 Mounts *Mounts Disk *Disk //DiskStats *DiskStats SockStat *SockStat } func (p *Proc) run() error { if err := obtainCPUGroup().Info(); nil == err { p.CPUGroup = obtainCPUGroup() } if err := obtainMemInfo().Info(); nil == err { p.MemInfo = obtainMemInfo() } if err := obtainLoadAvg().Info(); nil == err { p.LoadAvg = obtainLoadAvg() } //swaps := &Swaps{} //if err := swaps.Info(); nil == err { // p.Swaps = swaps //} if err := obtainVersion().Info(); nil == err { p.Version = obtainVersion() } if err := obtainStat().Info(); nil == err { p.Stat = obtainStat() } //cGroup := &CGroup{} //if err := cGroup.Info(); nil == err { // p.CGroup = cGroup //} if usage, err := UsageCPU(); nil == err { p.UsageCPU = usage } if err := obtainMounts().Info(); nil == err { p.Mounts = obtainMounts() } if err := obtainDisk().Info(); nil != err { p.Disk = obtainDisk() } //if err := obtainDiskStats().Info(); nil != err { // p.DiskStats = obtainDiskStats() //} if err := obtainSockStat().Info(); nil != err { p.SockStat = obtainSockStat() } bs, err := ioutil.ReadFile(host) if nil != err { return err } p.Hostname = gnomon.StringTrim(string(bs)) return nil }
package main import ( "sync" "time" ) const ( CHECK_FAIL = 0 CHECK_OK ) type CheckResult int type HealthCheck struct { LastCheck time.Time LastCheckResult CheckResult } type EndpointEntry struct { Host string `json:"hostname"` Port int `json:"port"` Url string `json:"url"` Health []HealthCheck `json:"health-checks"` } type ServiceRegistry struct { ServiceName string Entries []*EndpointEntry } type EndpointRegistration struct { ServiceName string `json:"serviceName"` Url string `json:"url` Hostname string `json:"hostname"` Port int `json:"port"` } type ServicesInfo struct { sync.RWMutex Data map[string]*ServiceRegistry } func NewServicesInfo() *ServicesInfo { return &ServicesInfo{Data: make(map[string]*ServiceRegistry)} } func (s *ServicesInfo) Get(key string) ([]EndpointEntry, bool) { (*s).RLock() defer (*s).RUnlock() reg, ok := s.Data[key] var ret []EndpointEntry if ok { for _, v := range reg.Entries { var copy EndpointEntry copy = *v ret = append(ret, copy) } return ret, true } return ret, false } func (s *ServicesInfo) Set(key string, registration EndpointRegistration) { s.Lock() defer s.Unlock() reg, ok := s.Data[key] if !ok { reg = &ServiceRegistry{ServiceName: key, Entries: []*EndpointEntry{}} s.Data[key] = reg } entry := &EndpointEntry{Host: registration.Hostname, Port: registration.Port, Url: registration.Url, Health: []HealthCheck{}} reg.Entries = append(reg.Entries, entry) } func (s *ServicesInfo) Unset(key string, registration EndpointRegistration) { s.Lock() defer s.Unlock() reg, ok := s.Data[key] if !ok { return } for i, entry := range reg.Entries { matches := entry.matches(&registration) if matches { reg.Entries = append(reg.Entries[:i], reg.Entries[i+1:]...) } } } func (e *EndpointEntry) matches(reg *EndpointRegistration) bool { return reg != nil && e != nil && e.Host == reg.Hostname && e.Port == reg.Port && e.Url == reg.Url }
package utils type SliceConstraint interface { int | int64 | string } type R[T SliceConstraint] []T // slice去除重复数据 func RemoveRespSlice[S SliceConstraint](req []S) []S { if len(req) == 0 { return nil } result := make(R[S], 0) temp := map[S]struct{}{} for _, val := range req { if _, ok := temp[val]; !ok { temp[val] = struct{}{} result = append(result, val) } } return result } // slice去重 func SliceRemoveDuplicate[S SliceConstraint](arr R[S]) R[S] { temp := make(map[S]struct{}, len(arr)) // len避免扩容,struct节省空间 k := 0 for _, value := range arr { // 0(n) if _, ok := temp[value]; !ok { temp[value] = struct{}{} arr[k] = value // 记录非重复k,值前移,原地去重 0(n) k++ } } return arr[:k] } // 移除slice中特定的元素 func RemoveSpecificBySlice[S SliceConstraint](arr R[S], param S) R[S] { for i := 0; i < len(arr); i++ { if arr[i] == param { arr = append(arr[:i], arr[i+1:]...) // 无内存分配.提高性能 i-- // 保持正确的索引 } } return arr }
package greeting import "fmt" func Greeting(txt string) string { return fmt.Sprintf("<b>%s</b>", txt) }
package main import "fmt" // go 运算符 和其他语言一样 // 假定 A 值为 10,B 值为 20 //+ 相加 A + B 输出结果 30 //- 相减 A - B 输出结果 -10 //* 相乘 A * B 输出结果 200 /// 相除 B / A 输出结果 2 //% 求余 B % A 输出结果 0 //++ 自增 A++ 输出结果 11 //-- 自减 A-- 输出结果 9 func main() { var a bool = true var b bool = true if a && b { fmt.Printf("第一行 - 条件为 true\n") } if a || b { fmt.Printf("第二行 - 条件为 true\n") } //修改 a 和 b 的值 a = false b = true if a && b { fmt.Printf("第三行 - 条件为 true\n") } else { fmt.Printf("第三行 - 条件为 false\n") } if !(a && b) { fmt.Printf("第四行 - 条件为 true\n") } }
// Copyright 2022 The ChromiumOS Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package productivitycuj import ( "context" "fmt" "regexp" "strconv" "strings" "time" "chromiumos/tast/common/action" "chromiumos/tast/errors" "chromiumos/tast/local/chrome" "chromiumos/tast/local/chrome/browser" "chromiumos/tast/local/chrome/cuj" "chromiumos/tast/local/chrome/uiauto" "chromiumos/tast/local/chrome/uiauto/checked" "chromiumos/tast/local/chrome/uiauto/nodewith" "chromiumos/tast/local/chrome/uiauto/role" "chromiumos/tast/local/chrome/webutil" "chromiumos/tast/local/input" "chromiumos/tast/testing" ) const ( // docsTab indicates the tab name of the "Google Docs". docsTab = "Google Docs" // slidesTab indicates the tab name of the "Google Slides". slidesTab = "Google Slides" // sheetsTab indicates the tab name of the "Google Sheets". sheetsTab = "Google Sheets" ) var ( menuBarBanner = nodewith.Name("Menu bar").Role(role.Banner) fileItem = nodewith.Name("File").Role(role.MenuItem).Ancestor(menuBarBanner) fileExpanded = fileItem.Expanded() ) // GoogleDocs implements the ProductivityApp interface. type GoogleDocs struct { br *browser.Browser tconn *chrome.TestConn ui *uiauto.Context kb *input.KeyboardEventWriter uiHdl cuj.UIActionHandler tabletMode bool } // CreateDocument creates a new document from GDocs. func (app *GoogleDocs) CreateDocument(ctx context.Context) error { conn, err := app.br.NewConn(ctx, cuj.NewGoogleDocsURL) if err != nil { return errors.Wrapf(err, "failed to open URL: %s", cuj.GoogleDocsURL) } if err := webutil.WaitForQuiescence(ctx, conn, longerUIWaitTime); err != nil { return errors.Wrap(err, "failed to wait for page to finish loading") } if err := cuj.MaximizeBrowserWindow(ctx, app.tconn, app.tabletMode, docsTab); err != nil { return errors.Wrap(err, "failed to maximize the Google Docs page") } docWebArea := nodewith.NameContaining(docsTab).Role(role.RootWebArea).First() canvas := nodewith.Role(role.Canvas).Ancestor(docWebArea).First() return uiauto.Combine("type word to document", app.maybeCloseWelcomeDialog, app.ui.WaitUntilExists(canvas), app.kb.TypeAction(docText), )(ctx) } // CreateSlides creates a new presentation from GDocs. func (app *GoogleDocs) CreateSlides(ctx context.Context) error { conn, err := app.br.NewConn(ctx, cuj.NewGoogleSlidesURL) if err != nil { return errors.Wrapf(err, "failed to open URL: %s", cuj.GoogleSlidesURL) } if err := webutil.WaitForQuiescence(ctx, conn, longerUIWaitTime); err != nil { return errors.Wrap(err, "failed to wait for page to finish loading") } slidesWebArea := nodewith.NameContaining("Google Slides").Role(role.RootWebArea) title := nodewith.Name("title").Role(role.StaticText).Ancestor(slidesWebArea) subtitle := nodewith.Name("subtitle").Role(role.StaticText).Ancestor(slidesWebArea) return uiauto.Combine("open a new presentation", app.uiHdl.Click(title), app.kb.TypeAction(titleText), app.uiHdl.Click(subtitle), app.kb.TypeAction(subtitleText), )(ctx) } // CreateSpreadsheet creates a new spreadsheet by copying from sample spreadsheet. func (app *GoogleDocs) CreateSpreadsheet(ctx context.Context, cr *chrome.Chrome, sampleSheetURL, outDir string) (string, error) { conn, err := app.br.NewConn(ctx, sampleSheetURL+"/copy") if err != nil { return "", errors.Wrapf(err, "failed to open URL: %s", sampleSheetURL) } defer conn.Close() defer conn.CloseTarget(ctx) if err := webutil.WaitForQuiescence(ctx, conn, longerUIWaitTime); err != nil { return "", errors.Wrap(err, "failed to wait for page to finish loading") } copyButton := nodewith.Name("Make a copy").Role(role.Button) if err := app.ui.DoDefault(copyButton)(ctx); err != nil { return "", errors.Wrap(err, "failed to open the copied data spreadsheet") } if err := app.renameFile(sheetName)(ctx); err != nil { return "", err } return sheetName, nil } // OpenSpreadsheet creates a new document from GDocs. func (app *GoogleDocs) OpenSpreadsheet(ctx context.Context, filename string) error { testing.ContextLog(ctx, "Opening an existing spreadsheet: ", filename) conn, err := app.br.NewConn(ctx, cuj.GoogleSheetsURL) if err != nil { return errors.Wrapf(err, "failed to open URL: %s", cuj.GoogleSheetsURL) } if err := webutil.WaitForQuiescence(ctx, conn, longerUIWaitTime); err != nil { return errors.Wrap(err, "failed to wait for page to finish loading") } section := nodewith.NameRegex(regexp.MustCompile("^(Today|Yesterday|Previous (7|30) days|Earlier).*")).Role(role.ListBox).First() fileOption := nodewith.NameContaining(sheetName).Role(role.ListBoxOption).Ancestor(section).First() return uiauto.Combine("search file from recently opened", app.uiHdl.Click(fileOption), app.validateEditMode, )(ctx) } // MoveDataFromDocToSheet moves data from document to spreadsheet. func (app *GoogleDocs) MoveDataFromDocToSheet(ctx context.Context) error { testing.ContextLog(ctx, "Moving data from document to spreadsheet") content := nodewith.Name("Document content").Role(role.TextField).Editable() if err := uiauto.Combine("cut selected text from the document", app.uiHdl.SwitchToChromeTabByName(docsTab), app.uiHdl.Click(content), app.kb.AccelAction("Ctrl+A"), app.kb.AccelAction("Ctrl+X"), )(ctx); err != nil { return err } if err := uiauto.Combine("switch to Google Sheets and jump to the target cell", app.uiHdl.SwitchToChromeTabByName(sheetsTab), app.maybeCloseEditHistoryDialog, app.selectCell("H3"), )(ctx); err != nil { return err } return uiauto.Combine("paste content into the cell", app.kb.AccelAction("Ctrl+V"), app.kb.AccelAction("Enter"), )(ctx) } // MoveDataFromSheetToDoc moves data from spreadsheet to document. func (app *GoogleDocs) MoveDataFromSheetToDoc(ctx context.Context) error { testing.ContextLog(ctx, "Moving data from document to spreadsheet") if err := uiauto.Combine("cut selected text from cell", app.selectCell("H1"), app.kb.AccelAction("Ctrl+X"), )(ctx); err != nil { return err } content := nodewith.Name("Document content").Role(role.TextField).Editable() return uiauto.Combine("switch to Google Docs and paste the content", app.uiHdl.SwitchToChromeTabByName(docsTab), app.ui.WaitUntilExists(content), app.kb.AccelAction("Ctrl+V"), )(ctx) } // ScrollPage scrolls the document and spreadsheet. func (app *GoogleDocs) ScrollPage(ctx context.Context) error { testing.ContextLog(ctx, "Scrolling the document and spreadsheet") for _, tabName := range []string{docsTab, sheetsTab} { if err := scrollTabPageByName(ctx, app.uiHdl, tabName); err != nil { return err } } return nil } // SwitchToOfflineMode switches to offline mode and switches back to online mode. func (app *GoogleDocs) SwitchToOfflineMode(ctx context.Context) error { expandFileMenu := uiauto.IfSuccessThen( app.ui.WithTimeout(defaultUIWaitTime).WaitUntilGone(fileExpanded), app.uiHdl.ClickUntil(fileItem, app.ui.WithTimeout(defaultUIWaitTime).WaitUntilExists(fileExpanded)), ) removeOffline := nodewith.Role(role.MenuItemCheckBox).Name("Remove offline access k") checkOffline := uiauto.NamedCombine("check whether offline mode is available", expandFileMenu, app.ui.WithTimeout(defaultUIWaitTime).WaitUntilExists(removeOffline), ) makeOfflineModeAvailable := uiauto.NamedCombine("make offline mode available", expandFileMenu, app.kb.TypeAction("k"), checkOffline, uiauto.IfSuccessThen(app.ui.WithTimeout(defaultUIWaitTime).WaitUntilExists(fileExpanded), app.uiHdl.Click(fileItem)), ) return uiauto.IfFailThen(checkOffline, makeOfflineModeAvailable)(ctx) } // UpdateCells updates one of the independent cells and propagate values to dependent cells. func (app *GoogleDocs) UpdateCells(ctx context.Context) error { if err := app.maybeCloseEditHistoryDialog(ctx); err != nil { return errors.Wrap(err, `failed to close "See edit history of a cell" dialog`) } if err := app.editCellValue(ctx, "A3", "100"); err != nil { return errors.Wrap(err, "failed to edit the value of the cell") } var sum int if err := uiauto.Retry(retryTimes, func(ctx context.Context) error { val, err := app.getCellValue(ctx, "B1") if err != nil { return errors.Wrap(err, "failed to get the value of the cell") } sum, err = strconv.Atoi(val) if err != nil { return errors.Wrap(err, "failed to convert type to integer") } return nil })(ctx); err != nil { return err } if expectedSum := calculateSum(3, 100); sum != expectedSum { return errors.Errorf("failed to validate the sum %d rows: got: %v; want: %v", rangeOfCells, sum, expectedSum) } return nil } // VoiceToTextTesting uses the "Dictate" function to achieve voice-to-text (VTT) and directly input text into office documents. func (app *GoogleDocs) VoiceToTextTesting(ctx context.Context, expectedText string, playAudio action.Action) error { testing.ContextLog(ctx, "Using voice to text (VTT) to enter text directly to document") // allowPermission allows microphone if browser asks for the permission. allowPermission := func(ctx context.Context) error { alertDialog := nodewith.NameContaining("Use your microphone").ClassName("RootView").Role(role.AlertDialog).First() allowButton := nodewith.Name("Allow").Role(role.Button).Ancestor(alertDialog) if err := app.ui.WithTimeout(defaultUIWaitTime).WaitUntilExists(allowButton)(ctx); err != nil { testing.ContextLog(ctx, "No action to grant microphone permission") return nil } return app.ui.DoDefaultUntil(allowButton, app.ui.WithTimeout(defaultUIWaitTime).WaitUntilGone(alertDialog))(ctx) } checkDictationResult := func(ctx context.Context) error { testing.ContextLog(ctx, "Check if the result is as expected") return testing.Poll(ctx, func(ctx context.Context) error { if err := uiauto.Combine("copy the content of the document to the clipboard", app.kb.AccelAction("Ctrl+A"), uiauto.Sleep(500*time.Millisecond), // Wait for all text to be selected. app.kb.AccelAction("Ctrl+C"), )(ctx); err != nil { return err } clipData, err := getClipboardText(ctx, app.tconn) if err != nil { return err } ignoreCaseData := strings.TrimSuffix(strings.ToLower(clipData), "\n") if !strings.Contains(ignoreCaseData, strings.ToLower(expectedText)) { return errors.Errorf("failed to validate input value ignoring case: got: %s; want: %s", clipData, expectedText) } return nil }, &testing.PollOptions{Interval: time.Second, Timeout: 15 * time.Second}) } pasteTableContainer := nodewith.Name("Paste table").Role(role.GenericContainer) cancelButton := nodewith.Name("Cancel").Role(role.Button).Ancestor(pasteTableContainer) tools := nodewith.Name("Tools").Role(role.MenuItem).Ancestor(menuBarBanner) toolsExpanded := tools.Expanded() voiceTypingItem := nodewith.Name("Voice typing v Ctrl+Shift+S").Role(role.MenuItem) voiceTypingDialog := nodewith.Name("Voice typing").Role(role.Dialog) dictationButton := nodewith.Name("Start dictation").Role(role.ToggleButton).FinalAncestor(voiceTypingDialog) // Click "Tools" and then "Voice typing". A microphone box appears. // Click the microphone box when ready to speak. if err := uiauto.Combine("turn on the voice typing", app.uiHdl.SwitchToChromeTabByName(docsTab), app.closeDialogs, uiauto.IfSuccessThen( app.ui.WithTimeout(defaultUIWaitTime).WaitUntilExists(cancelButton), uiauto.NamedAction("click the cancel button", app.uiHdl.Click(cancelButton)), ), app.ui.DoDefaultUntil(tools, app.ui.WithTimeout(defaultUIWaitTime).WaitUntilExists(toolsExpanded)), app.ui.WaitUntilExists(voiceTypingItem), // Sometimes the "Voice typing" menu item can be found but UI has not showed up yet. app.ui.DoDefault(voiceTypingItem), app.ui.DoDefaultUntil(dictationButton, app.checkDictionButton), allowPermission, )(ctx); err != nil { return err } return uiauto.Combine("play an audio file and check dictation results", // Make sure that the dictation does not stop by waiting a long time. uiauto.IfFailThen(app.checkDictionButton, app.ui.DoDefaultUntil(dictationButton, app.checkDictionButton)), playAudio, checkDictationResult, app.uiHdl.Click(dictationButton), // Click again to stop voice typing. )(ctx) } // Cleanup cleans up the resources used by running the GDocs testing. // It removes the document and slide which we created in the test case and close all tabs after completing the test. // This function should be called as deferred function after the app is created. func (app *GoogleDocs) Cleanup(ctx context.Context, sheetName string) error { moveToTrash := nodewith.NameContaining("Move to trash t").Role(role.MenuItem) dialog := nodewith.Name("File moved to trash").Role(role.Dialog) homeScreen := nodewith.NameRegex(regexp.MustCompile("^Go to (Docs|Slides|Sheets) home screen")).Role(role.Button).Ancestor(dialog) for _, tabName := range []string{docsTab, slidesTab, sheetsTab} { if err := uiauto.NamedCombine("remove the "+tabName, app.uiHdl.SwitchToChromeTabByName(tabName), app.closeDialogs, app.uiHdl.Click(fileItem), app.uiHdl.Click(moveToTrash), app.uiHdl.Click(homeScreen), )(ctx); err != nil { return err } } return nil } // SetBrowser sets browser to chrome or lacros. func (app *GoogleDocs) SetBrowser(br *browser.Browser) { app.br = br } // maybeCloseWelcomeDialog closes the "Welcome to Google Docs/Slides/Sheets" dialog if it exists. func (app *GoogleDocs) maybeCloseWelcomeDialog(ctx context.Context) error { welcomeDialog := nodewith.NameRegex(regexp.MustCompile("^Welcome to Google (Docs|Slides|Sheets)$")).Role(role.Dialog) closeButton := nodewith.Name("Close").Ancestor(welcomeDialog) return uiauto.IfSuccessThen( app.ui.WithTimeout(defaultUIWaitTime).WaitUntilExists(welcomeDialog), app.uiHdl.Click(closeButton), )(ctx) } // validateEditMode checks if the share button exists to confirm whether to enter the edit mode. func (app *GoogleDocs) validateEditMode(ctx context.Context) error { shareButton := nodewith.Name("Share. Private to only me. ").Role(role.Button) // Make sure share button exists to ensure to enter the edit mode. This is especially necessary on low-end DUTs. return app.ui.WithTimeout(longerUIWaitTime).WaitUntilExists(shareButton)(ctx) } // selectCell selects the specified cell using the name box. func (app *GoogleDocs) selectCell(cell string) action.Action { nameBox := nodewith.Name("Name box (Ctrl + J)").Role(role.GenericContainer) nameField := nodewith.Role(role.TextField).FinalAncestor(nameBox) nameFieldFocused := nameField.Focused() nameFieldText := nodewith.Name(cell).Role(role.StaticText).Ancestor(nameField).Editable() return uiauto.NamedCombine(fmt.Sprintf("to select cell %q", cell), app.ui.DoDefaultUntil(nameField, app.ui.WithTimeout(defaultUIWaitTime).WaitUntilExists(nameFieldFocused)), app.kb.AccelAction("Ctrl+A"), app.kb.TypeAction(cell), app.kb.AccelAction("Enter"), app.ui.WaitUntilExists(nameFieldText), // Given time to jump to the specific cell and select it. // And because we cannot be sure whether the target cell is focused, we have to wait a short time. uiauto.Sleep(500*time.Millisecond), ) } // getCellValue gets the value of the specified cell. func (app *GoogleDocs) getCellValue(ctx context.Context, cell string) (clipData string, err error) { if err := app.selectCell(cell)(ctx); err != nil { return "", err } if err := testing.Poll(ctx, func(ctx context.Context) error { // Due to the unstable network, there might be no data in the clipboard after the copy operation. // Therefore, we also need to retry the copy operation. if err := app.kb.AccelAction("Ctrl+C")(ctx); err != nil { return err } clipData, err = getClipboardText(ctx, app.tconn) if err != nil { return err } if clipData == "Retrieving data. Wait a few seconds and try to cut or copy again." { return errors.New("clipboard data is not yet ready") } return nil }, &testing.PollOptions{Timeout: 2 * time.Minute}); err != nil { return "", err } testing.ContextLogf(ctx, "Getting cell %q value: %s", cell, clipData) return clipData, nil } // editCellValue edits the cell to the specified value. func (app *GoogleDocs) editCellValue(ctx context.Context, cell, value string) error { workingText := nodewith.Name("Working…").Role(role.StaticText) return uiauto.NamedCombine(fmt.Sprintf("write cell %q value: %v", cell, value), app.selectCell(cell), app.kb.TypeAction(value), app.kb.AccelAction("Enter"), uiauto.IfSuccessThen( app.ui.WithTimeout(defaultUIWaitTime).WaitUntilExists(workingText), app.ui.WaitUntilGone(workingText), ), )(ctx) } // renameFile renames the name of the spreadsheet. func (app *GoogleDocs) renameFile(sheetName string) uiauto.Action { renameItem := nodewith.Name("Rename r").Role(role.MenuItem) renameField := nodewith.Name("Rename").Role(role.TextField).Editable().Focused() inputFileName := func(ctx context.Context) error { return testing.Poll(ctx, func(ctx context.Context) error { if err := uiauto.Combine("input file name", app.kb.AccelAction("Ctrl+A"), app.kb.TypeAction(sheetName), )(ctx); err != nil { return err } node, err := app.ui.Info(ctx, renameField) if err != nil { return err } if node.Value != sheetName { return errors.New("file name is incorrect") } return nil }, &testing.PollOptions{Timeout: time.Minute}) } return uiauto.Combine("rename the file", app.validateEditMode, app.ui.Retry(retryTimes, uiauto.Combine(`select "Rename" from the "File" menu`, uiauto.IfSuccessThen(app.ui.WithTimeout(defaultUIWaitTime).WaitUntilExists(fileItem), app.ui.DoDefaultUntil(fileItem, app.ui.WithTimeout(defaultUIWaitTime).WaitUntilExists(fileExpanded))), uiauto.IfSuccessThen(app.ui.WithTimeout(defaultUIWaitTime).WaitUntilExists(renameItem), app.ui.DoDefaultUntil(renameItem, app.ui.WithTimeout(defaultUIWaitTime).WaitUntilExists(renameField))), )), uiauto.NamedAction("input the file name", inputFileName), app.kb.AccelAction("Enter"), uiauto.Sleep(2*time.Second), // Wait Google Sheets to save the changes. ) } // maybeCloseEditHistoryDialog closes the "See edit history of a cell" dialog if it exists. func (app *GoogleDocs) maybeCloseEditHistoryDialog(ctx context.Context) error { dialog := nodewith.Name("See edit history of a cell").Role(role.Dialog) button := nodewith.Name("GOT IT").Role(role.Button).Ancestor(dialog) return uiauto.IfSuccessThen(app.ui.WithTimeout(defaultUIWaitTime).WaitUntilExists(dialog), app.uiHdl.Click(button))(ctx) } // closeDialogs closes dialogs if the display is different from what we expected. func (app *GoogleDocs) closeDialogs(ctx context.Context) error { testing.ContextLog(ctx, "Checking if any dialogs need to be closed") unableToLoadDialog := nodewith.Name("Unable to load file").Role(role.Dialog) dialogButton := nodewith.Name("Reload").Ancestor(unableToLoadDialog).First() reloadContainer := nodewith.Name("Reload to allow offline editing. Reload").Role(role.GenericContainer) reloadButton := nodewith.Name("Reload").Role(role.Button).FinalAncestor(reloadContainer) // dialogsInfo holds the information of dialogs that will be encountered and needs to be handled during testing. // The order of slices starts with the most frequent occurrence. dialogsInfo := []dialogInfo{ { name: "Unable to load file", dialog: unableToLoadDialog, node: dialogButton, }, { name: "Reload to allow offline editing. Reload", dialog: reloadContainer, node: reloadButton, }, } for _, info := range dialogsInfo { name, dialog, button := info.name, info.dialog, info.node testing.ContextLogf(ctx, "Checking if the %q dialog exists", name) if err := app.ui.WaitUntilExists(dialog)(ctx); err != nil { continue } return app.uiHdl.ClickUntil(button, app.ui.WithTimeout(defaultUIWaitTime).WaitUntilGone(button))(ctx) } return nil } // checkDictionButton checks if the "Start dictation" button is checked. func (app *GoogleDocs) checkDictionButton(ctx context.Context) error { startTime := time.Now() voiceTypingDialog := nodewith.Name("Voice typing").Role(role.Dialog) dictationButton := nodewith.Name("Start dictation").Role(role.ToggleButton).FinalAncestor(voiceTypingDialog) return testing.Poll(ctx, func(ctx context.Context) error { button, err := app.ui.WithTimeout(time.Second).Info(ctx, dictationButton) if err != nil { return err } if button.Checked != checked.True { return errors.New("button not checked yet") } testing.ContextLogf(ctx, "Takes %v seconds to verify the dictation button is checked", time.Since(startTime).Seconds()) return nil }, &testing.PollOptions{Timeout: defaultUIWaitTime}) } // NewGoogleDocs creates GoogleDocs instance which implements ProductivityApp interface. func NewGoogleDocs(tconn *chrome.TestConn, kb *input.KeyboardEventWriter, uiHdl cuj.UIActionHandler, tabletMode bool) *GoogleDocs { return &GoogleDocs{ tconn: tconn, ui: uiauto.New(tconn), kb: kb, uiHdl: uiHdl, tabletMode: tabletMode, } } var _ ProductivityApp = (*GoogleDocs)(nil)
package helm import ( "fmt" "os" "github.com/onsi/ginkgo" "helm.sh/helm/v3/pkg/action" "helm.sh/helm/v3/pkg/chart" "helm.sh/helm/v3/pkg/chart/loader" "helm.sh/helm/v3/pkg/cli" "helm.sh/helm/v3/pkg/release" "helm.sh/helm/v3/pkg/storage/driver" "helm.sh/helm/v3/pkg/strvals" ) var ( logf = ginkgo.GinkgoT().Logf ) func NewHelmConfig(namespace string) (*action.Configuration, error) { helmCfg := &action.Configuration{} err := helmCfg.Init(cli.New().RESTClientGetter(), namespace, "", logf) if err != nil { return helmCfg, err } return helmCfg, nil } // InstallChart installs the chart or upgrade the same name release. func InstallChart(releaseName string, namespace string, chartDir string, patches map[string]interface{}) (*release.Release, error) { _ = os.Setenv("HELM_NAMESPACE", namespace) defer func() { _ = os.Unsetenv("HELM_NAMESPACE") }() helmCfg, err := NewHelmConfig(namespace) if err != nil { return nil, fmt.Errorf("failed to init helm configuration: %w", err) } var helmRun func(chart *chart.Chart, values map[string]interface{}) (*release.Release, error) helmHistory := action.NewHistory(helmCfg) helmHistory.Max = 1 if _, err := helmHistory.Run(releaseName); err != nil { if err != driver.ErrReleaseNotFound { return nil, fmt.Errorf("failed to get release history: %w", err) } helmInstall := action.NewInstall(helmCfg) helmInstall.Namespace = namespace helmInstall.CreateNamespace = true helmInstall.Atomic = true helmInstall.ReleaseName = releaseName helmRun = helmInstall.Run } else { helmUpgrade := action.NewUpgrade(helmCfg) helmUpgrade.Namespace = namespace helmUpgrade.MaxHistory = 1 helmUpgrade.Atomic = true helmRun = func(chart *chart.Chart, values map[string]interface{}) (*release.Release, error) { return helmUpgrade.Run(releaseName, chart, values) } } // load chart loadedChart, err := loader.LoadDir(chartDir) if err != nil { return nil, fmt.Errorf("failed to load chart: %w", err) } // apply patches for key, value := range patches { patchStr := fmt.Sprintf("%s=%v", key, value) if err := strvals.ParseInto(patchStr, loadedChart.Values); err != nil { return nil, fmt.Errorf("failed to parse into chart value: %w", err) } } return helmRun(loadedChart, loadedChart.Values) } // UninstallChart uninstalls the chart. func UninstallChart(releaseName string, namespace string) (*release.UninstallReleaseResponse, error) { _ = os.Setenv("HELM_NAMESPACE", namespace) defer func() { _ = os.Unsetenv("HELM_NAMESPACE") }() helmCfg, err := NewHelmConfig(namespace) if err != nil { return nil, fmt.Errorf("failed to init helm configuration: %w", err) } return action.NewUninstall(helmCfg).Run(releaseName) }
// tiger插件,一个脚手架工具,用于来初始化一个Tigo项目 package main import ( "Tigo/TigoWeb" "fmt" "io/ioutil" "os" "os/exec" "strings" ) const ( DemoCode = `package main import ( "github.com/karldoenitz/Tigo/TigoWeb" ) // HelloHandler it's a demo handler type HelloHandler struct { TigoWeb.BaseHandler } // Get http get method func (h *HelloHandler) Get() { // write your code here h.ResponseAsHtml("<p1 style='color: red'>Hello Tiger Go!</p1>") } // urls url mapping var urls = []TigoWeb.Pattern{ {"/hello-world", HelloHandler{}, nil}, } func main() { application := TigoWeb.Application{ IPAddress: "0.0.0.0", Port: 8888, UrlPatterns: urls, } application.Run() } ` mainCode = `package main import ( "github.com/karldoenitz/Tigo/TigoWeb" "%s/handler" ) // Write you url mapping here var urls = []TigoWeb.Pattern{ {"/ping", handler.PingHandler{}, nil}, } func main() { application := TigoWeb.Application{ IPAddress: "0.0.0.0", Port: 8080, UrlPatterns: urls, } application.Run() } ` handlerCode = `// you can write your code here. // You can add 'Post', 'Put', 'Delete' and other methods to handler. package handler import ( "github.com/karldoenitz/Tigo/TigoWeb" ) type %s struct { TigoWeb.BaseHandler } func (p *%s) Get() { // write your code here p.ResponseAsText("Pong") } func (p *%s) Post() { // write your code here p.ResponseAsText("Pong") } ` configCodeJson = `{ "cookie": "%s", "ip": "0.0.0.0", "port": 8080, "log": { "trace": "stdout", "info": "%s/log/run-info.log", "warning": "%s/log/run.log", "error": "%s/log/run.log" } } ` configCodeYaml = `cookie: %s ip: 0.0.0.0 port: 8080 log: trace: stdout info: "%s/log/run-info.log" warning: "%s/log/run.log" error: "%s/log/run.log" ` cmdVerbose = ` use command tiger to create a Tigo projection. Usage: tiger <command> [args] The commands are: addHandler to add a handler for Tigo projection create to create a Tigo projection conf to add a configuration for Tigo projection mod to run go mod version to show Tigo version Use "go help <command>" for more information about a command. ` cmdCreateVerbose = ` use this command to create a Tigo project. "tiger create <project_name>" can create a project with name "project_name", "tiger create demo" can create a demo project. ` cmdConfVerbose = ` use this command to add a configuration. if it's an empty folder, this command will throw an error. the new configuration will replace the old configuration. ` cmdAddHandlerVerbose = ` use this command to add a handler with defined name. "tiger addHandler <handler_name>" will add a handler named "handler_name". ` ) // getWorkingDirPath 获取当前工作路径 func getWorkingDirPath() string { dir, err := os.Getwd() if err != nil { panic(err) } return dir } // getCmdArgs 获取命令行参数及命令个数 func getCmdArgs() (args []string, argNum int) { args = os.Args[1:] argNum = len(args) return } // printCmdUsage 打印help // - args: 命令行输入的参数 func printCmdUsage(args []string) { args = append(args, "") cmd := args[1] switch cmd { case "create": fmt.Print(cmdCreateVerbose) break case "conf": fmt.Print(cmdConfVerbose) break case "addHandler": fmt.Print(cmdAddHandlerVerbose) break default: fmt.Print(cmdVerbose) break } } // execEngine 执行引擎 // - args: 执行参数 func execEngine(args []string) { switch args[0] { case "create": execCreate(args[1]) break case "conf": execConf(args[1]) break case "addHandler": execAddHandler(args[1]) break } } // execCreate 执行create命令 // - arg create命令的参数 func execCreate(arg string) { // 先创建目录 workDir := getWorkingDirPath() projectPath := fmt.Sprintf("%s/%s", workDir, arg) if err := os.Mkdir(projectPath, os.ModePerm); err != nil { panic(err.Error()) } if arg == "demo" { // 再创建文件 f, err := os.Create(fmt.Sprintf("%s/main.go", projectPath)) if err != nil { panic(err.Error()) } if _, err := f.WriteString(DemoCode); err != nil { panic(err) } fmt.Println("project `demo` created successfully") fmt.Println("Execute go mod") _ = f.Close() return } // 创建非demo项目的main文件 f, err := os.Create(fmt.Sprintf("%s/main.go", projectPath)) if err != nil { panic(err.Error()) } if _, err := f.WriteString(fmt.Sprintf(mainCode, arg)); err != nil { panic(err) } // 创建handler文件 if err := os.Mkdir(projectPath+"/handler", os.ModePerm); err != nil { fmt.Println(err.Error()) } fHandler, err := os.Create(fmt.Sprintf("%s/handler/pinghandler.go", projectPath)) if err != nil { fmt.Println(err.Error()) } _, _ = fHandler.WriteString(fmt.Sprintf(handlerCode, "PingHandler", "PingHandler")) _ = f.Close() _ = fHandler.Close() fmt.Printf("project `%s` created successfully\n", arg) fmt.Println("Execute go mod") } // execCmd 执行cmd命令 // - commands: 需要执行的命令 func execCmd(commands []string) bool { cmd := exec.Command(commands[0], commands[1:]...) err := cmd.Run() if err != nil { fmt.Printf("cmd.Run() failed with %s\n", err) return false } return true } // goMod 执行go mod func goMod() { dir, _ := os.Getwd() splitPath := strings.Split(dir, "/") proName := splitPath[len(splitPath)-1] execCmd([]string{"go", "mod", "init", proName}) execCmd([]string{"go", "mod", "tidy"}) execCmd([]string{"go", "mod", "vendor"}) } // execAddHandler 在当前Tigo项目中增加一个handler // - handlerName: handler名字 func execAddHandler(handlerName string) { workDir := getWorkingDirPath() handlerPath := fmt.Sprintf("%s/handler", workDir) _ = os.Mkdir(handlerPath, os.ModePerm) // 如果有则新建一个handler文件,并注入代码 fileName := strings.ToLower(handlerName) fHandler, err := os.Create(fmt.Sprintf("%s/%s.go", handlerPath, fileName)) if err != nil { fmt.Println(err.Error()) return } _, _ = fHandler.WriteString(fmt.Sprintf(handlerCode, handlerName, handlerName)) _ = fHandler.Close() // 再判断是否有main文件 _, err = os.Stat(fmt.Sprintf("%s/main.go", workDir)) if err != nil { // 如果没有则退出 fmt.Println(err.Error()) return } // 如果有则检测代码,并在urls中插入一个url映射 content, err := ioutil.ReadFile(fmt.Sprintf("%s/main.go", workDir)) if err != nil { fmt.Printf("read file error:%v\n", err) return } // 寻找main.go中的url配置 codes := strings.Split(string(content), "\n") var isFoundUrls bool var newCodes []string url := strings.Replace(fileName, "handler", "", -1) for _, code := range codes { if code == "var urls = []TigoWeb.Pattern{" { isFoundUrls = true } if code == "}" && isFoundUrls { code = fmt.Sprintf("\t{\"/%s\", handler.%s{}, nil},\n}", url, handlerName) isFoundUrls = false newCodes = append(newCodes, code) continue } newCodes = append(newCodes, code) } newCode := strings.Join(newCodes, "\n") f, err := os.Create(fmt.Sprintf("%s/main.go", workDir)) if err != nil { fmt.Println(err.Error()) return } _, _ = f.WriteString(newCode) _ = f.Close() } // execConf 增加配置文件 // - arg: 配置文件名称 func execConf(arg string) { workDir := getWorkingDirPath() configPath := fmt.Sprintf("%s/%s", workDir, arg) _ = os.Mkdir(fmt.Sprintf("%s/log", workDir), os.ModePerm) f, err := os.Create(configPath) if err != nil { fmt.Println(err.Error()) return } if strings.HasSuffix(arg, ".json") { _, _ = f.WriteString(fmt.Sprintf(configCodeJson, arg, workDir, workDir, workDir)) } else { _, _ = f.WriteString(fmt.Sprintf(configCodeYaml, arg, workDir, workDir, workDir)) } _ = f.Close() content, err := ioutil.ReadFile(fmt.Sprintf("%s/main.go", workDir)) if err != nil { fmt.Printf("read file error:%v\n", err) return } // 寻找main.go中的application.Run()配置 codes := strings.Split(string(content), "\n") var newCodes []string for _, code := range codes { if code == "\tapplication.Run()" { code = fmt.Sprintf("\tapplication.ConfigPath = \"%s\"\n\tapplication.Run()", configPath) newCodes = append(newCodes, code) continue } newCodes = append(newCodes, code) } newCode := strings.Join(newCodes, "\n") f, err = os.Create(fmt.Sprintf("%s/main.go", workDir)) if err != nil { fmt.Println(err.Error()) return } _, err = f.WriteString(newCode) if err != nil { fmt.Println(err.Error()) } _ = f.Close() } func main() { // 获取命令行参数,根据参数判断是否是创建demo, // 如果创建demo,则直接把`DemoCode`注入到目标文件中就行 // tiger支持的命令: // - create xxx: 创建项目 // - addHandler xxx: 增加xxx命名的handler // - conf xxx: 用xxx命名的配置文件替换现有配置文件,没有则新建 // - mod: 进行go mod // - version: 获取当前Tigo版本号 args, argsCnt := getCmdArgs() if argsCnt < 1 { fmt.Print(cmdVerbose) return } if args[0] == "mod" { goMod() return } if args[0] == "version" { fmt.Println(TigoWeb.Version) return } if args[0] == "help" { printCmdUsage(args) return } execEngine(args) }
// Copyright 2021 The ChromiumOS Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package firmware import ( "context" "encoding/json" "fmt" "regexp" "sort" "strings" "time" "github.com/golang/protobuf/ptypes/empty" "github.com/google/go-cmp/cmp" common "chromiumos/tast/common/firmware" commonbios "chromiumos/tast/common/firmware/bios" "chromiumos/tast/common/servo" "chromiumos/tast/remote/firmware/bios" "chromiumos/tast/remote/firmware/fixture" pb "chromiumos/tast/services/cros/firmware" "chromiumos/tast/testing" "chromiumos/tast/testing/hwdep" ) func init() { testing.AddTest(&testing.Test{ Func: ServoGBBFlags, Desc: "Verifies GBB flags state can be obtained and manipulated via the servo interface", Timeout: 8 * time.Minute, Contacts: []string{"cros-fw-engprod@google.com", "jbettis@google.com"}, Attr: []string{"group:firmware", "firmware_cr50", "firmware_ccd"}, SoftwareDeps: []string{"flashrom"}, ServiceDeps: []string{"tast.cros.firmware.BiosService"}, Fixture: fixture.NormalMode, Data: []string{"fw-config.json"}, // b/111215677: CCD servo detection doesn't work on soraka. HardwareDeps: hwdep.D(hwdep.SkipOnModel("soraka")), }) } func dutControl(ctx context.Context, s *testing.State, svo *servo.Servo, commands [][]string) { for _, section := range commands { for _, cmd := range section { s.Logf("dut-control %q", cmd) parts := strings.SplitN(cmd, ":", 2) if len(parts) == 1 { if _, err := svo.GetString(ctx, servo.StringControl(cmd)); err != nil { s.Errorf("Could not read servo string %s: %v", cmd, err) } } else { if err := svo.SetString(ctx, servo.StringControl(parts[0]), parts[1]); err != nil { s.Errorf("Could not set servo string %s: %v", cmd, err) } } } } } type fwConfig struct { DUTControlOff [][]string `json:"dut_control_off"` DUTControlOn [][]string `json:"dut_control_on"` FlashExtraFlagsFlashrom []string `json:"flash_extra_flags_flashrom"` Programmer string `json:"programmer"` } // ServoGBBFlags has been tested to pass with Suzy-Q, Servo V4, Servo V4 + ServoMicro in dual V4 mode. // Verified fail on Servo V4 + ServoMicro w/o dual v4 mode. // Has not been tested with with C2D2 (assumed to pass). func ServoGBBFlags(ctx context.Context, s *testing.State) { var flashCmds map[string]map[string]fwConfig fwConfigRaw, err := s.DataFileSystem().Open("fw-config.json") if err != nil { s.Fatal("Failed to open fw-config.json") } defer fwConfigRaw.Close() dec := json.NewDecoder(fwConfigRaw) err = dec.Decode(&flashCmds) if err != nil { s.Fatal("Failed to Unmarshall fw-config.json: ", err) } h := s.FixtValue().(*fixture.Value).Helper if err := h.RequirePlatform(ctx); err != nil { s.Fatal("Failed to require platform: ", err) } boardFlashCmds, ok := flashCmds[h.Board] if !ok { s.Logf("Board %q does not have fw-config, using generic", h.Board) boardFlashCmds = flashCmds["generic"] } if err := h.RequireServo(ctx); err != nil { s.Fatal("Failed to connect to servo: ", err) } if err := h.Servo.RequireCCD(ctx); err != nil { s.Fatal("Servo does not have CCD: ", err) } if val, err := h.Servo.GetString(ctx, servo.GSCCCDLevel); err != nil { s.Fatal("Failed to get gsc_ccd_level") } else if val != servo.Open { s.Logf("CCD is not open, got %q. Attempting to unlock", val) if err := h.Servo.SetString(ctx, servo.CR50Testlab, servo.Open); err != nil { s.Fatal("Failed to unlock CCD") } } servoType, err := h.Servo.GetServoType(ctx) if err != nil { s.Fatal("Failed to get servo type: ", err) } dualModePattern := regexp.MustCompile(`^(.*_with)_.*_and(_ccd.*)$`) if parts := dualModePattern.FindStringSubmatch(servoType); parts != nil { // This is a dual mode servo, but we want the ccd flash config servoType = parts[1] + parts[2] } servoFlashCmds, ok := boardFlashCmds[servoType] if !ok { s.Logf("Servo %q does not have fw-config, using ccd_cr50", servoType) servoFlashCmds = boardFlashCmds["ccd_cr50"] } programmer := servoFlashCmds.Programmer if programmer == "" { s.Fatalf("servoFlashCmds does not have programmer configured: %+v", servoFlashCmds) } ccdSerial, err := h.Servo.GetCCDSerial(ctx) if err != nil { s.Fatal("Failed to get servo serials: ", err) } programmer = fmt.Sprintf(programmer, ccdSerial) s.Logf("Programmer is %s", programmer) if err = h.RequireBiosServiceClient(ctx); err != nil { s.Fatal("Requiring BiosServiceClient: ", err) } if err = h.Servo.WatchdogRemove(ctx, servo.WatchdogCCD); err != nil { s.Fatal("Failed to remove ccd watchdog: ", err) } s.Log("Getting GBB flags from BiosService") old, err := h.BiosServiceClient.GetGBBFlags(ctx, &empty.Empty{}) if err != nil { s.Fatal("initial GetGBBFlags failed: ", err) } s.Log("Current GBB flags: ", old.Set) s.Log("Reading fw image over CCD") h.DisconnectDUT(ctx) // Some of the dutControl commands will reboot dutControl(ctx, s, h.Servo, servoFlashCmds.DUTControlOn) img, err := bios.NewRemoteImage(ctx, h.ServoProxy, programmer, commonbios.GBBImageSection, servoFlashCmds.FlashExtraFlagsFlashrom) if err != nil { s.Error("Could not read firmware: ", err) } dutControl(ctx, s, h.Servo, servoFlashCmds.DUTControlOff) if s.HasError() { return } cf, sf, err := img.GetGBBFlags() if err != nil { s.Fatal("Could not get GBB flags: ", err) } ret := pb.GBBFlagsState{Clear: cf, Set: sf} s.Log("CDD GBB flags: ", ret.Set) sortSlice := cmp.Transformer("Sort", func(in []pb.GBBFlag) []pb.GBBFlag { out := append([]pb.GBBFlag(nil), in...) sort.Slice(out, func(i, j int) bool { return out[i] < out[j] }) return out }) if !cmp.Equal(old.Set, ret.Set, sortSlice) { s.Fatal("GBB flags from CDD do not match SSH'd GBB flags ", cmp.Diff(old.Set, ret.Set, sortSlice)) } // Flashrom restarts the dut, so wait for it to boot s.Log("Waiting for reboot") if err := h.WaitConnect(ctx); err != nil { s.Fatalf("Failed to connect to DUT: %s", err) } // We need to change some GBB flag, but it doesn't really matter which. // Toggle DEV_SCREEN_SHORT_DELAY cf = common.GBBToggle(cf, pb.GBBFlag_DEV_SCREEN_SHORT_DELAY) sf = common.GBBToggle(sf, pb.GBBFlag_DEV_SCREEN_SHORT_DELAY) if err := img.ClearAndSetGBBFlags(cf, sf); err != nil { s.Fatal("Failed to toggle GBB flag in image: ", err) } s.Log("Writing fw image over CCD") h.DisconnectDUT(ctx) // Some of the dutControl commands will reboot dutControl(ctx, s, h.Servo, servoFlashCmds.DUTControlOn) if err = bios.WriteRemoteFlashrom(ctx, h.ServoProxy, programmer, img, commonbios.GBBImageSection, servoFlashCmds.FlashExtraFlagsFlashrom); err != nil { s.Error("Failed to write flashrom: ", err) } dutControl(ctx, s, h.Servo, servoFlashCmds.DUTControlOff) if s.HasError() { return } // Flashrom restarts the dut, so wait for it to boot s.Log("Waiting for reboot") if err := h.WaitConnect(ctx); err != nil { s.Fatalf("Failed to connect to DUT: %s", err) } if err := h.RequireBiosServiceClient(ctx); err != nil { s.Fatal("Requiring BiosServiceClient: ", err) } s.Log("Getting GBB flags from BiosService") newFlags, err := h.BiosServiceClient.GetGBBFlags(ctx, &empty.Empty{}) if err != nil { s.Fatal("final GetGBBFlags failed: ", err) } s.Log("Updated GBB flags: ", newFlags.Set) expected := pb.GBBFlagsState{Clear: cf, Set: sf} if !cmp.Equal(expected.Set, newFlags.Set, sortSlice) { s.Fatal("Updated GBB flags do not match SSH'd GBB flags ", cmp.Diff(expected.Set, newFlags.Set, sortSlice)) } }
package connector import ( gp "code.google.com/p/goprotobuf/proto" "common" "errors" "logger" "pockerclient" "proto" "rpc" "time" ) //创建函数 type CreateMsgFun func() gp.Message var mapRpc map[string]CreateMsgFun //消息回调用 func init() { mapRpc = make(map[string]CreateMsgFun) // mapRpc["Notice"] = func() gp.Message { return &rpc.Notice{} } // mapRpc["ClanChatMessage"] = func() gp.Message { return &rpc.ClanChatMessage{} } mapRpc["Msg"] = func() gp.Message { return &rpc.Msg{} } // mapRpc["PlayerMail"] = func() gp.Message { return &rpc.PlayerMail{} } mapRpc["S2CChatWorld"] = func() gp.Message { return &rpc.S2CChatWorld{} } mapRpc["S2CChatP2P"] = func() gp.Message { return &rpc.S2CChatP2P{} } mapRpc["ActionNotifyACK"] = func() gp.Message { return &rpc.ActionNotifyACK{} } mapRpc["ActionACK"] = func() gp.Message { return &rpc.ActionACK{} } mapRpc["GameStartACK"] = func() gp.Message { return &rpc.GameStartACK{} } mapRpc["LeaveRoomACK"] = func() gp.Message { return &rpc.LeaveRoomACK{} } mapRpc["EnterRoomACK"] = func() gp.Message { return &rpc.EnterRoomACK{} } mapRpc["JieSuanNotifyACK"] = func() gp.Message { return &rpc.JieSuanNotifyACK{} } mapRpc["CountdownNotifyACK"] = func() gp.Message { return &rpc.CountdownNotifyACK{} } mapRpc["PassCardNotifyACK"] = func() gp.Message { return &rpc.PassCardNotifyACK{} } mapRpc["PassedNotifyACK"] = func() gp.Message { return &rpc.PassedNotifyACK{} } mapRpc["BroadCastNotify"] = func() gp.Message { return &rpc.BroadCastNotify{} } mapRpc["AddMailNotify"] = func() gp.Message { return &rpc.AddMailNotify{} } mapRpc["FightRoomChatNotify"] = func() gp.Message { return &rpc.FightRoomChatNotify{} } mapRpc["EnterCustomRoomACK"] = func() gp.Message { return &rpc.EnterCustomRoomACK{} } mapRpc["LeaveCustomRoomACK"] = func() gp.Message { return &rpc.LeaveCustomRoomACK{} } mapRpc["RoomListACK"] = func() gp.Message { return &rpc.RoomListACK{} } mapRpc["CreateRoomACK"] = func() gp.Message { return &rpc.CreateRoomACK{} } mapRpc["FindRoomACK"] = func() gp.Message { return &rpc.FindRoomACK{} } mapRpc["JieSanRoomNotify"] = func() gp.Message { return &rpc.JieSanRoomNotify{} } mapRpc["JieSanRoomUpdateStatusNotify"] = func() gp.Message { return &rpc.JieSanRoomUpdateStatusNotify{} } mapRpc["SendFriendChat"] = func() gp.Message { return &rpc.SendFriendChat{} } mapRpc["FinalJieSuanNotifyACK"] = func() gp.Message { return &rpc.FinalJieSuanNotifyACK{} } mapRpc["FriendStatusNofify"] = func() gp.Message { return &rpc.FriendStatusNofify{} } mapRpc["DelFriendNofity"] = func() gp.Message { return &rpc.DelFriendNofity{} } mapRpc["InviteFirendsJionCustomRoomNotify"] = func() gp.Message { return &rpc.InviteFirendsJionCustomRoomNotify{} } mapRpc["PockerRoomInfo"] = func() gp.Message { return &rpc.PockerRoomInfo{} } mapRpc["PockerManBase"] = func() gp.Message { return &rpc.PockerManBase{} } mapRpc["S2CAction"] = func() gp.Message { return &rpc.S2CAction{} } mapRpc["MJEnterRoomACK"] = func() gp.Message { return &rpc.MJEnterRoomACK{} } mapRpc["MJLeaveRoomACK"] = func() gp.Message { return &rpc.MJLeaveRoomACK{} } mapRpc["MJGameStartACK"] = func() gp.Message { return &rpc.MJGameStartACK{} } mapRpc["MJActionACK"] = func() gp.Message { return &rpc.MJActionACK{} } mapRpc["MJActionNotifyACK"] = func() gp.Message { return &rpc.MJActionNotifyACK{} } mapRpc["MJCountdownNotifyACK"] = func() gp.Message { return &rpc.MJCountdownNotifyACK{} } mapRpc["MJJieSuanNotifyACK"] = func() gp.Message { return &rpc.MJJieSuanNotifyACK{} } mapRpc["MJRemoveCardNotifyACK"] = func() gp.Message { return &rpc.MJRemoveCardNotifyACK{} } mapRpc["LeavePockerRoom"] = func() gp.Message { return &rpc.LeavePockerRoom{} } mapRpc["PayResultNotify"] = func() gp.Message { return &rpc.PayResultNotify{} } } //来自Center的消息 func (self *CenterService) SendMsg2Player(req *proto.ChatSendMsg2Player, reply *proto.ChatSendMsg2PlayerResult) (err error) { logger.Info("Come into SendMsg2Player", req.MsgName) f, ok := mapRpc[req.MsgName] if !ok { logger.Error("CenterService.SendMsg2Player wrong msgname", req.MsgName) return errors.New("wrong msgname:" + req.MsgName) } msg := f() if err := common.DecodeMessage(req.Buf, msg); err != nil { //logger.Info("CenterService.DecodeMessage error") return err } //所有玩家 if len(req.PlayerList) == 0 { self.saveChatMsg(req.MsgName, msg) } else { for _, uid := range req.PlayerList { if p, ok := cns.getPlayerByUid(uid); ok { if req.MsgName == "LeaveRoomACK" || req.MsgName == "MJLeaveRoomACK" || req.MsgName == "LeaveCustomRoomACK" { p.SetGameType("") p.SetRoomType(int32(0)) logger.Info("*************离开房间:%s", req.MsgName) } else if req.MsgName == "LeavePockerRoom" { logger.Info("================扑克离开房间") p.SetGameType("") p.SetRoomType(int32(0)) return nil } else if req.MsgName == "S2CAction" { s, ok := msg.(*rpc.S2CAction) if !ok { logger.Error("SendMsg2Player S2CAction err") return } if p.GetUid() == uid && s.GetAct() == int32(1) { logger.Info("================扑克玩家离开 正常发送请求") pkMsg := &rpc.C2SAction{} pkMsg.SetAct(int32(1)) pkMsg.SetUid(s.GetOperater()) pockerclient.ReqAction(pkMsg) } } WriteResult(p.conn, msg) } } } return nil } func (self *CenterService) saveChatMsg(method string, msg gp.Message) { if method != "S2CChatWorld" { cns.serverForClient.ServerBroadcast(msg) return } // 世界聊天不主动推送 存储起来等玩家来取 cns.chatLock.Lock() defer cns.chatLock.Unlock() timeNow := uint32(time.Now().Unix()) index := uint32(1) if len(cns.chatMsgs) > 0 { info := cns.chatMsgs[len(cns.chatMsgs)-1] index = info.msgIndex + 1 if index == 0 { index = 1 } } info := &stChatMsg{ sendTime: timeNow, msgIndex: index, msg: msg, } maxChatNum := uint32(GetGlobalCfg("WORLD_CHAT_SAVE_NUMBER")) if len(cns.chatMsgs) < int(maxChatNum) { cns.chatMsgs = append(cns.chatMsgs, info) } else { cns.chatMsgs = cns.chatMsgs[1:] cns.chatMsgs = append(cns.chatMsgs, info) } } func (self *CenterService) SendMsg2LocalPlayer(req *proto.ChatSendMsg2LPlayer, reply *proto.ChatSendMsg2LPlayerResult) (err error) { f, ok := mapRpc[req.MsgName] if !ok { logger.Error("CenterService.SendMsg2LocalPlayer wrong msgname", req.MsgName) return errors.New("wrong msgname l:" + req.MsgName) } msg := f() if err := common.DecodeMessage(req.Buf, msg); err != nil { return err } for _, seg := range cns.players { seg.l.RLock() for _, p := range seg.players { // logger.Info("", p.GetLevel()) //判断各种条件 // if req.Channel == rpc.Login_All || // req.Channel == common.GetPlatformByGamelocation(p.GetGamelocation()) { // if p.GetLevel() >= req.LevelMin && // p.GetLevel() <= req.LevelMax { WriteResult(p.conn, msg) // } // } } seg.l.RUnlock() } return nil } func (self *CenterService) C2SCostResource(req *proto.ReqCostRes, rst *proto.CommonRst) error { for _, uid := range req.PlayerList { p, ok := cns.getPlayerByUid(uid) if !ok { logger.Error("C2SCostResource cns.getPlayerByUid return nil, uid:%s", uid) continue } p.Billing(req) } return nil } //支付结果通知 func (self *CenterService) SendPayResult2Player(req *proto.ReqRechargeNofity, rst *proto.CommonRst) error { for _, uid := range req.PlayerList { p, ok := cns.getPlayerByUid(uid) if !ok { logger.Error("SendPayResult2Player cns.getPlayerByUid return nil, uid:%s", uid) continue } msg := &rpc.PayResultNotify{} if err := common.DecodeMessage(req.Buf, msg); err != nil { return err } p.OnRecharged(msg) } return nil } //公共方法 func (self *CenterService) CallCnserverFunc(req *proto.CallCnserverMsg, rst *proto.CommonRst) error { for _, uid := range req.Uids { p, ok := cns.getPlayerByUid(uid) if !ok { logger.Error("CallCnserverFunc cns.getPlayerByUid return nil, uid:%s", uid) continue } if req.Param1 == "PockerEnd" { p.TaskTrigger(SIG_PLAY_POCKER, false) } } return nil } //统计在线人数 func (self *CenterService) GetOnlineNumber(req *proto.GetOnlineNumber, rst *proto.GetOnlineNumberRst) error { rst.Numbers = cns.getOnlineNumbers() return nil } func (self *CenterService) LogOnlineNumber(req *proto.GetOnlineNumberRst, rst *proto.GetOnlineNumber) error { //tlog // go TLogOnlineNumbers(req.Numbers) return nil }
package lc // Time: O(1) for SumRange() // Benchmark: 56ms 9.6mb | 37% 17% type NumArray struct { sums []int } func Constructor(nums []int) NumArray { if len(nums) == 0 { return NumArray{[]int{}} } // precalculate the sums. sums := make([]int, len(nums)) sums[0] = nums[0] for i := 1; i < len(nums); i++ { sums[i] = sums[i-1] + nums[i] } return NumArray{sums} } func (this *NumArray) SumRange(i int, j int) int { if i == 0 { return this.sums[j] } return this.sums[j] - this.sums[i-1] }
package psql import ( "fmt" "github.com/OIT-ads-web/widgets_import" "github.com/jmoiron/sqlx" _ "github.com/lib/pq" "log" ) var Database *sqlx.DB func GetConnection() *sqlx.DB { return Database } func MakeConnection(conf widgets_import.Config) error { psqlInfo := fmt.Sprintf("host=%s port=%d user=%s "+ "password=%s dbname=%s sslmode=disable", conf.Database.Server, conf.Database.Port, conf.Database.User, conf.Database.Password, conf.Database.Database) db, err := sqlx.Open("postgres", psqlInfo) if err != nil { log.Println("m=GetPool,msg=connection has failed", err) } Database = db return err }
package config var ( CosmosRPCHost = "localhost:9090" )
package sqlstore import ( "github.com/imflop/clnk/internal/app/models" uuid "github.com/satori/go.uuid" "time" ) // LinkRepository ... type LinkRepository struct { store *Store } // Create ... func (r *LinkRepository) Create(originalURL string) (*models.Link, error) { l := &models.Link{} u := uuid.NewV4() datetime := time.Now().Format(time.RFC3339) err := r.store.db.QueryRow( "INSERT INTO links (uuid, original_url, created_at, updated_at) VALUES ($1, $2, $3, $4) RETURNING id", u, originalURL, datetime, datetime, ).Scan(&l.ID) if err != nil { return nil, err } return l, nil } // Find ... func (r *LinkRepository) Find(id int) (*models.Link, error) { l := &models.Link{} err := r.store.db.QueryRow( "SELECT uuid, original_url, short_url FROM links WHERE id=$1", id, ).Scan(&l.UUID, &l.OriginalURL, &l.ShortURL) if err != nil { return nil, err } return l, nil } // Update ... func (r *LinkRepository) Update(id int, shortURL string) (*models.Link, error) { l := &models.Link{} err := r.store.db.QueryRow( "UPDATE links SET short_url=$1 WHERE id=$2 RETURNING short_url", shortURL, id, ).Scan(&l.ShortURL) if err != nil { return nil, err } return l, nil }
// Copyright 2021 The Cockroach Authors. // // Use of this software is governed by the Business Source License // included in the file licenses/BSL.txt. // // As of the Change Date specified in that file, in accordance with // the Business Source License, use of this software will be governed // by the Apache License, Version 2.0, included in the file // licenses/APL.txt. package cli import ( "bytes" "context" "fmt" "github.com/cockroachdb/cockroach/pkg/kv/kvserver/liveness/livenesspb" "github.com/cockroachdb/cockroach/pkg/roachpb" "github.com/cockroachdb/cockroach/pkg/server/serverpb" "github.com/cockroachdb/cockroach/pkg/server/status/statuspb" "github.com/cockroachdb/errors" ) const ( debugBase = "debug" eventsName = debugBase + "/events" livenessName = debugBase + "/liveness" nodesPrefix = debugBase + "/nodes" rangelogName = debugBase + "/rangelog" reportsPrefix = debugBase + "/reports" schemaPrefix = debugBase + "/schema" settingsName = debugBase + "/settings" problemRangesName = reportsPrefix + "/problemranges" ) // makeClusterWideZipRequests defines the zipRequests that are to be // performed just once for the entire cluster. func makeClusterWideZipRequests( admin serverpb.AdminClient, status serverpb.StatusClient, ) []zipRequest { return []zipRequest{ // NB: we intentionally omit liveness since it's already pulled manually (we // act on the output to special case decommissioned nodes). { fn: func(ctx context.Context) (interface{}, error) { return admin.Events(ctx, &serverpb.EventsRequest{}) }, pathName: eventsName, }, { fn: func(ctx context.Context) (interface{}, error) { return admin.RangeLog(ctx, &serverpb.RangeLogRequest{}) }, pathName: rangelogName, }, { fn: func(ctx context.Context) (interface{}, error) { return admin.Settings(ctx, &serverpb.SettingsRequest{}) }, pathName: settingsName, }, { fn: func(ctx context.Context) (interface{}, error) { return status.ProblemRanges(ctx, &serverpb.ProblemRangesRequest{}) }, pathName: problemRangesName, }, } } // Tables containing cluster-wide info that are collected using SQL // into a debug zip. var debugZipTablesPerCluster = []string{ "crdb_internal.cluster_contention_events", "crdb_internal.cluster_database_privileges", "crdb_internal.cluster_queries", "crdb_internal.cluster_sessions", "crdb_internal.cluster_settings", "crdb_internal.cluster_transactions", "crdb_internal.jobs", "system.jobs", // get the raw, restorable jobs records too. "system.descriptor", // descriptors also contain job-like mutation state. "system.namespace", "system.namespace2", // TODO(sqlexec): consider removing in 20.2 or later. "system.scheduled_jobs", "crdb_internal.kv_node_status", "crdb_internal.kv_store_status", "crdb_internal.schema_changes", "crdb_internal.partitions", "crdb_internal.zones", "crdb_internal.invalid_objects", } // collectClusterData runs the data collection that only needs to // occur once for the entire cluster. // Also see collectSchemaData below. func (zc *debugZipContext) collectClusterData( ctx context.Context, firstNodeDetails *serverpb.DetailsResponse, ) (nodeList []statuspb.NodeStatus, livenessByNodeID nodeLivenesses, err error) { clusterWideZipRequests := makeClusterWideZipRequests(zc.admin, zc.status) for _, r := range clusterWideZipRequests { if err := zc.runZipRequest(ctx, r); err != nil { return nil, nil, err } } for _, table := range debugZipTablesPerCluster { query := fmt.Sprintf(`SELECT * FROM %s`, table) if override, ok := customQuery[table]; ok { query = override } if err := zc.dumpTableDataForZip(zc.firstNodeSQLConn, debugBase, table, query); err != nil { return nil, nil, errors.Wrapf(err, "fetching %s", table) } } { var nodes *serverpb.NodesResponse err := zc.runZipFn(ctx, "requesting nodes", func(ctx context.Context) error { nodes, err = zc.status.Nodes(ctx, &serverpb.NodesRequest{}) return err }) if cErr := zc.z.createJSONOrError(debugBase+"/nodes.json", nodes, err); cErr != nil { return nil, nil, cErr } // In case nodes came up back empty (the Nodes() RPC failed), we // still want to inspect the per-node endpoints on the head // node. As per the above, we were able to connect at least to // that. nodeList = []statuspb.NodeStatus{{Desc: roachpb.NodeDescriptor{ NodeID: firstNodeDetails.NodeID, Address: firstNodeDetails.Address, SQLAddress: firstNodeDetails.SQLAddress, }}} if nodes != nil { // If the nodes were found, use that instead. nodeList = nodes.Nodes } // We'll want livenesses to decide whether a node is decommissioned. var lresponse *serverpb.LivenessResponse err = zc.runZipFn(ctx, "requesting liveness", func(ctx context.Context) error { lresponse, err = zc.admin.Liveness(ctx, &serverpb.LivenessRequest{}) return err }) if cErr := zc.z.createJSONOrError(livenessName+".json", nodes, err); cErr != nil { return nil, nil, cErr } livenessByNodeID = map[roachpb.NodeID]livenesspb.NodeLivenessStatus{} if lresponse != nil { livenessByNodeID = lresponse.Statuses } } return nodeList, livenessByNodeID, nil } // collectSchemaData collects the SQL logical schema once, for the entire cluster // using the first node. This runs at the end, after all the per-node queries have // been completed, because it has a higher likelihood to fail. func (zc *debugZipContext) collectSchemaData(ctx context.Context) error { // Run the debug doctor code over the schema. { var doctorData bytes.Buffer fmt.Printf("doctor examining cluster...") doctorErr := runClusterDoctor(nil, nil, zc.firstNodeSQLConn, &doctorData, zc.timeout) if err := zc.z.createRawOrError(reportsPrefix+"/doctor.txt", doctorData.Bytes(), doctorErr); err != nil { return err } } // Collect the SQL schema. { var databases *serverpb.DatabasesResponse if err := zc.runZipFn(ctx, "requesting list of SQL databases", func(ctx context.Context) error { var err error databases, err = zc.admin.Databases(ctx, &serverpb.DatabasesRequest{}) return err }); err != nil { if err := zc.z.createError(schemaPrefix, err); err != nil { return err } } else { fmt.Printf("%d found\n", len(databases.Databases)) var dbEscaper fileNameEscaper for _, dbName := range databases.Databases { prefix := schemaPrefix + "/" + dbEscaper.escape(dbName) var database *serverpb.DatabaseDetailsResponse requestErr := zc.runZipFn(ctx, fmt.Sprintf("requesting database details for %s", dbName), func(ctx context.Context) error { var err error database, err = zc.admin.DatabaseDetails(ctx, &serverpb.DatabaseDetailsRequest{Database: dbName}) return err }) if err := zc.z.createJSONOrError(prefix+"@details.json", database, requestErr); err != nil { return err } if requestErr != nil { continue } fmt.Printf("%d tables found\n", len(database.TableNames)) var tbEscaper fileNameEscaper for _, tableName := range database.TableNames { name := prefix + "/" + tbEscaper.escape(tableName) var table *serverpb.TableDetailsResponse requestErr := zc.runZipFn(ctx, fmt.Sprintf("requesting table details for %s.%s", dbName, tableName), func(ctx context.Context) error { var err error table, err = zc.admin.TableDetails(ctx, &serverpb.TableDetailsRequest{Database: dbName, Table: tableName}) return err }) if err := zc.z.createJSONOrError(name+".json", table, requestErr); err != nil { return err } } } } } return nil }
package tests import ( "testing" "github.com/muhammadandikakurniawan/training_go_salt/packages" ) func TestLengthOfLongestSubstring(t *testing.T) { packages.LengthOfLongestSubstring("abba") }
package web3 import ( "github.com/tharsis/ethermint/version" "github.com/ethereum/go-ethereum/common/hexutil" "github.com/ethereum/go-ethereum/crypto" ) // PublicAPI is the web3_ prefixed set of APIs in the Web3 JSON-RPC spec. type PublicAPI struct{} // NewPublicAPI creates an instance of the Web3 API. func NewPublicAPI() *PublicAPI { return &PublicAPI{} } // ClientVersion returns the client version in the Web3 user agent format. func (a *PublicAPI) ClientVersion() string { return version.Version() } // Sha3 returns the keccak-256 hash of the passed-in input. func (a *PublicAPI) Sha3(input hexutil.Bytes) hexutil.Bytes { return crypto.Keccak256(input) }
//Copyright 2019 Chris Wojno // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated // documentation files (the "Software"), to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the // Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE // WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS // OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. package vsql_engine import ( "context" "errors" "github.com/wojnosystems/vsql/vparam" "github.com/wojnosystems/vsql/vrows" "github.com/wojnosystems/vsql_engine/engine_context" "testing" ) func TestEngine_Query(t *testing.T) { expectedRows := &vrows.RowserMock{} var actualRows vrows.Rowser expectedParams := vparam.New("SELECT * FROM puppies") var actualParams vparam.Queryer engine := NewSingle() engine.QueryMW().Append(func(ctx context.Context, c engine_context.Queryer) { actualParams = c.Query() c.SetRows(expectedRows) c.Next(ctx) }) rows, _ := engine.Query(context.Background(), expectedParams) if actualParams != expectedParams { t.Error("expected parameters to be passed") } engine.RowsNextMW().Append(func(ctx context.Context, c engine_context.RowsNexter) { actualRows = c.Rows() c.Next(ctx) }) rows.Next() if actualRows != expectedRows { t.Error("expected actual rows to be set") } expectedErr := errors.New("boom") didRun := false engine.RowsCloseMW().Append(func(ctx context.Context, c engine_context.Rowser) { didRun = true if actualRows != c.Rows() { t.Error("expected the same rows object to be returned") } c.SetError(expectedErr) c.Next(ctx) }) err := rows.Close() if !didRun { t.Error("expected RowsClose to run") } if err != expectedErr { t.Error("expected error to be returned") } }
package DataBase import ( "../../../bin/gorm" "fmt" "errors" "log" "../DTO" _ "../../../bin/pq" ) var DatabaseConnection *gorm.DB //database const ( DB_USER = "postgres" DB_PASSWORD = "postgres" DB_NAME = "postgres" ) func init () { log.Print("connecting to Data Base Postgresql") err:=errors.New("") DatabaseInfo := fmt.Sprintf("user=%s password=%s dbname=%s sslmode=disable", DB_USER, DB_PASSWORD, DB_NAME) DatabaseConnection,err =gorm.Open("postgres",DatabaseInfo) if err!= nil { panic(err.Error()) } //defer DatabaseConnection.Close() DataBase:=DatabaseConnection.DB() //defer DataBase.Close() err =DataBase.Ping() if err!= nil { panic(err.Error()) } log.Println("creating tables using GORM ") DatabaseConnection.DropTableIfExists(&DTO.MessageDTO{}) DatabaseConnection.CreateTable(&DTO.MessageDTO{}) } func GetDB() *gorm.DB { return DatabaseConnection } func SaveMessages( dto *DTO.MessageDTO) { GetDB().Debug().Save(&dto) }
package http import ( "net" "strings" "github.com/caos/logging" ) func CreateListener(endpoint string) net.Listener { l, err := net.Listen("tcp", Endpoint(endpoint)) logging.Log("SERVE-6vasef").OnError(err).Fatal("creating listener failed") return l } func Endpoint(endpoint string) string { if strings.Contains(endpoint, ":") { return endpoint } return ":" + endpoint }
package cmd import ( "bufio" "github.com/qwenode/gogo/sanitize" "io/ioutil" "os/exec" ) // commandFunc call by CommandFn type commandFunc func(output string, errCode int) bool // CommandFn run exec.command(name,arg...).CombinedOutput() func CommandFn(fn commandFunc, name string, arg ...string) bool { output, err := exec.Command(name, arg...).CombinedOutput() if err != nil { return fn(string(output), sanitize.Int(err.Error())) } return fn(string(output), 0) } // CommandLineFn run exec.command(name,arg...).CombinedOutput(), just one command,actually exec /bin/bash -c "your command" func CommandLineFn(fn commandFunc, c string) bool { return CommandFn(fn, "/bin/bash", "-c", c) } // commandStdoutFunc call by CommandRealtimeStdout type commandStdoutFunc func(output string, errCode int, done bool) bool // CommandRealtimeStdout run exec.command(name,arg...) and realtime output func CommandRealtimeStdout(fn commandStdoutFunc, name string, arg ...string) bool { command := exec.Command(name, arg...) pipe, _ := command.StdoutPipe() stderrPipe, _ := command.StderrPipe() defer pipe.Close() defer stderrPipe.Close() if err := command.Start(); err != nil { all, _ := ioutil.ReadAll(stderrPipe) return fn(string(all), sanitize.Int(string(all)), true) } reader := bufio.NewReader(pipe) r := true for { readString, err := reader.ReadString('\n') if err != nil { all, _ := ioutil.ReadAll(stderrPipe) r = fn(string(all), sanitize.Int(string(all)), true) break } r = fn(readString, 0, false) if r == false { break } } return r } // CommandLineRealtimeStdout run exec.command(name,arg...) and realtime output ,just one command,actually exec /bin/bash -c "your command" func CommandLineRealtimeStdout(fn commandStdoutFunc, c string) bool { return CommandRealtimeStdout(fn, "/bin/bash", "-c", c) } //TODO add CommandRealtimeStdoutTimeout run with timeout //TODO add CommandFnTimeout run with timeout
package main import ( "flag" "fmt" "github.com/thejerf/afibmon/heartmon" "github.com/thejerf/suture" ) var address = flag.String("address", ":18498", "the address to bind the server to") func main() { flag.Parse() supervisor := suture.NewSimple("heartmon supervisor") server, err := heartmon.NewServer(*address) if err != nil { panic("Can't bind: " + err.Error()) } supervisor.Add(server) fmt.Println("Beginning serving") supervisor.Serve() }
package interactor import ( "github.com/gobjserver/gobjserver/core/entity" "github.com/gobjserver/gobjserver/core/gateway" ) // GetObjectInteractor . type GetObjectInteractor interface { Get(objectName string) []*entity.Object GetByObjectID(objectName string, objectID string) (*entity.Object, error) GetAll() ([]string, error) } // GetObjectInteractorImpl is the implementation of GetObjectInteractor interface. type GetObjectInteractorImpl struct { Gateway gateway.ObjectGateway } // Get gets objects . func (interactor GetObjectInteractorImpl) Get(objectName string) []*entity.Object { return interactor.Gateway.Find(objectName) } // GetByObjectID gets object by ObjectID . func (interactor GetObjectInteractorImpl) GetByObjectID(objectName string, objectID string) (*entity.Object, error) { return interactor.Gateway.FindByID(objectName, objectID) } // GetAll gets all objects . func (interactor GetObjectInteractorImpl) GetAll() ([]string, error) { return interactor.Gateway.FindAll() }
/* vim:set sw=8 ts=8 noet: * * Copyright (c) 2017 Torchbox Ltd. * * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely. This software is provided 'as-is', without any express or implied * warranty. */ package main import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" ) type DatabaseSpec struct { Type string `json:"type"` Secret string `json:"secretName"` Class string `json:"class"` } type DatabaseStatus struct { Phase string `json:"phase"` Error string `json:"error,omitempty"` Server string `json:"server,omitempty"` } type Database struct { metav1.TypeMeta `json:",inline"` metav1.ObjectMeta `json:"metadata"` Spec DatabaseSpec `json:"spec"` Status DatabaseStatus `json:"status,omitempty"` } type DatabaseList struct { metav1.TypeMeta `json:",inline"` metav1.ListMeta `json:"metadata"` Items []Database `json:"items"` }
package database import ( "bytes" "encoding/json" "fmt" "github.com/boltdb/bolt" ) //DB , database struct type DB struct { conn *bolt.DB } //Datastore , db interface type Datastore interface { CreateBuckets(bucket string) error CreateSubBuckets(mBucket, sBucket string) error AddRecord(bucket, key string, v interface{}) error GetRecord(bucket, key string) ([]byte, error) DeleteRecord(bucket, key string) error AddRecordSubBucket(mainBucket, subBucket, key string, v interface{}) error GetRecordSubBucket(mainBucket, subBucket, key string) ([]byte, error) DeleteRecordSubBucket(mainBucket, subBucket, key string) error Close() } //NewConn , create new db connection func NewConn() (*DB, error) { db, err := bolt.Open("./ts3.db", 0664, nil) if err != nil { return nil, err } return &DB{conn: db}, nil } //CreateBuckets , in case if database is deleted func (db *DB) CreateBuckets(bucket string) error { err := db.conn.Update(func(tx *bolt.Tx) error { _, err := tx.CreateBucketIfNotExists([]byte(bucket)) if err != nil { return err } return nil }) if err != nil { return err } return nil } //CreateSubBuckets , creates sub bucket of bucket func (db *DB) CreateSubBuckets(mBucket, sBucket string) error { err := db.conn.Update(func(tx *bolt.Tx) error { b, err := tx.CreateBucketIfNotExists([]byte(mBucket)) if err != nil { return err } b.CreateBucketIfNotExists([]byte(sBucket)) return nil }) if err != nil { return err } return nil } //Close ,closes db con func (db *DB) Close() { db.conn.Close() } //AddRecord , adds new key to database func (db *DB) AddRecord(bucket, key string, v interface{}) error { err := db.conn.Update(func(tx *bolt.Tx) error { bucket, err := tx.CreateBucketIfNotExists([]byte(bucket)) if err != nil { return err } data, errx := marshalJSON(v) if errx != nil { return errx } err = bucket.Put([]byte(key), data) if err != nil { return err } return nil }) if err != nil { return err } return nil } //GetRecord , gets key from database func (db *DB) GetRecord(bucket, key string) ([]byte, error) { var buffer bytes.Buffer err := db.conn.View(func(tx *bolt.Tx) error { bucket := tx.Bucket([]byte(bucket)) if bucket == nil { return fmt.Errorf("Bucket doesn't exists") } buffer.Write(bucket.Get([]byte(key))) return nil }) if err != nil { return nil, err } return buffer.Bytes(), nil } //DeleteRecord , deletes key from database func (db *DB) DeleteRecord(bucket, key string) error { err := db.conn.Update(func(tx *bolt.Tx) error { b := tx.Bucket([]byte(bucket)) b.Delete([]byte(key)) return nil }) if err != nil { return err } return nil } //AddRecordSubBucket , adds record to sub bucket in database func (db *DB) AddRecordSubBucket(mainBucket, subBucket, key string, v interface{}) error { err := db.conn.Update(func(tx *bolt.Tx) error { bucket, err := tx.CreateBucketIfNotExists([]byte(mainBucket)) if err != nil { return err } data, errx := marshalJSON(v) if errx != nil { return errx } b, e := bucket.CreateBucketIfNotExists([]byte(subBucket)) if e != nil { return e } err = b.Put([]byte(key), data) if err != nil { return err } return nil }) if err != nil { return err } return nil } //GetRecordSubBucket , get key from sub bucket func (db *DB) GetRecordSubBucket(mainBucket, subBucket, key string) ([]byte, error) { var buffer bytes.Buffer err := db.conn.View(func(tx *bolt.Tx) error { bucket := tx.Bucket([]byte(mainBucket)) if bucket == nil { return fmt.Errorf("MainBucket doesn't exists") } b := bucket.Bucket([]byte(subBucket)) if b == nil { return fmt.Errorf("SubBucket doesn't exists") } buffer.Write(b.Get([]byte(key))) return nil }) if err != nil { return nil, err } return buffer.Bytes(), nil } //DeleteRecordSubBucket , get key from sub bucket func (db *DB) DeleteRecordSubBucket(mainBucket, subBucket, key string) error { err := db.conn.View(func(tx *bolt.Tx) error { bucket := tx.Bucket([]byte(mainBucket)) if bucket == nil { return fmt.Errorf("MainBucket doesn't exists") } b := bucket.Bucket([]byte(subBucket)) if b == nil { return fmt.Errorf("SubBucket doesn't exists") } b.Delete([]byte(key)) return nil }) if err != nil { return err } return nil } func marshalJSON(v interface{}) ([]byte, error) { return json.Marshal(v) }
package urlpath_test import ( "fmt" "testing" "github.com/ehsoc/urlpath" ) type DiffTests struct { root, path, want string err bool } var diffChildTests = []DiffTests{ {"/abc/def", "/abc/def", "", false}, {"/abc/def", "/abc/def/ghijklmn/opqrstuvwyz1234", "/ghijklmn/opqrstuvwyz1234", false}, {"/abc/def", "/abc/defeeeeeee", "", true}, {"/abc/def", "/abc/def/ghi", "/ghi", false}, {"/abc/def", "/abc/def/ghi/jkl", "/ghi/jkl", false}, {"/abc", "/a", "", true}, {"/", "/", "", false}, {"/ab", "/abc", "", true}, {"/ab", "/abc", "", true}, {"/api/v1/123", "/abc/api/v1/123", "", true}, {"api/v1 /123", "/api/v1 /123", "", false}, {"/api/v1/123", "api/v1/123", "", false}, {"", "", "", false}, } type CleanTests struct { path, want string } var cleanTests = []CleanTests{ {"/", "/"}, {"/abc/", "/abc"}, {"abc/", "/abc"}, {"/ ", "/"}, {" ", "/"}, {" ", "/"}, {" /abc/def/gh/ ", "/abc/def/gh"}, } func TestClean(t *testing.T) { for _, tt := range cleanTests { t.Run(fmt.Sprintf("Clean(%q)", tt.path), func(t *testing.T) { got := urlpath.Clean(tt.path) if got != tt.want { t.Errorf("got: %q want: %q", got, tt.want) } }) } } func TestDiffChild(t *testing.T) { for _, tt := range diffChildTests { t.Run(fmt.Sprintf("DiffPath(%q,%q)", tt.root, tt.path), func(t *testing.T) { got, err := urlpath.DiffChild(tt.root, tt.path) if tt.err && err == nil { t.Fatalf("expecting error") } if !tt.err && err != nil { t.Fatalf("not expecting error") } if got != tt.want { t.Errorf("got: %q want: %q", got, tt.want) } }) } }
package runtime import ( "strconv" ) // Signed integer data type type Int int func (v Int) Eq(other Value) bool { return v == other } func (v Int) Gt(other Value) bool { y, ok := other.(Int) if ok == false { return v.Type() > other.Type() } return v > y } func (v Int) Lt(other Value) bool { y, ok := other.(Int) if ok == false { return v.Type() < other.Type() } return v < y } func (v Int) Eval(env Env) (Value, error) { return v, nil } func (v Int) Type() Type { return IntType } func (v Int) String() string { return strconv.Itoa(int(v)) } func (v Int) Add(x Value) (Value, error) { i, ok := x.(Int) if ok == false { return nil, BadType(IntType, x.Type()) } return v + i, nil } func (v Int) Sub(x Value) (Value, error) { i, ok := x.(Int) if ok == false { return nil, BadType(IntType, x.Type()) } return v - i, nil } func (v Int) Mul(x Value) (Value, error) { i, ok := x.(Int) if ok == false { return nil, BadType(IntType, x.Type()) } return v * i, nil } func (v Int) Div(x Value) (Value, error) { i, ok := x.(Int) if ok == false { return nil, BadType(IntType, x.Type()) } if i == Int(0) { return nil, DivisionByZero() } return v / i, nil }
package main import ( "database/sql" "log" "github.com/mylxsw/container" "github.com/mylxsw/container/example/repo" _ "github.com/proullon/ramsql/driver" ) type Demo struct { UserRepo repo.UserRepo `autowire:"@"` roleRepo repo.RoleRepo `autowire:"@"` // 支持 private 字段 } func main() { cc := container.New() // 绑定对象创建函数 cc.MustSingleton(repo.NewUserRepo) cc.MustSingleton(repo.NewRoleRepo) cc.MustSingleton(func() (*sql.DB, error) { db, err := sql.Open("ramsql", "database address") if err != nil { return nil, err } // add some test data _, _ = db.Exec("CREATE TABLE user(id int primary key, name varchar, role_id int)") _, _ = db.Exec("INSERT INTO user(id, name, role_id) VALUES(1, 'mylxsw', 1)") _, _ = db.Exec("CREATE TABLE role(id int primary key, name varchar)") _, _ = db.Exec("INSERT INTO role(id, name) VALUES(1, 'manager')") return db, nil }) // 使用 ResolveWithError err := cc.ResolveWithError(func(userRepo repo.UserRepo, roleRepo repo.RoleRepo) error { user, err := userRepo.GetUser(1) if err != nil { return err } role, _ := roleRepo.GetUserRole(user.RoleID) log.Printf("resole: id=%d, name=%s, role=%s", user.ID, user.Name, role.Name) return nil }) if err != nil { panic(err) } // 使用 AutoWire 初始化结构体 { demo := Demo{} cc.Must(cc.AutoWire(&demo)) user, err := demo.UserRepo.GetUser(1) if err != nil { panic(err) } role, _ := demo.roleRepo.GetUserRole(user.RoleID) log.Printf("autowire: id=%d, name=%s, role=%s", user.ID, user.Name, role.Name) } }
// Copyright 2021 The ChromiumOS Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Package cellular provides functions for testing Cellular connectivity. package cellular import ( "context" "io/ioutil" "math/rand" "net" "os" "path/filepath" "strconv" "strings" "time" "chromiumos/tast/common/mmconst" "chromiumos/tast/common/shillconst" "chromiumos/tast/common/testexec" "chromiumos/tast/ctxutil" "chromiumos/tast/errors" "chromiumos/tast/local/modemmanager" "chromiumos/tast/local/shill" "chromiumos/tast/local/upstart" "chromiumos/tast/testing" "chromiumos/tast/timing" ) const defaultTimeout = shillconst.DefaultTimeout // ModemInfo Gets modem info from host_info_labels. type ModemInfo struct { Type string IMEI string SupportedBands string SimCount int } // SIMProfileInfo Gets profile info from host_info_labels. type SIMProfileInfo struct { ICCID string SimPin string SimPuk string CarrierName string } // SIMInfo Gets SIM info from host_info_labels. type SIMInfo struct { SlotID int Type string EID string TestEsim bool ProfileInfo []*SIMProfileInfo } // LabelMap is the type label map. type LabelMap map[string][]string // Helper fetches Cellular Device and Service properties. type Helper struct { Manager *shill.Manager Device *shill.Device enableEthernetFunc func(ctx context.Context) enableWifiFunc func(ctx context.Context) Labels []string modemInfo *ModemInfo simInfo []*SIMInfo carrierName string devicePools []string } // NewHelper creates a Helper object and ensures that a Cellular Device is present. func NewHelper(ctx context.Context) (*Helper, error) { ctx, st := timing.Start(ctx, "Helper.NewHelper") defer st.End() manager, err := shill.NewManager(ctx) if err != nil { return nil, errors.Wrap(err, "failed to create Manager object") } available, err := manager.IsAvailable(ctx, shill.TechnologyCellular) if err != nil || !available { return nil, errors.Wrap(err, "Cellular Technology not available") } device, err := manager.DeviceByType(ctx, shillconst.TypeCellular) if err != nil || device == nil { return nil, errors.Wrap(err, "failed to get Cellular Device") } helper := Helper{Manager: manager, Device: device} // Ensure Cellular is enabled. if enabled, err := manager.IsEnabled(ctx, shill.TechnologyCellular); err != nil { return nil, errors.Wrap(err, "error requesting enabled state") } else if !enabled { if _, err := helper.Enable(ctx); err != nil { return nil, errors.Wrap(err, "unable to enable Cellular") } } CheckIfVilbozVerizonAndFixAttachAPN(ctx) // Start collecting DBus logs if err := helper.CaptureDBusLogs(ctx); err != nil { testing.ContextLog(ctx, "Warning: Unable to start DBus log capture: ", err) } return &helper, nil } // NewHelperWithLabels creates a Helper object and populates label info from host_info_labels, ensuring that a Cellular Device is present. func NewHelperWithLabels(ctx context.Context, labels []string) (*Helper, error) { helper, err := NewHelper(ctx) if err != nil { return nil, err } if err := helper.GetHostInfoLabels(ctx, labels); err != nil { return nil, errors.Wrap(err, "unable to read labels") } // Get ICCID and PIN/PUK codes iccid, err := helper.GetCurrentICCID(ctx) if err != nil { return nil, errors.Wrap(err, "could not get current ICCID") } currentPin, currentPuk, err := helper.GetPINAndPUKForICCID(ctx, iccid) if err != nil { return nil, errors.Wrap(err, "could not get Pin and Puk") } // Disable pin lock with default pin and puk with dut puk if locked. if err := helper.ClearSIMLock(ctx, currentPin, currentPuk); err != nil { return nil, errors.Wrap(err, "failed to unlock dut with default pin") } return helper, nil } // NewHelperWithConnectedCellular creates a Helper object with label info and ensures that Cellular is connected. func NewHelperWithConnectedCellular(ctx context.Context) (*Helper, error) { if _, err := modemmanager.NewModemWithSim(ctx); err != nil { return nil, errors.Wrap(err, "could not find MM dbus object with a valid sim") } helper, err := NewHelper(ctx) if err != nil { return nil, err } err = helper.connectAndCheck(ctx) if err != nil { return nil, err } return helper, nil } // CheckIfVilbozVerizonAndFixAttachAPN checks if the device is a vilboz with a verizon SIM card, // and tries to fix the attach APN if that's the case. This is needed because there are 2 bugs // in the modem FW that prevent clearing the attach APN(b/253685780). func CheckIfVilbozVerizonAndFixAttachAPN(ctx context.Context) { modem, err := modemmanager.NewModem(ctx) if err != nil { return } variant, err := GetDeviceVariant(ctx) if err != nil || variant != "vilboz" { return } operatorID, err := modem.GetOperatorIdentifier(ctx) if err != nil || operatorID != "311480" { return } modem3gpp, err := modem.GetModem3gpp(ctx) if err != nil { return } testing.ContextLog(ctx, "Verizon Vilboz device: Try fixing the attach APN") if err := modemmanager.SetInitialEpsBearerSettings(ctx, modem3gpp, map[string]interface{}{"apn": "vzwinternet", "ip-type": mmconst.BearerIPFamilyIPv4v6}); err != nil { testing.ContextLog(ctx, "Failed to set initial EPS bearer settings: ", err) } } // WaitForEnabledState polls for the specified enable state for cellular. func (h *Helper) WaitForEnabledState(ctx context.Context, expected bool) error { return testing.Poll(ctx, func(ctx context.Context) error { enabled, err := h.Manager.IsEnabled(ctx, shill.TechnologyCellular) if err != nil { return errors.Wrap(err, "failed to get enabled state") } if enabled != expected { return errors.Errorf("unexpected enabled state, got %t, expected %t", enabled, expected) } return nil }, &testing.PollOptions{ Timeout: defaultTimeout, Interval: 500 * time.Millisecond, }) } // Enable calls Manager.EnableTechnology(cellular) and returns true if the enable succeeded, or an error otherwise. func (h *Helper) Enable(ctx context.Context) (time.Duration, error) { ctx, st := timing.Start(ctx, "Helper.Enable") defer st.End() start := time.Now() h.Manager.EnableTechnology(ctx, shill.TechnologyCellular) if err := h.WaitForEnabledState(ctx, true); err != nil { return 0, err } if err := h.Device.WaitForProperty(ctx, shillconst.DevicePropertyPowered, true, defaultTimeout); err != nil { return 0, errors.Wrap(err, "expected powered to become true, got false") } if err := h.Device.WaitForProperty(ctx, shillconst.DevicePropertyScanning, false, defaultTimeout); err != nil { return 0, errors.Wrap(err, "expected scanning to become false, got true") } return time.Since(start), nil } // Disable calls Manager.DisableTechnology(cellular) and returns true if the disable succeeded, or an error otherwise. func (h *Helper) Disable(ctx context.Context) (time.Duration, error) { ctx, st := timing.Start(ctx, "Helper.Disable") defer st.End() start := time.Now() h.Manager.DisableTechnology(ctx, shill.TechnologyCellular) if err := h.WaitForEnabledState(ctx, false); err != nil { return 0, err } if err := h.Device.WaitForProperty(ctx, shillconst.DevicePropertyPowered, false, defaultTimeout); err != nil { return 0, err } if err := h.Device.WaitForProperty(ctx, shillconst.DevicePropertyScanning, false, defaultTimeout); err != nil { return 0, errors.Wrap(err, "expected scanning to become false, got true") } return time.Since(start), nil } // FindService returns the first connectable Cellular Service. // If no such Cellular Service is available, returns a nil service and an error. func (h *Helper) FindService(ctx context.Context) (*shill.Service, error) { ctx, st := timing.Start(ctx, "Helper.FindService") defer st.End() // Look for any connectable Cellular service. cellularProperties := map[string]interface{}{ shillconst.ServicePropertyConnectable: true, shillconst.ServicePropertyType: shillconst.TypeCellular, } return h.Manager.WaitForServiceProperties(ctx, cellularProperties, defaultTimeout) } // FindServiceForDeviceWithProps returns the first connectable Cellular Service matching the Device ICCID and the given props. // If no such Cellular Service is available, returns a nil service and an error. func (h *Helper) FindServiceForDeviceWithProps(ctx context.Context, props map[string]interface{}) (*shill.Service, error) { ctx, st := timing.Start(ctx, "Helper.FindServiceForDeviceWithProps") defer st.End() deviceProperties, err := h.Device.GetProperties(ctx) if err != nil { return nil, errors.Wrap(err, "failed to get Cellular Device properties") } deviceICCID, err := deviceProperties.GetString(shillconst.DevicePropertyCellularICCID) if err != nil { return nil, errors.Wrap(err, "device missing ICCID") } if deviceICCID == "" { return nil, errors.Wrap(err, "device has empty ICCID") } necessaryProps := map[string]interface{}{ shillconst.ServicePropertyCellularICCID: deviceICCID, shillconst.ServicePropertyConnectable: true, shillconst.ServicePropertyType: shillconst.TypeCellular, } for k, v := range necessaryProps { props[k] = v } service, err := h.Manager.WaitForServiceProperties(ctx, props, defaultTimeout) if err != nil { return nil, errors.Wrapf(err, "Service not found for: %+v", props) } return service, nil } // FindServiceForDevice is a convenience function to call FindServiceForDeviceWithProps with an empty set of extra props. func (h *Helper) FindServiceForDevice(ctx context.Context) (*shill.Service, error) { ctx, st := timing.Start(ctx, "Helper.FindServiceForDevice") defer st.End() return h.FindServiceForDeviceWithProps(ctx, make(map[string]interface{})) } // AutoConnectCleanupTime provides enough time for a successful dbus operation. // If a timeout occurs during cleanup, the operation will fail anyway. const AutoConnectCleanupTime = 1 * time.Second // SetServiceAutoConnect sets the AutoConnect property of the Cellular Service // associated with the Cellular Device to |autoConnect| if the current value // does not match |autoConnect|. // Returns true when Service.AutoConnect is set and the operation succeeds. // Returns an error if any operation fails. func (h *Helper) SetServiceAutoConnect(ctx context.Context, autoConnect bool) (bool, error) { ctx, st := timing.Start(ctx, "Helper.SetServiceAutoConnect") defer st.End() service, err := h.FindServiceForDevice(ctx) if err != nil { return false, errors.Wrap(err, "failed to get Cellular Service") } properties, err := service.GetProperties(ctx) if err != nil { return false, errors.Wrap(err, "unable to get properties") } curAutoConnect, err := properties.GetBool(shillconst.ServicePropertyAutoConnect) if err != nil { return false, errors.Wrap(err, "unable to get AutoConnect") } if autoConnect == curAutoConnect { return false, nil } if err := service.SetProperty(ctx, shillconst.ServicePropertyAutoConnect, autoConnect); err != nil { return false, errors.Wrap(err, "failed to set Service.AutoConnect") } return true, nil } // ConnectToDefault connects to the default Cellular Service. func (h *Helper) ConnectToDefault(ctx context.Context) (time.Duration, error) { ctx, st := timing.Start(ctx, "Helper.ConnectToDefault") defer st.End() start := time.Now() service, err := h.FindServiceForDevice(ctx) if err != nil { return 0, err } if err := h.ConnectToService(ctx, service); err != nil { return 0, err } return time.Since(start), nil } // ConnectToServiceWithTimeout connects to a Cellular Service with a specified timeout. // It ensures that the connect attempt succeeds, repeating attempts if necessary. // Otherwise an error is returned. func (h *Helper) ConnectToServiceWithTimeout(ctx context.Context, service *shill.Service, timeout time.Duration) error { ctx, st := timing.Start(ctx, "Helper.ConnectToServiceWithTimeout") defer st.End() props, err := service.GetProperties(ctx) if err != nil { return err } name, err := props.GetString(shillconst.ServicePropertyName) if err != nil { return err } if err := testing.Poll(ctx, func(ctx context.Context) error { // check if we are already connected, since services may choose to return an error if Connect is attempted on an already connected service. isConnected, err := service.IsConnected(ctx) if err != nil { return err } if isConnected { return nil } if err := service.Connect(ctx); err != nil { return err } if err := service.WaitForConnectedOrError(ctx); err != nil { return err } return nil }, &testing.PollOptions{ Timeout: timeout, Interval: 5 * time.Second, }); err != nil { return errors.Wrapf(err, "connect to %s failed", name) } return nil } // ConnectToService connects to a Cellular Service. // It ensures that the connect attempt succeeds, repeating attempts if necessary. // Otherwise an error is returned. func (h *Helper) ConnectToService(ctx context.Context, service *shill.Service) error { ctx, st := timing.Start(ctx, "Helper.ConnectToService") defer st.End() // Connect requires a longer default timeout than other operations. return h.ConnectToServiceWithTimeout(ctx, service, defaultTimeout*6) } // Connect to default service if the current cellular service is not connected, otherwise return an error func (h *Helper) Connect(ctx context.Context) (*shill.Service, error) { ctx, st := timing.Start(ctx, "Helper.Connect") defer st.End() service, err := h.FindServiceForDevice(ctx) if err != nil { return nil, errors.Wrap(err, "unable to find Cellular Service for Device") } if isConnected, err := service.IsConnected(ctx); err != nil { return nil, errors.Wrap(err, "unable to get IsConnected for Service") } else if !isConnected { if _, err := h.ConnectToDefault(ctx); err != nil { return nil, errors.Wrap(err, "unable to Connect to default service") } } // Ensure service's state matches expectations. if err := service.WaitForProperty(ctx, shillconst.ServicePropertyState, shillconst.ServiceStateOnline, 30*time.Second); err != nil { return nil, errors.Wrap(err, "failed to get service state") } return service, nil } // Disconnect from the Cellular Service and ensure that the disconnect succeeded, otherwise return an error. func (h *Helper) Disconnect(ctx context.Context) (time.Duration, error) { ctx, st := timing.Start(ctx, "Helper.Disconnect") defer st.End() start := time.Now() service, err := h.FindServiceForDevice(ctx) if err != nil { return 0, err } if err := service.Disconnect(ctx); err != nil { return 0, err } if err := service.WaitForProperty(ctx, shillconst.ServicePropertyIsConnected, false, defaultTimeout); err != nil { return 0, err } return time.Since(start), nil } // IsConnected return err if shillconst.ServicePropertyIsConnected is not true func (h *Helper) IsConnected(ctx context.Context) error { service, err := h.FindServiceForDevice(ctx) if err != nil { return err } if err := service.WaitForProperty(ctx, shillconst.ServicePropertyIsConnected, true, defaultTimeout); err != nil { return err } return nil } // SetDeviceProperty sets a Device property and waits for the property to be set. func (h *Helper) SetDeviceProperty(ctx context.Context, prop string, value interface{}, timeout time.Duration) error { ctx, st := timing.Start(ctx, "Helper.SetDeviceProperty") defer st.End() pw, err := h.Device.CreateWatcher(ctx) if err != nil { return errors.Wrap(err, "failed to create watcher") } defer pw.Close(ctx) // If the Modem is starting, SetProperty may fail, so poll while that is the case. if err := testing.Poll(ctx, func(ctx context.Context) error { if err := h.Device.SetProperty(ctx, prop, value); err != nil { if strings.Contains(err.Error(), shillconst.ErrorModemNotStarted) { return err } return testing.PollBreak(err) } return nil }, &testing.PollOptions{Timeout: timeout}); err != nil { return errors.Wrapf(err, "unable to set Device property: %s", prop) } expectCtx, cancel := context.WithTimeout(ctx, timeout) defer cancel() if err := pw.Expect(expectCtx, prop, value); err != nil { return errors.Wrapf(err, "%s not set", prop) } return nil } // InitDeviceProperty sets a device property and returns a function to restore the initial value. func (h *Helper) InitDeviceProperty(ctx context.Context, prop string, value interface{}) (func(ctx context.Context), error) { ctx, st := timing.Start(ctx, "Helper.InitDeviceProperty") defer st.End() return initProperty(ctx, h.Device.PropertyHolder, prop, value) } // InitServiceProperty sets a service property and returns a function to restore the initial value. func (h *Helper) InitServiceProperty(ctx context.Context, prop string, value interface{}) (func(ctx context.Context), error) { ctx, st := timing.Start(ctx, "Helper.InitServiceProperty") defer st.End() service, err := h.FindServiceForDevice(ctx) if err != nil { return nil, errors.Wrap(err, "failed to get cellular service") } return initProperty(ctx, service.PropertyHolder, prop, value) } // PropertyCleanupTime provides enough time for a successful dbus operation at the end of the test. const PropertyCleanupTime = 1 * time.Second // initProperty sets a property and returns a function to restore the initial value. func initProperty(ctx context.Context, properties *shill.PropertyHolder, prop string, value interface{}) (func(ctx context.Context), error) { ctx, st := timing.Start(ctx, "Helper.initProperty") defer st.End() prevValue, err := properties.GetAndSetProperty(ctx, prop, value) if err != nil { return nil, errors.Wrap(err, "failed to read and initialize property") } return func(ctx context.Context) { if err := properties.SetProperty(ctx, prop, prevValue); err != nil { testing.ContextLogf(ctx, "Failed to restore %s: %s", prop, err) } }, nil } // RestartModemManager - restart modemmanager with debug logs enabled/disabled. // Return nil if restart succeeds, else return error. func (h *Helper) RestartModemManager(ctx context.Context, enableDebugLogs bool) error { ctx, st := timing.Start(ctx, "Helper.RestartModemManager") defer st.End() logLevel := "INFO" if enableDebugLogs { logLevel = "DEBUG" } if err := upstart.RestartJob(ctx, "modemmanager", upstart.WithArg("MM_LOGLEVEL", logLevel)); err != nil { return errors.Wrap(err, "failed to restart modemmanager") } return nil } // ResetShill restarts shill and clears all profiles. func (h *Helper) ResetShill(ctx context.Context) []error { var errs []error if err := upstart.StopJob(ctx, "shill"); err != nil { errs = append(errs, errors.Wrap(err, "failed to stop shill")) } if err := os.Remove(shillconst.DefaultProfilePath); err != nil && !os.IsNotExist(err) { errs = append(errs, errors.Wrap(err, "failed to remove default profile")) } if err := upstart.RestartJob(ctx, "shill"); err != nil { // No more can be done if shill doesn't start return append(errs, errors.Wrap(err, "failed to restart shill")) } manager, err := shill.NewManager(ctx) if err != nil { // No more can be done if a manager interface cannot be created return append(errs, errors.Wrap(err, "failed to create new shill manager")) } // Disable Wifi to avoid log pollution manager.DisableTechnology(ctx, shill.TechnologyWifi) if err = manager.PopAllUserProfiles(ctx); err != nil { errs = append(errs, errors.Wrap(err, "failed to pop all user profiles")) } // Wait until a service is connected. expectProps := map[string]interface{}{ shillconst.ServicePropertyIsConnected: true, } if _, err := manager.WaitForServiceProperties(ctx, expectProps, 30*time.Second); err != nil { errs = append(errs, errors.Wrap(err, "failed to wait for connected service")) } return errs } // CaptureDBusLogs - Capture DBus system logs // Return nil if DBus log collection succeeds, else return error. func (h *Helper) CaptureDBusLogs(ctx context.Context) error { outDir, ok := testing.ContextOutDir(ctx) if !ok { return errors.New("failed to get out dir") } f, err := os.Create(filepath.Join(outDir, "dbus-system.txt")) if err != nil { return err } cmd := testexec.CommandContext(ctx, "/usr/bin/dbus-monitor", "--system", "sender=org.chromium.flimflam", "destination=org.chromium.flimflam", "path_namespace=/org/freedesktop/ModemManager1") if f != nil { cmd.Stdout = f cmd.Stderr = f } if err := cmd.Start(); err != nil { f.Close() return errors.Wrap(err, "failed to start command") } go func() { defer cmd.Kill() defer cmd.Wait() defer f.Close() <-ctx.Done() }() return nil } // ResetModem calls Device.ResetModem(cellular) and returns true if the reset succeeded, or an error otherwise. func (h *Helper) ResetModem(ctx context.Context) (time.Duration, error) { ctx, st := timing.Start(ctx, "Helper.ResetModem") defer st.End() start := time.Now() if err := h.Device.Reset(ctx); err != nil { return time.Since(start), errors.Wrap(err, "reset modem failed") } testing.ContextLog(ctx, "Reset modem called") if err := h.WaitForEnabledState(ctx, false); err != nil { return time.Since(start), err } if err := h.WaitForEnabledState(ctx, true); err != nil { return time.Since(start), err } if err := h.Device.WaitForProperty(ctx, shillconst.DevicePropertyPowered, true, defaultTimeout); err != nil { return time.Since(start), errors.Wrap(err, "expected powered to become true, got false") } if err := h.Device.WaitForProperty(ctx, shillconst.DevicePropertyScanning, false, defaultTimeout); err != nil { return time.Since(start), errors.Wrap(err, "expected scanning to become false, got true") } return time.Since(start), nil } // IsSimLockEnabled returns lockenabled value. func (h *Helper) IsSimLockEnabled(ctx context.Context) bool { lockStatus, err := h.GetCellularSIMLockStatus(ctx) if err != nil { testing.ContextLog(ctx, "getcellularsimlockstatus -lock: ", err.Error()) } lock := false lockEnabled := lockStatus[shillconst.DevicePropertyCellularSIMLockStatusLockEnabled] if lockEnabled != nil { testing.ContextLog(ctx, "lock enabled status: ", lockEnabled) lock = lockEnabled.(bool) } return lock } // IsSimPinLocked returns true if locktype value is 'sim-pin' // locktype value is 'sim-pin2' for QC and 'none' when not locked. func (h *Helper) IsSimPinLocked(ctx context.Context) bool { lockStatus, err := h.GetCellularSIMLockStatus(ctx) if err != nil { testing.ContextLog(ctx, "getcellularsimlockstatus -pin: ", err.Error()) } lockType := lockStatus[shillconst.DevicePropertyCellularSIMLockStatusLockType] lock := "" if lockType != nil { lock = lockType.(string) testing.ContextLog(ctx, "pin lock type value: ", lock) } return lock == shillconst.DevicePropertyValueSIMLockTypePIN } // IsSimPukLocked returns true if locktype value is 'sim-puk' // locktype value is 'sim-pin2' for QC and value 'none' when not locked. func (h *Helper) IsSimPukLocked(ctx context.Context) bool { lockStatus, err := h.GetCellularSIMLockStatus(ctx) if err != nil { testing.ContextLog(ctx, "getcellularsimlockstatus -puk: ", err.Error()) } lockType := lockStatus[shillconst.DevicePropertyCellularSIMLockStatusLockType] lock := "" if lockType != nil { lock = lockType.(string) testing.ContextLog(ctx, "puk locktype: ", lock) } return lock == shillconst.DevicePropertyValueSIMLockTypePUK } // GetRetriesLeft helps to get modem property UnlockRetries value. func (h *Helper) GetRetriesLeft(ctx context.Context) (int32, error) { lockStatus, err := h.GetCellularSIMLockStatus(ctx) if err != nil { return 0, errors.Wrap(err, "getcellularsimlockstatus failed reading retriesleft") } retriesLeft := lockStatus[shillconst.DevicePropertyCellularSIMLockStatusRetriesLeft] if retriesLeft == nil { return 0, errors.New("failed to get retriesLeft") } retries, ok := retriesLeft.(int32) if !ok { return 0, errors.New("int32 type assert failed for retriesleft property") } if retries < 0 { return 0, errors.New("negative retriesleft property") } testing.ContextLog(ctx, "retriesleft value : ", retries) return retries, nil } // In the case of [service].Error.PinError, the error message gives details: // [interface].PinRequired // [interface].PinBlocked // [interface].IncorrectPin // UnlockDut is to unlock sim pin before every test. func (h *Helper) UnlockDut(ctx context.Context, currentPin, currentPuk string) error { // Check if pin enabled and locked/set. if h.IsSimLockEnabled(ctx) || h.IsSimPinLocked(ctx) { // Disable pin. if err := h.Device.RequirePin(ctx, currentPin, false); err != nil { return errors.Wrap(err, "failed to disable lock") } } return nil } // ClearSIMLock clears puk, pin lock if any of them enabled and locked. func (h *Helper) ClearSIMLock(ctx context.Context, pin, puk string) error { if !h.IsSimLockEnabled(ctx) && !h.IsSimPukLocked(ctx) { return nil } // Clear puk lock if puk locked which is unusual. if h.IsSimPukLocked(ctx) { if len(puk) == 0 { return errors.New("ClearSIMLock needs PUK code to unlock SIM") } retriesLeft, err := h.GetRetriesLeft(ctx) if err != nil { if retriesLeft == 1 { return errors.New("Provided PUK code seems invalid. " + "SIM is PUK locked with only one chance to unlock!") } if retriesLeft == 0 { return errors.New("SIM card blocked and need to be replaced") } } if err := h.Device.UnblockPin(ctx, puk, pin); err != nil { return errors.Wrap(err, "failed to UnblockPin") } } // Clear pin lock, this can also happen after puk unlocked. if h.IsSimPinLocked(ctx) { if err := h.Device.EnterPin(ctx, pin); err != nil { testing.ContextLog(ctx, "At EnterPin in ClearSIMLock: ", err) // Block SIM with PUK lock and set new PIN code if err := h.PukLockSim(ctx, pin); err != nil { return errors.Wrap(err, "failed to lock SIM card with PukLockSim") } if err := h.Device.UnblockPin(ctx, puk, pin); err != nil { return errors.Wrap(err, "failed to clear PUK lock with UnblockPin") } if err := h.Device.EnterPin(ctx, pin); err != nil { return errors.Wrap(err, "failed to unlock SIM card with EnterPin") } } } // Disable sim lock. if err := h.Device.RequirePin(ctx, pin, false); err != nil { return errors.Wrap(err, "failed to clear pin lock with RequirePin") } testing.ContextLog(ctx, "clearsimlock disabled locks with pin: ", pin) return nil } // GetCellularSIMLockStatus dict gets Cellular.SIMLockStatus dictionary from shill properties. func (h *Helper) GetCellularSIMLockStatus(ctx context.Context) (map[string]interface{}, error) { if err := h.Device.WaitForProperty(ctx, shillconst.DevicePropertyScanning, false, defaultTimeout); err != nil { return nil, errors.Wrap(err, "expected scanning to become false, got true") } // Gather Shill Device properties. deviceProps, err := h.Device.GetShillProperties(ctx) if err != nil { return nil, errors.Wrap(err, "failed to get device properties") } // Verify Device.SimSlots. info, err := deviceProps.Get(shillconst.DevicePropertyCellularSIMLockStatus) if err != nil { return nil, errors.Wrap(err, "failed to get device cellularsimlockstatus property") } simLockStatus := make(map[string]interface{}) simLockStatus, ok := info.(map[string]interface{}) if !ok { return nil, errors.Wrap(err, "invalid format for device cellularsimlockstatus") } testing.ContextLog(ctx, "simlockstatus: ", simLockStatus) return simLockStatus, nil } // Helper functions for SIM lock/unlock. // random generates a random integer in given range. func random(min, max int) int { return rand.Intn(max-min) + min } // BadPin obtains a pin that does not match the valid sim-pin. func (h *Helper) BadPin(ctx context.Context, currentPin string) (string, error) { randomPin := random(1000, 9999) pin, _ := strconv.Atoi(currentPin) if randomPin == pin { randomPin++ } return strconv.Itoa(randomPin), nil } // BadPuk obtains a puk that does not match the valid sim-puk. func (h *Helper) BadPuk(ctx context.Context, currentPuk string) (string, error) { randomPuk := random(10000000, 99999999) puk, _ := strconv.Atoi(currentPuk) if randomPuk == puk { randomPuk++ } return strconv.Itoa(randomPuk), nil } // PinLockSim is a helper method to pin-lock a sim, assuming nothing bad happens. func (h *Helper) PinLockSim(ctx context.Context, newPin string) error { if h.IsSimPinLocked(ctx) { return nil } if err := h.Device.RequirePin(ctx, newPin, true); err != nil { return errors.Wrap(err, "failed to enable lock with new pin") } return nil } // PukLockSim is a helper method to puk-lock a SIM, assuming nothing bad happens. func (h *Helper) PukLockSim(ctx context.Context, currentPin string) error { if err := h.PinLockSim(ctx, currentPin); err != nil { return errors.Wrap(err, "failed at pinlocksim") } // Reset modem to reflect if puk locked. if _, err := h.ResetModem(ctx); err != nil { return errors.Wrap(err, "reset modem failed after pin lock set") } locked := h.IsSimPinLocked(ctx) if locked == true { testing.ContextLog(ctx, "pinlocked with: ", currentPin) } locked = false retriesCnt := 0 // Max incorrect retries before SIM card becomes PUK locked is usually 3 for retriesCnt < 10 && locked == false { retriesCnt++ if err := h.EnterIncorrectPin(ctx, currentPin); err != nil { testing.ContextLog(ctx, "Failed to enter incorrect pin: ", err.Error()) continue } if err := h.Device.WaitForProperty(ctx, shillconst.DevicePropertyScanning, false, defaultTimeout); err != nil { return errors.Wrap(err, "expected scanning to become false, got true") } locked = h.IsSimPukLocked(ctx) } if !locked { return errors.New("expected sim to be puk-locked") } return nil } // EnterIncorrectPin gets incorrect pin and tries to unlock. func (h *Helper) EnterIncorrectPin(ctx context.Context, currentPin string) error { badPin, err := h.BadPin(ctx, currentPin) testing.ContextLog(ctx, "Created badpin is: ", badPin) if err != nil { return errors.Wrap(err, "failed to generate bad pin") } if err = h.Device.EnterPin(ctx, badPin); err == nil { return errors.Wrap(err, "random PIN was accepted by SIM card: "+badPin) } // For flimflam errors with org.chromium.flimflam.Error.IncorrectPin. if strings.Contains(err.Error(), shillconst.ErrorIncorrectPin) || strings.Contains(err.Error(), shillconst.ErrorIncorrectPassword) || strings.Contains(err.Error(), shillconst.ErrorPukRequired) || strings.Contains(err.Error(), shillconst.ErrorPinBlocked) { return nil } // If puk locked with unknown error, ignoring error as intention is to do puk lock. locked := h.IsSimPukLocked(ctx) if locked { return nil } return errors.Wrap(err, "unusual pin error") } // EnterIncorrectPuk generates bad puk and tries to unlock. func (h *Helper) EnterIncorrectPuk(ctx context.Context, currentPin, currentPuk string) error { badPuk, err := h.BadPuk(ctx, currentPuk) if err != nil { return errors.Wrap(err, "failed to generate bad puk") } if err = h.Device.UnblockPin(ctx, badPuk, currentPin); err == nil { return errors.Wrap(err, "failed to send bad puk: "+badPuk) } errorIncorrectPuk := errors.New("org.freedesktop.ModemManager1.Sim.Error.IncorrectPuk") if errors.Is(err, errorIncorrectPuk) { return nil } return errors.Wrap(err, "unusual puk error") } // getCellularDeviceDictProperty gets a shill device dictionary property func (h *Helper) getCellularDeviceDictProperty(ctx context.Context, propertyName string) (map[string]string, error) { props, err := h.Device.GetProperties(ctx) if err != nil { return nil, errors.Wrap(err, "failed to get Device properties") } info, err := props.Get(propertyName) if err != nil { return nil, errors.Wrapf(err, "error getting property %q", propertyName) } dictProp, ok := info.(map[string]string) if !ok { return nil, errors.Wrapf(err, "invalid format for %q", propertyName) } return dictProp, nil } // GetHomeProviderFromShill returns current home provider UUID and code from shill. func (h *Helper) GetHomeProviderFromShill(ctx context.Context) (uuid, code string, err error) { ctx, st := timing.Start(ctx, "Helper.GetHomeProviderFromShill") defer st.End() homeProviderMap, err := h.getCellularDeviceDictProperty(ctx, shillconst.DevicePropertyCellularHomeProvider) if err != nil { return "", "", errors.New("invalid format for Home Provider property") } uuid, ok := homeProviderMap[shillconst.OperatorUUIDKey] if !ok { return "", "", errors.New("home provider UUID not found") } code, ok = homeProviderMap[shillconst.OperatorCode] if !ok { return "", "", errors.New("home provider operator code not found") } return uuid, code, nil } // GetServingOperatorFromShill returns current serving operator UUID and code from shill. func (h *Helper) GetServingOperatorFromShill(ctx context.Context) (uuid, code string, err error) { ctx, st := timing.Start(ctx, "Helper.GetServingOperatorFromShill") defer st.End() servingOperatorMap, err := h.getCellularServiceDictProperty(ctx, shillconst.ServicePropertyCellularServingOperator) if err != nil { return "", "", errors.Wrap(err, "failed to get last good APN info") } uuid, ok := servingOperatorMap[shillconst.OperatorUUIDKey] if !ok { return "", "", errors.New("serving operator UUID not found") } code, ok = servingOperatorMap[shillconst.OperatorCode] if !ok { return "", "", errors.New("service operator code not found") } return uuid, code, nil } // getCellularDeviceProperty gets a shill device string property func (h *Helper) getCellularDeviceProperty(ctx context.Context, propertyName string) (string, error) { props, err := h.Device.GetProperties(ctx) if err != nil { return "", errors.Wrap(err, "failed to get Device properties") } info, err := props.GetString(propertyName) if err != nil { return "", errors.Wrapf(err, "error getting property %q", propertyName) } return info, nil } // GetIMEIFromShill gets the current modem IMEI from shill. func (h *Helper) GetIMEIFromShill(ctx context.Context) (string, error) { return h.getCellularDeviceProperty(ctx, shillconst.DevicePropertyCellularIMEI) } // GetIMSIFromShill gets the current modem IMSI from shill. func (h *Helper) GetIMSIFromShill(ctx context.Context) (string, error) { return h.getCellularDeviceProperty(ctx, shillconst.DevicePropertyCellularIMSI) } // SetServiceProvidersExclusiveOverride adds an override MODB to shill. // The function returns a closure to delete the override file. func SetServiceProvidersExclusiveOverride(ctx context.Context, sourceFile string) (func(), error) { input, err := ioutil.ReadFile(sourceFile) if err != nil { return nil, errors.Wrapf(err, "failed to read %q", sourceFile) } err = ioutil.WriteFile(shillconst.ServiceProviderOverridePath, input, 0644) if err != nil { return nil, errors.Wrapf(err, "failed to write %q", shillconst.ServiceProviderOverridePath) } return func() { os.Remove(shillconst.ServiceProviderOverridePath) }, nil } // getCellularServiceDictProperty gets a shill service dictionary property func (h *Helper) getCellularServiceDictProperty(ctx context.Context, propertyName string) (map[string]string, error) { // Verify that a connectable Cellular service exists and ensure it is connected. service, err := h.FindServiceForDevice(ctx) if err != nil { return nil, errors.Wrap(err, "unable to find Cellular Service for Device") } props, err := service.GetShillProperties(ctx) if err != nil { return nil, errors.Wrap(err, "error getting Service properties") } info, err := props.Get(propertyName) if err != nil { return nil, errors.Wrapf(err, "error getting property %q", propertyName) } dictProp, ok := info.(map[string]string) if !ok { return nil, errors.Wrapf(err, "invalid format for %q", propertyName) } return dictProp, nil } // getCellularServiceProperty gets a shill service dictionary property func (h *Helper) getCellularServiceProperty(ctx context.Context, propertyName string) (string, error) { // Verify that a connectable Cellular service exists and ensure it is connected. service, err := h.FindServiceForDevice(ctx) if err != nil { return "", errors.Wrap(err, "unable to find Cellular Service for Device") } props, err := service.GetShillProperties(ctx) if err != nil { return "", errors.Wrap(err, "error getting Service properties") } info, err := props.GetString(propertyName) if err != nil { return "", errors.Wrapf(err, "error getting property %q", propertyName) } return info, nil } // SetAPN sets the Custom/OTHER APN property `Cellular.APN`. func (h *Helper) SetAPN(ctx context.Context, apn map[string]string) error { ctx, st := timing.Start(ctx, "Helper.SetApn") defer st.End() service, err := h.FindServiceForDevice(ctx) if err != nil { return errors.Wrap(err, "failed to get Cellular Service") } if err := service.SetProperty(ctx, shillconst.ServicePropertyCellularAPN, apn); err != nil { return errors.Wrap(err, "failed to set Cellular.APN") } return nil } // GetCellularLastAttachAPN gets Cellular.LastAttachAPN dictionary from shill properties. func (h *Helper) GetCellularLastAttachAPN(ctx context.Context) (map[string]string, error) { return h.getCellularServiceDictProperty(ctx, shillconst.ServicePropertyCellularLastAttachAPN) } // GetCellularLastGoodAPN gets Cellular.LastAttachAPN dictionary from shill properties. func (h *Helper) GetCellularLastGoodAPN(ctx context.Context) (map[string]string, error) { return h.getCellularServiceDictProperty(ctx, shillconst.ServicePropertyCellularLastGoodAPN) } // GetCurrentIPType returns current ip_type of LastGoodAPN. func (h *Helper) GetCurrentIPType(ctx context.Context) (string, error) { apnInfo, err := h.getCellularServiceDictProperty(ctx, shillconst.ServicePropertyCellularLastGoodAPN) if err != nil { return "", errors.Wrap(err, "failed to get last good APN info") } ipType := apnInfo["ip_type"] if len(ipType) > 0 { return ipType, nil } return "ipv4", nil } // GetNetworkProvisionedCellularIPTypes returns the currently provisioned IP types func (h *Helper) GetNetworkProvisionedCellularIPTypes(ctx context.Context) (ipv4, ipv6 bool, err error) { // Verify that a connectable Cellular service exists and ensure it is connected. service, err := h.Connect(ctx) if err != nil { return false, false, errors.Wrap(err, "unable to find Cellular Service") } configs, err := service.GetIPConfigs(ctx) if err != nil { return false, false, errors.Wrap(err, "failed to get IPConfigs from service") } ipv4Present := false ipv6Present := false for _, config := range configs { props, err := config.GetIPProperties(ctx) if err != nil { return false, false, errors.Wrap(err, "failed to get IPConfig properties") } testing.ContextLog(ctx, "Address :", props.Address) ip := net.ParseIP(props.Address) if ip == nil { continue } if ip.To4() != nil { testing.ContextLog(ctx, "IPv4 Address :", props.Address, " len(ip): ", len(ip)) ipv4Present = true } else { testing.ContextLog(ctx, "IPv6 Address :", props.Address, " len(ip): ", len(ip)) ipv6Present = true } } if ipv4Present == false && ipv6Present == false { return false, false, errors.New("no IP networks provisioned") } return ipv4Present, ipv6Present, nil } // GetCurrentICCID gets current ICCID func (h *Helper) GetCurrentICCID(ctx context.Context) (string, error) { return h.getCellularServiceProperty(ctx, shillconst.ServicePropertyCellularICCID) } // GetCurrentNetworkName gets current Network name func (h *Helper) GetCurrentNetworkName(ctx context.Context) (string, error) { return h.getCellularServiceProperty(ctx, shillconst.ServicePropertyName) } // disableNonCellularInterfaceforTesting disable all non cellular interfaces func (h *Helper) disableNonCellularInterfaceforTesting(ctx context.Context) error { ctx, cancel := ctxutil.Shorten(ctx, shill.EnableWaitTime*2) defer cancel() // Disable Ethernet and/or WiFi if present and defer re-enabling. if enableFunc, err := h.Manager.DisableTechnologyForTesting(ctx, shill.TechnologyEthernet); err != nil { return errors.Wrap(err, "unable to disable Ethernet") } else if enableFunc != nil { h.enableEthernetFunc = enableFunc } if enableFunc, err := h.Manager.DisableTechnologyForTesting(ctx, shill.TechnologyWifi); err != nil { return errors.Wrap(err, "unable to disable Wifi") } else if enableFunc != nil { h.enableWifiFunc = enableFunc } return nil } // enablePreviouslyDisabledNonCellularInterfaceforTesting enable previously disabled interfaces func (h *Helper) enablePreviouslyDisabledNonCellularInterfaceforTesting(ctx context.Context) { if h.enableEthernetFunc != nil { h.enableEthernetFunc(ctx) } if h.enableWifiFunc != nil { h.enableWifiFunc(ctx) } h.enableEthernetFunc = nil h.enableWifiFunc = nil } // RunTestOnCellularInterface setup the device for cellular tests. func (h *Helper) RunTestOnCellularInterface(ctx context.Context, testBody func(ctx context.Context) error) error { if _, err := h.Connect(ctx); err != nil { return errors.Wrap(err, "failed to connect to cellular service") } if err := h.disableNonCellularInterfaceforTesting(ctx); err != nil { return errors.Wrap(err, "failed to disable non cellular interface") } defer h.enablePreviouslyDisabledNonCellularInterfaceforTesting(ctx) return testBody(ctx) } // PrintHostInfoLabels prints the host info labels func (h *Helper) PrintHostInfoLabels(ctx context.Context) { for _, label := range h.Labels { testing.ContextLog(ctx, "Labels :", label) } } // PrintModemInfo prints modem details func (h *Helper) PrintModemInfo(ctx context.Context) { testing.ContextLog(ctx, "Modem Type : ", h.modemInfo.Type) testing.ContextLog(ctx, "Modem IMEI : ", h.modemInfo.IMEI) testing.ContextLog(ctx, "Modem Supported Bands : ", h.modemInfo.SupportedBands) testing.ContextLog(ctx, "Modem SIM Count : ", h.modemInfo.SimCount) } // PrintSIMInfo prints SIM details func (h *Helper) PrintSIMInfo(ctx context.Context) { for _, s := range h.simInfo { testing.ContextLog(ctx, "SIM Slot ID : ", s.SlotID) testing.ContextLog(ctx, "SIM Type : ", s.Type) testing.ContextLog(ctx, "SIM Test eSIM : ", s.TestEsim) testing.ContextLog(ctx, "SIM EID : ", s.EID) for _, p := range s.ProfileInfo { testing.ContextLog(ctx, "SIM Profile ICCID : ", p.ICCID) testing.ContextLog(ctx, "SIM Profile PIN : ", p.SimPin) testing.ContextLog(ctx, "SIM Profile PUK : ", p.SimPuk) testing.ContextLog(ctx, "SIM Profile Carrier Name : ", p.CarrierName) } } } // GetHostInfoLabels reads the labels from autotest_host_info_labels func (h *Helper) GetHostInfoLabels(ctx context.Context, labels []string) error { h.Labels = labels h.PrintHostInfoLabels(ctx) h.modemInfo = GetModemInfoFromHostInfoLabels(ctx, labels) h.simInfo = GetSIMInfoFromHostInfoLabels(ctx, labels) h.carrierName = GetCellularCarrierFromHostInfoLabels(ctx, labels) testing.ContextLog(ctx, "Carrier Name : ", h.carrierName) h.devicePools = GetDevicePoolFromHostInfoLabels(ctx, labels) testing.ContextLog(ctx, "Pools : ", h.devicePools) return nil } // GetPINAndPUKForICCID returns the pin and puk info for the given iccid from host_info_label func (h *Helper) GetPINAndPUKForICCID(ctx context.Context, iccid string) (string, string, error) { for _, s := range h.simInfo { for _, p := range s.ProfileInfo { if p.ICCID == iccid { return p.SimPin, p.SimPuk, nil } } } return "", "", nil } // GetLabelCarrierName return the current carrier name func (h *Helper) GetLabelCarrierName(ctx context.Context) string { return h.carrierName } // connectAndCheck verifies that cellular is connected and has sufficient signal coverage to run test cases func (h *Helper) connectAndCheck(ctx context.Context) error { service, err := h.Connect(ctx) if err != nil { return errors.Wrap(err, "unable to connect to cellular service") } // Poll max 3 times in 30 seconds to ensure service's signal quality matches expectations. if err := testing.Poll(ctx, func(ctx context.Context) error { signalStrength, err := service.GetSignalStrength(ctx) if err != nil { return errors.Wrap(err, "unable to get service SignalStrength") } testing.ContextLog(ctx, "SignalStrength: ", signalStrength) if signalStrength < shillconst.CellularServiceMinSignalStrength { return errors.Wrapf(err, "signal strength below minimum acceptable threshold - %d < %d ", signalStrength, shillconst.CellularServiceMinSignalStrength) } return nil }, &testing.PollOptions{ Timeout: 15 * time.Second, Interval: 5 * time.Second}); err != nil { return errors.Wrap(err, "failed SignalStrength check") } return nil }
package Maximum_Repeating_Substring import "testing" func Test_maxRepeating(t *testing.T) { type args struct { sequence string word string } tests := []struct { name string args args want int }{ // TODO: Add test cases. { "case", args{ sequence: "bbbbbb", word: "bb", }, 3, }, { "case", args{ sequence: "ababc", word: "ba", }, 1, }, { "case", args{ sequence: "cabcabc", word: "ab", }, 1, }, { "case", args{ sequence: "cababc", word: "ab", }, 2, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { if got := maxRepeating(tt.args.sequence, tt.args.word); got != tt.want { t.Errorf("maxRepeating() = %v, want %v", got, tt.want) } }) } }
package main import ( "io" "net/http" ) type gyan struct{} func (g gyan) ServeHTTP(w http.ResponseWriter, r *http.Request) { switch r.URL.Path { case "/dog/": io.WriteString(w, "dog ... woof") case "/cat": io.WriteString(w, "Cat ... Meow") } } func main() { var g gyan myMux := http.NewServeMux() myMux.Handle("/dog/", g) myMux.Handle("/cat", g) http.ListenAndServe(":8080", myMux) }
package sync import ( "fmt" "log" "strings" ) // MustParseAll parse sync string or fail with Fatal func MustParseAll(strings []string) (result []Sync) { for _, str := range strings { sync, err := Parse(str) if err != nil { log.Fatalf("Invalid formated sync [%s], must be in format: '<source>:<destination>', for example '~/local/dir:/data'", str) } result = append(result, sync) } return result } // Parse parses a sync string in the form "~/local/dir:/data" func Parse(str string) (Sync, error) { parts := strings.Split(str, ":") if len(parts) == 2 { return Sync{ Source: parts[0], Destination: parts[1], }, nil } return Sync{}, fmt.Errorf("Invalid formated sync [%s], must be in format: '<source>:<destination>', for example '~/local/dir:/data'", str) }
package main /* Given an absolute path for a file (Unix-style), simplify it. For example, path = "/home/", => "/home" path = "/a/./b/../../c/", => "/c" Corner Cases: Did you consider the case where path = "/../"? In this case, you should return "/". Another corner case is the path might contain multiple slashes '/' together, such as "/home//foo/". In this case, you should ignore redundant slashes and return "/home/foo". */ import ( "strings" "fmt" ) func simplifyPath(path string) string { p := strings.Split(path,"/") ret := make([]string,0) for i:=0;i<len(p);i++ { if p[i]=="" || p[i]=="." { continue } if p[i] == ".." { if len(ret) > 0 { ret = ret[:len(ret)-1] } } else { ret=append(ret,p[i]) } } return "/" + strings.Join(ret,"/") } func main() { fmt.Println(simplifyPath("/..")) fmt.Println(simplifyPath("/home/")) fmt.Println(simplifyPath("/a/./b/../../c/")) }
package requests import ( "net/url" "github.com/atomicjolt/canvasapi" ) // HideAllStreamItems Hide all stream items for the user // https://canvas.instructure.com/doc/api/users.html // type HideAllStreamItems struct { } func (t *HideAllStreamItems) GetMethod() string { return "DELETE" } func (t *HideAllStreamItems) GetURLPath() string { return "" } func (t *HideAllStreamItems) GetQuery() (string, error) { return "", nil } func (t *HideAllStreamItems) GetBody() (url.Values, error) { return nil, nil } func (t *HideAllStreamItems) GetJSON() ([]byte, error) { return nil, nil } func (t *HideAllStreamItems) HasErrors() error { return nil } func (t *HideAllStreamItems) Do(c *canvasapi.Canvas) error { _, err := c.SendRequest(t) if err != nil { return err } return nil }
package main import ( "fmt" ) // START OMIT func main() { a1 := [...]int{1, 2, 3} s1 := a1[0:2] // same as s1 := a1[:2] var s2 []int // len == 0, cap == 0, s2 == nil s3 := make([]int, 2) // len == 2, cap == 2. Same as make([]int,2,2) s1 = append(s1, 5) s2 = append(s2, 5) s3 = append(s3, 5) fmt.Println(s1, s2, s3) } // END OMIT
package config import ( "github.com/google/wire" "github.com/spf13/viper" ) // Init 初始化viper func New() (*viper.Viper, error) { var ( err error v = viper.New() ) v.SetEnvPrefix("IOJ") err = v.BindEnv("host") if err != nil { return nil, err } v.SetDefault("host", "http://10.20.107.171:2333") return v, err } var ProviderSet = wire.NewSet(New)
package model import ( "time" "github.com/satori/go.uuid" ) // List is a struct representing a TODO list type List struct { UUID uuid.UUID `db:"uuid" json:"list_uuid"` Name string `db:"name" json:"list_name"` Owner string `db:"owner" json:"owner"` Tasks *[]*Task `json:"tasks"` CreatedAt time.Time `db:"created_at" json:"created_at"` UpdatedAt time.Time `db:"updated_at" json:"updated_at"` } // NewList returns empty List structs func NewList() *List { return &List{} }
package user import ( "fmt" userModel "go_simpleweibo/app/models/user" "go_simpleweibo/app/requests" "go_simpleweibo/pkg/flash" "github.com/gin-gonic/gin" ) type UserLoginForm struct { Email string Password string } // Validate : 验证函数 func (u *UserLoginForm) Validate() (errors []string) { errors = requests.RunValidators( requests.ValidatorMap{ "email": { requests.RequiredValidator(u.Email), requests.MaxLengthValidator(u.Email, 255), requests.EmailValidator(u.Email), }, "password": { requests.RequiredValidator(u.Password), }, }, requests.ValidatorMsgArr{ "email": { "邮箱不能为空", "邮箱长度不能大于 255 个字符", "邮箱格式错误", }, "password": { "密码不能为空", }, }, ) return errors } // ValidateAndLogin 验证参数并且获取用户 func (u *UserLoginForm) ValidateAndGetUser(c *gin.Context) (user *userModel.User, errors []string) { errors = u.Validate() if len(errors) != 0 { fmt.Println(errors) return nil, errors } // 通过邮箱获取用户,并且判断密码是否正确 user, err := userModel.GetByEmail(u.Email) fmt.Println(user) if err != nil { errors = append(errors, "该邮箱没有注册过用户: "+err.Error()) return nil, errors } if err := user.Compare(u.Password); err != nil { flash.NewDangerFlash(c, "很抱歉,您的邮箱和密码不匹配") return nil, errors } return user, []string{} }
package utils import ( "bytes" "crypto/aes" "crypto/cipher" "crypto/sha1" "encoding/base64" "encoding/binary" "encoding/json" "encoding/xml" "fmt" "io" "io/ioutil" "log" "math/rand" "net/http" "sort" "strings" "time" ) type WXAccessToken struct { ErrorCode int `json:"errorcode"` Errmsg string `json:"errmsg"` AccessToken string `json:"access_token"` ExpiresIn int `json:"expires_in"` } type BaiDuAccessToken struct { AccessToken string `json:"access_token"` ExpiresIn uint32 `json:"expires_in"` RefreshToken string `json:"refresh_token"` Scope string `json:"scope"` SessionKey string `json:"session_key"` SessionSecret string `json:"session_secret"` } type MSG struct { XMLName xml.Name `xml:"xml"` ToUserName string `xml:"ToUserName,CDATA"` Encrypt string `xml:"Encrypt,CDATA"` AgentID string `xml:"AgentID,CDATA"` MsgType string `xml:"MsgType,CDATA"` MediaId string `xml:"MediaId,CDATA"` Content string `xml:"Content,CDATA"` Format string `xml:"Format,CDATA"` MsgSignature string Timestamp string Nonce string EchoStr string } type BaiDuVoice struct { Format string `json:"format"` Rate int `json:"rate"` Channel int `json:"channel"` Cuid string `json:"cuid"` DevPid int `json:"dev_pid"` Token string `json:"token"` Speech string `json:"speech"` Len int `json:"len"` } type BaiDuVoiceResult struct { ErrNo int `json:"err_no"` ErrMsg string `json:"err_msg"` CorpusNo string `json:"corpus_no"` SN string `json:"sn"` Result []string `json:"result"` } func (msg *MSG) CheckErr(err error) { if err != nil { log.Printf("error is: %v", err) } } func (msg *MSG) PKCS7Padding(ciphertext []byte, blockSize int) []byte { padding := blockSize - len(ciphertext)%blockSize padtext := bytes.Repeat([]byte{byte(padding)}, padding) return append(ciphertext, padtext...) } func (msg *MSG) DecryptStr(str string, key string) []byte { aeskey, err := base64.StdEncoding.DecodeString(key + "=") msg.CheckErr(err) iv := aeskey[:16] tmpstr, err := base64.StdEncoding.DecodeString(str) block, err := aes.NewCipher(aeskey) msg.CheckErr(err) blockSize := block.BlockSize() blockMode := cipher.NewCBCDecrypter(block, iv) origData := make([]byte, len(tmpstr)) blockMode.CryptBlocks(origData, []byte(tmpstr)) origData = msg.PKCS7Padding(origData, blockSize) content := origData[16:] msg_len := binary.BigEndian.Uint32(content[:4]) return content[4 : msg_len+4] } func (msg *MSG) EncryptStr(str string, key string) []byte { aeskey, err := base64.StdEncoding.DecodeString(key + "=") msg.CheckErr(err) iv := aeskey[:16] block, err := aes.NewCipher(aeskey) msg.CheckErr(err) blockSize := block.BlockSize() pad_msg := msg.PKCS7Padding([]byte(str), blockSize) blockMode := cipher.NewCBCEncrypter(block, iv) origData := make([]byte, len(pad_msg)) blockMode.CryptBlocks(origData, pad_msg) base64_msg := make([]byte, base64.StdEncoding.EncodedLen(len(origData))) base64.StdEncoding.Encode(base64_msg, origData) return base64_msg } func (msg *MSG) MakeMsgSignature(token string) string { h := sha1.New() keys := make([]string, 10) keys = append(keys, token) keys = append(keys, msg.Timestamp) keys = append(keys, msg.Nonce) keys = append(keys, msg.EchoStr) keys = append(keys, msg.Encrypt) sort.Strings(keys) check_str := strings.Join(keys, "") io.WriteString(h, check_str) res := h.Sum(nil) return fmt.Sprintf("%x", res) } func (msg *MSG) MakeTimestampNonce() (int64, uint64) { timestamp := time.Now().Unix() rand.Seed(timestamp) nonce := rand.Uint64() return timestamp, nonce } func (msg *MSG) MakeGarbleByte(basestr string) []byte { var buf = make([]byte, 4) randbyte := msg.GetRandomString(16) pandbyte := msg.GetRandomString(10) msg_len := len(basestr) binary.BigEndian.PutUint32(buf, uint32(msg_len)) tmp_bytesarray := [][]byte{randbyte, buf, []byte(basestr), pandbyte} return bytes.Join(tmp_bytesarray, []byte("")) } func (msg *MSG) GetRandomString(maxlen uint32) []byte { str := "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" bytes_str := []byte(str) result := []byte{} r := rand.New(rand.NewSource(time.Now().UnixNano())) for i := uint32(0); i < maxlen; i++ { result = append(result, bytes_str[r.Intn(len(bytes_str))]) } return result } func (msg *MSG) CreateMessage(secretkey string) []byte { randomstr_16 := msg.GetRandomString(16) msg_str_len := len([]byte(secretkey)) var buf = make([]byte, 8) binary.BigEndian.PutUint32(buf, uint32(msg_str_len)) msg_str := fmt.Sprintf("%s%d%s", randomstr_16, buf, secretkey) return []byte(msg_str) } func (msg *MSG) Verify(token string) bool { tmpstr := msg.MakeMsgSignature(token) if strings.Compare(msg.MsgSignature, tmpstr) == 0 { return true } return false } func GetWXAccessToken(access_token_resp *WXAccessToken, corpid string, corpsecret string) { wx_access_tokey := "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=" + corpid + "&&corpsecret=" + corpsecret for { resp, err := http.Get(wx_access_tokey) if err != nil { log.Println(err) } defer resp.Body.Close() body, _ := ioutil.ReadAll(resp.Body) json.Unmarshal(body, access_token_resp) if access_token_resp.ErrorCode != 0 { log.Println(access_token_resp.Errmsg) } time.Sleep(time.Duration(access_token_resp.ExpiresIn-100) * time.Second) } } func GetBaiDuYuYingAccessToken(access_token_resp *BaiDuAccessToken, apikey string, secretkey string) { baidu_oauth := fmt.Sprintf("https://openapi.baidu.com/oauth/2.0/token?grant_type=client_credentials&client_id=%s&client_secret=%s", apikey, secretkey) for { resp, err := http.Get(baidu_oauth) if err != nil { log.Println(err) } defer resp.Body.Close() body, _ := ioutil.ReadAll(resp.Body) json.Unmarshal(body, access_token_resp) time.Sleep(time.Duration(access_token_resp.ExpiresIn-100) * time.Second) } } func GetWXVoiceBody(wxtoken string, wxmediaid string) (string, int) { wx_media_url := fmt.Sprintf("https://qyapi.weixin.qq.com/cgi-bin/media/get?access_token=%s&media_id=%s", wxtoken, wxmediaid) resp, err := http.Get(wx_media_url) if err != nil { log.Println(err) } defer resp.Body.Close() body, _ := ioutil.ReadAll(resp.Body) return base64.StdEncoding.EncodeToString(body), len(body) } func GetBaiduVoiceResult(voice *BaiDuVoice) BaiDuVoiceResult { var result BaiDuVoiceResult post_data, err := json.Marshal(voice) if err != nil { log.Println(err) } resp, err := http.Post("http://vop.baidu.com/server_api", "application/json", bytes.NewReader(post_data)) if err != nil { log.Println(err) } defer resp.Body.Close() body, _ := ioutil.ReadAll(resp.Body) err = json.Unmarshal(body, &result) if err != nil { log.Println(err) } return result }
package main import ( "fmt" "time" ) func printText() { for i:=0; i<5; i++ { fmt.Println("text", i) time.Sleep(500 * time.Millisecond) } } func printNumber() { for i:=0; i<5; i++ { fmt.Println(i) time.Sleep(200 * time.Millisecond) } } func main() { start := time.Now() go printNumber() go printText() time.Sleep(3000 * time.Millisecond) fmt.Println(time.Since(start)) }
// Copyright 2020 The VectorSQL Authors. // // Code is licensed under Apache License, Version 2.0. package xlog import ( "testing" ) func Assert(tb testing.TB, condition bool, msg string, v ...interface{}) { if !condition { tb.FailNow() } } func TestGetLog(t *testing.T) { GetLog().Debug("DEBUG") log := NewStdLog() log.SetLevel("INFO") GetLog().Debug("DEBUG") GetLog().Info("INFO") } func TestStdLog(t *testing.T) { log := NewStdLog() log.Println("........DEFAULT........") log.Debug("DEBUG") log.Info("INFO") log.Warning("WARNING") log.Error("ERROR") log.Println("........DEBUG........") log.SetLevel("DEBUG") log.Debug("DEBUG") log.Info("INFO") log.Warning("WARNING") log.Error("ERROR") log.Println("........INFO........") log.SetLevel("INFO") log.Debug("DEBUG") log.Info("INFO") log.Warning("WARNING") log.Error("ERROR") log.Println("........WARNING........") log.SetLevel("WARNING") log.Debug("DEBUG") log.Info("INFO") log.Warning("WARNING") log.Error("ERROR") log.Println("........ERROR........") log.SetLevel("ERROR") log.Debug("DEBUG") log.Info("INFO") log.Warning("WARNING") log.Error("ERROR") } func TestLogLevel(t *testing.T) { log := NewStdLog() { log.SetLevel("DEBUG") want := DEBUG got := log.opts.Level Assert(t, want == got, "want[%v]!=got[%v]", want, got) } { log.SetLevel("DEBUGX") want := DEBUG got := log.opts.Level Assert(t, want == got, "want[%v]!=got[%v]", want, got) } { log.SetLevel("PANIC") want := PANIC got := log.opts.Level Assert(t, want == got, "want[%v]!=got[%v]", want, got) } { log.SetLevel("WARNING") want := WARNING got := log.opts.Level Assert(t, want == got, "want[%v]!=got[%v]", want, got) } }
package util import ( "fmt" "reflect" "strings" "time" "github.com/appscode/go/log" "github.com/appscode/go/types" snapshot_cs "github.com/kubernetes-csi/external-snapshotter/pkg/client/clientset/versioned" core "k8s.io/api/core/v1" kerr "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/util/wait" "k8s.io/client-go/kubernetes" core_util "kmodules.xyz/client-go/core/v1" "kmodules.xyz/client-go/meta" store "kmodules.xyz/objectstore-api/api/v1" oc_cs "kmodules.xyz/openshift/client/clientset/versioned" wapi "kmodules.xyz/webhook-runtime/apis/workload/v1" "stash.appscode.dev/stash/apis" api "stash.appscode.dev/stash/apis/stash/v1alpha1" v1beta1_api "stash.appscode.dev/stash/apis/stash/v1beta1" ) const ( StashContainer = "stash" StashInitContainer = "stash-init" LocalVolumeName = "stash-local" ScratchDirVolumeName = "stash-scratchdir" TmpDirVolumeName = "tmp-dir" TmpDirMountPath = "/tmp" PodinfoVolumeName = "stash-podinfo" RecoveryJobPrefix = "stash-recovery-" ScaledownCronPrefix = "stash-scaledown-cron-" CheckJobPrefix = "stash-check-" AnnotationRestic = "restic" AnnotationRecovery = "recovery" AnnotationOperation = "operation" AnnotationOldReplica = "old-replica" OperationRecovery = "recovery" OperationCheck = "check" AppLabelStash = "stash" AppLabelStashV1Beta1 = "stash-v1beta1" OperationScaleDown = "scale-down" RepositoryFinalizer = "stash" SnapshotIDLength = 8 ModelSidecar = "sidecar" ModelCronJob = "cronjob" LabelApp = "app" LabelBackupConfiguration = "backup-configuration" StashSecretVolume = "stash-secret-volume" StashSecretMountDir = "/etc/stash/repository/secret" KeyPodName = "POD_NAME" KeyNodeName = "NODE_NAME" RetryInterval = 50 * time.Millisecond ReadinessTimeout = 2 * time.Minute ) func IsBackupTarget(target *v1beta1_api.BackupTarget, w *wapi.Workload) bool { if target != nil && target.Ref.APIVersion == w.APIVersion && target.Ref.Kind == w.Kind && target.Ref.Name == w.Name { return true } return false } func IsRestoreTarget(target *v1beta1_api.RestoreTarget, w *wapi.Workload) bool { if target != nil && target.Ref.APIVersion == w.APIVersion && target.Ref.Kind == w.Kind && target.Ref.Name == w.Name { return true } return false } func GetString(m map[string]string, key string) string { if m == nil { return "" } return m[key] } func UpsertScratchVolume(volumes []core.Volume) []core.Volume { return core_util.UpsertVolume(volumes, core.Volume{ Name: ScratchDirVolumeName, VolumeSource: core.VolumeSource{ EmptyDir: &core.EmptyDirVolumeSource{}, }, }) } func UpsertTmpVolume(volumes []core.Volume, settings v1beta1_api.EmptyDirSettings) []core.Volume { return core_util.UpsertVolume(volumes, core.Volume{ Name: TmpDirVolumeName, VolumeSource: core.VolumeSource{ EmptyDir: &core.EmptyDirVolumeSource{ Medium: settings.Medium, SizeLimit: settings.SizeLimit, }, }, }) } func UpsertTmpVolumeMount(volumeMounts []core.VolumeMount) []core.VolumeMount { return core_util.UpsertVolumeMountByPath(volumeMounts, core.VolumeMount{ Name: TmpDirVolumeName, MountPath: TmpDirMountPath, }) } // https://kubernetes.io/docs/tasks/inject-data-application/downward-api-volume-expose-pod-information/#store-pod-fields func UpsertDownwardVolume(volumes []core.Volume) []core.Volume { return core_util.UpsertVolume(volumes, core.Volume{ Name: PodinfoVolumeName, VolumeSource: core.VolumeSource{ DownwardAPI: &core.DownwardAPIVolumeSource{ Items: []core.DownwardAPIVolumeFile{ { Path: "labels", FieldRef: &core.ObjectFieldSelector{ FieldPath: "metadata.labels", }, }, }, }, }, }) } func UpsertSecretVolume(volumes []core.Volume, secretName string) []core.Volume { return core_util.UpsertVolume(volumes, core.Volume{ Name: StashSecretVolume, VolumeSource: core.VolumeSource{ Secret: &core.SecretVolumeSource{ SecretName: secretName, }, }, }) } // UpsertSecurityContext update current SecurityContext with new SecurityContext. // If a field is not present in the new SecurityContext, value of the current SecurityContext for this field will be used. func UpsertSecurityContext(currentSC, newSC *core.SecurityContext) *core.SecurityContext { if newSC == nil { return currentSC } var finalSC *core.SecurityContext if currentSC == nil { finalSC = &core.SecurityContext{} } else { finalSC = currentSC.DeepCopy() } if newSC.Capabilities != nil { finalSC.Capabilities = newSC.Capabilities } if newSC.Privileged != nil { finalSC.Privileged = newSC.Privileged } if newSC.SELinuxOptions != nil { finalSC.SELinuxOptions = newSC.SELinuxOptions } if newSC.RunAsUser != nil { finalSC.RunAsUser = newSC.RunAsUser } if newSC.RunAsGroup != nil { finalSC.RunAsGroup = newSC.RunAsGroup } if newSC.RunAsNonRoot != nil { finalSC.RunAsNonRoot = newSC.RunAsNonRoot } if newSC.ReadOnlyRootFilesystem != nil { finalSC.ReadOnlyRootFilesystem = newSC.ReadOnlyRootFilesystem } if newSC.AllowPrivilegeEscalation != nil { finalSC.AllowPrivilegeEscalation = newSC.AllowPrivilegeEscalation } if newSC.ProcMount != nil { finalSC.ProcMount = newSC.ProcMount } return finalSC } // UpsertPodSecurityContext update current SecurityContext with new SecurityContext. // If a field is not present in the new SecurityContext, value of the current SecurityContext for this field will be used. func UpsertPodSecurityContext(currentSC, newSC *core.PodSecurityContext) *core.PodSecurityContext { if newSC == nil { return currentSC } var finalSC *core.PodSecurityContext if currentSC == nil { finalSC = &core.PodSecurityContext{} } else { finalSC = currentSC.DeepCopy() } if newSC.SELinuxOptions != nil { finalSC.SELinuxOptions = newSC.SELinuxOptions } if newSC.RunAsUser != nil { finalSC.RunAsUser = newSC.RunAsUser } if newSC.RunAsGroup != nil { finalSC.RunAsGroup = newSC.RunAsGroup } if newSC.RunAsNonRoot != nil { finalSC.RunAsNonRoot = newSC.RunAsNonRoot } if newSC.SupplementalGroups != nil { finalSC.SupplementalGroups = newSC.SupplementalGroups } if newSC.FSGroup != nil { finalSC.FSGroup = newSC.FSGroup } if newSC.Sysctls != nil { finalSC.Sysctls = newSC.Sysctls } return finalSC } func MergeLocalVolume(volumes []core.Volume, backend *store.Backend) []core.Volume { // check if stash-local volume already exist oldPos := -1 for i, vol := range volumes { if vol.Name == LocalVolumeName { oldPos = i break } } if backend != nil && backend.Local != nil { // backend is local backend. we have to mount the local volume inside sidecar vol, _ := backend.Local.ToVolumeAndMount(LocalVolumeName) if oldPos != -1 { volumes[oldPos] = vol } else { volumes = core_util.UpsertVolume(volumes, vol) } } else { // backend is not local backend. we have to remove stash-local volume if we had mounted before if oldPos != -1 { volumes = append(volumes[:oldPos], volumes[oldPos+1:]...) } } return volumes } func EnsureVolumeDeleted(volumes []core.Volume, name string) []core.Volume { for i, v := range volumes { if v.Name == name { return append(volumes[:i], volumes[i+1:]...) } } return volumes } func RecoveryEqual(old, new *api.Recovery) bool { var oldSpec, newSpec *api.RecoverySpec if old != nil { oldSpec = &old.Spec } if new != nil { newSpec = &new.Spec } return reflect.DeepEqual(oldSpec, newSpec) } func WorkloadExists(k8sClient kubernetes.Interface, namespace string, workload api.LocalTypedReference) error { if err := workload.Canonicalize(); err != nil { return err } switch workload.Kind { case apis.KindDeployment: _, err := k8sClient.AppsV1().Deployments(namespace).Get(workload.Name, metav1.GetOptions{}) return err case apis.KindReplicaSet: _, err := k8sClient.AppsV1().ReplicaSets(namespace).Get(workload.Name, metav1.GetOptions{}) return err case apis.KindReplicationController: _, err := k8sClient.CoreV1().ReplicationControllers(namespace).Get(workload.Name, metav1.GetOptions{}) return err case apis.KindStatefulSet: _, err := k8sClient.AppsV1().StatefulSets(namespace).Get(workload.Name, metav1.GetOptions{}) return err case apis.KindDaemonSet: _, err := k8sClient.AppsV1().DaemonSets(namespace).Get(workload.Name, metav1.GetOptions{}) return err default: return fmt.Errorf(`unrecognized workload "Kind" %v`, workload.Kind) } } func GetConfigmapLockName(workload api.LocalTypedReference) string { return strings.ToLower(fmt.Sprintf("lock-%s-%s", workload.Kind, workload.Name)) } func GetBackupConfigmapLockName(r v1beta1_api.TargetRef) string { return strings.ToLower(fmt.Sprintf("lock-%s-%s-backup", r.Kind, r.Name)) } func GetRestoreConfigmapLockName(r v1beta1_api.TargetRef) string { return strings.ToLower(fmt.Sprintf("lock-%s-%s-restore", r.Kind, r.Name)) } func DeleteConfigmapLock(k8sClient kubernetes.Interface, namespace string, workload api.LocalTypedReference) error { return k8sClient.CoreV1().ConfigMaps(namespace).Delete(GetConfigmapLockName(workload), &metav1.DeleteOptions{}) } func DeleteBackupConfigMapLock(k8sClient kubernetes.Interface, namespace string, r v1beta1_api.TargetRef) error { return k8sClient.CoreV1().ConfigMaps(namespace).Delete(GetBackupConfigmapLockName(r), &metav1.DeleteOptions{}) } func DeleteRestoreConfigMapLock(k8sClient kubernetes.Interface, namespace string, r v1beta1_api.TargetRef) error { return k8sClient.CoreV1().ConfigMaps(namespace).Delete(GetRestoreConfigmapLockName(r), &metav1.DeleteOptions{}) } func DeleteAllConfigMapLocks(k8sClient kubernetes.Interface, namespace, name, kind string) error { // delete backup configMap lock if exist err := DeleteBackupConfigMapLock(k8sClient, namespace, v1beta1_api.TargetRef{Name: name, Kind: kind}) if err != nil && !kerr.IsNotFound(err) { return err } // delete restore configMap lock if exist err = DeleteRestoreConfigMapLock(k8sClient, namespace, v1beta1_api.TargetRef{Name: name, Kind: kind}) if err != nil && !kerr.IsNotFound(err) { return err } // backward compatibility err = DeleteConfigmapLock(k8sClient, namespace, api.LocalTypedReference{Kind: kind, Name: name}) if err != nil && !kerr.IsNotFound(err) { return err } return nil } func WorkloadReplicas(kubeClient *kubernetes.Clientset, namespace string, workloadKind string, workloadName string) (int32, error) { switch workloadKind { case apis.KindDeployment: obj, err := kubeClient.AppsV1().Deployments(namespace).Get(workloadName, metav1.GetOptions{}) if err != nil { return 0, err } else { return *obj.Spec.Replicas, nil } case apis.KindReplicationController: obj, err := kubeClient.CoreV1().ReplicationControllers(namespace).Get(workloadName, metav1.GetOptions{}) if err != nil { return 0, err } else { return *obj.Spec.Replicas, nil } case apis.KindReplicaSet: obj, err := kubeClient.AppsV1().ReplicaSets(namespace).Get(workloadName, metav1.GetOptions{}) if err != nil { return 0, err } else { return *obj.Spec.Replicas, nil } default: return 0, fmt.Errorf("unknown workload type") } } func HasOldReplicaAnnotation(k8sClient *kubernetes.Clientset, namespace string, workload api.LocalTypedReference) bool { var workloadAnnotation map[string]string switch workload.Kind { case apis.KindDeployment: obj, err := k8sClient.AppsV1().Deployments(namespace).Get(workload.Name, metav1.GetOptions{}) if err != nil { log.Fatalln(err) } workloadAnnotation = obj.Annotations case apis.KindReplicationController: obj, err := k8sClient.CoreV1().ReplicationControllers(namespace).Get(workload.Name, metav1.GetOptions{}) if err != nil { log.Fatalln(err) } workloadAnnotation = obj.Annotations case apis.KindReplicaSet: obj, err := k8sClient.AppsV1().ReplicaSets(namespace).Get(workload.Name, metav1.GetOptions{}) if err != nil { log.Fatalln(err) } workloadAnnotation = obj.Annotations case apis.KindStatefulSet: // do nothing. we didn't scale down. case apis.KindDaemonSet: // do nothing. default: return false } return meta.HasKey(workloadAnnotation, AnnotationOldReplica) } func WaitUntilDeploymentReady(c kubernetes.Interface, meta metav1.ObjectMeta) error { return wait.PollImmediate(RetryInterval, ReadinessTimeout, func() (bool, error) { if obj, err := c.AppsV1().Deployments(meta.Namespace).Get(meta.Name, metav1.GetOptions{}); err == nil { return types.Int32(obj.Spec.Replicas) == obj.Status.ReadyReplicas, nil } return false, nil }) } func WaitUntilDaemonSetReady(kubeClient kubernetes.Interface, meta metav1.ObjectMeta) error { return wait.PollImmediate(RetryInterval, ReadinessTimeout, func() (bool, error) { if obj, err := kubeClient.AppsV1().DaemonSets(meta.Namespace).Get(meta.Name, metav1.GetOptions{}); err == nil { return obj.Status.DesiredNumberScheduled == obj.Status.NumberReady, nil } return false, nil }) } func WaitUntilReplicaSetReady(c kubernetes.Interface, meta metav1.ObjectMeta) error { return wait.PollImmediate(RetryInterval, ReadinessTimeout, func() (bool, error) { if obj, err := c.AppsV1().ReplicaSets(meta.Namespace).Get(meta.Name, metav1.GetOptions{}); err == nil { return types.Int32(obj.Spec.Replicas) == obj.Status.ReadyReplicas, nil } return false, nil }) } func WaitUntilRCReady(c kubernetes.Interface, meta metav1.ObjectMeta) error { return wait.PollImmediate(RetryInterval, ReadinessTimeout, func() (bool, error) { if obj, err := c.CoreV1().ReplicationControllers(meta.Namespace).Get(meta.Name, metav1.GetOptions{}); err == nil { return types.Int32(obj.Spec.Replicas) == obj.Status.ReadyReplicas, nil } return false, nil }) } func WaitUntilStatefulSetReady(kubeClient kubernetes.Interface, meta metav1.ObjectMeta) error { return wait.PollImmediate(RetryInterval, ReadinessTimeout, func() (bool, error) { if obj, err := kubeClient.AppsV1().StatefulSets(meta.Namespace).Get(meta.Name, metav1.GetOptions{}); err == nil { return types.Int32(obj.Spec.Replicas) == obj.Status.ReadyReplicas, nil } return false, nil }) } func WaitUntilDeploymentConfigReady(c oc_cs.Interface, meta metav1.ObjectMeta) error { return wait.PollImmediate(RetryInterval, ReadinessTimeout, func() (bool, error) { if obj, err := c.AppsV1().DeploymentConfigs(meta.Namespace).Get(meta.Name, metav1.GetOptions{}); err == nil { return obj.Spec.Replicas == obj.Status.ReadyReplicas, nil } return false, nil }) } func WaitUntilVolumeSnapshotReady(c snapshot_cs.Interface, meta metav1.ObjectMeta) error { return wait.PollImmediate(RetryInterval, 2*time.Hour, func() (bool, error) { if obj, err := c.VolumesnapshotV1alpha1().VolumeSnapshots(meta.Namespace).Get(meta.Name, metav1.GetOptions{}); err == nil { return obj.Status.ReadyToUse == true, nil } return false, nil }) } func WaitUntilPVCReady(c kubernetes.Interface, meta metav1.ObjectMeta) error { return wait.PollImmediate(RetryInterval, 2*time.Hour, func() (bool, error) { if obj, err := c.CoreV1().PersistentVolumeClaims(meta.Namespace).Get(meta.Name, metav1.GetOptions{}); err == nil { return obj.Status.Phase == core.ClaimBound, nil } return false, nil }) }
package tun2socks import ( "log" "net" "os" "os/signal" "syscall" "github.com/FlowerWrong/tun2socks/configure" "github.com/FlowerWrong/tun2socks/util" ) func (app *App) SignalHandler() *App { // signal handler c := make(chan os.Signal) signal.Notify(c, syscall.SIGHUP, syscall.SIGINT, syscall.SIGTERM, syscall.SIGQUIT, syscall.SIGUSR1, syscall.SIGUSR2) go func(app *App) { for s := range c { switch s { case syscall.SIGHUP, syscall.SIGINT, syscall.SIGTERM, syscall.SIGQUIT: log.Println("Exit", s) util.Exit() case syscall.SIGUSR1: log.Println("Usr1", s) case syscall.SIGUSR2: log.Println("Usr2", s) // parse config file := app.Cfg.File app.Cfg = new(configure.AppConfig) err := app.Cfg.Parse(file) if err != nil { log.Fatal("Get default proxy failed", err) } if app.Cfg.DNS.DNSMode == "fake" { app.FakeDNS.RulePtr.Reload(app.Cfg.Rule, app.Cfg.Pattern) var ip, subnet, _ = net.ParseCIDR(app.Cfg.General.Network) app.FakeDNS.DNSTablePtr.Reload(ip, subnet) } app.Proxies.Reload(app.Cfg.Proxy) log.Println("Routes hot reloaded") app.AddRoutes() break default: log.Println("Other", s) } } }(app) return app }
// Unless explicitly stated otherwise all files in this repository are licensed // under the Apache License Version 2.0. // This product includes software developed at Datadog (https://www.datadoghq.com/). // Copyright 2016-present Datadog, Inc. package override import ( "testing" "github.com/DataDog/datadog-operator/apis/datadoghq/v2alpha1" apiutils "github.com/DataDog/datadog-operator/apis/utils" "github.com/stretchr/testify/assert" v1 "k8s.io/api/apps/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" ) func TestDeployment(t *testing.T) { deployment := v1.Deployment{ ObjectMeta: metav1.ObjectMeta{ Name: "current-name", }, Spec: v1.DeploymentSpec{ Replicas: apiutils.NewInt32Pointer(1), }, } override := v2alpha1.DatadogAgentComponentOverride{ Name: apiutils.NewStringPointer("new-name"), Replicas: apiutils.NewInt32Pointer(2), } Deployment(&deployment, &override) assert.Equal(t, "new-name", deployment.Name) assert.Equal(t, int32(2), *deployment.Spec.Replicas) }
package main import exam "gitee.com/erdanli/ipproxypool/internal/examination" func main() { // avaliableProxyIP, _ := exam.TestJiangXianLi() // _, _, result := storage.MangoDB() exam.DeleteUnavailableProxyIP() }
package metrics import ( "net/url" "github.com/cerana/cerana/acomm" "github.com/cerana/cerana/pkg/errors" "github.com/shirou/gopsutil/mem" ) // MemoryResult is the result for the Memory handler. type MemoryResult struct { Swap *mem.SwapMemoryStat `json:"swap"` Virtual *mem.VirtualMemoryStat `json:"virtual"` } // Memory returns information about the virtual and swap memory. func (m *Metrics) Memory(req *acomm.Request) (interface{}, *url.URL, error) { swap, err := mem.SwapMemory() if err != nil { return nil, nil, errors.Wrap(err) } virtual, err := mem.VirtualMemory() if err != nil { return nil, nil, errors.Wrap(err) } return &MemoryResult{Swap: swap, Virtual: virtual}, nil, nil }
// Copyright 2021 The ChromiumOS Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package network import ( "context" "time" "github.com/golang/protobuf/ptypes/empty" "chromiumos/tast/common/network/diag" "chromiumos/tast/errors" "chromiumos/tast/remote/wificell" "chromiumos/tast/remote/wificell/hostapd" "chromiumos/tast/rpc" "chromiumos/tast/services/cros/network" "chromiumos/tast/testing" ) func init() { testing.AddTest(&testing.Test{ Func: DiagSignalStrength, LacrosStatus: testing.LacrosVariantNeeded, Desc: "Tests that the WiFi signal strength network diagnostic routine reports the correct verdict if the signal strength is both attenuated and unattenuated", Contacts: []string{ "khegde@chromium.org", // test maintainer "cros-network-health@google.com", // network-health team }, ServiceDeps: []string{wificell.TFServiceName, "tast.cros.network.NetDiagService"}, SoftwareDeps: []string{"chrome"}, Attr: []string{"group:wificell_roam", "wificell_roam_perf"}, Fixture: "wificellFixtRoaming", Timeout: time.Minute * 2, }) } // DiagSignalStrength tests that when the WiFi signal is unattenuated, the WiFi // signal strength network diagnostics routine passes, and when the signal is // attenuated, the routine fails. func DiagSignalStrength(ctx context.Context, s *testing.State) { var apOpts = []hostapd.Option{ hostapd.Mode(hostapd.Mode80211nPure), hostapd.Channel(1), hostapd.HTCaps(hostapd.HTCapHT20), hostapd.SSID(hostapd.RandomSSID("TAST_SIGNAL_STRENGTH_")), } tf := s.FixtValue().(*wificell.TestFixture) ap, err := tf.ConfigureAP(ctx, apOpts, nil) if err != nil { s.Fatal("Failed to configure AP: ", err) } defer tf.DeconfigAP(ctx, ap) ctx, cancel := tf.ReserveForDeconfigAP(ctx, ap) defer cancel() attenuator := tf.Attenuator() setAttenuation := func(attenDb float64) error { // Loop through all attenuator channels (tx/rx for two access points). for c := 0; c <= 3; c++ { if err := attenuator.SetAttenuation(ctx, c, attenDb); err != nil { return err } } return nil } // Set attenuator to minimum value and test that the signal strength is strong. if err := setAttenuation(0); err != nil { s.Fatal("Failed to set minimum attenuation: ", err) } if _, err := tf.ConnectWifiAP(ctx, ap); err != nil { s.Fatal("Failed to connect to the WiFi AP: ", err) } defer tf.CleanDisconnectWifi(ctx) ctx, cancel = tf.ReserveForDisconnect(ctx) defer cancel() if err := tf.VerifyConnection(ctx, ap); err != nil { s.Fatal("Failed to verify connection: ", err) } cl, err := rpc.Dial(ctx, s.DUT(), s.RPCHint()) if err != nil { s.Fatal("Failed to connect to the RPC service on the DUT: ", err) } di := network.NewNetDiagServiceClient(cl.Conn) _, err = di.SetupDiagAPI(ctx, &empty.Empty{}) if err != nil { s.Fatal("Failed to setup diag API: ", err) } runAndValidateRoutine := func(expectedResult *diag.RoutineResult) error { req := &network.RunRoutineRequest{ Routine: diag.RoutineSignalStrength, } res, err := di.RunRoutine(ctx, req) if err != nil { s.Fatal("Failed to run diag routine: ", err) } result := &diag.RoutineResult{ Verdict: diag.RoutineVerdict(res.Verdict), Problems: res.Problems, } if err := diag.CheckRoutineResult(result, expectedResult); err != nil { return errors.Wrap(err, "routine result did not match") } return nil } // The routine is expected to pass with no attenuation. expectedResult := &diag.RoutineResult{ Verdict: diag.VerdictNoProblem, Problems: []uint32{}, } if err := runAndValidateRoutine(expectedResult); err != nil { s.Fatal("Failed to run and validate routine with no attenuation: ", err) } // Reset the attenuator to ensure the networks are available for the next // tests. // TODO(http://b/188068031): remove when handled by the fixture. defer func() { if err := setAttenuation(0); err != nil { s.Log("Failed to set minimum attenuation: ", err) } }() // Attenuate the signal with each poll request. This should still leave the // network connected, but with a weak signal. weakConnectionAttenuationDb := 60.0 const problemWeakSignal = 0 expectedResult = &diag.RoutineResult{ Verdict: diag.VerdictProblem, Problems: []uint32{problemWeakSignal}, } if err := testing.Poll(ctx, func(ctx context.Context) error { if err := setAttenuation(weakConnectionAttenuationDb); err != nil { s.Fatal("Failed to attenuate connection: ", err) } weakConnectionAttenuationDb = weakConnectionAttenuationDb + 0.5 if err := runAndValidateRoutine(expectedResult); err != nil { return err } return nil }, &testing.PollOptions{Timeout: 20 * time.Second}); err != nil { s.Fatal("Timeout waiting for routine to have expected results with attenuation: ", err) } }
package api import ( "encoding/json" "net/http" "github.com/adi/sketo/db" ) func alive(acpDB *db.DB) func(rw http.ResponseWriter, r *http.Request) { return func(rw http.ResponseWriter, r *http.Request) { rw.Header().Add("Content-Type", "application/json") jsonEnc := json.NewEncoder(rw) rw.WriteHeader(200) err := jsonEnc.Encode(healthStatus{ Status: "ok", }) // Alternative return for future use: // rw.WriteHeader(500) if err != nil { rw.WriteHeader(500) rw.Write([]byte("Server error\n")) return } } } func ready(acpDB *db.DB) func(rw http.ResponseWriter, r *http.Request) { return func(rw http.ResponseWriter, r *http.Request) { rw.Header().Add("Content-Type", "application/json") jsonEnc := json.NewEncoder(rw) rw.WriteHeader(200) err := jsonEnc.Encode(healthStatus{ Status: "ok", }) // Alternative return for future use: // rw.WriteHeader(503) // err := jsonEnc.Encode(healthNotReadyStatus{ // Errors: map[string]string{ // "database": "Unreachable", // }, // }) if err != nil { rw.WriteHeader(500) rw.Write([]byte("Server error\n")) return } } }
package bank1 var deposits = make(chan int) // send amount to deposits var balances = make(chan int) // receive balane var withdrawRes = make(chan bool) var withdraw = make(chan withdrawMes) // send amount to withdraw type withdrawMes struct { ch chan bool amount int } func Deposit(amount int) { deposits <- amount } func Balance() int { return <-balances } func Withdraw(amount int) bool { ch := make(chan bool) withdraw <- withdrawMes{ch: ch, amount: amount} return <-ch } func teller() { var balance int // balance is confined to teller goroutine for { select { case amount := <-deposits: balance += amount case m := <-withdraw: if m.amount > balance { m.ch <- false continue } balance -= m.amount m.ch <- true case balances <- balance: } } } func init() { go teller() }
package model type harbors map[string]Harbor // Harbor is a Catan harbor, consisting out of a simple name, and the resource it has the trade benefit for type Harbor struct { Name string Resource } var ( HarborGrain = &Harbor{Name: "2:1 Grain", Resource: *Grain} HarborBrick = &Harbor{Name: "2:1 Brick", Resource: *Brick} HarborOre = &Harbor{Name: "2:1 Ore", Resource: *Ore} HarborWool = &Harbor{Name: "2:1 Wool", Resource: *Wool} HarborLumber = &Harbor{Name: "2:1 Lumber", Resource: *Lumber} HarborAll = &Harbor{Name: "3:1", Resource: *All} HarborNone = &Harbor{Name: "None", Resource: *None} Harbors = harbors{ Grain.Code: *HarborGrain, Lumber.Code: *HarborLumber, All.Code: *HarborAll, None.Code: *HarborNone, Wool.Code: *HarborWool, Ore.Code: *HarborOre, Brick.Code: *HarborBrick, } )
// Copyright 2020 The LUCI Authors. // // 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 changelist import ( "context" "math/rand" "sync" "testing" "time" "google.golang.org/protobuf/types/known/timestamppb" "go.chromium.org/luci/common/clock/testclock" "go.chromium.org/luci/common/errors" "go.chromium.org/luci/common/logging" "go.chromium.org/luci/common/logging/gologger" gerritpb "go.chromium.org/luci/common/proto/gerrit" "go.chromium.org/luci/gae/filter/featureBreaker" "go.chromium.org/luci/gae/filter/featureBreaker/flaky" "go.chromium.org/luci/gae/filter/txndefer" "go.chromium.org/luci/gae/impl/memory" "go.chromium.org/luci/gae/service/datastore" "go.chromium.org/luci/cv/internal/common" . "github.com/smartystreets/goconvey/convey" . "go.chromium.org/luci/common/testing/assertions" ) func TestCL(t *testing.T) { t.Parallel() Convey("CL", t, func() { ctx := memory.Use(context.Background()) epoch := datastore.RoundTime(testclock.TestRecentTimeUTC) ctx, _ = testclock.UseTime(ctx, testclock.TestRecentTimeUTC) eid, err := GobID("x-review.example.com", 12) So(err, ShouldBeNil) Convey("Gerrit ExternalID", func() { u, err := eid.URL() So(err, ShouldBeNil) So(u, ShouldEqual, "https://x-review.example.com/12") _, err = GobID("https://example.com", 12) So(err, ShouldErrLike, "invalid host") }) Convey("get not exists", func() { _, err := eid.Get(ctx) So(err, ShouldResemble, datastore.ErrNoSuchEntity) }) Convey("create", func() { cl, err := eid.GetOrInsert(ctx, func(cl *CL) { cl.Snapshot = makeSnapshot(epoch) }) Convey("GetOrInsert succeed", func() { So(err, ShouldBeNil) So(cl.ExternalID, ShouldResemble, eid) // ID must be autoset to non-0 value. So(cl.ID, ShouldNotEqual, 0) So(cl.EVersion, ShouldEqual, 1) So(cl.UpdateTime, ShouldResemble, epoch) }) Convey("Get exists", func() { cl2, err := eid.Get(ctx) So(err, ShouldBeNil) So(cl2.ID, ShouldEqual, cl.ID) So(cl2.ExternalID, ShouldEqual, eid) So(cl2.EVersion, ShouldEqual, 1) So(cl2.UpdateTime, ShouldEqual, cl.UpdateTime) So(cl2.Snapshot, ShouldResembleProto, cl.Snapshot) }) Convey("GetOrInsert already exists", func() { cl3, err := eid.GetOrInsert(ctx, func(cl *CL) { cl.Snapshot = &Snapshot{Patchset: 999} }) So(err, ShouldBeNil) So(cl3.ID, ShouldEqual, cl.ID) So(cl3.ExternalID, ShouldResemble, eid) So(cl3.EVersion, ShouldEqual, 1) So(cl3.UpdateTime, ShouldEqual, cl.UpdateTime) So(cl3.Snapshot, ShouldResembleProto, cl.Snapshot) }) Convey("Delete works", func() { err := Delete(ctx, cl.ID) So(err, ShouldBeNil) _, err = eid.Get(ctx) So(err, ShouldResemble, datastore.ErrNoSuchEntity) So(datastore.Get(ctx, cl), ShouldResemble, datastore.ErrNoSuchEntity) Convey("delete is now noop", func() { err := Delete(ctx, cl.ID) So(err, ShouldBeNil) }) }) }) }) } func TestExternalID(t *testing.T) { t.Parallel() Convey("ExternalID works", t, func() { Convey("GobID", func() { eid, err := GobID("x-review.example.com", 12) So(err, ShouldBeNil) So(eid, ShouldResemble, ExternalID("gerrit/x-review.example.com/12")) host, change, err := eid.ParseGobID() So(err, ShouldBeNil) So(host, ShouldResemble, "x-review.example.com") So(change, ShouldEqual, 12) }) Convey("Invalid GobID", func() { _, _, err := ExternalID("meh").ParseGobID() So(err, ShouldErrLike, "is not a valid GobID") _, _, err = ExternalID("gerrit/x/y").ParseGobID() So(err, ShouldErrLike, "is not a valid GobID") }) }) } func TestLookup(t *testing.T) { t.Parallel() Convey("Lookup works", t, func() { ctx := memory.Use(context.Background()) const n = 10 ids := make([]common.CLID, n) eids := make([]ExternalID, n) for i := range eids { eids[i] = MustGobID("x-review.example.com", int64(i+1)) if i%2 == 0 { cl, err := eids[i].GetOrInsert(ctx, func(*CL) {}) So(err, ShouldBeNil) ids[i] = cl.ID } } actual, err := Lookup(ctx, eids) So(err, ShouldBeNil) So(actual, ShouldResemble, ids) }) } func TestUpdate(t *testing.T) { t.Parallel() Convey("Update works", t, func() { epoch := testclock.TestRecentTimeUTC ctx := memory.Use(context.Background()) eid, err := GobID("x-review.example.com", 12) So(err, ShouldBeNil) Convey("new CL is created", func() { snap := makeSnapshot(epoch) acfg := makeApplicableConfig() asdep := makeDependentMeta(epoch) err := Update(ctx, eid, 0 /* unknown CLID */, UpdateFields{ Snapshot: snap, ApplicableConfig: acfg, AddDependentMeta: asdep, }, func(ctx context.Context, cl *CL) error { So(datastore.CurrentTransaction(ctx), ShouldNotBeNil) So(cl.EVersion, ShouldEqual, 1) return nil }) So(err, ShouldBeNil) cl, err := eid.Get(ctx) So(err, ShouldBeNil) So(cl.Snapshot, ShouldResembleProto, snap) So(cl.ApplicableConfig, ShouldResembleProto, acfg) So(cl.DependentMeta, ShouldResembleProto, asdep) So(cl.EVersion, ShouldEqual, 1) }) Convey("update existing", func() { acfg := makeApplicableConfig() cl, err := eid.GetOrInsert(ctx, func(cl *CL) { // no snapshot attached yet cl.ApplicableConfig = acfg cl.DependentMeta = makeDependentMeta(epoch, luciProject, "another-project") }) So(err, ShouldBeNil) snap := makeSnapshot(epoch) err = Update(ctx, eid, 0 /* unknown CLID */, UpdateFields{Snapshot: snap}, func(ctx context.Context, cl *CL) error { So(datastore.CurrentTransaction(ctx), ShouldNotBeNil) So(cl.EVersion, ShouldEqual, 2) return nil }) So(err, ShouldBeNil) cl2, err := eid.Get(ctx) So(err, ShouldBeNil) So(cl2.ID, ShouldEqual, cl.ID) So(cl2.EVersion, ShouldEqual, 2) So(cl2.Snapshot, ShouldResembleProto, snap) So(cl2.ApplicableConfig, ShouldResembleProto, makeApplicableConfig()) // 1 entry should have been removed due to matching snapshot's project. asdep := makeDependentMeta(epoch, "another-project") So(cl2.DependentMeta, ShouldResembleProto, asdep) Convey("with known CLID", func() { snap2 := makeSnapshot(epoch.Add(time.Minute)) err = Update(ctx, "" /*unspecified externalID*/, cl.ID, UpdateFields{Snapshot: snap2}, func(ctx context.Context, cl *CL) error { So(datastore.CurrentTransaction(ctx), ShouldNotBeNil) So(cl.EVersion, ShouldEqual, 3) return nil }) So(err, ShouldBeNil) cl3, err := eid.Get(ctx) So(err, ShouldBeNil) So(cl3.ID, ShouldEqual, cl.ID) So(cl3.EVersion, ShouldEqual, 3) So(cl3.Snapshot, ShouldResembleProto, snap2) So(cl3.ApplicableConfig, ShouldResembleProto, makeApplicableConfig()) So(cl3.DependentMeta, ShouldResembleProto, asdep) }) Convey("skip update if same", func() { err = Update(ctx, "", cl.ID, UpdateFields{ Snapshot: makeSnapshot(epoch.Add(-time.Minute)), ApplicableConfig: makeApplicableConfig(), AddDependentMeta: makeDependentMeta(epoch.Add(-time.Minute), "another-project"), }, func(context.Context, *CL) error { panic("must not be called") }) So(err, ShouldBeNil) cl3, err := eid.Get(ctx) So(err, ShouldBeNil) So(cl3.ID, ShouldEqual, cl.ID) So(cl3.EVersion, ShouldEqual, 2) So(cl3.Snapshot, ShouldResembleProto, snap) So(cl3.ApplicableConfig, ShouldResembleProto, acfg) So(cl3.DependentMeta, ShouldResembleProto, asdep) }) Convey("adds/updates DependentMeta", func() { asdep3 := makeDependentMeta(epoch.Add(time.Minute), "another-project", "2nd") err = Update(ctx, "", cl.ID, UpdateFields{AddDependentMeta: asdep3}, nil) So(err, ShouldBeNil) cl3, err := eid.Get(ctx) So(err, ShouldBeNil) So(cl3.DependentMeta, ShouldResembleProto, asdep3) err = Update(ctx, "", cl.ID, UpdateFields{ AddDependentMeta: makeDependentMeta(epoch.Add(time.Hour), "2nd", "3rd"), }, nil) So(err, ShouldBeNil) cl4, err := eid.Get(ctx) So(err, ShouldBeNil) So(cl4.DependentMeta, ShouldResembleProto, &DependentMeta{ ByProject: map[string]*DependentMeta_Meta{ "another-project": { UpdateTime: timestamppb.New(epoch.Add(time.Minute)), NoAccess: true, }, "2nd": { UpdateTime: timestamppb.New(epoch.Add(time.Hour)), NoAccess: true, }, "3rd": { UpdateTime: timestamppb.New(epoch.Add(time.Hour)), NoAccess: true, }, }, }) }) }) }) } func TestConcurrentUpdate(t *testing.T) { t.Parallel() Convey("Update is atomic when called concurrently with flaky datastore", t, func() { // use Seconds with lots of 0s at the end for easy grasp of assertion // failures since they are done on protos. epoch := (&timestamppb.Timestamp{Seconds: 14500000000}).AsTime() ctx, _ := testclock.UseTime(context.Background(), epoch) ctx = txndefer.FilterRDS(memory.Use(ctx)) ctx, fb := featureBreaker.FilterRDS(ctx, nil) datastore.GetTestable(ctx).Consistent(true) if testing.Verbose() { ctx = logging.SetLevel(gologger.StdConfig.Use(ctx), logging.Debug) } // Use a single random source for all flaky.Errors(...) instances. Otherwise // they repeat the same random pattern each time withBrokenDS is called. rnd := rand.NewSource(0) // Make datastore very faulty. fb.BreakFeaturesWithCallback( flaky.Errors(flaky.Params{ Rand: rnd, DeadlineProbability: 0.4, ConcurrentTransactionProbability: 0.4, }), featureBreaker.DatastoreFeatures..., ) // Number of tries per worker. // With probabilities above, it typically takes <60 tries. const R = 200 // Number of workers. const N = 10 eid, err := GobID("x-review.example.com", 12) So(err, ShouldBeNil) wg := sync.WaitGroup{} wg.Add(N) for d := 0; d < N; d++ { // Simulate opposing Snapshot and DependentMeta timestamps for better // test coverage. // For a co-prime p,N: // assert sorted(set([((p*d)%N) for d in xrange(N)])) == range(N) // 47, 59 are actual primes. snapTS := epoch.Add(time.Second * time.Duration((47*d)%N)) asdepTS := epoch.Add(time.Second * time.Duration((73*d)%N)) go func() { defer wg.Done() snap := makeSnapshot(snapTS) asdep := makeDependentMeta(asdepTS, "another-project") var err error for i := 0; i < R; i++ { if err = Update(ctx, eid, 0, UpdateFields{snap, nil, asdep}, nil); err == nil { t.Logf("succeeded after %d tries", i) return } } panic(errors.Annotate(err, "all %d tries exhausted", R).Err()) }() } wg.Wait() // "Fix" datastore, letting us examine it. fb.BreakFeaturesWithCallback( func(context.Context, string) error { return nil }, featureBreaker.DatastoreFeatures..., ) cl, err := eid.Get(ctx) So(err, ShouldBeNil) // Since all workers have succeded, the latest snapshot // (by ExternalUpdateTime) must be the current snapshot in datastore. latestTS := epoch.Add((N - 1) * time.Second) So(cl.Snapshot, ShouldResembleProto, makeSnapshot(latestTS)) So(cl.DependentMeta, ShouldResembleProto, makeDependentMeta(latestTS, "another-project")) // Furthermore, there must have been at most N non-noop UpdateSnapshot // calls (one per worker, iff they did exactly in the increasing order of // the ExternalUpdateTime). t.Logf("%d updates done", cl.EVersion) So(cl.EVersion, ShouldBeLessThan, N+1) }) } const luciProject = "luci-project" func makeSnapshot(updatedTime time.Time) *Snapshot { return &Snapshot{ ExternalUpdateTime: timestamppb.New(updatedTime), Kind: &Snapshot_Gerrit{Gerrit: &Gerrit{ Info: &gerritpb.ChangeInfo{ CurrentRevision: "deadbeef", Revisions: map[string]*gerritpb.RevisionInfo{ "deadbeef": { Number: 1, Kind: gerritpb.RevisionInfo_REWORK, }, }, }, }}, MinEquivalentPatchset: 1, Patchset: 2, LuciProject: luciProject, } } func makeApplicableConfig() *ApplicableConfig { return &ApplicableConfig{ Projects: []*ApplicableConfig_Project{ {Name: luciProject, ConfigGroupIds: []string{"blah"}}, }, } } func makeDependentMeta(updatedTime time.Time, projects ...string) *DependentMeta { if len(projects) == 0 { projects = []string{luciProject} } a := &DependentMeta{ByProject: make(map[string]*DependentMeta_Meta, len(projects))} for _, p := range projects { a.ByProject[p] = &DependentMeta_Meta{ NoAccess: true, UpdateTime: timestamppb.New(updatedTime), } } return a }
// Copyright 2020 Insolar Network Ltd. // All rights reserved. // This material is licensed under the Insolar License version 1.0, // available at https://github.com/insolar/block-explorer/blob/master/LICENSE.md. // +build heavy_mock_integration package api import ( "testing" "github.com/insolar/block-explorer/test/heavymock" "github.com/insolar/block-explorer/test/integration" "github.com/insolar/block-explorer/testutils" "github.com/insolar/insolar/ledger/heavy/exporter" "github.com/insolar/insolar/pulse" "github.com/stretchr/testify/require" ) func TestGetPulse(t *testing.T) { ts := integration.NewBlockExplorerTestSetup(t).WithHTTPServer(t) defer ts.Stop(t) size := 5 recordsCount := 1 records := testutils.GenerateRecordsWithDifferencePulsesSilence(size, recordsCount) pulses := make([]pulse.Number, size) for i, r := range records { pulses[i] = r.Record.ID.GetPulseNumber() } err := heavymock.ImportRecords(ts.ConMngr.ImporterClient, records) require.NoError(t, err) ts.BE.PulseClient.SetNextFinalizedPulseFunc(ts.ConMngr.Importer) ts.StartBE(t) defer ts.StopBE(t) ts.WaitRecordsCount(t, size, 5000) c := GetHTTPClient() pulsesResp := c.Pulses(t, nil) require.Len(t, pulsesResp.Result, size) t.Run("existing pulses", func(t *testing.T) { t.Log("C5218 Get pulse data") for i, p := range pulses[:len(pulses)-1] { response := c.Pulse(t, int64(p)) require.Equal(t, pulsesResp.Result[len(pulsesResp.Result)-1-i].PulseNumber, response.PulseNumber) require.Equal(t, int64(p), response.PulseNumber) // first pulse in db don't have prev if i == 0 { require.EqualValues(t, 0, response.PrevPulseNumber) } else { require.Equal(t, response.PulseNumber-10, response.PrevPulseNumber) } require.Equal(t, response.PulseNumber+10, response.NextPulseNumber) require.Equal(t, recordsCount, int(response.JetDropAmount)) require.Equal(t, recordsCount, int(response.RecordAmount)) require.NotEmpty(t, response.Timestamp) require.Empty(t, response.Message) require.Empty(t, response.ValidationFailures) } }) t.Run("non existing pulse", func(t *testing.T) { t.Log("C5219 Get pulse, not found non existing pulse") c.PulseWithError(t, int64(pulses[len(pulses)-1]+1000), notFound404) }) t.Run("zero pulse", func(t *testing.T) { t.Log("C5221 Get pulse, pulse is zero value") c.PulseWithError(t, int64(pulses[len(pulses)-1]+1000), notFound404) }) t.Run("empty pulse", func(t *testing.T) { t.Log("C5222 Get pulse, pulse is an empty pulse") t.Skip("waiting for PENV-347") newRecords := []*exporter.Record{testutils.GenerateRecordInNextPulse(pulses[size-1]), testutils.GenerateRecordInNextPulse(pulses[size-1] + 10), testutils.GenerateRecordInNextPulse(pulses[size-1] + 20)} require.NoError(t, heavymock.ImportRecords(ts.ConMngr.ImporterClient, newRecords[1:])) ts.WaitRecordsCount(t, size+1, 5000) emptyPulse := int64(newRecords[0].Record.ID.Pulse()) // TODO check if emptyPulse exists or not in the pulses list _ = c.Pulses(t, nil) r := c.Pulse(t, emptyPulse) require.Equal(t, emptyPulse, r.PulseNumber) }) }
// Copyright 2020 Insolar Network Ltd. // All rights reserved. // This material is licensed under the Insolar License version 1.0, // available at https://github.com/insolar/block-explorer/blob/master/LICENSE.md. // +build unit package belogger import ( "bytes" "encoding/json" "runtime" "strconv" "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/insolar/assured-ledger/ledger-core/v2/log" "github.com/insolar/assured-ledger/ledger-core/v2/log/global" "github.com/insolar/assured-ledger/ledger-core/v2/log/logcommon" "github.com/insolar/block-explorer/configuration" ) // Beware, test results there depends on test file name (caller_test.go)! const pkgRegexPrefix = "^instrumentation/belogger/" type loggerField struct { Caller string Func string } func logFields(t *testing.T, b []byte) loggerField { var lf loggerField err := json.Unmarshal(b, &lf) require.NoErrorf(t, err, "failed decode: '%v'", string(b)) return lf } func TestLog_ZerologCaller(t *testing.T) { l, err := NewLog(configuration.Log{ Level: "info", Adapter: "zerolog", Formatter: "json", }) require.NoError(t, err, "log creation") var b bytes.Buffer l, err = l.Copy().WithOutput(&b).WithCaller(logcommon.CallerField).Build() require.NoError(t, err) _, _, line, _ := runtime.Caller(0) l.Info("test") lf := logFields(t, b.Bytes()) assert.Regexp(t, pkgRegexPrefix+"caller_test.go:"+strconv.Itoa(line+1), lf.Caller, "log contains call place") assert.NotContains(t, "github.com/insolar/block-explorer", lf.Caller, "log not contains package name") assert.Equal(t, "", lf.Func, "log not contains func name") } // this test result depends on test name! func TestLog_ZerologCallerWithFunc(t *testing.T) { l, err := NewLog(configuration.Log{ Level: "info", Adapter: "zerolog", Formatter: "json", }) require.NoError(t, err, "log creation") var b bytes.Buffer l, err = l.Copy().WithOutput(&b).WithCaller(logcommon.CallerFieldWithFuncName).Build() require.NoError(t, err) _, _, line, _ := runtime.Caller(0) l.Info("test") lf := logFields(t, b.Bytes()) assert.Regexp(t, pkgRegexPrefix+"caller_test.go:"+strconv.Itoa(line+1), lf.Caller, "log contains proper caller place") assert.NotContains(t, "github.com/insolar/block-explorer", lf.Caller, "log not contains package name") assert.Equal(t, "TestLog_ZerologCallerWithFunc", lf.Func, "log contains func name") } func TestLog_BilogCaller(t *testing.T) { l, err := NewLog(configuration.Log{ Level: "info", Adapter: "bilog", Formatter: "json", }) require.NoError(t, err, "log creation") var b bytes.Buffer l, err = l.Copy().WithOutput(&b).WithCaller(logcommon.CallerField).Build() require.NoError(t, err) _, _, line, _ := runtime.Caller(0) l.Info("test") lf := logFields(t, b.Bytes()) assert.Regexp(t, pkgRegexPrefix+"caller_test.go:"+strconv.Itoa(line+1), lf.Caller, "log contains call place") assert.NotContains(t, "github.com/insolar/block-explorer", lf.Caller, "log not contains package name") assert.Equal(t, "", lf.Func, "log not contains func name") } // this test result depends on test name! func TestLog_BilogCallerWithFunc(t *testing.T) { l, err := NewLog(configuration.Log{ Level: "info", Adapter: "bilog", Formatter: "json", }) require.NoError(t, err, "log creation") var b bytes.Buffer l, err = l.Copy().WithOutput(&b).WithCaller(logcommon.CallerFieldWithFuncName).Build() require.NoError(t, err) _, _, line, _ := runtime.Caller(0) l.Info("test") lf := logFields(t, b.Bytes()) assert.Regexp(t, pkgRegexPrefix+"caller_test.go:"+strconv.Itoa(line+1), lf.Caller, "log contains proper caller place") assert.NotContains(t, "github.com/insolar/block-explorer", lf.Caller, "log not contains package name") assert.Equal(t, "TestLog_BilogCallerWithFunc", lf.Func, "log contains func name") } func TestLog_GlobalCaller(t *testing.T) { defer global.SaveLogger()() var b bytes.Buffer gl2, err := global.Logger().Copy().WithOutput(&b).WithCaller(logcommon.CallerField).Build() require.NoError(t, err) global.SetLogger(gl2) global.SetLevel(log.InfoLevel) _, _, line, _ := runtime.Caller(0) global.Info("test") global.Debug("test2shouldNotBeThere") s := b.String() lf := logFields(t, []byte(s)) assert.Regexp(t, pkgRegexPrefix+"caller_test.go:"+strconv.Itoa(line+1), lf.Caller, "log contains proper call place") assert.Equal(t, "", lf.Func, "log not contains func name") assert.NotContains(t, s, "test2shouldNotBeThere") } func TestLog_GlobalCallerWithFunc(t *testing.T) { defer global.SaveLogger()() var b bytes.Buffer gl2, err := global.Logger().Copy().WithOutput(&b).WithCaller(logcommon.CallerFieldWithFuncName).Build() require.NoError(t, err) global.SetLogger(gl2) global.SetLevel(log.InfoLevel) _, _, line, _ := runtime.Caller(0) global.Info("test") global.Debug("test2shouldNotBeThere") s := b.String() lf := logFields(t, []byte(s)) assert.Regexp(t, pkgRegexPrefix+"caller_test.go:"+strconv.Itoa(line+1), lf.Caller, "log contains proper call place") assert.Equal(t, "TestLog_GlobalCallerWithFunc", lf.Func, "log contains func name") assert.NotContains(t, s, "test2shouldNotBeThere") }
// Copyright (C) 2017 Google 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. package transform import ( "context" "github.com/google/gapid/gapis/api" ) // Injector is an implementation of Transformer that can inject commands into // the stream. type Injector struct { injections map[api.CmdID][]api.Cmd } // Inject emits cmd after the command with identifier after. func (t *Injector) Inject(after api.CmdID, cmd api.Cmd) { if t.injections == nil { t.injections = make(map[api.CmdID][]api.Cmd) } t.injections[after] = append(t.injections[after], cmd) } // Transform implements the Transformer interface. func (t *Injector) Transform(ctx context.Context, id api.CmdID, cmd api.Cmd, out Writer) error { if err := out.MutateAndWrite(ctx, id, cmd); err != nil { return err } if r, ok := t.injections[id]; ok { for _, injection := range r { if err := out.MutateAndWrite(ctx, api.CmdNoID, injection); err != nil { return err } } delete(t.injections, id) } return nil } // Flush implements the Transformer interface. func (t *Injector) Flush(ctx context.Context, out Writer) error { return nil } func (t *Injector) PreLoop(ctx context.Context, output Writer) {} func (t *Injector) PostLoop(ctx context.Context, output Writer) {} func (t *Injector) BuffersCommands() bool { return false }
package main import "fmt" /* - Utiliza o formato key:value. - E.g. nome e telefone - Performance excelente para lookups. - map[key]value{ key: value } - Acesso: m[key] - Key sem value retorna zero. Isso pode trazer problemas. - Para verificar: comma ok idiom. - v, ok := m[key] - ok é um boolean, true/false - Na prática: if v, ok := m[key]; ok { } - Para adicionar um item: m[v] = value - Maps *não tem ordem.* */ func main() { amigos := map[string]int{ "alfredo": 5551234, "joana": 9996674, } fmt.Println(amigos) fmt.Println(amigos["joana"]) amigos["gopher"] = 444444 fmt.Println(amigos) fmt.Println(amigos["gopher"], "\n\n") // comma ok idiom if será, ok := amigos["fantasma"]; !ok { fmt.Println("não tem!") } else { fmt.Println(será) } }
/* Copyright 2016 - Jaume Arús Author Jaume Arús - jaumearus@gmail.com Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you 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 lib_gc_runner import ( "errors" "fmt" "time" ) // Getting a runner instance // Parameters : // tasks_checking_interval: Frequency in milliseconds of tasks checking done by the runner. func GetRunner(tasks_checking_interval int64) (Runner_I, error) { return &runner{tasks_checking_interval: tasks_checking_interval, tasks: make(map[int64]*RunningTask), isRunnnig: false}, nil } type RunningTask struct { Task Task_I Args []interface{} FirstWakingUp time.Time RunningFrom []time.Time } type Runner_I interface { Start() error Shutdown() error WakeUpTask(Task_I, ...interface{}) error IsTaskRunning(int64) (bool, error) GetRunningTasksIDs() ([]int64, error) FinishTaskById(int64) error } type runner struct { tasks_checking_interval int64 tasks map[int64]*RunningTask isRunnnig bool } // Waking up a new task, that implements the Task_I interface // Parameters: // task: The task to be waked up // args: A list of one or more arguments which will be passed to the task implementation as parameters func (r *runner) WakeUpTask(task Task_I, args ...interface{}) error { // Check if already exists a task with the same ID if _, ok := r.tasks[task.GetID()]; ok { return errors.New(fmt.Sprintf("Already exists a task with ID: %d", task.GetID())) } else { // Register the task r.tasks[task.GetID()] = &RunningTask{Task: task, Args: args} return nil } } func (r *runner) IsTaskRunning(id int64) (bool, error) { if t, ok := r.tasks[id]; !ok { return false, errors.New(fmt.Sprintf("There is not any task with ID %d !!!", id)) } else { return t.Task.IsRunning(), nil } } func (r *runner) GetRunningTasksIDs() ([]int64, error) { ids := make([]int64, len(r.tasks)) c := 0 for id, _ := range r.tasks { ids[c] = id c += 1 } return ids, nil } // Starting the runner. If this method is not called, the tasks wont be fire up func (r *runner) Start() error { go func(r *runner) { t := time.NewTicker(time.Duration(r.tasks_checking_interval) * time.Millisecond) for _ = range t.C { if !r.isRunnnig { r.run() } } }(r) return nil } func (r *runner) Shutdown() error { var finisher TaskManager_I for _, task := range r.tasks { t := task finisher = &taskManager{t.Task} finisher.Finish() } return nil } func (r *runner) FinishTaskById(id int64) error { if t, ok := r.tasks[id]; !ok { return errors.New(fmt.Sprintf("There is not any task with ID %d !!!", id)) } else { finisher := &taskManager{t.Task} finisher.Finish() return nil } } func (r *runner) run() { defer func() { r.isRunnnig = false }() t := time.NewTicker(time.Duration(r.tasks_checking_interval) * time.Millisecond) for _ = range t.C { r.checkTasks() } } // Checking the status of the tasks. // This method is invoked with the frequency filled in the tasks_checking_interval of the method GetRunner() func (r *runner) checkTasks() error { var t time.Time var runningTime int64 var taskDuration int64 for _, rtask := range r.tasks { t = time.Now() if rtask.RunningFrom == nil { // The task has not been woke up yet. Waking it up... rtask.FirstWakingUp = t rtask.RunningFrom = []time.Time{t} rtask.Task.Run(rtask.Args) } else { // Check task duration (task duration <= 0 stands for infinite task) runningTime = int64(t.Sub(rtask.FirstWakingUp).Seconds() * 1000) taskDuration = int64(rtask.Task.GetDuration().Seconds() * 1000) //fmt.Printf("*jas* task %d, isrunning %t, isfinished %t, taskDuration %d, runningTime %d\n", rtask.Task.GetID(), rtask.Task.IsRunning(), rtask.Task.IsFinished(), taskDuration, runningTime) if rtask.Task.IsFinished() || (taskDuration > 0 && (runningTime >= taskDuration)) { if rtask.Task.IsRunning() { // This finishes the task and fires up the response sending rtask.Task.Finalize() } delete(r.tasks, rtask.Task.GetID()) } else { // Check if the task is running if !rtask.Task.IsRunning() { rtask.RunningFrom = append(rtask.RunningFrom, t) rtask.Task.Run(rtask.Args) } else { // Keeping the task running .. //fmt.Printf("*jas* Keeping the task running (rt/td) %d / %d ..\n",runningTime,taskDuration) } } } } return nil }
package model import ( "github.com/jinzhu/gorm" _"github.com/go-sql-driver/mysql" "github.com/siliconvalley001/wen/user/setting" "fmt" ) var ( DB *gorm.DB err error ) type AllConfig struct { } func init(){ if _,err:=setting.InitSetting();err!=nil{ panic(err) } fmt.Println(setting.Con.Mys.Name) DB,err=gorm.Open("mysql",fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?parseTime=true&loc=Local", setting.Con.Mys.Name, setting.Con.Mys.PassWord, setting.Con.Mys.Host, setting.Con.Mys.Port, setting.Con.Mys.DBName, )) if err!=nil{ panic(err) } DB.SingularTable(true) DB.DB().SetMaxOpenConns(setting.Con.Mys.MaxOpenConns) DB.DB().SetMaxIdleConns(setting.Con.Mys.MaxIdleConns) DB.AutoMigrate(&User{}) }
package msgraph import ( "encoding/json" "fmt" "time" ) // globalSupportedTimeZones represents the instance that will be initialized once on runtime // and load all TimeZones form Microsoft, correlate them to IANA and set proper time.Location var globalSupportedTimeZones supportedTimeZones // supportedTimeZones represents multiple instances grabbed by https://developer.microsoft.com/en-us/graph/docs/api-reference/v1.0/api/outlookuser_supportedtimezones type supportedTimeZones struct { Value []supportedTimeZone } // GetTimeZoneByAlias searches in the given set of supportedTimeZones for the TimeZone with the given alias. Returns // either the time.Location or an error if it cannot be found. func (s supportedTimeZones) GetTimeZoneByAlias(alias string) (*time.Location, error) { for _, searchItem := range s.Value { if searchItem.Alias == alias { return searchItem.TimeLoc, nil } } return nil, fmt.Errorf("could not find given time.Location for Alias %v", alias) } // GetTimeZoneByAlias searches in the given set of supportedTimeZones for the TimeZone with the given alias. Returns // either the time.Location or an error if it cannot be found. func (s supportedTimeZones) GetTimeZoneByDisplayName(displayName string) (*time.Location, error) { for _, searchItem := range s.Value { if searchItem.DisplayName == displayName { return searchItem.TimeLoc, nil } } return nil, fmt.Errorf("could not find given time.Location for DisplayName %v", displayName) } // supportedTimeZone represents one instance grabbed by https://developer.microsoft.com/en-us/graph/docs/api-reference/v1.0/api/outlookuser_supportedtimezones type supportedTimeZone struct { Alias string DisplayName string TimeLoc *time.Location } func (s *supportedTimeZone) UnmarshalJSON(data []byte) error { tmp := struct { Alias string `json:"alias"` DisplayName string `json:"displayName"` }{} err := json.Unmarshal(data, &tmp) if err != nil { return err } s.Alias = tmp.Alias s.DisplayName = tmp.DisplayName ianaName, ok := WinIANA[s.DisplayName] if !ok { return fmt.Errorf("cannot map %v to IANA", s.DisplayName) } loc, err := time.LoadLocation(ianaName) if err != nil { return fmt.Errorf("cannot time.LoadLocation for original \"%v\" mapped to IANA \"%v\"", s.DisplayName, ianaName) } s.TimeLoc = loc return nil } // WinIANA contains a mapping for all Windows Time Zones to IANA time zones usable for time.LoadLocation. // This list was initially copied from https://github.com/thinkovation/windowsiana/blob/master/windowsiana.go // on 30th of August 2018, 14:00 and then extended on the same day. // // The full list of time zones that have been added and are now supported come from an an API-Call described here: // https://developer.microsoft.com/en-us/graph/docs/api-reference/v1.0/api/outlookuser_supportedtimezones var WinIANA = map[string]string{ "(UTC-12:00) International Date Line West": "Etc/GMT+12", "(UTC-11:00) Co-ordinated Universal Time-11": "Etc/GMT+11", "(UTC-11:00) Coordinated Universal Time-11": "Etc/GMT+11", "(UTC-10:00) Aleutian Islands": "US/Aleutian", "(UTC-10:00) Hawaii": "Pacific/Honolulu", "(UTC-09:30) Marquesas Islands": "Pacific/Marquesas", "(UTC-09:00) Alaska": "America/Anchorage", "(UTC-09:00) Co-ordinated Universal Time-09": "Etc/GMT+9", "(UTC-09:00) Coordinated Universal Time-09": "Etc/GMT+9", "(UTC-08:00) Baja California": "America/Tijuana", "(UTC-08:00) Co-ordinated Universal Time-08": "Etc/GMT+8", "(UTC-08:00) Coordinated Universal Time-08": "Etc/GMT+8", "(UTC-08:00) Pacific Time (US & Canada)": "America/Los_Angeles", "(UTC-07:00) Arizona": "America/Phoenix", "(UTC-07:00) Chihuahua, La Paz, Mazatlan": "America/Chihuahua", "(UTC-07:00) Mountain Time (US & Canada)": "America/Denver", "(UTC-07:00) Yukon": "Etc/GMT+7", "(UTC-07:00) La Paz, Mazatlan": "America/Mazatlan", "(UTC-06:00) Central America": "America/Guatemala", "(UTC-06:00) Central Time (US & Canada)": "America/Chicago", "(UTC-06:00) Easter Island": "Pacific/Easter", "(UTC-06:00) Guadalajara, Mexico City, Monterrey": "America/Mexico_City", "(UTC-06:00) Saskatchewan": "America/Regina", "(UTC-05:00) Bogota, Lima, Quito, Rio Branco": "America/Bogota", "(UTC-05:00) Chetumal": "America/Cancun", "(UTC-05:00) Eastern Time (US & Canada)": "America/New_York", "(UTC-05:00) Haiti": "America/Port-au-Prince", "(UTC-05:00) Havana": "America/Havana", "(UTC-05:00) Indiana (East)": "America/Indianapolis", "(UTC-05:00) Turks and Caicos": "Etc/GMT+5", "(UTC-04:00) Asuncion": "America/Asuncion", "(UTC-04:00) Atlantic Time (Canada)": "America/Halifax", "(UTC-04:00) Caracas": "America/Caracas", "(UTC-04:00) Cuiaba": "America/Cuiaba", "(UTC-04:00) Georgetown, La Paz, Manaus, San Juan": "America/La_Paz", "(UTC-04:00) Santiago": "America/Santiago", "(UTC-04:00) Turks and Caicos": "America/Grand_Turk", "(UTC-03:30) Newfoundland": "America/St_Johns", "(UTC-03:00) Araguaina": "America/Araguaina", "(UTC-03:00) Brasilia": "America/Sao_Paulo", "(UTC-03:00) Cayenne, Fortaleza": "America/Cayenne", "(UTC-03:00) City of Buenos Aires": "America/Buenos_Aires", "(UTC-03:00) Greenland": "America/Godthab", "(UTC-03:00) Montevideo": "America/Montevideo", "(UTC-03:00) Punta Arenas": "America/Punta_Arenas", "(UTC-03:00) Saint Pierre and Miquelon": "America/Miquelon", "(UTC-03:00) Salvador": "America/Bahia", "(UTC-02:00) Co-ordinated Universal Time-02": "Etc/GMT+2", "(UTC-02:00) Coordinated Universal Time-02": "Etc/GMT+2", "(UTC-02:00) Mid-Atlantic - Old": "Etc/GMT+2", "(UTC-01:00) Azores": "Atlantic/Azores", "(UTC-01:00) Cabo Verde Is.": "Atlantic/Cape_Verde", "(UTC) Co-ordinated Universal Time": "Etc/GMT", "(UTC) Coordinated Universal Time": "Etc/GMT", "(UTC+00:00) Casablanca": "Africa/Casablanca", "(UTC+00:00) Dublin, Edinburgh, Lisbon, London": "Europe/London", "(UTC+00:00) Monrovia, Reykjavik": "Atlantic/Reykjavik", "(UTC+01:00) Amsterdam, Berlin, Bern, Rome, Stockholm, Vienna": "Europe/Berlin", "(UTC+01:00) Belgrade, Bratislava, Budapest, Ljubljana, Prague": "Europe/Budapest", "(UTC+01:00) Brussels, Copenhagen, Madrid, Paris": "Europe/Paris", "(UTC+01:00) Casablanca": "Africa/Casablanca", "(UTC+01:00) Sarajevo, Skopje, Warsaw, Zagreb": "Europe/Warsaw", "(UTC+01:00) West Central Africa": "Africa/Lagos", "(UTC+01:00) Windhoek": "Africa/Windhoek", "(UTC+02:00) Amman": "Asia/Amman", "(UTC+02:00) Athens, Bucharest": "Europe/Bucharest", "(UTC+02:00) Beirut": "Asia/Beirut", "(UTC+02:00) Cairo": "Africa/Cairo", "(UTC+02:00) Chisinau": "Europe/Chisinau", "(UTC+02:00) Damascus": "Asia/Damascus", "(UTC+02:00) Gaza, Hebron": "Asia/Gaza", "(UTC+02:00) Harare, Pretoria": "Africa/Johannesburg", "(UTC+02:00) Helsinki, Kyiv, Riga, Sofia, Tallinn, Vilnius": "Europe/Kiev", "(UTC+02:00) Istanbul": "Europe/Istanbul", "(UTC+03:00) Istanbul": "Europe/Istanbul", "(UTC+02:00) Jerusalem": "Asia/Jerusalem", "(UTC+02:00) Juba": "Africa/Juba", "(UTC+02:00) Kaliningrad": "Europe/Kaliningrad", "(UTC+02:00) Windhoek": "Africa/Windhoek", "(UTC+02:00) Khartoum": "Africa/Khartoum", "(UTC+02:00) Tripoli": "Africa/Tripoli", "(UTC+03:00) Amman": "Asia/Amman", "(UTC+03:00) Baghdad": "Asia/Baghdad", "(UTC+03:00) Kuwait, Riyadh": "Asia/Riyadh", "(UTC+03:00) Minsk": "Europe/Minsk", "(UTC+03:00) Moscow, St. Petersburg": "Europe/Moscow", "(UTC+03:00) Moscow, St. Petersburg, Volgograd": "Europe/Moscow", "(UTC+03:00) Nairobi": "Africa/Nairobi", "(UTC+03:00) Volgograd": "Europe/Volgograd", "(UTC+03:30) Tehran": "Asia/Tehran", "(UTC+04:00) Abu Dhabi, Muscat": "Asia/Dubai", "(UTC+04:00) Astrakhan, Ulyanovsk": "Europe/Samara", "(UTC+04:00) Baku": "Asia/Baku", "(UTC+04:00) Izhevsk, Samara": "Europe/Samara", "(UTC+04:00) Port Louis": "Indian/Mauritius", "(UTC+04:00) Saratov": "Europe/Saratov", "(UTC+04:00) Tbilisi": "Asia/Tbilisi", "(UTC+04:00) Volgograd": "Europe/Volgograd", "(UTC+04:00) Yerevan": "Asia/Yerevan", "(UTC+04:30) Kabul": "Asia/Kabul", "(UTC+05:00) Ashgabat, Tashkent": "Asia/Tashkent", "(UTC+05:00) Ekaterinburg": "Asia/Yekaterinburg", "(UTC+05:00) Islamabad, Karachi": "Asia/Karachi", "(UTC+05:00) Qyzylorda": "Asia/Qyzylorda", "(UTC+05:30) Chennai, Kolkata, Mumbai, New Delhi": "Asia/Calcutta", "(UTC+05:30) Sri Jayawardenepura": "Asia/Colombo", "(UTC+05:45) Kathmandu": "Asia/Kathmandu", "(UTC+06:00) Astana": "Asia/Almaty", "(UTC+06:00) Dhaka": "Asia/Dhaka", "(UTC+06:00) Omsk": "Asia/Omsk", "(UTC+06:00) Novosibirsk": "Asia/Novosibirsk", "(UTC+06:00) Nur-Sultan": "Asia/Almaty", "(UTC+06:30) Yangon (Rangoon)": "Asia/Rangoon", "(UTC+07:00) Bangkok, Hanoi, Jakarta": "Asia/Bangkok", "(UTC+07:00) Barnaul, Gorno-Altaysk": "Asia/Krasnoyarsk", "(UTC+07:00) Hovd": "Asia/Hovd", "(UTC+07:00) Krasnoyarsk": "Asia/Krasnoyarsk", "(UTC+07:00) Novosibirsk": "Asia/Novosibirsk", "(UTC+07:00) Tomsk": "Asia/Tomsk", "(UTC+08:00) Beijing, Chongqing, Hong Kong SAR, Urumqi": "Asia/Shanghai", "(UTC+08:00) Beijing, Chongqing, Hong Kong, Urumqi": "Asia/Shanghai", "(UTC+08:00) Irkutsk": "Asia/Irkutsk", "(UTC+08:00) Kuala Lumpur, Singapore": "Asia/Singapore", "(UTC+08:00) Perth": "Australia/Perth", "(UTC+08:00) Taipei": "Asia/Taipei", "(UTC+08:00) Ulaanbaatar": "Asia/Ulaanbaatar", "(UTC+08:30) Pyongyang": "Asia/Pyongyang", "(UTC+09:00) Pyongyang": "Asia/Pyongyang", "(UTC+08:45) Eucla": "Australia/Eucla", "(UTC+09:00) Chita": "Asia/Chita", "(UTC+09:00) Osaka, Sapporo, Tokyo": "Asia/Tokyo", "(UTC+09:00) Seoul": "Asia/Seoul", "(UTC+09:00) Yakutsk": "Asia/Yakutsk", "(UTC+09:30) Adelaide": "Australia/Adelaide", "(UTC+09:30) Darwin": "Australia/Darwin", "(UTC+10:00) Brisbane": "Australia/Brisbane", "(UTC+10:00) Canberra, Melbourne, Sydney": "Australia/Sydney", "(UTC+10:00) Guam, Port Moresby": "Pacific/Port_Moresby", "(UTC+10:00) Hobart": "Australia/Hobart", "(UTC+10:00) Vladivostok": "Asia/Vladivostok", "(UTC+10:30) Lord Howe Island": "Australia/Lord_Howe", "(UTC+11:00) Bougainville Island": "Pacific/Bougainville", "(UTC+11:00) Chokurdakh": "Asia/Srednekolymsk", "(UTC+11:00) Magadan": "Asia/Magadan", "(UTC+11:00) Norfolk Island": "Pacific/Norfolk", "(UTC+11:00) Sakhalin": "Asia/Sakhalin", "(UTC+11:00) Solomon Is., New Caledonia": "Pacific/Guadalcanal", "(UTC+12:00) Anadyr, Petropavlovsk-Kamchatsky": "Asia/Kamchatka", "(UTC+12:00) Auckland, Wellington": "Pacific/Auckland", "(UTC+12:00) Co-ordinated Universal Time+12": "Etc/GMT-12", "(UTC+12:00) Coordinated Universal Time+12": "Etc/GMT-12", "(UTC+12:00) Petropavlovsk-Kamchatsky - Old": "Etc/GMT-12", "(UTC+12:00) Fiji": "Pacific/Fiji", "(UTC+12:45) Chatham Islands": "Pacific/Chatham", "(UTC+13:00) Nuku'alofa": "Pacific/Tongatapu", "(UTC+13:00) Co-ordinated Universal Time+13": "Etc/GMT-13", "(UTC+13:00) Coordinated Universal Time+13": "Etc/GMT-13", "(UTC+13:00) Samoa": "Pacific/Apia", "(UTC+14:00) Kiritimati Island": "Pacific/Kiritimati"}
package cpool import ( "errors" "github.com/toolkits/consistent" "github.com/toolkits/file" "github.com/toolkits/logger" "github.com/toolkits/rpool/conn_pool" "strings" "sync" ) type RingBackend struct { sync.RWMutex Addrs map[string][]string Ring *consistent.Consistent Pools map[string]*conn_pool.ConnPool } func (t *RingBackend) LocateRing(pkey string) (string, error) { t.RLock() defer t.RUnlock() if t.Ring == nil { return "", errors.New("nil ring") } name, err := t.Ring.Get(pkey) if err != nil { return "", err } return name, nil } func (t *RingBackend) GetConnPoolsByName(name string) ([]*conn_pool.ConnPool, error) { conns := []*conn_pool.ConnPool{} t.RLock() defer t.RUnlock() addr_list, ok := t.Addrs[name] if !ok { return conns, errors.New("no such name") } if len(addr_list) == 0 { return conns, errors.New("empty addrs") } for _, addr := range addr_list { c, ok := t.Pools[addr] if !ok { continue } conns = append(conns, c) } if len(conns) == 0 { return conns, errors.New("no conn pool") } return conns, nil } func (t *RingBackend) InitRing(replicas int) { var tmp_ring *consistent.Consistent = consistent.New() tmp_ring.NumberOfReplicas = replicas t.RLock() for name, _ := range t.Addrs { tmp_ring.Add(name) } t.RUnlock() t.Lock() defer t.Unlock() t.Ring = tmp_ring } func (t *RingBackend) LoadAddrs(f string) error { if !file.IsExist(f) { return errors.New("backends file is not exist") } file_content, err := file.ToString(f) if err != nil { return err } file_content = strings.Trim(file_content, " \n\t") lines := strings.Split(file_content, "\n") if len(lines) == 0 { return errors.New("empty backends") } tmp_addrs := make(map[string][]string) for _, line := range lines { fields := strings.Fields(line) size := len(fields) if size < 2 { logger.Warn("invalid backend %s", line) continue } name := fields[0] addr := fields[1:size] tmp_addrs[name] = addr } t.Lock() defer t.Unlock() t.Addrs = tmp_addrs return nil } func (t *RingBackend) DestroyConnPools() { t.Lock() for _, pool := range t.Pools { pool.Destroy() } t.Unlock() }
// Copyright 2018 The go-Dacchain Authors // This file is part of the go-Dacchain library. // // The go-Dacchain library is free software: you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // The go-Dacchain library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public License // along with the go-Dacchain library. If not, see <http://www.gnu.org/licenses/>. package ntp import ( "fmt" "os" "sync" "sync/atomic" "testing" "time" ) // Ensure that the clock's After channel sends at the correct time. func TestClock_After(t *testing.T) { var ok bool go func() { time.Sleep(10 * time.Millisecond) ok = true }() go func() { time.Sleep(30 * time.Millisecond) t.Fatal("too late") }() gosched() <-New().After(20 * time.Millisecond) if !ok { t.Fatal("too early") } } // Ensure that the clock's AfterFunc executes at the correct time. func TestClock_AfterFunc(t *testing.T) { var ok bool go func() { time.Sleep(10 * time.Millisecond) ok = true }() go func() { time.Sleep(30 * time.Millisecond) t.Fatal("too late") }() gosched() var wg sync.WaitGroup wg.Add(1) New().AfterFunc(20*time.Millisecond, func() { wg.Done() }) wg.Wait() if !ok { t.Fatal("too early") } } // Ensure that the clock's time matches the standary library. func TestClock_Now(t *testing.T) { a := time.Now().Round(time.Second) b := New().Now().Round(time.Second) if !a.Equal(b) { t.Errorf("not equal: %s != %s", a, b) } } // Ensure that the clock sleeps for the appropriate amount of time. func TestClock_Sleep(t *testing.T) { var ok bool go func() { time.Sleep(10 * time.Millisecond) ok = true }() go func() { time.Sleep(30 * time.Millisecond) t.Fatal("too late") }() gosched() New().Sleep(20 * time.Millisecond) if !ok { t.Fatal("too early") } } // Ensure that the clock ticks correctly. func TestClock_Tick(t *testing.T) { var ok bool go func() { time.Sleep(10 * time.Millisecond) ok = true }() go func() { time.Sleep(50 * time.Millisecond) t.Fatal("too late") }() gosched() c := New().Tick(20 * time.Millisecond) <-c <-c if !ok { t.Fatal("too early") } } // Ensure that the clock's ticker ticks correctly. func TestClock_Ticker(t *testing.T) { var ok bool go func() { time.Sleep(100 * time.Millisecond) ok = true }() go func() { time.Sleep(200 * time.Millisecond) t.Fatal("too late") }() gosched() ticker := New().Ticker(50 * time.Millisecond) <-ticker.C <-ticker.C if !ok { t.Fatal("too early") } } // Ensure that the clock's ticker can stop correctly. func TestClock_Ticker_Stp(t *testing.T) { var ok bool go func() { time.Sleep(10 * time.Millisecond) ok = true }() gosched() ticker := New().Ticker(20 * time.Millisecond) <-ticker.C ticker.Stop() select { case <-ticker.C: t.Fatal("unexpected send") case <-time.After(30 * time.Millisecond): } } // Ensure that the clock's timer waits correctly. func TestClock_Timer(t *testing.T) { var ok bool go func() { time.Sleep(10 * time.Millisecond) ok = true }() go func() { time.Sleep(30 * time.Millisecond) t.Fatal("too late") }() gosched() timer := New().Timer(20 * time.Millisecond) <-timer.C if !ok { t.Fatal("too early") } if timer.Stop() { t.Fatal("timer still running") } } // Ensure that the clock's timer can be stopped. func TestClock_Timer_Stop(t *testing.T) { var ok bool go func() { time.Sleep(10 * time.Millisecond) ok = true }() timer := New().Timer(20 * time.Millisecond) if !timer.Stop() { t.Fatal("timer not running") } if timer.Stop() { t.Fatal("timer wasn't cancelled") } select { case <-timer.C: t.Fatal("unexpected send") case <-time.After(30 * time.Millisecond): } } // Ensure that the clock's timer can be reset. func TestClock_Timer_Reset(t *testing.T) { var ok bool go func() { time.Sleep(20 * time.Millisecond) ok = true }() go func() { time.Sleep(30 * time.Millisecond) t.Fatal("too late") }() gosched() timer := New().Timer(10 * time.Millisecond) if !timer.Reset(20 * time.Millisecond) { t.Fatal("timer not running") } <-timer.C if !ok { t.Fatal("too early") } } // Ensure that the mock's After channel sends at the correct time. func TestMock_After(t *testing.T) { var ok int32 clock := NewMock() // Create a channel to execute after 10 mock seconds. ch := clock.After(10 * time.Second) go func(ch <-chan time.Time) { <-ch atomic.StoreInt32(&ok, 1) }(ch) // Move clock forward to just before the time. clock.Add(9 * time.Second) if atomic.LoadInt32(&ok) == 1 { t.Fatal("too early") } // Move clock forward to the after channel's time. clock.Add(1 * time.Second) if atomic.LoadInt32(&ok) == 0 { t.Fatal("too late") } } // Ensure that the mock's After channel doesn't block on write. func TestMock_UnusedAfter(t *testing.T) { mock := NewMock() mock.After(1 * time.Millisecond) done := make(chan bool, 1) go func() { mock.Add(1 * time.Second) done <- true }() select { case <-done: case <-time.After(1 * time.Second): t.Fatal("mock.Add hung") } } // Ensure that the mock's AfterFunc executes at the correct time. func TestMock_AfterFunc(t *testing.T) { var ok int32 clock := NewMock() // Execute function after duration. clock.AfterFunc(10*time.Second, func() { atomic.StoreInt32(&ok, 1) }) // Move clock forward to just before the time. clock.Add(9 * time.Second) if atomic.LoadInt32(&ok) == 1 { t.Fatal("too early") } // Move clock forward to the after channel's time. clock.Add(1 * time.Second) if atomic.LoadInt32(&ok) == 0 { t.Fatal("too late") } } // Ensure that the mock's AfterFunc doesn't execute if stopped. func TestMock_AfterFunc_Stop(t *testing.T) { // Execute function after duration. clock := NewMock() timer := clock.AfterFunc(10*time.Second, func() { t.Fatal("unexpected function execution") }) gosched() // Stop timer & move clock forward. timer.Stop() clock.Add(10 * time.Second) gosched() } // Ensure that the mock's current time can be changed. func TestMock_Now(t *testing.T) { begin := time.Now() var n int64 //var n int32 clock := NewMock() clock.Set(time.Now()) tick := time.NewTicker(1 * time.Second) go func() { for { select { case <-tick.C: n++ start := time.Now() clock.Set(time.Unix(begin.Unix()+n, 0)) end := time.Now() t.Log(end.Unix() - start.Unix()) t.Log("111") } } }() t.Logf("clock now:%v\n", clock.now) t.Logf("local now:%v\n", time.Now()) time.Sleep(6 * time.Second) t.Logf("clock now:%v\n", clock.now) t.Logf("local now:%v\n", time.Now()) //if now := clock.Now(); !now.Equal(time.Unix(0, 0)) { // t.Fatalf("expected epoch, got: %v", now) //} // //// Add 10 seconds and check the time. //clock.Add(10 * time.Second) //if now := clock.Now(); !now.Equal(time.Unix(10, 0)) { // t.Fatalf("expected epoch, got: %v", now) //} } func TestNewNtpClock(t *testing.T) { //ntpTime := time.Now().Add(2 * time.Second) clock, err := NewNtpClock() if err != nil { t.Fatalf("failed to init ntp time:%s\n", err) } t.Logf("clock now:%v\n", clock.now) t.Logf("local now:%v\n", time.Now()) time.Sleep(6 * time.Second) t.Logf("clock now:%v\n", clock.now) t.Logf("local now:%v\n", time.Now()) } func TestMock_Since(t *testing.T) { clock := NewMock() beginning := clock.Now() clock.Add(500 * time.Second) if since := clock.Since(beginning); since.Seconds() != 500 { t.Fatalf("expected 500 since beginning, actually: %v", since.Seconds()) } } // Ensure that the mock can sleep for the correct time. func TestMock_Sleep(t *testing.T) { var ok int32 clock := NewMock() // Create a channel to execute after 10 mock seconds. go func() { clock.Sleep(10 * time.Second) atomic.StoreInt32(&ok, 1) }() gosched() // Move clock forward to just before the sleep duration. clock.Add(9 * time.Second) if atomic.LoadInt32(&ok) == 1 { t.Fatal("too early") } // Move clock forward to the after the sleep duration. clock.Add(1 * time.Second) if atomic.LoadInt32(&ok) == 0 { t.Fatal("too late") } } // Ensure that the mock's Tick channel sends at the correct time. func TestMock_Tick(t *testing.T) { var n int32 clock := NewMock() // Create a channel to increment every 10 seconds. go func() { tick := clock.Tick(10 * time.Second) for { <-tick atomic.AddInt32(&n, 1) } }() gosched() // Move clock forward to just before the first tick. clock.Add(9 * time.Second) if atomic.LoadInt32(&n) != 0 { t.Fatalf("expected 0, got %d", n) } // Move clock forward to the start of the first tick. clock.Add(1 * time.Second) if atomic.LoadInt32(&n) != 1 { t.Fatalf("expected 1, got %d", n) } // Move clock forward over several ticks. clock.Add(30 * time.Second) if atomic.LoadInt32(&n) != 4 { t.Fatalf("expected 4, got %d", n) } } // Ensure that the mock's Ticker channel sends at the correct time. func TestMock_Ticker(t *testing.T) { var n int32 clock := NewMock() // Create a channel to increment every microsecond. go func() { ticker := clock.Ticker(1 * time.Microsecond) for { <-ticker.C atomic.AddInt32(&n, 1) } }() gosched() // Move clock forward. clock.Add(10 * time.Microsecond) if atomic.LoadInt32(&n) != 10 { t.Fatalf("unexpected: %d", n) } } // Ensure that the mock's Ticker channel won't block if not read from. func TestMock_Ticker_Overflow(t *testing.T) { clock := NewMock() ticker := clock.Ticker(1 * time.Microsecond) clock.Add(10 * time.Microsecond) ticker.Stop() } // Ensure that the mock's Ticker can be stopped. func TestMock_Ticker_Stop(t *testing.T) { var n int32 clock := NewMock() // Create a channel to increment every second. ticker := clock.Ticker(1 * time.Second) go func() { for { <-ticker.C atomic.AddInt32(&n, 1) } }() gosched() // Move clock forward. clock.Add(5 * time.Second) if atomic.LoadInt32(&n) != 5 { t.Fatalf("expected 5, got: %d", n) } ticker.Stop() // Move clock forward again. clock.Add(5 * time.Second) if atomic.LoadInt32(&n) != 5 { t.Fatalf("still expected 5, got: %d", n) } } // Ensure that multiple tickers can be used together. func TestMock_Ticker_Multi(t *testing.T) { var n int32 clock := NewMock() go func() { a := clock.Ticker(1 * time.Microsecond) b := clock.Ticker(3 * time.Microsecond) for { select { case <-a.C: atomic.AddInt32(&n, 1) case <-b.C: atomic.AddInt32(&n, 100) } } }() gosched() // Move clock forward. clock.Add(10 * time.Microsecond) gosched() if atomic.LoadInt32(&n) != 310 { t.Fatalf("unexpected: %d", n) } } func ExampleMock_After() { // Create a new mock clock. clock := NewMock() count := 0 ready := make(chan struct{}) // Create a channel to execute after 10 mock seconds. go func() { ch := clock.After(10 * time.Second) close(ready) <-ch count = 100 }() <-ready // Print the starting value. fmt.Printf("%s: %d\n", clock.Now().UTC(), count) // Move the clock forward 5 seconds and print the value again. clock.Add(5 * time.Second) fmt.Printf("%s: %d\n", clock.Now().UTC(), count) // Move the clock forward 5 seconds to the tick time and check the value. clock.Add(5 * time.Second) fmt.Printf("%s: %d\n", clock.Now().UTC(), count) // Output: // 1970-01-01 00:00:00 +0000 UTC: 0 // 1970-01-01 00:00:05 +0000 UTC: 0 // 1970-01-01 00:00:10 +0000 UTC: 100 } func ExampleMock_AfterFunc() { // Create a new mock clock. clock := NewMock() count := 0 // Execute a function after 10 mock seconds. clock.AfterFunc(10*time.Second, func() { count = 100 }) gosched() // Print the starting value. fmt.Printf("%s: %d\n", clock.Now().UTC(), count) // Move the clock forward 10 seconds and print the new value. clock.Add(10 * time.Second) fmt.Printf("%s: %d\n", clock.Now().UTC(), count) // Output: // 1970-01-01 00:00:00 +0000 UTC: 0 // 1970-01-01 00:00:10 +0000 UTC: 100 } func ExampleMock_Sleep() { // Create a new mock clock. clock := NewMock() count := 0 // Execute a function after 10 mock seconds. go func() { clock.Sleep(10 * time.Second) count = 100 }() gosched() // Print the starting value. fmt.Printf("%s: %d\n", clock.Now().UTC(), count) // Move the clock forward 10 seconds and print the new value. clock.Add(10 * time.Second) fmt.Printf("%s: %d\n", clock.Now().UTC(), count) // Output: // 1970-01-01 00:00:00 +0000 UTC: 0 // 1970-01-01 00:00:10 +0000 UTC: 100 } func ExampleMock_Ticker() { // Create a new mock clock. clock := NewMock() count := 0 ready := make(chan struct{}) // Increment count every mock second. go func() { ticker := clock.Ticker(1 * time.Second) close(ready) for { <-ticker.C count++ } }() <-ready // Move the clock forward 10 seconds and print the new value. clock.Add(10 * time.Second) fmt.Printf("Count is %d after 10 seconds\n", count) // Move the clock forward 5 more seconds and print the new value. clock.Add(5 * time.Second) fmt.Printf("Count is %d after 15 seconds\n", count) // Output: // Count is 10 after 10 seconds // Count is 15 after 15 seconds } func ExampleMock_Timer() { // Create a new mock clock. clock := NewMock() count := 0 ready := make(chan struct{}) // Increment count after a mock second. go func() { timer := clock.Timer(1 * time.Second) close(ready) <-timer.C count++ }() <-ready // Move the clock forward 10 seconds and print the new value. clock.Add(10 * time.Second) fmt.Printf("Count is %d after 10 seconds\n", count) // Output: // Count is 1 after 10 seconds } func TestCheckLocalTimeIsNtp(t *testing.T) { //err := checkLocalTimeIsNtp() //errString := err.Error() //if strings.Contains(errString,"i/o timeout") { // fmt.Println("超时") //} //if err != nil { // t.Fatalf("ntp error:%s", err) //} err := CheckLocalTimeIsNtp() if err != nil { t.Fatalf("ntp error:%s", err) } } func TestClock_Since(t *testing.T) { ntpTime, err := Time(NtpHost) if err != nil { fmt.Println(err) return } fmt.Println(ntpTime) } func warn(v ...interface{}) { fmt.Fprintln(os.Stderr, v...) } func warnf(msg string, v ...interface{}) { fmt.Fprintf(os.Stderr, msg+"\n", v...) }
//obnoxious teenager responds to comments/questions package bob import ( "strings" "unicode" ) func IsUpper(s string) bool { for _, r := range s { if !unicode.IsUpper(r) && unicode.IsLetter(r) { return false } } return true } // Response based on input func Hey(input string) string { upper := IsUpper(input) if (strings.HasSuffix(input, "?")) && upper { return "Calm down, I know what I'm doing!" } if !(strings.HasSuffix(input, "?")) && upper { return "Whoa, chill out!" } if (strings.HasSuffix(input, "?")) && !upper { return "Sure." } if input == "" { return "Fine. Be that way!" } return "Whatever." }
package dao import ( "mall/app/api/web/wechat/model" "github.com/jinzhu/gorm" ) func (d *Dao) QueryMcGroupsOne(p model.McGroupsQuery) (*model.McGroups, error) { db := d.parseMcGroupsQuery(p) var g model.McGroups err := db.First(&g).Error if err != nil { return nil, err } return &g, nil } func (d *Dao) parseMcGroupsQuery(p model.McGroupsQuery) *gorm.DB { db := d.orm.Model(&model.McGroups{}) if p.Uniacid != 0 { db = db.Where("uniacid = ?", p.Uniacid) } if p.Isdefault != -1 { db = db.Where("isdefault = ?", p.Isdefault) } return db }
package odoo import ( "fmt" ) // Base represents base model. type Base struct { LastUpdate *Time `xmlrpc:"__last_update,omptempty"` DisplayName *String `xmlrpc:"display_name,omptempty"` Id *Int `xmlrpc:"id,omptempty"` } // Bases represents array of base model. type Bases []Base // BaseModel is the odoo model name. const BaseModel = "base" // Many2One convert Base to *Many2One. func (b *Base) Many2One() *Many2One { return NewMany2One(b.Id.Get(), "") } // CreateBase creates a new base model and returns its id. func (c *Client) CreateBase(b *Base) (int64, error) { ids, err := c.CreateBases([]*Base{b}) if err != nil { return -1, err } if len(ids) == 0 { return -1, nil } return ids[0], nil } // CreateBase creates a new base model and returns its id. func (c *Client) CreateBases(bs []*Base) ([]int64, error) { var vv []interface{} for _, v := range bs { vv = append(vv, v) } return c.Create(BaseModel, vv) } // UpdateBase updates an existing base record. func (c *Client) UpdateBase(b *Base) error { return c.UpdateBases([]int64{b.Id.Get()}, b) } // UpdateBases updates existing base records. // All records (represented by ids) will be updated by b values. func (c *Client) UpdateBases(ids []int64, b *Base) error { return c.Update(BaseModel, ids, b) } // DeleteBase deletes an existing base record. func (c *Client) DeleteBase(id int64) error { return c.DeleteBases([]int64{id}) } // DeleteBases deletes existing base records. func (c *Client) DeleteBases(ids []int64) error { return c.Delete(BaseModel, ids) } // GetBase gets base existing record. func (c *Client) GetBase(id int64) (*Base, error) { bs, err := c.GetBases([]int64{id}) if err != nil { return nil, err } if bs != nil && len(*bs) > 0 { return &((*bs)[0]), nil } return nil, fmt.Errorf("id %v of base not found", id) } // GetBases gets base existing records. func (c *Client) GetBases(ids []int64) (*Bases, error) { bs := &Bases{} if err := c.Read(BaseModel, ids, nil, bs); err != nil { return nil, err } return bs, nil } // FindBase finds base record by querying it with criteria. func (c *Client) FindBase(criteria *Criteria) (*Base, error) { bs := &Bases{} if err := c.SearchRead(BaseModel, criteria, NewOptions().Limit(1), bs); err != nil { return nil, err } if bs != nil && len(*bs) > 0 { return &((*bs)[0]), nil } return nil, fmt.Errorf("base was not found with criteria %v", criteria) } // FindBases finds base records by querying it // and filtering it with criteria and options. func (c *Client) FindBases(criteria *Criteria, options *Options) (*Bases, error) { bs := &Bases{} if err := c.SearchRead(BaseModel, criteria, options, bs); err != nil { return nil, err } return bs, nil } // FindBaseIds finds records ids by querying it // and filtering it with criteria and options. func (c *Client) FindBaseIds(criteria *Criteria, options *Options) ([]int64, error) { ids, err := c.Search(BaseModel, criteria, options) if err != nil { return []int64{}, err } return ids, nil } // FindBaseId finds record id by querying it with criteria. func (c *Client) FindBaseId(criteria *Criteria, options *Options) (int64, error) { ids, err := c.Search(BaseModel, criteria, options) if err != nil { return -1, err } if len(ids) > 0 { return ids[0], nil } return -1, fmt.Errorf("base was not found with criteria %v and options %v", criteria, options) }
package core import ( "github.com/golang/glog" "github.com/mefuwei/wdns/storage" "github.com/miekg/dns" "net" "strconv" ) const ( resovePath = "/etc/resolv.conf" ) var ( defaultServers = []string{"114.114.114.114"} defaultPort = 53 // TODO used config storageType = "redis" redisAddr = "localhost:6379" redisPasswd = "" redisDb = 1 ) type DnsHandler struct{} func (d *DnsHandler) ServeDNS(w dns.ResponseWriter, r *dns.Msg) { h := NewHandler(w, r) h.Do() } func NewHandler(w dns.ResponseWriter, r *dns.Msg) *Handler { question := r.Question[0] name, qtype := question.Name, question.Qtype remoteAddr := w.RemoteAddr().String() respMsg := new(dns.Msg) respMsg.SetReply(r) h := &Handler{ Client: new(dns.Client), W: w, ReqMsg: r, RespMsg: respMsg, Name: name, Qtype: qtype, RemoteAddr: remoteAddr, } return h } type Handler struct { Client *dns.Client // exchange client W dns.ResponseWriter // write at msg ReqMsg *dns.Msg // dns client request msg type RespMsg *dns.Msg // output to dns client msg Name string // dns question name Qtype uint16 // dns question type RemoteAddr string } // TODO get backend sorage for common object and this config. func (h *Handler) Do() { bs := storage.GetStorage(storageType, redisAddr, redisPasswd, redisDb) if msg, err := bs.Get(h.Name, h.Qtype); err != nil { // if not match local dns proxy to resolve h.Exchange() return } else { // backend storage return a null msg msg = msg.SetReply(h.RespMsg) h.Write(msg) return } } func (h *Handler) Exchange() { var Servers []string var Port string config, err := dns.ClientConfigFromFile(resovePath) if err != nil { glog.Errorf("Parse %s failed use default nameserver, %s", resovePath, err.Error()) Servers = defaultServers Port = strconv.Itoa(defaultPort) } else { Servers = config.Servers Port = config.Port } // do exchange for _, srv := range Servers { server := net.JoinHostPort(srv, Port) if respMsg, _, err := h.Client.Exchange(h.ReqMsg, server); err == nil { h.Write(respMsg) return } } } // Write msg to client func (h *Handler) Write(msg *dns.Msg) { if err := h.W.WriteMsg(msg); err != nil { glog.Errorf("[%s] fuck-dns write dns failed, %s", h.RemoteAddr, err.Error()) } else { glog.Infof("[%s] query name: %s type: %d write success", h.RemoteAddr, h.Name, h.Qtype) } }
package oas3 import ( "bytes" "fmt" "log" "net/http" "net/textproto" "strings" "github.com/getkin/kin-openapi/openapi3" "github.com/SVilgelm/oas3-server/pkg/utils" "github.com/gorilla/mux" ) type response struct { http.ResponseWriter buf *bytes.Buffer statusCode int } func (w *response) WriteHeader(statusCode int) { w.statusCode = statusCode } func (w *response) Write(body []byte) (int, error) { return w.buf.Write(body) } func (w *response) send() { if w.statusCode == 0 { w.statusCode = 200 } w.ResponseWriter.WriteHeader(w.statusCode) if _, err := w.ResponseWriter.Write(w.buf.Bytes()); err != nil { log.Print(err) } } func processValues(param *openapi3.Parameter, values []string) string { if param.Schema.Value.Type != "array" { if len(values) == 1 { return values[0] } return strings.Join(values, " ") } else if param.Schema.Value.Items.Value.Type == "string" { size := 2 + 2*len(values) + len(values) - 1 // [] + ""*len(values) + commas for _, v := range values { size += len(v) } b := strings.Builder{} b.Grow(size) b.WriteString(`[`) b.WriteString(`"`) b.WriteString(values[0]) b.WriteString(`"`) for _, v := range values[1:] { b.WriteString(`,"`) b.WriteString(v) b.WriteString(`"`) } b.WriteString(`]`) return b.String() } return "[" + strings.Join(values, ",") + "]" } func getRealValue(in, name string, r *http.Request, item *Item, route *mux.Route) (string, bool) { switch in { case openapi3.ParameterInCookie: cookie, err := r.Cookie(name) if err != nil { return "", false } return cookie.Value, true case openapi3.ParameterInQuery: values := r.URL.Query()[name] if len(values) == 0 { return "", false } param := item.FindParam(in, name, route) if param == nil { return "", false } return processValues(param, values), true case openapi3.ParameterInHeader: values := r.Header[textproto.CanonicalMIMEHeaderKey(name)] if len(values) == 0 { return "", false } param := item.FindParam(in, name, route) if param == nil { return "", false } return processValues(param, values), true case openapi3.ParameterInPath: vars := mux.Vars(r) pathValue, ok := vars[name] if !ok { return "", false } return pathValue, true } return "", false } func getRealParameters(r *http.Request, item *Item, route *mux.Route) *utils.DoubleMapString { valuesCache := make(utils.DoubleMapString) for in, pr := range item.meta[route].requestParamsNotString { for name := range pr { value, ok := getRealValue(in, name, r, item, route) if !ok { continue } valuesCache.Set(in, name, value) } } return &valuesCache } func getParameterDataBuilder(valuesCache *utils.DoubleMapString, item *Item, route *mux.Route) *strings.Builder { size := 2 // {} if len(*valuesCache) > 0 { size += 5*len(*valuesCache) + len(*valuesCache) - 1 // len(in) * "":{} commas for in, pr := range *valuesCache { size += len(in) size += 3*len(pr) + len(pr) - 1 // len(pr) * "": + commas for name, value := range pr { size += len(name) + len(value) if !item.meta[route].requestParamsNotString[in][name] { size += 2 // "" } } } } builder := strings.Builder{} builder.Grow(size) return &builder } func prepareParametersData(r *http.Request, item *Item, route *mux.Route) []byte { valuesCache := getRealParameters(r, item, route) builder := getParameterDataBuilder(valuesCache, item, route) builder.WriteString(`{`) dataQuote := `"` for in, pr := range *valuesCache { builder.WriteString(dataQuote) dataQuote = `,"` builder.WriteString(in) builder.WriteString(`":{`) inQuote := `"` for name, value := range pr { builder.WriteString(inQuote) inQuote = `,"` builder.WriteString(name) builder.WriteString(`":`) if item.meta[route].requestParamsNotString[in][name] { builder.WriteString(value) } else { builder.WriteString(`"`) builder.WriteString(value) builder.WriteString(`"`) } } builder.WriteString(`}`) } builder.WriteString(`}`) return []byte(builder.String()) } func validateRequest(r *http.Request, item *Item, route *mux.Route) error { rs := item.meta[route].requestSchema if rs != nil { data := prepareParametersData(r, item, route) valErr, err := rs.ValidateBytes(data) if err != nil { return err } if len(valErr) > 0 { return fmt.Errorf("validating request parameters: %+v", valErr) } } return nil } type MiddlewareHandler struct { doRequestValidation bool doResponseValidation bool mapper *Mapper next http.Handler } func (m *MiddlewareHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { route := mux.CurrentRoute(r) item := m.mapper.ByRoute(route) if item == nil { m.next.ServeHTTP(w, r) return } ctx := WithOperation(r.Context(), item) r = r.WithContext(ctx) if m.doRequestValidation { if err := validateRequest(r, item, route); err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return } } if m.doResponseValidation { rw := response{ ResponseWriter: w, buf: new(bytes.Buffer), } m.next.ServeHTTP(&rw, r) rw.send() } else { m.next.ServeHTTP(w, r) } } // Middleware puts the model into the current context and run validations func Middleware(mapper *Mapper, doRequestValidation, doResponseValidation bool) mux.MiddlewareFunc { return func(next http.Handler) http.Handler { m := MiddlewareHandler{ doRequestValidation: doRequestValidation, doResponseValidation: doResponseValidation, mapper: mapper, next: next, } return &m } }
package p16 import ( "testing" ) func TestDance(t *testing.T) { tests := []struct { Input string Key string Result string }{ { Input: "@t.txt", Key: "abcde", Result: "baedc", }, { Input: "@a.txt", Key: "abcdefghijklmnop", Result: "cknmidebghlajpfo", }, } for i, test := range tests { s := Dance(test.Input, test.Key) if s != test.Result { t.Fatalf("a.%d: %s '%s' (should be %s)", i, test.Input, s, test.Result) } } } func TestLotsOfDances(t *testing.T) { tests := []struct { Input string Key string Result string }{ { Input: "@a.txt", Key: "abcdefghijklmnop", Result: "cbolhmkgfpenidaj", }, } for i, test := range tests { s := LotsOfDances(test.Input, test.Key) if s != test.Result { t.Fatalf("b.%d: %s '%s' (should be %s)", i, test.Input, s, test.Result) } } }
package kafka_test import ( "context" "fmt" "time" "github.com/Shopify/sarama" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" "github.com/sirupsen/logrus" ) var _ = Describe("Kafka", func() { Context("admin test", func() { It("create topic", func() { topicDetail := &sarama.TopicDetail{ NumPartitions: 1, ReplicationFactor: 1} err = kafkaAdmin.CreateTopic(kafkaTopicName4Test, topicDetail, false) Expect(err).NotTo(HaveOccurred()) }) It("list topic", func() { var result map[string]sarama.TopicDetail result, err = kafkaAdmin.ListTopics() Expect(err).NotTo(HaveOccurred()) Expect(result).To(HaveKey(kafkaTopicName4Test)) }) It("describe topic", func() { var result []*sarama.TopicMetadata result, err = kafkaAdmin.DescribeTopics([]string{kafkaTopicName4Test}) Expect(err).NotTo(HaveOccurred()) Expect(result[0].Name).To(Equal(kafkaTopicName4Test)) }) It("delete topic", func() { err = kafkaAdmin.DeleteTopic(kafkaTopicName4Test) Expect(err).NotTo(HaveOccurred()) }) }) Context("producer test", func() { It("sync producer", func() { _, _, err = syncProducer.SendMessage(&sarama.ProducerMessage{ Topic: kafkaTopicName, Value: sarama.StringEncoder("sync producer"), }) Expect(err).NotTo(HaveOccurred()) }) It("async producer", func() { asyncProducer.Input() <- &sarama.ProducerMessage{ Topic: kafkaTopicName, Value: sarama.StringEncoder("async producer"), } select { case msg := <-asyncProducer.Successes(): Expect(msg.Offset).NotTo(BeZero()) case err = <-asyncProducer.Errors(): Fail("async producer failed") case <-time.After(time.Second): Fail("timed out waiting for output") } }) }) Context("consumer test", func() { It("consumer messages", func() { var partitions []int32 partitions, err = kafkaConsumer.Partitions(kafkaTopicName) Expect(err).NotTo(HaveOccurred()) Expect(len(partitions)).To(Equal(1)) var pc sarama.PartitionConsumer pc, err = kafkaConsumer.ConsumePartition(kafkaTopicName, 0, sarama.OffsetOldest) Expect(err).NotTo(HaveOccurred()) results := []string{} CONSUME: for { select { case tmp := <-pc.Messages(): results = append(results, string(tmp.Value)) case <-time.After(5 * time.Second): break CONSUME } } Expect(len(results)).To(Equal(2)) Expect(results).To(ContainElement("sync producer")) Expect(results).To(ContainElement("async producer")) }) }) Context("consumer group test", func() { It("consumer messages", func() { topics := []string{kafkaTopicName} ctx := context.Background() handler := &ConsumerGroupHandler{ messageChannel: make(chan *sarama.ConsumerMessage, 10), } go func() { err = kafkaConsumerGroup.Consume(ctx, topics, handler) Expect(err).NotTo(HaveOccurred()) }() results := []string{} CONSUME: for { select { case tmp := <-handler.messageChannel: results = append(results, string(tmp.Value)) case <-time.After(5 * time.Second): break CONSUME } } Expect(len(results)).To(Equal(2)) Expect(results).To(ContainElement("sync producer")) Expect(results).To(ContainElement("async producer")) }) }) }) type ConsumerGroupHandler struct { messageChannel chan *sarama.ConsumerMessage } func (ConsumerGroupHandler) Setup(s sarama.ConsumerGroupSession) error { fmt.Println("Partition allocation -", s.Claims()) return nil } func (ConsumerGroupHandler) Cleanup(s sarama.ConsumerGroupSession) error { fmt.Println("Consumer group clean up initiated") return nil } func (h ConsumerGroupHandler) ConsumeClaim(sess sarama.ConsumerGroupSession, claim sarama.ConsumerGroupClaim) error { for msg := range claim.Messages() { h.messageChannel <- msg fmt.Printf("Message topic:%q partition:%d offset:%d\n", msg.Topic, msg.Partition, msg.Offset) if err != nil { logrus.Error("Fail to process message", err) continue } sess.MarkMessage(msg, "") } return nil }
package builder import ( "context" "net" "net/http" "net/http/httptest" "os" "path/filepath" "testing" "github.com/google/go-containerregistry/pkg/name" "github.com/google/go-containerregistry/pkg/registry" v1 "github.com/google/go-containerregistry/pkg/v1" "github.com/google/go-containerregistry/pkg/v1/layout" "github.com/google/go-containerregistry/pkg/v1/remote" "github.com/openshift/library-go/pkg/image/reference" "github.com/stretchr/testify/require" "github.com/openshift/oc-mirror/internal/testutils" ) func TestCreateLayout(t *testing.T) { tests := []struct { name string existingImage bool err string }{ { name: "Success/ExistingImage", existingImage: true, }, { name: "Success/NewImage", existingImage: false, }, } for _, test := range tests { t.Run(test.name, func(t *testing.T) { tmpdir := t.TempDir() server := httptest.NewServer(registry.New()) t.Cleanup(server.Close) targetRef, err := testutils.WriteTestImage(server, tmpdir) require.NoError(t, err) builder := NewImageBuilder([]name.Option{name.Insecure}, nil) var lp layout.Path if test.existingImage { lp, err = builder.CreateLayout(targetRef, t.TempDir()) } else { lp, err = builder.CreateLayout("", tmpdir) } if test.err == "" { require.NoError(t, err) ii, err := lp.ImageIndex() require.NoError(t, err) im, err := ii.IndexManifest() require.NoError(t, err) require.Len(t, im.Manifests, 1) } else { require.EqualError(t, err, test.err) } }) } } func TestRun(t *testing.T) { tests := []struct { name string existingImage bool pinToDigest bool update configUpdateFunc configAssertFunc func(cfg v1.ConfigFile) bool multiarch bool // create a multi arch image err error }{ { name: "Success/ExistingImage", existingImage: true, }, { name: "Success/NewImage", existingImage: false, }, { name: "Success/WithConfigUpdate", existingImage: true, update: func(cfg *v1.ConfigFile) { cfg.Config.Cmd = []string{"newcommand"} }, configAssertFunc: func(cfg v1.ConfigFile) bool { return cfg.Config.Cmd[0] == "newcommand" }, }, { name: "Failure/DigestReference", pinToDigest: true, err: &ErrInvalidReference{}, }, { name: "Success/ExistingImage - multi arch", existingImage: true, multiarch: true, }, { name: "Success/NewImage - multi arch", existingImage: false, multiarch: true, }, { name: "Success/WithConfigUpdate - multi arch", existingImage: true, update: func(cfg *v1.ConfigFile) { cfg.Config.Cmd = []string{"newcommand"} }, configAssertFunc: func(cfg v1.ConfigFile) bool { return cfg.Config.Cmd[0] == "newcommand" }, multiarch: true, }, { name: "Failure/DigestReference - multi arch", pinToDigest: true, err: &ErrInvalidReference{}, multiarch: true, }, { name: "Success/ExistingImage - multi arch with filter", existingImage: true, multiarch: true, }, } for _, test := range tests { t.Run(test.name, func(t *testing.T) { tmpdir := t.TempDir() // each test case gets its own server server := httptest.NewServer(registry.New()) t.Cleanup(server.Close) var targetRef string var err error if test.multiarch { targetRef, err = testutils.WriteMultiArchTestImage(server, tmpdir) // targetRef, err := testutils.WriteMultiArchTestImageWithURL("http://localhost:5000", tmpdir) } else { targetRef, err = testutils.WriteTestImage(server, tmpdir) // targetRef, err := testutils.WriteTestImageWithURL("http://localhost:5000", tmpdir) } require.NoError(t, err) if test.pinToDigest { targetRef, err = pinToDigest(targetRef) require.NoError(t, err) } d1 := []byte("hello\ngo\n") require.NoError(t, os.WriteFile(filepath.Join(tmpdir, "test"), d1, 0644)) add, err := LayerFromPath("/testfile", filepath.Join(tmpdir, "test")) require.NoError(t, err) builder := NewImageBuilder([]name.Option{name.Insecure}, nil) var layout layout.Path if test.existingImage { layout, err = builder.CreateLayout(targetRef, t.TempDir()) require.NoError(t, err) } else { layout, err = builder.CreateLayout("", tmpdir) require.NoError(t, err) } err = builder.Run(context.Background(), targetRef, layout, test.update, []v1.Layer{add}...) if test.err == nil { require.NoError(t, err) // Get new image information ref, err := name.ParseReference(targetRef, name.Insecure) require.NoError(t, err) /* There's an important distinction between what's possible in OCI layout versus docker registries, and you need to understand this when reading this test. The WriteMultiArchTestImage function creates an OCI layout AND pushes to the dummy registry. An OCI layout path contains an index.json where the manifest entries reference either a manifest list or an actual image. Since the index.json is technically its own index, you can have "index indirection" where the manifest entry in index.json points to a SHA within the blobs directory that is itself an "index". For example: Single arch in an index.json { "schemaVersion": 2, "manifests": [ { "mediaType": "application/vnd.docker.distribution.manifest.v2+json", "digest": "sha256:1234...", "size": 111 } ] } multi arch with "indirection" in an index.json { "schemaVersion": 2, "manifests": [ { "mediaType": "application/vnd.docker.distribution.manifest.list.v2+json", "digest": "sha256:5678...", "size": 321 } ] } multi arch without "indirection" in an index.json (this scenario is probably not likely) { "schemaVersion": 2, "mediaType": "application/vnd.docker.distribution.manifest.list.v2+json", "manifests": [ { "mediaType": "application/vnd.docker.distribution.manifest.v2+json", "size": 525, "digest": "sha256:9123...", "platform": { "architecture": "amd64", "os": "linux" } }, { "mediaType": "application/vnd.docker.distribution.manifest.v2+json", "size": 525, "digest": "sha256:4567...", "platform": { "architecture": "s390x", "os": "linux" } } ] } However, in a "remote" docker registry, manifest indirection does not exist. So when reading the descriptor from the "remote", we should expect to see a direct reference to either the manifest list or image. */ var desc *remote.Descriptor // make remote call to our dummy server to get its descriptor desc, err = remote.Get(ref) require.NoError(t, err) // figure out an image to test against var img v1.Image if test.multiarch { require.True(t, desc.MediaType.IsIndex(), "expected a multi arch index") idx, err := desc.ImageIndex() require.NoError(t, err) mf, err := idx.IndexManifest() require.NoError(t, err) for _, innerDescriptor := range mf.Manifests { img, err = idx.Image(innerDescriptor.Digest) require.NoError(t, err) } } else { // single arch tests we can just get the image directly // NOTE: WriteTestImage pushes an OCI image to the registry, so its technically a "manifest list" // and the image is "resolved" using the platform associated with the image reference, or the default // (i.e. linux/amd64) if platform is not present img, err = desc.Image() require.NoError(t, err) } // make sure we've actually found an image to work with require.NotNil(t, img) layers, err := img.Layers() require.NoError(t, err) idx, err := desc.ImageIndex() require.NoError(t, err) im, err := idx.IndexManifest() require.NoError(t, err) // Check that new layer is present expectedDigest, err := add.Digest() require.NoError(t, err) var found bool for _, ly := range layers { dg, err := ly.Digest() require.NoError(t, err) if dg == expectedDigest { found = true } } require.True(t, found) if test.multiarch { // multi arch test has two manifests (linux/amd64 and linux/s390x) require.Len(t, im.Manifests, 2) } else { // single arch test has a single image, so only one manifest require.Len(t, im.Manifests, 1) } if test.update != nil { config, err := img.ConfigFile() require.NoError(t, err) require.True(t, test.configAssertFunc(*config)) } } else { require.ErrorAs(t, err, &test.err) } }) } } func NewTestServerWithURL(URL string, handler http.Handler) (*httptest.Server, error) { ts := httptest.NewUnstartedServer(handler) if URL != "" { l, err := net.Listen("tcp", URL) if err != nil { return nil, err } ts.Listener.Close() ts.Listener = l } ts.Start() return ts, nil } func TestLayoutFromPath(t *testing.T) { tests := []struct { name string dir bool targetPath string err string }{ { name: "Valid/DirPath", targetPath: "testdir/", dir: true, }, { name: "Valid/FilePath", targetPath: "testfile", dir: false, }, } for _, test := range tests { t.Run(test.name, func(t *testing.T) { tmpdir := t.TempDir() // prep directory with files to write into layer d1 := []byte("hello\ngo\n") require.NoError(t, os.WriteFile(filepath.Join(tmpdir, "test"), d1, 0644)) var sourcePath string if test.dir { sourcePath = tmpdir } else { sourcePath = filepath.Join(tmpdir, "test") } layer, err := LayerFromPath(test.targetPath, sourcePath) if test.err == "" { require.NoError(t, err) digest, err := layer.Digest() require.NoError(t, err) require.Contains(t, digest.String(), ":") } else { require.EqualError(t, err, test.err) } }) } } func pinToDigest(unpinnedImage string) (string, error) { ref, err := reference.Parse(unpinnedImage) if err != nil { return "", err } ref.ID = "sha256:fc1ca63b4a6ac038808ae33c4498b122f9cf7a43dca278228e985986d3f81091" return ref.Exact(), nil }
package main import ( "fmt" ) func main() { // grade1 := 97 // grade2 := 85 // grade3 := 93 // fmt.Printf("Grades: %v, %v, %v \n", grade1, grade2, grade3) // ----------------------------------------------------------- // grades := [3]int{97, 85, 93} // fmt.Printf("Grades: %v \n", grades) // ----------------------------------------------------------- // grades := [...]int{97, 85, 93} // fmt.Printf("Grades: %v", grades) // ----------------------------------------------------------- // ARRAY INSERT var students [3]string fmt.Printf("Students: %v \n", students) students[0] = "Lisa" fmt.Printf("Students: %v \n", students) }
package middleware import ( "strings" "github.com/labstack/echo/v4" "github.com/labstack/echo/v4/middleware" ) // The SkipperFunc signature, used to serve the main request without logs. // See `Configuration` too. type ( SkipperFunc = middleware.Skipper ) // DefaultSkipper returns false which processes the middleware. var ( DefaultSkipper = middleware.DefaultSkipper ) // SkipHandler 统一处理跳过函数 func SkipHandler(ctx echo.Context, skippers ...SkipperFunc) bool { for _, skipper := range skippers { if skipper(ctx) { return true } } return false } // HigherSkipperFunc 进一步包装处理函数 type HigherSkipperFunc func(...string) SkipperFunc // AllowPathPrefixSkipper 检查请求路径是否包含指定的前缀,如果包含则跳过 func AllowPathPrefixSkipper(prefixes ...string) SkipperFunc { return func(c echo.Context) bool { for _, p := range prefixes { if strings.HasPrefix(c.Path(), p) { return true } } return false } } // AllowPathPrefixNoSkipper 检查请求路径是否包含指定的前缀,如果包含则不跳过 func AllowPathPrefixNoSkipper(prefixes ...string) SkipperFunc { return func(c echo.Context) bool { for _, p := range prefixes { if strings.HasPrefix(c.Path(), p) { return false } } return true } }
// +build cairo package expr import ( "testing" "time" ) func TestEvalExpressionGraph(t *testing.T) { now32 := int32(time.Now().Unix()) tests := []evalTestItem{ { &expr{ target: "threshold", etype: etFunc, args: []*expr{ {val: 42.42, etype: etConst}, }, argString: "42.42", }, map[MetricRequest][]*MetricData{}, []*MetricData{makeResponse("42.42", []float64{42.42, 42.42}, 1, now32)}, }, { &expr{ target: "threshold", etype: etFunc, args: []*expr{ {val: 42.42, etype: etConst}, {valStr: "fourty-two", etype: etString}, }, argString: "42.42,'fourty-two'", }, map[MetricRequest][]*MetricData{}, []*MetricData{makeResponse("fourty-two", []float64{42.42, 42.42}, 1, now32)}, }, { &expr{ target: "threshold", etype: etFunc, args: []*expr{ {val: 42.42, etype: etConst}, {valStr: "fourty-two", etype: etString}, {valStr: "blue", etype: etString}, }, argString: "42.42,'fourty-two','blue'", }, map[MetricRequest][]*MetricData{}, []*MetricData{makeResponse("fourty-two", []float64{42.42, 42.42}, 1, now32)}, }, { &expr{ target: "threshold", etype: etFunc, args: []*expr{ {val: 42.42, etype: etConst}, }, namedArgs: map[string]*expr{ "label": {valStr: "fourty-two", etype: etString}, }, argString: "42.42,label='fourty-two'", }, map[MetricRequest][]*MetricData{}, []*MetricData{makeResponse("fourty-two", []float64{42.42, 42.42}, 1, now32)}, }, { &expr{ target: "threshold", etype: etFunc, args: []*expr{ {val: 42.42, etype: etConst}, }, namedArgs: map[string]*expr{ "color": {valStr: "blue", etype: etString}, //TODO(nnuss): test blue is being set rather than just not causing expression to parse/fail }, argString: "42.42,color='blue'", }, map[MetricRequest][]*MetricData{}, []*MetricData{makeResponse("42.42", []float64{42.42, 42.42}, 1, now32)}, }, { &expr{ target: "threshold", etype: etFunc, args: []*expr{ {val: 42.42, etype: etConst}, }, namedArgs: map[string]*expr{ "label": {valStr: "fourty-two-blue", etype: etString}, "color": {valStr: "blue", etype: etString}, //TODO(nnuss): test blue is being set rather than just not causing expression to parse/fail }, argString: "42.42,label='fourty-two-blue',color='blue'", }, map[MetricRequest][]*MetricData{}, []*MetricData{makeResponse("fourty-two-blue", []float64{42.42, 42.42}, 1, now32)}, }, { // BUG(nnuss): This test actually fails with color = "" because of // how getStringNamedOrPosArgDefault works but we don't notice // because we're not testing color is set. // You may manually verify with this request URI: /render/?format=png&target=threshold(42.42,"gold",label="fourty-two-aurum") &expr{ target: "threshold", etype: etFunc, args: []*expr{ {val: 42.42, etype: etConst}, {valStr: "gold", etype: etString}, }, namedArgs: map[string]*expr{ "label": {valStr: "fourty-two-aurum", etype: etString}, }, argString: "42.42,'gold',label='fourty-two-aurum'", }, map[MetricRequest][]*MetricData{}, []*MetricData{makeResponse("fourty-two-aurum", []float64{42.42, 42.42}, 1, now32)}, }, } for _, tt := range tests { testEvalExpr(t, &tt) } }
// Copyright 2022 The ChromiumOS Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package intel import ( "context" "net/http" "net/http/httptest" "time" "chromiumos/tast/common/perf" "chromiumos/tast/local/chrome" "chromiumos/tast/local/media/devtools" "chromiumos/tast/testing" ) func init() { testing.AddTest(&testing.Test{ Func: VP8VideoDecoder, LacrosStatus: testing.LacrosVariantUnneeded, Desc: "Verifies whether VP8 decoder is supported or not", Contacts: []string{"ambalavanan.m.m@intel.com", "intel-chrome-system-automation-team@intel.com"}, SoftwareDeps: []string{"chrome"}, Attr: []string{"group:mainline", "informational"}, Data: []string{"1080p_60fps_600frames.vp8.webm", "video.html", "playback.js"}, Fixture: "chromeLoggedIn", Timeout: 3 * time.Minute, }) } func VP8VideoDecoder(ctx context.Context, s *testing.State) { cr := s.FixtValue().(*chrome.Chrome) srv := httptest.NewServer(http.FileServer(s.DataFileSystem())) defer srv.Close() url := srv.URL + "/video.html" conn, err := cr.NewConn(ctx, url) if err != nil { s.Fatal("Failed to load video.html: ", err) } defer conn.Close() videoFile := "1080p_60fps_600frames.vp8.webm" if err := conn.Call(ctx, nil, "playRepeatedly", videoFile, false, true); err != nil { s.Fatal("Failed to play video: ", err) } // Video Element in the page to play a video. videoElement := "document.getElementsByTagName('video')[0]" var decodedFrameCount, droppedFrameCount int64 if err := conn.Eval(ctx, videoElement+".getVideoPlaybackQuality().totalVideoFrames", &decodedFrameCount); err != nil { s.Fatal("Failed to get number of decoded frames: ", err) } if err := conn.Eval(ctx, videoElement+".getVideoPlaybackQuality().droppedVideoFrames", &droppedFrameCount); err != nil { s.Fatal("Failed to get number of dropped frames: ", err) } var droppedFramePercent float64 if decodedFrameCount != 0 { droppedFramePercent = 100.0 * float64(droppedFrameCount) / float64(decodedFrameCount) } else { s.Log("No decoded frames; setting dropped percent to 100") droppedFramePercent = 100.0 } p := perf.NewValues() p.Set(perf.Metric{ Name: "dropped_frames", Unit: "frames", Direction: perf.SmallerIsBetter, }, float64(droppedFrameCount)) p.Set(perf.Metric{ Name: "dropped_frames_percent", Unit: "percent", Direction: perf.SmallerIsBetter, }, droppedFramePercent) s.Logf("Dropped frames: %d (%f%%)", droppedFrameCount, droppedFramePercent) observer, err := conn.GetMediaPropertiesChangedObserver(ctx) if err != nil { s.Fatal("Failed to retrieve DevTools Media messages: ", err) } isPlatform, decoderName, err := devtools.GetVideoDecoder(ctx, observer, url) if err != nil { s.Fatal("Failed to parse Media DevTools: ", err) } wantDecoder := "VaapiVideoDecoder" if !isPlatform && decoderName != wantDecoder { s.Fatalf("Failed: Hardware decoding accelerator was expected with decoder name but wasn't used: got: %q, want: %q", decoderName, wantDecoder) } if err := conn.Eval(ctx, videoElement+".pause()", nil); err != nil { s.Fatal("Failed to stop video: ", err) } }
package main import ( "fmt" "github.com/plunder-app/plunder/pkg/parlay/parlaytypes" ) func (e *etcdMembers) generateActions() []parlaytypes.Action { var generatedActions []parlaytypes.Action var a parlaytypes.Action if e.InitCA == true { // Ensure that a new Certificate Authority is generated // Create action a = parlaytypes.Action{ // Generate etcd server certificate ActionType: "command", Command: fmt.Sprintf("kubeadm init phase certs etcd-ca"), CommandSudo: "root", Name: "Initialise Certificate Authority", } generatedActions = append(generatedActions, a) } // Default to < 1.12 API version if e.APIVersion == "" { e.APIVersion = "v1beta1" } // Generate the configuration directories a.ActionType = "command" a.Command = fmt.Sprintf("mkdir -m 777 -p /tmp/%s/ /tmp/%s/ /tmp/%s/", e.Address1, e.Address2, e.Address3) a.Name = "Generate temporary directories" generatedActions = append(generatedActions, a) // Generate the kubeadm configuration files // Node 0 a.Name = "build kubeadm config for node 0" a.Command = fmt.Sprintf("echo '%s' > /tmp/%s/kubeadmcfg.yaml", e.buildKubeadm(e.APIVersion, e.Hostname1, e.Address1), e.Address1) generatedActions = append(generatedActions, a) // Node 1 a.Name = "build kubeadm config for node 1" a.Command = fmt.Sprintf("echo '%s' > /tmp/%s/kubeadmcfg.yaml", e.buildKubeadm(e.APIVersion, e.Hostname2, e.Address2), e.Address2) generatedActions = append(generatedActions, a) // Node 2 a.Name = "build kubeadm config for node 2" a.Command = fmt.Sprintf("echo '%s' > /tmp/%s/kubeadmcfg.yaml", e.buildKubeadm(e.APIVersion, e.Hostname3, e.Address3), e.Address3) generatedActions = append(generatedActions, a) // Add certificate actions generatedActions = append(generatedActions, e.generateCertificateActions([]string{e.Address3, e.Address2, e.Address1})...) return generatedActions } func (e *etcdMembers) buildKubeadm(api, host, address string) string { var kubeadm string // Generates a kubeadm for setting up the etcd yaml kubeadm = fmt.Sprintf(etcdKubeadm, api, address, address, e.Hostname1, e.Address1, e.Hostname2, e.Address2, e.Hostname3, e.Address3, host, address, address, address, address) return kubeadm } // generateCertificateActions - Hosts need adding in backward to the array i.e. host 2 -> host 1 -> host 0 func (e *etcdMembers) generateCertificateActions(hosts []string) []parlaytypes.Action { var generatedActions []parlaytypes.Action var a parlaytypes.Action a.Command = "mkdir -p /etc/kubernetes/pki" a.CommandSudo = "root" a.Name = "Ensure that PKI directory exists" a.ActionType = "command" generatedActions = append(generatedActions, a) for i, v := range hosts { // Tidy any existing client certificates a.ActionType = "command" a.Command = "find /etc/kubernetes/pki -not -name ca.crt -not -name ca.key -type f -delete" a.Name = "Remove any existing client certificates before attempting to generate any new ones" generatedActions = append(generatedActions, a) // Generate etcd server certificate a.ActionType = "command" a.Command = fmt.Sprintf("kubeadm init phase certs etcd-server --config=/tmp/%s/kubeadmcfg.yaml", v) a.Name = fmt.Sprintf("Generate etcd server certificate for [%s]", v) generatedActions = append(generatedActions, a) // Generate peer certificate a.Command = fmt.Sprintf("kubeadm init phase certs etcd-peer --config=/tmp/%s/kubeadmcfg.yaml", v) a.Name = fmt.Sprintf("Generate peer certificate for [%s]", v) generatedActions = append(generatedActions, a) // Generate health check certificate a.Command = fmt.Sprintf("kubeadm init phase certs etcd-healthcheck-client --config=/tmp/%s/kubeadmcfg.yaml", v) a.Name = fmt.Sprintf("Generate health check certificate for [%s]", v) generatedActions = append(generatedActions, a) // Generate api-server client certificate a.Command = fmt.Sprintf("kubeadm init phase certs apiserver-etcd-client --config=/tmp/%s/kubeadmcfg.yaml", v) a.Name = fmt.Sprintf("Generate api-server client certificate for [%s]", v) generatedActions = append(generatedActions, a) // These steps are only required for the first two hosts if i != (len(hosts) - 1) { // Archive the certificates and the kubeadm configuration in a host specific archive name a.Command = fmt.Sprintf("tar -cvzf /tmp/%s.tar.gz $(find /etc/kubernetes/pki -type f) /tmp/%s/kubeadmcfg.yaml", v, v) a.Name = fmt.Sprintf("Archive generated certificates [%s]", v) generatedActions = append(generatedActions, a) // Download the archive files to the local machine a.ActionType = "download" a.Source = fmt.Sprintf("/tmp/%s.tar.gz", hosts[i]) a.Destination = fmt.Sprintf("/tmp/%s.tar.gz", hosts[i]) a.Name = fmt.Sprintf("Retrieve the certificate bundle for [%s]", v) generatedActions = append(generatedActions, a) } else { // This is the final host, grab the certificates for use by a manager a.Command = fmt.Sprintf("tar -cvzf /tmp/managercert.tar.gz /etc/kubernetes/pki/etcd/ca.crt /etc/kubernetes/pki/apiserver-etcd-client.crt /etc/kubernetes/pki/apiserver-etcd-client.key") a.Name = fmt.Sprintf("Archive generated certificates [%s]", v) generatedActions = append(generatedActions, a) // Download the archive files to the local machine a.ActionType = "download" a.Source = "/tmp/managercert.tar.gz" a.Destination = "/tmp/managercert.tar.gz" a.Name = "Retrieving the Certificates for the manager nodes" generatedActions = append(generatedActions, a) } } return generatedActions } // At some point the functions for the various kubeadm arease will be split into seperate files to ease management func (m *managerMembers) generateActions() []parlaytypes.Action { var generatedActions []parlaytypes.Action var a parlaytypes.Action if m.Stacked == false { // Not implemented yet TODO return nil } // Upload the initial etcd certificates to the first manager node a = parlaytypes.Action{ // Upload etcd server certificate ActionType: "upload", Source: "/tmp/managercert.tar.gz", Destination: "/tmp/managercert.tar.gz", Name: "Upload etcd server certificate to first manager", } generatedActions = append(generatedActions, a) // Install the certificates for etcd a.Name = "Installing the etcd certificates" a.ActionType = "command" a.CommandSudo = "root" a.Command = fmt.Sprintf("tar -xvzf /tmp/managercert.tar.gz -C /") generatedActions = append(generatedActions, a) // Generate the kubeadm configuration file a.Name = "Generating the Kubeadm file for the first manager node" a.Command = fmt.Sprintf("echo '%s' > /tmp/kubeadmcfg.yaml", m.buildKubeadm()) generatedActions = append(generatedActions, a) // Initialise the first node a.Name = "Initialise the first control plane node" a.Command = "kubeadm init --config /tmp/kubeadmcfg.yaml" generatedActions = append(generatedActions, a) return generatedActions } func (m *managerMembers) buildKubeadm() string { var kubeadm string // Generates a kubeadm for setting up the etcd yaml kubeadm = fmt.Sprintf(managerKubeadm, m.Version, "LB HOSTNAME FIXME", "LB HOSTNAME FIXME", 1000000, m.ETCDAddress1, m.ETCDAddress2, m.ETCDAddress3) return kubeadm }
package _2_Abstract_Factory_Pattern import ( "reflect" "testing" ) //步骤 8 //使用 FactoryProducer 来获取 AbstractFactory,通过传递类型信息来获取实体类的对象。 func TestAbstractFactoryPattern(t *testing.T) { tests := []struct { name string args string want string }{ {"color", "color", "color"}, {"Shape", "Shape", "Shape"}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { // 测试抽象工厂 factory := GetFactory(tt.args) if !reflect.DeepEqual(factory.Name(), tt.want) { t.Errorf("GetFactory() = %v, want %v", factory.Name(), tt.want) } // 测试 color 工厂 colorTests := []struct { name string args string want string }{ {"Red", "Red", "Red"}, {"Blue", "Blue", "Blue"}, {"Green", "Green", "Green"}, } for _, ctt := range colorTests { t.Run(ctt.name, func(t *testing.T) { color := factory.GetColor(ctt.args) if factory.Name() != "color" { if !reflect.DeepEqual(color, nil) { t.Errorf("GetFactory() = %v, want %v", color, nil) } } else { if !reflect.DeepEqual(color.Fill(), ctt.want) { t.Errorf("GetFactory() = %v, want %v", color, ctt.want) } } }) } // 测试 shape 工厂 shapeTests := []struct { name string args string want string }{ {"Rectangle", "Rectangle", "Rectangle"}, {"Square", "Square", "Square"}, {"Circle", "Circle", "Circle"}, } for _, stt := range shapeTests { t.Run(stt.name, func(t *testing.T) { shape := factory.GetShape(stt.args) if factory.Name() != "Shape" { if !reflect.DeepEqual(shape, nil) { t.Errorf("GetFactory() = %v, want %v", shape, nil) } } else { if !reflect.DeepEqual(shape.Draw(), stt.want) { t.Errorf("GetFactory() = %v, want %v", shape, stt.want) } } }) } }) } }
// 写真・スケッなどのイメージデータを取り込む // 対象フォルダに有るイメージファイルを、ファイル名を和名として取り込む。 // 該当の和名が存在しない場合は、ログを出力して継続する package main import ( "database/sql" "flag" "fmt" "io/ioutil" "log" "os" "path/filepath" "strings" _ "github.com/mattn/go-sqlite3" ) //TODO 実行時の環境を引数で受け取れるように! const dbDir = "../../../db/" const imageDir = dbDir + "images" const dbName = dbDir + "searchPlant.sqlite3" var ( db *sql.DB tx *sql.Tx ) var ( addr = flag.Bool("addr", false, "find open address and print to final-port.txt") ) func begin() { var err error // トランザクションの開始 tx, err = db.Begin() if err != nil { log.Fatal(err) } } func commit() { var err error // トランザクションの正常終了 err = tx.Commit() if err != nil { log.Fatal(err) } } // 指定されたフォルダー以下にあるイメージファイルでファル名を和名とし持つものをすべてテーブルに登録する //TODO 同じ和名で複数のイメージがある場合の名前と取り込み方 func importImageFiles(rootPath, searchPath string) { var fileInfo os.FileInfo fis, err := ioutil.ReadDir(searchPath) if err != nil { panic(err) } for _, fi := range fis { fullPath := filepath.Join(searchPath, fi.Name()) if fi.IsDir() { importImageFiles(rootPath, fullPath) } else { var rows *sql.Rows rel, err := filepath.Rel(rootPath, fullPath) if err != nil { panic(err) } // ファイル名からサフィックスを取り出し、"png"なら画像ファイルとしてテーブルに取り込む switch strings.ToLower(filepath.Ext(rel)) { case ".png", ".jpg": fname := rel[0 : len(rel)-4] log.Printf("File(%s) is target File type base(%s)\n", rel, fname) // ファイル名(和名)からLnoを取得する。 str := "" str = str + "select lno from searchPlant_1 where name = ?;" rows, err = tx.Query(str, fname) if err != nil { log.Fatalf("%q: '%s'\n", err, str) } defer rows.Close() if rows.Next() { var lno int err = rows.Scan(&lno) if err != nil { panic(err) } log.Printf("lno(%d)\n", lno) // TODO ファイルの内容を読み込んでテーブルに登録 file, err := os.Open(fullPath) defer file.Close() if err != nil { panic(err) } fileInfo, err = os.Stat(fullPath) if err != nil { panic(err) } // 大きいファイルは無視する if fileInfo.Size() < 100000 { b := make([]byte, fileInfo.Size()) file.Read(b) //TODO テーブルに登録 str = "" //TODO とりあえず枝番は 1 で str = str + "insert or replace into plant_image (lno, sno, image) values(?, 1, ?);" _, err = tx.Exec(str, lno, b) if err != nil { log.Fatalf("%q: '%s'\n", err, str) } } else { log.Printf("File(%s) is too big!\n", rel) } } else { // 無ければログを出して次に進む log.Printf("file(%s) is not in database\n", fullPath) } /* //TODO 一定サイズごとに読み込んでDBに書き込む b := make([]byte, 1) file.Read(b) */ default: log.Printf("File(%s) is unknown File type\n", rel) } fmt.Println(rel) } } } func main() { var err error log.Println(">>>>> main in") defer log.Println("<<<<< main out") flag.Parse() _, err = os.Stat(dbName) if err != nil { // ファイルの情報が取得できないならエラー(存在しないとか) log.Fatal(err) } db, err = sql.Open("sqlite3", dbName) if err != nil { log.Fatal(err) } defer db.Close() begin() //TODO テーブルの削除や再作成もここで行う? /* -- 写真やイメージなどの取り込み用 -- TODO 取り込みのためには、プログラムが必要? drop table if exists plant_image; create table if not exists plant_image (lno number, sno number, image blob, primary key(lno, sno) ); */ importImageFiles(imageDir, imageDir) commit() }
package telemetry import ( rudder "github.com/rudderlabs/analytics-go" ) // rudderDataPlaneURL is set to the common Data Plane URL for all Mattermost Projects. // It can be set during build time. More info in the package documentation. var rudderDataPlaneURL = "https://pdat.matterlytics.com" // rudderWriteKey is set during build time. More info in the package documentation. var rudderWriteKey string // NewRudderClient creates a new telemetry client with Rudder using the default configuration. func NewRudderClient() (Client, error) { return NewRudderClientWithCredentials(rudderWriteKey, rudderDataPlaneURL) } // NewRudderClientWithCredentials lets you create a Rudder client with your own credentials. func NewRudderClientWithCredentials(writeKey, dataPlaneURL string) (Client, error) { client, err := rudder.NewWithConfig(writeKey, dataPlaneURL, rudder.Config{}) if err != nil { return nil, err } return &rudderWrapper{client: client}, nil } type rudderWrapper struct { client rudder.Client } func (r *rudderWrapper) Enqueue(t Track) error { var context *rudder.Context if t.InstallationID != "" { context = &rudder.Context{Traits: map[string]interface{}{"installationId": t.InstallationID}} } return r.client.Enqueue(rudder.Track{ UserId: t.UserID, Event: t.Event, Context: context, Properties: t.Properties, }) } func (r *rudderWrapper) Close() error { return r.client.Close() }
package main // Leetcode 333. (medium) func largestBSTSubtree(root *TreeNode) int { _, _, _, res := dfsLargestBSTSubtree(root) return res } func dfsLargestBSTSubtree(root *TreeNode) (bool, int, int, int) { if root == nil { return true, 1 << 31, -1 << 31, 0 } if root.Left == nil && root.Right == nil { return true, root.Val, root.Val, 1 } left, leftMin, leftMax, leftRes := dfsLargestBSTSubtree(root.Left) right, rightMin, rightMax, rightRes := dfsLargestBSTSubtree(root.Right) if !left || !right || root.Val <= leftMax || root.Val >= rightMin { return false, 0, 0, max(leftRes, rightRes) } if root.Left == nil { return true, root.Val, rightMax, rightRes + 1 } if root.Right == nil { return true, leftMin, root.Val, leftRes + 1 } return true, leftMin, rightMax, leftRes + rightRes + 1 }
package auth0 import ( "fmt" "net/url" "kolihub.io/koli/pkg/apis/authentication" "kolihub.io/koli/pkg/request" ) type AuthenticationInterface interface { ClientCredentials(token *authentication.Token) (*authentication.Token, error) } type ManagementInterface interface { Users() UserInterface } func NewForConfig(c *Config) (CoreInterface, error) { requestURL, err := url.Parse(c.Host) if err != nil { return nil, fmt.Errorf("failed parsing URL: %v", err) } client := request.NewRequest(c.Client, requestURL) if len(c.BearerToken) > 0 { client.SetHeader("Authorization", fmt.Sprintf("Bearer %s", c.BearerToken)) } return &CoreClient{restClient: client}, nil }
// Copyright (c) 2016-2019 Uber Technologies, 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. package httputil import ( "context" "crypto/tls" "errors" "fmt" "io" "io/ioutil" "net/http" "net/url" "time" "github.com/cenkalti/backoff" "github.com/go-chi/chi" "github.com/uber/kraken/core" "github.com/uber/kraken/utils/handler" ) var retryableCodes = map[int]struct{}{ http.StatusTooManyRequests: {}, http.StatusBadGateway: {}, http.StatusServiceUnavailable: {}, http.StatusGatewayTimeout: {}, } // RoundTripper is an alias of the http.RoundTripper for mocking purposes. type RoundTripper = http.RoundTripper // StatusError occurs if an HTTP response has an unexpected status code. type StatusError struct { Method string URL string Status int Header http.Header ResponseDump string } // NewStatusError returns a new StatusError. func NewStatusError(resp *http.Response) StatusError { defer resp.Body.Close() respBytes, err := ioutil.ReadAll(resp.Body) respDump := string(respBytes) if err != nil { respDump = fmt.Sprintf("failed to dump response: %s", err) } return StatusError{ Method: resp.Request.Method, URL: resp.Request.URL.String(), Status: resp.StatusCode, Header: resp.Header, ResponseDump: respDump, } } func (e StatusError) Error() string { if e.ResponseDump == "" { return fmt.Sprintf("%s %s %d", e.Method, e.URL, e.Status) } return fmt.Sprintf("%s %s %d: %s", e.Method, e.URL, e.Status, e.ResponseDump) } // IsStatus returns true if err is a StatusError of the given status. func IsStatus(err error, status int) bool { statusErr, ok := err.(StatusError) return ok && statusErr.Status == status } // IsCreated returns true if err is a "created", 201 func IsCreated(err error) bool { return IsStatus(err, http.StatusCreated) } // IsNotFound returns true if err is a "not found" StatusError. func IsNotFound(err error) bool { return IsStatus(err, http.StatusNotFound) } // IsConflict returns true if err is a "status conflict" StatusError. func IsConflict(err error) bool { return IsStatus(err, http.StatusConflict) } // IsAccepted returns true if err is a "status accepted" StatusError. func IsAccepted(err error) bool { return IsStatus(err, http.StatusAccepted) } // IsForbidden returns true if statis code is 403 "forbidden" func IsForbidden(err error) bool { return IsStatus(err, http.StatusForbidden) } func isRetryable(code int) bool { _, ok := retryableCodes[code] return ok } // IsRetryable returns true if the statis code indicates that the request is // retryable. func IsRetryable(err error) bool { statusErr, ok := err.(StatusError) return ok && isRetryable(statusErr.Status) } // NetworkError occurs on any Send error which occurred while trying to send // the HTTP request, e.g. the given host is unresponsive. type NetworkError struct { err error } func (e NetworkError) Error() string { return fmt.Sprintf("network error: %s", e.err) } // IsNetworkError returns true if err is a NetworkError. func IsNetworkError(err error) bool { _, ok := err.(NetworkError) return ok } type sendOptions struct { body io.Reader timeout time.Duration acceptedCodes map[int]bool headers map[string]string redirect func(req *http.Request, via []*http.Request) error retry retryOptions transport http.RoundTripper ctx context.Context // This is not a valid http option. It provides a way to override // parts of the url. For example, url.Scheme can be changed from // http to https. url *url.URL // This is not a valid http option. HTTP fallback is added to allow // easier migration from http to https. // In go1.11 and go1.12, the responses returned when http request is // sent to https server are different in the fallback mode: // go1.11 returns a network error whereas go1.12 returns BadRequest. // This causes TestTLSClientBadAuth to fail because the test checks // retry error. // This flag is added to allow disabling http fallback in unit tests. // NOTE: it does not impact how it runs in production. httpFallbackDisabled bool } // SendOption allows overriding defaults for the Send function. type SendOption func(*sendOptions) // SendNoop returns a no-op option. func SendNoop() SendOption { return func(o *sendOptions) {} } // SendBody specifies a body for http request func SendBody(body io.Reader) SendOption { return func(o *sendOptions) { o.body = body } } // SendTimeout specifies timeout for http request func SendTimeout(timeout time.Duration) SendOption { return func(o *sendOptions) { o.timeout = timeout } } // SendHeaders specifies headers for http request func SendHeaders(headers map[string]string) SendOption { return func(o *sendOptions) { o.headers = headers } } // SendAcceptedCodes specifies accepted codes for http request func SendAcceptedCodes(codes ...int) SendOption { m := make(map[int]bool) for _, c := range codes { m[c] = true } return func(o *sendOptions) { o.acceptedCodes = m } } // SendRedirect specifies a redirect policy for http request func SendRedirect(redirect func(req *http.Request, via []*http.Request) error) SendOption { return func(o *sendOptions) { o.redirect = redirect } } type retryOptions struct { backoff backoff.BackOff extraCodes map[int]bool } // RetryOption allows overriding defaults for the SendRetry option. type RetryOption func(*retryOptions) // RetryBackoff adds exponential backoff between retries. func RetryBackoff(b backoff.BackOff) RetryOption { return func(o *retryOptions) { o.backoff = b } } // RetryCodes adds more status codes to be retried (in addition to the default // 5XX codes). // // WARNING: You better know what you're doing to retry anything non-5XX. func RetryCodes(codes ...int) RetryOption { return func(o *retryOptions) { for _, c := range codes { o.extraCodes[c] = true } } } // SendRetry will we retry the request on network / 5XX errors. func SendRetry(options ...RetryOption) SendOption { retry := retryOptions{ backoff: backoff.WithMaxRetries( backoff.NewConstantBackOff(250*time.Millisecond), 2), extraCodes: make(map[int]bool), } for _, o := range options { o(&retry) } return func(o *sendOptions) { o.retry = retry } } // DisableHTTPFallback disables http fallback when https request fails. func DisableHTTPFallback() SendOption { return func(o *sendOptions) { o.httpFallbackDisabled = true } } // SendTLS sets the transport with TLS config for the HTTP client. func SendTLS(config *tls.Config) SendOption { return func(o *sendOptions) { if config == nil { return } o.transport = &http.Transport{TLSClientConfig: config} o.url.Scheme = "https" } } // SendTLSTransport sets the transport with TLS config for the HTTP client. func SendTLSTransport(transport http.RoundTripper) SendOption { return func(o *sendOptions) { o.transport = transport o.url.Scheme = "https" } } // SendTransport sets the transport for the HTTP client. func SendTransport(transport http.RoundTripper) SendOption { return func(o *sendOptions) { o.transport = transport } } // SendContext sets the context for the HTTP client. func SendContext(ctx context.Context) SendOption { return func(o *sendOptions) { o.ctx = ctx } } // Send sends an HTTP request. May return NetworkError or StatusError (see above). func Send(method, rawurl string, options ...SendOption) (*http.Response, error) { u, err := url.Parse(rawurl) if err != nil { return nil, fmt.Errorf("parse url: %s", err) } opts := &sendOptions{ body: nil, timeout: 60 * time.Second, acceptedCodes: map[int]bool{http.StatusOK: true}, headers: map[string]string{}, retry: retryOptions{backoff: &backoff.StopBackOff{}}, transport: nil, // Use HTTP default. ctx: context.Background(), url: u, httpFallbackDisabled: true, } for _, o := range options { o(opts) } req, err := newRequest(method, opts) if err != nil { return nil, err } client := &http.Client{ Timeout: opts.timeout, CheckRedirect: opts.redirect, Transport: opts.transport, } var resp *http.Response for { resp, err = client.Do(req) // Retry without tls. During migration there would be a time when the // component receiving the tls request does not serve https response. // TODO (@evelynl): disable retry after tls migration. if err != nil && req.URL.Scheme == "https" && !opts.httpFallbackDisabled { originalErr := err resp, err = fallbackToHTTP(client, method, opts) if err != nil { // Sometimes the request fails for a reason unrelated to https. // To keep this reason visible, we always include the original // error. err = fmt.Errorf( "failed to fallback https to http, original https error: %s,\n"+ "fallback http error: %s", originalErr, err) } } if err != nil || (isRetryable(resp.StatusCode) && !opts.acceptedCodes[resp.StatusCode]) || (opts.retry.extraCodes[resp.StatusCode]) { d := opts.retry.backoff.NextBackOff() if d == backoff.Stop { break // Backoff timed out. } time.Sleep(d) continue } break } if err != nil { return nil, NetworkError{err} } if !opts.acceptedCodes[resp.StatusCode] { return nil, NewStatusError(resp) } return resp, nil } // Get sends a GET http request. func Get(url string, options ...SendOption) (*http.Response, error) { return Send("GET", url, options...) } // Head sends a HEAD http request. func Head(url string, options ...SendOption) (*http.Response, error) { return Send("HEAD", url, options...) } // Post sends a POST http request. func Post(url string, options ...SendOption) (*http.Response, error) { return Send("POST", url, options...) } // Put sends a PUT http request. func Put(url string, options ...SendOption) (*http.Response, error) { return Send("PUT", url, options...) } // Patch sends a PATCH http request. func Patch(url string, options ...SendOption) (*http.Response, error) { return Send("PATCH", url, options...) } // Delete sends a DELETE http request. func Delete(url string, options ...SendOption) (*http.Response, error) { return Send("DELETE", url, options...) } // PollAccepted wraps GET requests for endpoints which require 202-polling. func PollAccepted( url string, b backoff.BackOff, options ...SendOption) (*http.Response, error) { b.Reset() for { resp, err := Get(url, options...) if err != nil { if IsAccepted(err) { d := b.NextBackOff() if d == backoff.Stop { break // Backoff timed out. } time.Sleep(d) continue } return nil, err } return resp, nil } return nil, errors.New("backoff timed out on 202 responses") } // GetQueryArg gets an argument from http.Request by name. // When the argument is not specified, it returns a default value. func GetQueryArg(r *http.Request, name string, defaultVal string) string { v := r.URL.Query().Get(name) if v == "" { v = defaultVal } return v } // ParseParam parses a parameter from url. func ParseParam(r *http.Request, name string) (string, error) { param := chi.URLParam(r, name) if param == "" { return "", handler.Errorf("param %s is required", name).Status(http.StatusBadRequest) } val, err := url.PathUnescape(param) if err != nil { return "", handler.Errorf("path unescape %s: %s", name, err).Status(http.StatusBadRequest) } return val, nil } // ParseDigest parses a digest from url. func ParseDigest(r *http.Request, name string) (core.Digest, error) { raw, err := ParseParam(r, name) if err != nil { return core.Digest{}, err } d, err := core.ParseSHA256Digest(raw) if err != nil { return core.Digest{}, handler.Errorf("parse digest: %s", err).Status(http.StatusBadRequest) } return d, nil } func newRequest(method string, opts *sendOptions) (*http.Request, error) { req, err := http.NewRequest(method, opts.url.String(), opts.body) if err != nil { return nil, fmt.Errorf("new request: %s", err) } req = req.WithContext(opts.ctx) if opts.body == nil { req.ContentLength = 0 } for key, val := range opts.headers { req.Header.Set(key, val) } return req, nil } func fallbackToHTTP( client *http.Client, method string, opts *sendOptions) (*http.Response, error) { req, err := newRequest(method, opts) if err != nil { return nil, err } req.URL.Scheme = "http" return client.Do(req) } func min(a, b time.Duration) time.Duration { if a < b { return a } return b }
package command import "github.com/goodmustache/pt/command/display" type UserList struct { Config Config UI UI } func (cmd UserList) Execute(_ []string) error { configuredUsers, err := cmd.Config.GetUsers() if err != nil { return err } users := []display.UserRow{} for _, user := range configuredUsers { users = append(users, display.UserRow{ ID: user.ID, Username: user.Username, Name: user.Name, Email: user.Email, }) } cmd.UI.PrintTable(users) return nil }
package exchange import ( . "ftnox.com/common" . "ftnox.com/config" "ftnox.com/auth" "github.com/jaekwon/GoLLRB/llrb" //"github.com/davecgh/go-spew/spew" "net/http" "time" "fmt" ) // Simplified order for orderbook API type SOrder struct { Amount uint64 `json:"a"` Price string `json:"p"` } // Helper for getting the market from request param func GetParamMarket(r *http.Request, paramName string) *Market { mName := GetParam(r, paramName) market := Markets[mName] if market == nil { ReturnJSON(API_INVALID_PARAM, "Market "+mName+" does not exist") } return market } func MarketsHandler(w http.ResponseWriter, r *http.Request) { type marketInfo struct { Coin string `json:"coin"` BasisCoin string `json:"basisCoin"` Last float64 `json:"last"` BestBid float64 `json:"bestBid"` BestAsk float64 `json:"bestAsk"` } var infos = []marketInfo{} for _, marketName := range MarketNames { market := Markets[marketName] infos = append(infos, marketInfo{ Coin: market.Coin, BasisCoin: market.BasisCoin, Last: market.PriceLogger.LastPrice(), BestBid: market.BestBidPrice(), BestAsk: market.BestAskPrice(), }) } ReturnJSON(API_OK, infos) } func OrderBookHandler(w http.ResponseWriter, r *http.Request) { market := GetParamMarket(r, "market") // Take a snapshot of each so we don't return overlapping bids/asks. mBids, mAsks := market.Bids.Snapshot(), market.Asks.Snapshot() bids, asks := []*SOrder{}, []*SOrder{} var curSOrder *SOrder mBids.AscendGreaterOrEqual(mBids.Min(), func(i llrb.Item) bool { bid := i.(*Order) sfAmount := uint64(0) sfPrice := F64ToS(bid.Price, 5) if bid.Amount != 0 { sfAmount = bid.Amount - bid.Filled } else { sfAmount = uint64(float64(bid.BasisAmount - bid.BasisFilled) * bid.Price) } if sfAmount == uint64(0) { return true } if curSOrder == nil || curSOrder.Price != sfPrice { curSOrder = &SOrder{sfAmount, sfPrice} bids = append(bids, curSOrder) } else { curSOrder.Amount += sfAmount } return true }) curSOrder = nil mAsks.AscendGreaterOrEqual(mAsks.Min(), func(i llrb.Item) bool { ask := i.(*Order) sfPrice := F64ToS(ask.Price, 5) sfAmount := ask.Amount - ask.Filled if sfAmount == uint64(0) { return true } if curSOrder == nil || curSOrder.Price != sfPrice { curSOrder = &SOrder{sfAmount, sfPrice} asks = append(asks, curSOrder) } else { curSOrder.Amount += sfAmount } return true }) res := map[string]interface{}{ "bids": bids, "asks": asks, } ReturnJSON(API_OK, res) } func AddOrderHandler(w http.ResponseWriter, r *http.Request, user *auth.User) { market := GetParamMarket(r, "market") orderType := GetParamRegexp(r, "order_type", RE_ORDER_TYPE, true) amount, _ := GetParamUint64Safe(r, "amount") basisAmount, _ := GetParamUint64Safe(r, "basis_amount") price := GetParamFloat64(r, "price") c := Config.GetCoin(market.Coin) bc := Config.GetCoin(market.BasisCoin) // Validation if amount == 0 && basisAmount == 0 { ReturnJSON(API_INVALID_PARAM, fmt.Sprintf("Please enter a valid order amount")) } if price <= 0 { ReturnJSON(API_INVALID_PARAM, fmt.Sprintf("Please enter a valid order price")) } // Round price to 5 significant figures price = F64ToF(price, 5) // Ensure that trades aren't dust. if amount > 0 && amount < c.MinTrade { ReturnJSON(API_INVALID_PARAM, fmt.Sprintf("Minimum order amount is %v %v", I64ToF64(int64(c.MinTrade)), market.Coin)) } if basisAmount > 0 && basisAmount < bc.MinTrade { ReturnJSON(API_INVALID_PARAM, fmt.Sprintf("Minimum order amount is %v %v", I64ToF64(int64(bc.MinTrade)), market.BasisCoin)) } if orderType == "A" && amount == 0 { amount = uint64(float64(basisAmount) / float64(price) + 0.5) } else if orderType == "B" && basisAmount == 0 { basisAmount = uint64(float64(amount) * float64(price) + 0.5) } order := &Order{ Type: orderType, UserId: user.Id, Coin: market.Coin, Amount: amount, BasisCoin: market.BasisCoin, BasisAmount: basisAmount, Price: price, } AddOrder(order) ReturnJSON(API_OK, order) } func CancelOrderHandler(w http.ResponseWriter, r *http.Request, user *auth.User) { id := GetParamInt64(r, "id") order := LoadOrder(id) if order == nil { ReturnJSON(API_INVALID_PARAM, "Order with that id does not exist") } CancelOrder(order) ReturnJSON(API_OK, "CANCELED") } func GetPendingOrdersHandler(w http.ResponseWriter, r *http.Request, user *auth.User) { market := GetParamMarket(r, "market") orders := LoadPendingOrdersByUser(user.Id, market.BasisCoin, market.Coin) ReturnJSON(API_OK, orders) } func TradeHistoryHandler(w http.ResponseWriter, r *http.Request, user *auth.User) { // TODO } func PriceLogHandler(w http.ResponseWriter, r *http.Request) { market := GetParamMarket(r, "market") start := GetParamInt64(r, "start") end := GetParamInt64(r, "end") if end == 0 || end < int64(0) { end = time.Now().Unix() + end } if start == 0 { ReturnJSON(API_INVALID_PARAM, "Parameter 'start' cannot be 0") } if start < 0 { start = time.Now().Unix() + start } // TODO: automatically adjust interval based on start & end. plogs := market.PriceLogger.LoadPrices(60*5, start, end) ReturnJSON(API_OK, plogs) }
package cmd import ( "testing" "github.com/flix-tech/confs.tech.push/confs" ) func TestFormatLocationAddsFlag(t *testing.T) { location := formatLocation(confs.Conference{ Name: "Go two", URL: "https://go2.com/", StartDate: "2019-08-21", EndDate: "2019-08-21", City: "Mariupol", Country: "Ukraine", }) expected := "Mariupol, Ukraine 🇺🇦" if location != expected { t.Errorf("Got error when formating location: expected '%s', got '%s'", expected, location) } } func TestFormatLocationWorksWithUnknownCountries(t *testing.T) { location := formatLocation(confs.Conference{ Name: "Go two", URL: "https://go2.com/", StartDate: "2019-08-21", EndDate: "2019-08-21", City: "Voodoocity", Country: "Voodooland", }) expected := "Voodoocity, Voodooland" if location != expected { t.Errorf("Got error when formating location: expected '%s', got '%s'", expected, location) } }
// Copyright 2022 Saferwall. All rights reserved. // Use of this source code is governed by Apache v2 license // license that can be found in the LICENSE file. package trid import ( "path" "path/filepath" "reflect" "runtime" "testing" ) func getAbsoluteFilePath(testfile string) string { _, p, _, _ := runtime.Caller(0) return path.Join(filepath.Dir(p), "..", "..", testfile) } var tridtests = []struct { in string out []string }{ {getAbsoluteFilePath("testdata/putty.exe"), []string{ "42.7% (.EXE) Win32 Executable (generic) (4505/5/1)", "19.2% (.EXE) OS/2 Executable (generic) (2029/13)", "19.0% (.EXE) Generic Win/DOS Executable (2002/3)", "18.9% (.EXE) DOS Executable Generic (2000/1)", }, }, } func TestScan(t *testing.T) { for _, tt := range tridtests { t.Run(tt.in, func(t *testing.T) { filePath := tt.in got, err := Scan(filePath) if err != nil { t.Errorf("TestScan(%s) got %v, want %v", tt.in, err, tt.in) } if !reflect.DeepEqual(got, tt.out) { t.Errorf("TestScan(%s) got %v, want %v", tt.in, got, tt.out) } }) } }
package cache import ( "fmt" "net/http" "net/http/httptest" "testing" "time" "github.com/stretchr/testify/require" ) type testHandler struct{} func (h *testHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, "hello world") } func TestHandler(t *testing.T) { curr := time.Now() c := NewHTTPCache(11) ts := httptest.NewServer(c.Middleware(&testHandler{})) assert := require.New(t) res, err := ts.Client().Get(ts.URL) assert.NoError(err, "expect no error from http get call") defer res.Body.Close() assert.Equal(res.StatusCode, http.StatusOK, "should be successful http request") assert.Equal( res.Header.Get("Expires"), curr.AddDate(0, 11, 0).Format(http.TimeFormat), "should match Expires header value", ) assert.Equal( res.Header.Get("Cache-Control"), fmt.Sprintf( "public, max-age=%d", int(time.Until(curr.AddDate(0, 11, 0)).Seconds()), ), "should match Cache-Control header value", ) }
// Package reflexcion // Created by RTT. // Author: teocci@yandex.com on 2021-Aug-12 package main import ( "fmt" "reflect" ) // 1. Reflection goes from interface value to reflection object. // TypeOf returns the reflection Type of the value in the interface{}. // func TypeOf(i interface{}) Type func fromInterfaceToObject() { defer fmt.Println() fmt.Println("1. Reflection goes from interface value to reflection object.") var x float64 = 3.4 fmt.Println("type:", reflect.TypeOf(x)) fmt.Println("value:", reflect.ValueOf(x).String()) fmt.Println() xValue := reflect.ValueOf(x) fmt.Println("type:", xValue.Type()) fmt.Println("kind is float64:", xValue.Kind() == reflect.Float64) fmt.Println("value:", xValue.Float()) fmt.Println() var y uint8 = 'y' yValue := reflect.ValueOf(y) fmt.Println("type:", yValue.Type()) // uint8. fmt.Println("kind is uint8: ", yValue.Kind() == reflect.Uint8) // true. y = uint8(yValue.Uint()) } // 2. Reflection goes from reflection object to interface value. // Interface returns v's value as an interface{}. // func (v Value) Interface() interface{} func fromObjectToInterface() { defer fmt.Println() fmt.Println("2. Reflection goes from reflection object to interface value.") var x float64 = 3.4 xValue := reflect.ValueOf(x) xNew := xValue.Interface().(float64) // y will have type float64. fmt.Println("xNew:", xNew) fmt.Println("xValue interface:", xValue.Interface()) fmt.Printf("value is %7.1e\n", xValue.Interface()) } // 3. To modify a reflection object, the value must be settable. // xValue := reflect.ValueOf(x) // xValue.SetFloat(7.1) // Error: will panic. // panic: reflect.Value.SetFloat using unaddressable value func modifyObjectIfSettable() { defer fmt.Println() fmt.Println("3. To modify a reflection object, the value must be settable.") var x float64 = 3.4 xValue := reflect.ValueOf(x) fmt.Println("settability of wValue:", xValue.CanSet()) // settability of wValue: false fmt.Println() xPointer := reflect.ValueOf(&x) // Note: take the address of x. fmt.Println("type of wPointer:", xPointer.Type()) fmt.Println("settability of wPointer:", xPointer.CanSet()) elem := xPointer.Elem() fmt.Println("settability of elem:", elem.CanSet()) // settability of elem: true elem.SetFloat(7.1) fmt.Println("elem value:", elem.Interface()) fmt.Println("x value:", x) fmt.Println() type T struct { A int B string } tObject := T{23, "skidoo"} tElem := reflect.ValueOf(&tObject).Elem() tType := tElem.Type() for i := 0; i < tElem.NumField(); i++ { f := tElem.Field(i) fmt.Printf("%d: %s %s = %v\n", i, tType.Field(i).Name, f.Type(), f.Interface()) } fmt.Println() tElem.Field(0).SetInt(77) tElem.Field(1).SetString("Sunset Strip") fmt.Println("t is now", tObject) } func main() { fromInterfaceToObject() fromObjectToInterface() modifyObjectIfSettable() }
// +build linux darwin freebsd package mount import ( "os" "testing" "time" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestFileModTime(t *testing.T) { run.skipIfNoFUSE(t) run.createFile(t, "file", "123") mtime := time.Date(2012, 11, 18, 17, 32, 31, 0, time.UTC) err := os.Chtimes(run.path("file"), mtime, mtime) require.NoError(t, err) info, err := os.Stat(run.path("file")) require.NoError(t, err) // avoid errors because of timezone differences assert.Equal(t, info.ModTime().Unix(), mtime.Unix()) run.rm(t, "file") }
// two pointers func maxSum(nums1 []int, nums2 []int) int { m, n := len(nums1), len(nums2) idx1, idx2 := 0, 0 var curr_sum1, curr_sum2 uint64 = 0, 0 for idx1 < m || idx2 < n { if idx1 < m && (idx2 == n || nums1[idx1] < nums2[idx2]) { curr_sum1 += uint64(nums1[idx1]) idx1++ } else if idx2 < n && (idx1 == m || nums1[idx1] > nums2[idx2]) { curr_sum2 += uint64(nums2[idx2]) idx2++ } else { tmp := max(curr_sum1, curr_sum2) + uint64(nums1[idx1]) curr_sum1, curr_sum2 = tmp, tmp idx1++ idx2++ } } return int(max(curr_sum1, curr_sum2) % (1e9 + 7)) } func max(num1, num2 uint64) uint64 { if num1 >= num2 { return num1 } else { return num2 } }
package rtc import ( "fmt" "time" "github.com/pokemium/worldwide/pkg/util" ) const ( S = iota M H DL DH ) // RTC Real Time Clock type RTC struct { Enable bool Mapped uint Ctr [5]byte Latched bool LatchedRTC LatchedRTC } // LatchedRTC Latched RTC type LatchedRTC struct{ Ctr [5]byte } func New(enable bool) *RTC { return &RTC{Enable: enable} } func (rtc *RTC) IncrementSecond() { if rtc.Enable && rtc.isActive() { rtc.incrementSecond() } } // Read fetch clock register func (rtc *RTC) Read(target byte) byte { if rtc.Latched { return rtc.LatchedRTC.Ctr[target-0x08] } return rtc.Ctr[target-0x08] } // Latch rtc func (rtc *RTC) Latch() { for i := 0; i < 5; i++ { rtc.LatchedRTC.Ctr[i] = rtc.Ctr[i] } } // Write set clock register func (rtc *RTC) Write(target, value byte) { rtc.Ctr[target-0x08] = value } func (rtc *RTC) incrementSecond() { rtc.Ctr[S]++ if rtc.Ctr[S] == 60 { rtc.incrementMinute() } } func (rtc *RTC) incrementMinute() { rtc.Ctr[M]++ rtc.Ctr[S] = 0 if rtc.Ctr[M] == 60 { rtc.incrementHour() } } func (rtc *RTC) incrementHour() { rtc.Ctr[H]++ rtc.Ctr[M] = 0 if rtc.Ctr[H] == 24 { rtc.incrementDay() } } func (rtc *RTC) incrementDay() { old := rtc.Ctr[DL] rtc.Ctr[DL]++ rtc.Ctr[H] = 0 // pass 256 days if rtc.Ctr[DL] < old { rtc.Ctr[DL] = 0 if rtc.Ctr[DH]&0x01 == 1 { // msb on day is set rtc.Ctr[DH] |= 0x80 rtc.Ctr[DH] &= 0x7f } else { // msb on day is clear rtc.Ctr[DH] |= 0x01 } } } func (rtc *RTC) isActive() bool { return !util.Bit(rtc.Ctr[DH], 6) } // Dump RTC on .sav format // // offset size desc // 0 4 time seconds // 4 4 time minutes // 8 4 time hours // 12 4 time days // 16 4 time days high // 20 4 latched time seconds // 24 4 latched time minutes // 28 4 latched time hours // 32 4 latched time days // 36 4 latched time days high // 40 4 unix timestamp when saving // 44 4 0 (probably the high dword of 64 bits time), absent in the 44 bytes version func (rtc *RTC) Dump() []byte { result := make([]byte, 48) result[0], result[4], result[8], result[12], result[16] = rtc.Ctr[S], rtc.Ctr[M], rtc.Ctr[H], rtc.Ctr[DL], rtc.Ctr[DH] latch := rtc.LatchedRTC result[20], result[24], result[28], result[32], result[36] = latch.Ctr[S], latch.Ctr[M], latch.Ctr[H], latch.Ctr[DL], latch.Ctr[DH] now := time.Now().Unix() result[40], result[41], result[42], result[43] = byte(now), byte(now>>8), byte(now>>16), byte(now>>24) return result } // Sync RTC data func (rtc *RTC) Sync(value []byte) { if len(value) != 44 && len(value) != 48 { fmt.Println("invalid RTC format") return } rtc.Ctr = [5]byte{value[0], value[4], value[8], value[12], value[16]} rtc.LatchedRTC.Ctr = [5]byte{value[20], value[24], value[28], value[32], value[36]} savTime := (uint32(value[43]) << 24) | (uint32(value[42]) << 16) | (uint32(value[41]) << 8) | uint32(value[40]) delta := uint32(time.Now().Unix()) - savTime for i := uint32(0); i < delta; i++ { rtc.incrementSecond() } }
package main import "testing" func TestContainsEmptySlice(t *testing.T) { res := contains([]string{}, "a") if res { t.Error("should be false for empty slice") } } func TestContainsNoMatch(t *testing.T) { res := contains([]string{"b", "c"}, "a") if res { t.Error("should be false for no match") } } func TestContainsMatch(t *testing.T) { res := contains([]string{"a", "b", "c"}, "b") if !res { t.Error("should be true for match") } } func TestPrepareOutputEmptyPlayers(t *testing.T) { players := Players{} teams := Teams{} res := prepareOutput(players, teams) if len(res) > 0 { t.Error("should be empty result") } } func TestPrepareOutputTwoPlayersPlayers(t *testing.T) { players := make(Players) players["1"] = &Player{ ID: "1", Name: "A A", Age: "12", Teams: []int{1, 2}, } players["2"] = &Player{ ID: "2", Name: "B B", Age: "15", Teams: []int{2}, } teams := make(Teams) teams[1] = "Team A" teams[2] = "Team B" res := prepareOutput(players, teams) if len(res) == 0 { t.Error("should not be empty result") } expectedLine1 := "A A; 12; Team A, Team B" if expectedLine1 != res[0] { t.Error("Expected to get:", expectedLine1, "but got:", res[0]) } } func TestParseTeamNotKnown(t *testing.T) { players := make(Players) teams := make(Teams) apiTeam := &ApiTeam{ Name: "Team A", } parseTeam(apiTeam, players, teams) if len(teams) > 0 { t.Error("should not parse teams which are not requested") } } func TestParseTeamNoPlayers(t *testing.T) { players := make(Players) teams := make(Teams) apiTeam := &ApiTeam{ Name: "Germany", } parseTeam(apiTeam, players, teams) if len(teams) != 1 { t.Error("should parse teams which are requested") } } func TestParseTeamsPlayerForDifferentTeams(t *testing.T) { players := make(Players) teams := make(Teams) apiPlayers := []*ApiPlayer{ &ApiPlayer{ ID: "1", Name: "Name", Age: "10", }, } apiTeam1 := &ApiTeam{ ID: 1, Name: "Germany", Players: apiPlayers, } apiTeam2 := &ApiTeam{ ID: 2, Name: "FC Bayern Munich", Players: apiPlayers, } parseTeam(apiTeam1, players, teams) parseTeam(apiTeam2, players, teams) if len(teams) != 2 { t.Error("there should be only two teams") } if len(players) != 1 { t.Error("there should be only one player") } }
package scalars_test import ( "strings" "time" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" "github.com/nrfta/go-graphql-scalars" ) var _ = Describe("Marshal/ Unmarshal DateTime Test", func() { var ( correctDateTime = "2006-01-02T15:04:05Z" wrongDateTime = "2019-06-2435" testDateTime, _ = time.Parse(time.RFC3339, correctDateTime) testStringBuilders = &strings.Builder{} ) var _ = Context("Unmarshal DateTime test", func() { It("returns a time object when valid datetime string passed in to UnmarshalDateTime", func() { dateTime, err := scalars.UnmarshalDateTime(correctDateTime) Expect(err).To(Succeed()) Expect(dateTime).Should(BeAssignableToTypeOf(time.Time{})) Expect(dateTime).To(Equal(testDateTime)) }) It("returns an error when invalid datetime format passed in to UnmarshalDateTime", func() { _, err := scalars.UnmarshalDateTime(wrongDateTime) Expect(err).ToNot(BeNil()) }) }) var _ = Context("Marshal DateTime Test", func() { It("returns a function that writes the time from string format into a slice of bytes", func() { scalars.MarshalDateTime(testDateTime).MarshalGQL(testStringBuilders) marshaledDateTimeString := testStringBuilders.String() marshaledDateTimeString = (marshaledDateTimeString[1 : len(marshaledDateTimeString)-1]) // gets rid of extra quotes around Marshalled String Expect(marshaledDateTimeString).To(Equal(correctDateTime)) Expect(scalars.UnmarshalDateTime(marshaledDateTimeString)).Should(BeAssignableToTypeOf(time.Time{})) }) }) })
// Copyright 2014 Dirk Jablonowski. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package device import ( "fmt" "github.com/dirkjabl/bricker/net/packet" ) // Type for the debounce period (ms) with which the threshold callback is triggered, // if the thresold keeps being reached. type Debounce struct { Value uint32 } // ThresholdFromPacket convert the packet payload to the mode. func (d *Debounce) FromPacket(p *packet.Packet) error { if err := CheckForFromPacket(d, p); err != nil { return err } return p.Payload.Decode(d) } // String fullfill the stringer interface. func (d *Debounce) String() string { txt := "Debounce " if d == nil { txt += "[nil]" } else { txt += fmt.Sprintf("[Value: %d]", d.Value) } return txt } // Copy creates a copy of the content. func (d *Debounce) Copy() Resulter { if d == nil { return nil } return &Debounce{Value: d.Value} }
/* * Copyright IBM Corporation 2021 * * 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 knownhosts import ( "bufio" "bytes" "encoding/base64" "errors" "fmt" "net" "os" "strings" "github.com/sirupsen/logrus" "golang.org/x/crypto/ssh" "golang.org/x/crypto/ssh/knownhosts" ) const ( markerCert = "@cert-authority" markerRevoked = "@revoked" ) func nextWord(line []byte) (string, []byte) { i := bytes.IndexAny(line, "\t ") if i == -1 { return string(line), nil } return string(line[:i]), bytes.TrimSpace(line[i:]) } // parseKnownHostsLine parses the line to extract the hostname/IP. // It also returns a bool to indicate if the line is a revocation or a certificate line and should be ignored. func parseKnownHostsLine(line []byte) (shouldIgnore bool, host, lineStr string, err error) { lineStr = string(line) shouldIgnore = false if w, next := nextWord(line); w == markerCert || w == markerRevoked { shouldIgnore = true line = next } host, line = nextWord(line) if len(line) == 0 { return shouldIgnore, "", "", errors.New("knownhosts: missing host pattern") } // ignore the keytype as it's in the key blob anyway. _, line = nextWord(line) if len(line) == 0 { return shouldIgnore, "", "", errors.New("knownhosts: missing key type pattern") } keyBlob, _ := nextWord(line) keyBytes, err := base64.StdEncoding.DecodeString(keyBlob) if err != nil { return shouldIgnore, "", "", err } if _, err = ssh.ParsePublicKey(keyBytes); err != nil { return shouldIgnore, "", "", err } return shouldIgnore, host, lineStr, nil } // ParseKnownHosts creates a host key database from the given OpenSSH host key file. // See the sshd manpage for more info: http://man.openbsd.org/sshd#SSH_KNOWN_HOSTS_FILE_FORMAT func ParseKnownHosts(path string) (map[string][]string, error) { knownHostsFile, err := os.Open(path) if err != nil { return nil, err } defer knownHostsFile.Close() domainToPublicKeys := map[string][]string{} scanner := bufio.NewScanner(knownHostsFile) lineNum := 0 for scanner.Scan() { lineNum++ line := bytes.TrimSpace(scanner.Bytes()) if len(line) == 0 || line[0] == '#' { continue } shouldIgnore, hostName, lineStr, err := parseKnownHostsLine(line) if err != nil { return nil, fmt.Errorf("Error occurred parsing known_hosts file at path %q on line no. %d Error: %q", path, lineNum, err) } if shouldIgnore { continue } if hostName[0] == '|' { // TODO: not sure if we can support hashed hosts. continue } for _, h := range strings.Split(hostName, ",") { if len(h) == 0 { continue } domainToPublicKeys[h] = append(domainToPublicKeys[h], lineStr) } } return domainToPublicKeys, scanner.Err() } func addKeyToMap(hostTokey map[string]ssh.PublicKey) ssh.HostKeyCallback { return func(hostPort string, address net.Addr, key ssh.PublicKey) error { host, port, err := net.SplitHostPort(hostPort) if err != nil { logrus.Errorf("Failed to split %s into host and the port. Error %q", hostPort, err) return err } logrus.Debugf("host %s on port %s at address %v has the key %v of type %T", host, port, address, key, key) hostTokey[host] = key return nil } } // GetKey returns the ssh public key for the given host. func GetKey(host string) ssh.PublicKey { // Setup defaultSSHPort := "22" defaultGitUser := "git" hostTokey := map[string]ssh.PublicKey{} config := &ssh.ClientConfig{ User: defaultGitUser, Auth: []ssh.AuthMethod{}, HostKeyCallback: addKeyToMap(hostTokey), } url := net.JoinHostPort(host, defaultSSHPort) // Get key _, err := ssh.Dial("tcp", url, config) logrus.Debug(`This error should say "handshake failed: ssh: unable to authenticate, attempted methods [none], no supported methods remain". Error:`, err) if err == nil { logrus.Warnf("This should have failed but it didn't.") } return hostTokey[host] } // GetKnownHostsLine returns the line to be added to the known_hosts file. // The line has the format: host <space> algo <space> base64 encoded public key func GetKnownHostsLine(host string) (string, error) { key := GetKey(host) if key == nil { return "", fmt.Errorf("Failed to get the ssh public key for the host %s", host) } line := knownhosts.Line([]string{host}, key) return line, nil }
package prompt import ( "bytes" "context" "io" "net/url" "reflect" "testing" "time" "github.com/stretchr/testify/assert" "github.com/tilt-dev/tilt/internal/store" "github.com/tilt-dev/tilt/internal/testutils" "github.com/tilt-dev/tilt/internal/testutils/bufsync" "github.com/tilt-dev/tilt/pkg/model" ) const FakeURL = "http://localhost:10350/" func TestOpenBrowser(t *testing.T) { f := newFixture(t) _ = f.prompt.OnChange(f.ctx, f.st, store.LegacyChangeSummary()) assert.Contains(t, f.out.String(), "(space) to open the browser") f.input.nextRune <- ' ' assert.Equal(t, FakeURL, f.b.WaitForURL(t)) } func TestOpenStream(t *testing.T) { f := newFixture(t) _ = f.prompt.OnChange(f.ctx, f.st, store.LegacyChangeSummary()) assert.Contains(t, f.out.String(), "(s) to stream logs") f.input.nextRune <- 's' action := f.st.WaitForAction(t, reflect.TypeOf(SwitchTerminalModeAction{})) assert.Equal(t, SwitchTerminalModeAction{Mode: store.TerminalModeStream}, action) } func TestOpenHUD(t *testing.T) { f := newFixture(t) _ = f.prompt.OnChange(f.ctx, f.st, store.LegacyChangeSummary()) assert.Contains(t, f.out.String(), "(t) to open legacy terminal mode") f.input.nextRune <- 't' action := f.st.WaitForAction(t, reflect.TypeOf(SwitchTerminalModeAction{})) assert.Equal(t, SwitchTerminalModeAction{Mode: store.TerminalModeHUD}, action) } func TestInitOutput(t *testing.T) { f := newFixture(t) f.prompt.SetInitOutput(bytes.NewBuffer([]byte("this is a warning\n"))) _ = f.prompt.OnChange(f.ctx, f.st, store.LegacyChangeSummary()) assert.Contains(t, f.out.String(), `this is a warning (space) to open the browser`) } type fixture struct { ctx context.Context cancel func() out *bufsync.ThreadSafeBuffer st *store.TestingStore b *fakeBrowser input *fakeInput prompt *TerminalPrompt } func newFixture(t *testing.T) *fixture { ctx, _, ta := testutils.CtxAndAnalyticsForTest() ctx, cancel := context.WithCancel(ctx) out := bufsync.NewThreadSafeBuffer() st := store.NewTestingStore() st.WithState(func(state *store.EngineState) { state.TerminalMode = store.TerminalModePrompt }) i := &fakeInput{ctx: ctx, nextRune: make(chan rune)} b := &fakeBrowser{url: make(chan string)} openInput := OpenInput(func() (TerminalInput, error) { return i, nil }) url, _ := url.Parse(FakeURL) prompt := NewTerminalPrompt(ta, openInput, b.OpenURL, out, "localhost", model.WebURL(*url)) ret := &fixture{ ctx: ctx, cancel: cancel, out: out, st: st, input: i, b: b, prompt: prompt, } t.Cleanup(ret.TearDown) return ret } func (f *fixture) TearDown() { f.cancel() } type fakeInput struct { ctx context.Context nextRune chan rune } func (i *fakeInput) Close() error { return nil } func (i *fakeInput) ReadRune() (rune, error) { select { case r := <-i.nextRune: return r, nil case <-i.ctx.Done(): return 0, i.ctx.Err() } } type fakeBrowser struct { url chan string } func (b *fakeBrowser) WaitForURL(t *testing.T) string { select { case <-time.After(time.Second): t.Fatal("timeout waiting for url") return "" case url := <-b.url: return url } } func (b *fakeBrowser) OpenURL(url string, w io.Writer) error { b.url <- url return nil }
package main import ( "bufio" "encoding/json" "fmt" "io/ioutil" "log" "math" "net" "net/http" "os" "strings" "sync" "github.com/aws/aws-xray-sdk-go/xray" "github.com/pkg/errors" ) const defaultPort = "8080" const defaultStage = "default" const maxTags = 1000 var tags [maxTags]string var tagsIdx int var tagsMutext = &sync.Mutex{} func getServerPort() string { port := os.Getenv("SERVER_PORT") if port != "" { return port } return defaultPort } func getStage() string { stage := os.Getenv("STAGE") if stage != "" { return stage } return defaultStage } func getSearchServiceEndpoint() (string, error) { searchServiceEndpoint := os.Getenv("SEARCH_SERVICE_ENDPOINT") if searchServiceEndpoint == "" { return "", errors.New("SEARCH_SERVICE_ENDPOINT is not set") } return searchServiceEndpoint, nil } type tagHandler struct{} func (h *tagHandler) ServeHTTP(writer http.ResponseWriter, request *http.Request) { tag, err := getTagFromSearchService(request) if err != nil { writer.WriteHeader(http.StatusInternalServerError) writer.Write([]byte("500 - Unexpected Error")) return } tagsMutext.Lock() defer tagsMutext.Unlock() addTag(tag) statsJson, err := json.Marshal(getRatios()) if err != nil { fmt.Fprintf(writer, `{"tag":"%s", "error":"%s"}`, tag, err) return } fmt.Fprintf(writer, `{"tag":"%s", "stats": %s}`, tag, statsJson) } func addTag(tag string) { tags[tagsIdx] = tag tagsIdx += 1 if tagsIdx >= maxTags { tagsIdx = 0 } } func getRatios() map[string]float64 { counts := make(map[string]int) var total = 0 for _, c := range tags { if c != "" { counts[c] += 1 total += 1 } } ratios := make(map[string]float64) for k, v := range counts { ratio := float64(v) / float64(total) ratios[k] = math.Round(ratio*100) / 100 } return ratios } type clearTagStatsHandler struct{} func (h *clearTagStatsHandler) ServeHTTP(writer http.ResponseWriter, request *http.Request) { tagsMutext.Lock() defer tagsMutext.Unlock() tagsIdx = 0 for i := range tags { tags[i] = "" } fmt.Fprint(writer, "cleared") } func getTagFromSearchService(request *http.Request) (string, error) { searchServiceEndpoint, err := getSearchServiceEndpoint() if err != nil { return "-n/a-", err } client := xray.Client(&http.Client{}) req, err := http.NewRequest(http.MethodGet, fmt.Sprintf("http://%s", searchServiceEndpoint), nil) if err != nil { return "-n/a-", err } resp, err := client.Do(req.WithContext(request.Context())) if err != nil { return "-n/a-", err } defer resp.Body.Close() body, err := ioutil.ReadAll(resp.Body) if err != nil { return "-n/a-", err } tag := strings.TrimSpace(string(body)) if len(tag) < 1 { return "-n/a-", errors.New("Empty response from searchService") } return tag, nil } func getTCPEchoEndpoint() (string, error) { tcpEchoEndpoint := os.Getenv("TCP_ECHO_ENDPOINT") if tcpEchoEndpoint == "" { return "", errors.New("TCP_ECHO_ENDPOINT is not set") } return tcpEchoEndpoint, nil } type tcpEchoHandler struct{} func (h *tcpEchoHandler) ServeHTTP(writer http.ResponseWriter, request *http.Request) { endpoint, err := getTCPEchoEndpoint() if err != nil { writer.WriteHeader(http.StatusInternalServerError) fmt.Fprintf(writer, "tcpecho endpoint is not set") return } log.Printf("Dialing tcp endpoint %s", endpoint) conn, err := net.Dial("tcp", endpoint) if err != nil { writer.WriteHeader(http.StatusInternalServerError) fmt.Fprintf(writer, "Dial failed, err:%s", err.Error()) return } defer conn.Close() strEcho := "Hello from gateway" log.Printf("Writing '%s'", strEcho) _, err = fmt.Fprintf(conn, strEcho) if err != nil { writer.WriteHeader(http.StatusInternalServerError) fmt.Fprintf(writer, "Write to server failed, err:%s", err.Error()) return } reply, err := bufio.NewReader(conn).ReadString('\n') if err != nil { writer.WriteHeader(http.StatusInternalServerError) fmt.Fprintf(writer, "Read from server failed, err:%s", err.Error()) return } fmt.Fprintf(writer, "Response from tcpecho server: %s", reply) } type pingHandler struct{} func (h *pingHandler) ServeHTTP(writer http.ResponseWriter, request *http.Request) { log.Println("ping requested, reponding with HTTP 200") writer.WriteHeader(http.StatusOK) } func main() { log.Println("Starting server, listening on port " + getServerPort()) searchServiceEndpoint, err := getSearchServiceEndpoint() if err != nil { log.Fatalln(err) } tcpEchoEndpoint, err := getTCPEchoEndpoint() if err != nil { log.Println(err) } log.Println("Using search-service at " + searchServiceEndpoint) log.Println("Using tcp-echo at " + tcpEchoEndpoint) xraySegmentNamer := xray.NewFixedSegmentNamer(fmt.Sprintf("%s-researchpreferences", getStage())) http.Handle("/tag", xray.Handler(xraySegmentNamer, &tagHandler{})) http.Handle("/tag/clear", xray.Handler(xraySegmentNamer, &clearTagStatsHandler{})) http.Handle("/tcpecho", xray.Handler(xraySegmentNamer, &tcpEchoHandler{})) http.Handle("/ping", xray.Handler(xraySegmentNamer, &pingHandler{})) log.Fatal(http.ListenAndServe(":"+getServerPort(), nil)) }
package main import ( "bytes" "encoding/gob" "fmt" "godist/datamanager" "godist/dto" "godist/qutils" "log" ) const url = "amqp://guest@localhost:5672" func main() { ch, conn := qutils.GetChannel(url) defer conn.Close() defer ch.Close() msgs, err := ch.Consume( qutils.PersistentDataQueue, "", false, true, false, false, nil, ) if err != nil { log.Fatalln("Failed to get a message") } for msg := range msgs { buf := bytes.NewReader(msg.Body) dec := gob.NewDecoder(buf) sd := &dto.SensorMessage{} dec.Decode(sd) fmt.Printf("Read: %s", sd) err := datamanager.SaveReading(sd) if err != nil { log.Printf("Failed to save reading from sensor %v. Error: %s", sd.Name, err.Error()) } else { msg.Ack(false) } } }
package v1beta1 import ( "context" "k8s.io/apimachinery/pkg/api/meta" "k8s.io/apimachinery/pkg/runtime" "sigs.k8s.io/controller-runtime/pkg/cache" "sigs.k8s.io/controller-runtime/pkg/client" "kubesphere.io/kubesphere/pkg/apiserver/query" ) type resourceCache struct { cache cache.Cache } func NewResourceCache(cache cache.Cache) Interface { return &resourceCache{cache: cache} } func (u *resourceCache) Get(namespace, name string, object client.Object) error { return u.cache.Get(context.Background(), client.ObjectKey{Namespace: namespace, Name: name}, object) } func (u *resourceCache) List(namespace string, query *query.Query, list client.ObjectList) error { listOpt := &client.ListOptions{ LabelSelector: query.Selector(), Namespace: namespace, } err := u.cache.List(context.Background(), list, listOpt) if err != nil { return err } extractList, err := meta.ExtractList(list) if err != nil { return err } filtered := DefaultList(extractList, query, compare, filter) if err := meta.SetList(list, filtered); err != nil { return err } return nil } func compare(left, right runtime.Object, field query.Field) bool { l, err := meta.Accessor(left) if err != nil { return false } r, err := meta.Accessor(right) if err != nil { return false } return DefaultObjectMetaCompare(l, r, field) } func filter(object runtime.Object, filter query.Filter) bool { o, err := meta.Accessor(object) if err != nil { return false } return DefaultObjectMetaFilter(o, filter) }