text
stringlengths
11
4.05M
package main func fact(number int) int { if number == 0 { return (1) } return number * fact(number-1) } func main() { println(fact(3)) }
// This file was generated for SObject ProcessDefinition, API Version v43.0 at 2018-07-30 03:47:31.578458672 -0400 EDT m=+17.921737582 package sobjects import ( "fmt" "strings" ) type ProcessDefinition struct { BaseSObject CreatedById string `force:",omitempty"` CreatedDate string `force:",omitempty"` Description string `force:",omitempty"` DeveloperName string `force:",omitempty"` Id string `force:",omitempty"` LastModifiedById string `force:",omitempty"` LastModifiedDate string `force:",omitempty"` LockType string `force:",omitempty"` Name string `force:",omitempty"` State string `force:",omitempty"` SystemModstamp string `force:",omitempty"` TableEnumOrId string `force:",omitempty"` Type string `force:",omitempty"` } func (t *ProcessDefinition) ApiName() string { return "ProcessDefinition" } func (t *ProcessDefinition) String() string { builder := strings.Builder{} builder.WriteString(fmt.Sprintf("ProcessDefinition #%s - %s\n", t.Id, t.Name)) builder.WriteString(fmt.Sprintf("\tCreatedById: %v\n", t.CreatedById)) builder.WriteString(fmt.Sprintf("\tCreatedDate: %v\n", t.CreatedDate)) builder.WriteString(fmt.Sprintf("\tDescription: %v\n", t.Description)) builder.WriteString(fmt.Sprintf("\tDeveloperName: %v\n", t.DeveloperName)) builder.WriteString(fmt.Sprintf("\tId: %v\n", t.Id)) builder.WriteString(fmt.Sprintf("\tLastModifiedById: %v\n", t.LastModifiedById)) builder.WriteString(fmt.Sprintf("\tLastModifiedDate: %v\n", t.LastModifiedDate)) builder.WriteString(fmt.Sprintf("\tLockType: %v\n", t.LockType)) builder.WriteString(fmt.Sprintf("\tName: %v\n", t.Name)) builder.WriteString(fmt.Sprintf("\tState: %v\n", t.State)) builder.WriteString(fmt.Sprintf("\tSystemModstamp: %v\n", t.SystemModstamp)) builder.WriteString(fmt.Sprintf("\tTableEnumOrId: %v\n", t.TableEnumOrId)) builder.WriteString(fmt.Sprintf("\tType: %v\n", t.Type)) return builder.String() } type ProcessDefinitionQueryResponse struct { BaseQuery Records []ProcessDefinition `json:"Records" force:"records"` }
package dbx import ( "dapan/config" "dapan/model" "fmt" "gorm.io/driver/mysql" "gorm.io/gorm" ) var DB *gorm.DB func SetMysqlDB() { database := config.NewDefaultConf() con := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=%s&parseTime=True&loc=Local", database.User, database.Password, database.Host, database.Port,database.DbName, database.Charset) db, err := gorm.Open(mysql.Open(con), &gorm.Config{}) if err != nil { panic(err) } db.AutoMigrate( &model.UserInfo{}, &model.UserRole{}, ) DB = db } func InitData() { roles := []model.UserRole{ { Name: "管理员", Value: "admin", }, { Name: "用户", Value: "user", }, } DB.Create(&roles) }
package api import ( "encoding/json" "net/http" "github.com/julienschmidt/httprouter" "github.com/prometheus/client_golang/prometheus/promhttp" "github.com/sirupsen/logrus" ) type API struct { Version string ListenAddress string log *logrus.Entry } type ResponseJSON struct { Status int `json:"status"` Message string `json:"message"` Values map[string]string `json:"values,omitempty"` Errors string `json:"errors,omitempty"` } func Start(listenAddress, version string) (*http.Server, error) { a := &API{ Version: version, ListenAddress: listenAddress, log: logrus.WithField("pkg", "api"), } a.log.Debugf("starting API server on %s", listenAddress) router := httprouter.New() router.HandlerFunc("GET", "/health-check", a.healthCheckHandler) router.HandlerFunc("GET", "/version", a.versionHandler) router.Handler("GET", "/metrics", promhttp.Handler()) srv := &http.Server{ Addr: listenAddress, Handler: router, } go func() { if err := srv.ListenAndServe(); err != nil { if err != http.ErrServerClosed { a.log.Errorf("unable to srv.ListenAndServe: %s", err) } } }() return srv, nil } func (a *API) healthCheckHandler(rw http.ResponseWriter, r *http.Request) { WriteJSON(http.StatusOK, map[string]string{"status": "ok"}, rw) } func (a *API) versionHandler(rw http.ResponseWriter, r *http.Request) { rw.Header().Set("Content-Type", "application/json; charset=UTF-8") response := &ResponseJSON{Status: http.StatusOK, Message: "batchcorp/plumber " + a.Version} WriteJSON(http.StatusOK, response, rw) } func WriteJSON(statusCode int, data interface{}, w http.ResponseWriter) { w.Header().Add("Content-type", "application/json") jsonData, err := json.Marshal(data) if err != nil { w.WriteHeader(500) logrus.Errorf("Unable to marshal data in WriteJSON: %s", err) return } w.WriteHeader(statusCode) if _, err := w.Write(jsonData); err != nil { logrus.Errorf("Unable to write response data: %s", err) return } } func WriteErrorJSON(statusCode int, msg string, w http.ResponseWriter) { WriteJSON(statusCode, map[string]string{"error": msg}, w) } func WriteSuccessJSON(statusCode int, msg string, w http.ResponseWriter) { WriteJSON(statusCode, map[string]string{"msg": msg}, w) }
package main import "fmt" func main() { //declaring a integer variable x var x int x=3 //assigning x the value 3 fmt.Println("x:", x) //prints 3 //declaring a integer variable y with value 20 in a single statement and prints it var y int=20 fmt.Println("y:", y) //declaring a variable z with value 50 and prints it //Here type int is not explicitly mentioned var z=50 fmt.Println("z:", z) //Multiple variables are assigned in single line- i with an integer and j with a string var i, j = 100,"hello" fmt.Println("i and j:", i,j) }
package main import ( "context" "flag" "fmt" "log" "os" "path/filepath" "strconv" "github.com/adhocteam/soapbox/buildinfo" pb "github.com/adhocteam/soapbox/proto" "google.golang.org/grpc" ) func main() { serverAddr := flag.String("server", "127.0.0.1:9090", "host:port of server") printVersion := flag.Bool("V", false, "print version and exit") flag.Parse() if *printVersion { fmt.Printf(" version: %s\n", buildinfo.Version) fmt.Printf(" git commit: %s\n", buildinfo.GitCommit) fmt.Printf(" build time: %s\n", buildinfo.BuildTime) return } if flag.NArg() < 1 { usage() os.Exit(1) } conn, err := grpc.Dial(*serverAddr, grpc.WithInsecure()) if err != nil { log.Fatalf("couldn't connect to server %s: %v", *serverAddr, err) } defer conn.Close() client := pb.NewApplicationsClient(conn) ctx := context.Background() type command func(context.Context, pb.ApplicationsClient, []string) error var cmd command switch flag.Arg(0) { case "create-application": cmd = createApplication case "list-applications": cmd = listApplications case "get-application": cmd = getApplication case "get-version": if err := getVersion(ctx, pb.NewVersionClient(conn), nil); err != nil { log.Fatalf("getting version: %v", err) } return default: log.Fatalf("unknown command %q", flag.Arg(0)) } if err := cmd(ctx, client, flag.Args()); err != nil { log.Fatalf("error executing command %s: %v", flag.Arg(0), err) } } func usage() { fmt.Fprintf(os.Stderr, "usage: %s <command>\n", filepath.Base(os.Args[0])) } func createApplication(ctx context.Context, client pb.ApplicationsClient, args []string) error { args = args[1:] if len(args) < 5 { return fmt.Errorf("5 arguments are required: name, description, github repo URL, user_id, and type (server, cronjob)") } user_id, err := strconv.Atoi(args[3]) var appType pb.ApplicationType switch args[4] { case "server": appType = pb.ApplicationType_SERVER case "cronjob": appType = pb.ApplicationType_CRONJOB default: return fmt.Errorf("unknown app type %q, expecting either 'server' or 'cronjob'", args[3]) } req := &pb.Application{ Name: args[0], Description: args[1], GithubRepoUrl: args[2], UserId: int32(user_id), Type: appType, } app, err := client.CreateApplication(ctx, req) if err != nil { return fmt.Errorf("error creating application: %v", err) } fmt.Printf("created application %q, ID %d", args[0], app.GetId()) return nil } func listApplications(ctx context.Context, client pb.ApplicationsClient, args []string) error { args = args[1:] if len(args) < 1 { return fmt.Errorf("1 argument required: User ID") } id, err := strconv.Atoi(args[0]) if err != nil { return fmt.Errorf("invalid ID: %v", err) } req := &pb.ListApplicationRequest{UserId: int32(id)} apps, err := client.ListApplications(ctx, req) if err != nil { return fmt.Errorf("error listing applications: %v", err) } for _, app := range apps.Applications { fmt.Printf("%d\t%s\n", app.Id, app.Name) } return nil } func getApplication(ctx context.Context, client pb.ApplicationsClient, args []string) error { args = args[1:] if len(args) < 1 { return fmt.Errorf("1 argument required: ID of application") } id, err := strconv.Atoi(args[0]) if err != nil { return fmt.Errorf("invalid ID: %v", err) } req := &pb.GetApplicationRequest{Id: int32(id)} app, err := client.GetApplication(ctx, req) if err != nil { return fmt.Errorf("getting application: %v", err) } fmt.Printf("name: %s\n", app.Name) fmt.Printf("ID: %d\n", app.Id) fmt.Printf("type: %s\n", pb.ApplicationType_name[int32(app.Type)]) fmt.Printf("created at: %s\n", app.CreatedAt) fmt.Printf("external DNS: %s\n", app.ExternalDns) fmt.Printf("Dockerfile path: %s\n", app.DockerfilePath) fmt.Printf("entrypoint override: %s\n", app.EntrypointOverride) fmt.Printf("description:\n%s\n", app.Description) return nil } func getVersion(ctx context.Context, client pb.VersionClient, args []string) error { resp, err := client.GetVersion(ctx, &pb.Empty{}) if err != nil { return fmt.Errorf("getting version: %v", err) } fmt.Println("Soapbox API") fmt.Println("-----------") fmt.Printf(" version: %s\n", resp.Version) fmt.Printf(" git commit: %s\n", resp.GitCommit) fmt.Printf(" build time: %s\n", resp.BuildTime) return nil }
package main import "fmt" func main() { c :=pipe(7,8,56) res :=square(c) for r:=range res{ fmt.Println(r) //fmt.Println(<-res) //fmt.Println(<-res) } } func pipe(nums ...int) chan int{ c1:=make(chan int) go func(){ for _,r:=range nums{ c1<-r } close(c1) }() return c1 } func square(c chan int) chan int{ out :=make(chan int) go func(){ for r:=range c{ out<-r*r //fmt.Println(sq) } close(out) }() return out }
package main /* Imports * 4 utility libraries for formatting, handling bytes, reading and writing JSON, and string manipulation * 2 specific Hyperledger Fabric specific libraries for Smart Contracts */ import ( "bytes" "encoding/json" "fmt" "strconv" "time" "github.com/hyperledger/fabric/core/chaincode/shim" sc "github.com/hyperledger/fabric/protos/peer" ) // Define the Smart Contract structure type SmartContract struct { } // Define the car structure, with 4 properties. Structure tags are used by encoding/json library type Drug struct { Name string `json:"name"` Quantity string `json:"quantity"` UseCase string `json:"usecase"` Manufacturer string `json:"manufacturer"` DeliveryOwner string `json:"delivery_owner"` Cost float64 `json:"cost"` UpdatedDate string `json:"updated_date"` } /* * The Init method is called when the Smart Contract "fabcar" is instantiated by the blockchain network * Best practice is to have any Ledger initialization in separate function -- see InitLedger() */ func (s *SmartContract) Init(APIstub shim.ChaincodeStubInterface) sc.Response { return shim.Success(nil) } /* * The Invoke method is called as a result of an application request to run the Smart Contract "fabcar" * The calling application program has also specified the particular smart contract function to be called, with arguments */ func (s *SmartContract) Invoke(APIstub shim.ChaincodeStubInterface) sc.Response { // Retrieve the requested Smart Contract function and arguments function, args := APIstub.GetFunctionAndParameters() // Route to the appropriate handler function to interact with the ledger appropriately if function == "QueryDrug" { return s.QueryDrug(APIstub, args) } else if function == "InitLedger" { return s.InitLedger(APIstub) } else if function == "CreateDrug" { return s.CreateDrug(APIstub, args) } else if function == "QueryAllDrugs" { return s.QueryAllDrugs(APIstub) } else if function == "ChangeOwner" { return s.changeDeliveryOwner(APIstub, args) } return shim.Error("Invalid Smart Contract function name.") } func (s *SmartContract) QueryDrug(APIstub shim.ChaincodeStubInterface, args []string) sc.Response { if len(args) != 1 { return shim.Error("Incorrect number of arguments. Expecting 1") } drugAsBytes, _ := APIstub.GetState(args[0]) return shim.Success(drugAsBytes) } func (s *SmartContract) InitLedger(APIstub shim.ChaincodeStubInterface) sc.Response { drugs := []Drug{ Drug{Name: "Paracetamol", Cost: 6.5, Quantity: "10", UseCase: "Sick Burner", Manufacturer: "ViePharmaCorp", DeliveryOwner: "ViePharmaCorp"}, Drug{Name: "Paracetamol2", Cost: 7, Quantity: "11", UseCase: "Sick Burner", Manufacturer: "ViePharmaCorp", DeliveryOwner: "ViePharmaCorp"}, Drug{Name: "Paracetamol3", Cost: 7.5, Quantity: "12", UseCase: "Sick Burner", Manufacturer: "ViePharmaCorp", DeliveryOwner: "ViePharmaCorp"}, Drug{Name: "Paracetamol4", Cost: 8, Quantity: "13", UseCase: "Sick Burner", Manufacturer: "ViePharmaCorp", DeliveryOwner: "ViePharmaCorp"}, } i := 0 for i < len(drugs) { fmt.Println("i is ", i) drugAsBytes, _ := json.Marshal(drugs[i]) APIstub.PutState("DRUG"+strconv.Itoa(i), drugAsBytes) fmt.Println("Added", drugs[i]) i = i + 1 } return shim.Success(nil) } func (s *SmartContract) CreateDrug(APIstub shim.ChaincodeStubInterface, args []string) sc.Response { if len(args) != 5 { return shim.Error("Incorrect number of arguments. Expecting 5") } newCost, _ := strconv.ParseFloat(args[4], 64) var drug = Drug{ Name: args[1], Quantity: args[2], UseCase: args[3], Cost: newCost, Manufacturer: "ViePharmaCorp", DeliveryOwner: "ViePharmaCorp", UpdatedDate: time.Now().Format("Mon Jan 2 15:04:05 -0700 MST 2006"), } drugAsBytes, _ := json.Marshal(drug) APIstub.PutState(args[0], drugAsBytes) return shim.Success(nil) } func (s *SmartContract) QueryAllDrugs(APIstub shim.ChaincodeStubInterface) sc.Response { startKey := "DRUG0" endKey := "DRUG999" resultsIterator, err := APIstub.GetStateByRange(startKey, endKey) if err != nil { return shim.Error(err.Error()) } defer resultsIterator.Close() // buffer is a JSON array containing QueryResults var buffer bytes.Buffer buffer.WriteString("[") bArrayMemberAlreadyWritten := false for resultsIterator.HasNext() { queryResponse, err := resultsIterator.Next() if err != nil { return shim.Error(err.Error()) } // Add a comma before array members, suppress it for the first array member if bArrayMemberAlreadyWritten == true { buffer.WriteString(",") } buffer.WriteString("{\"Key\":") buffer.WriteString("\"") buffer.WriteString(queryResponse.Key) buffer.WriteString("\"") buffer.WriteString(", \"Record\":") // Record is a JSON object, so we write as-is buffer.WriteString(string(queryResponse.Value)) buffer.WriteString("}") bArrayMemberAlreadyWritten = true } buffer.WriteString("]") fmt.Printf("- QueryAllDrugs:\n%s\n", buffer.String()) return shim.Success(buffer.Bytes()) } func (s *SmartContract) changeDeliveryOwner(APIstub shim.ChaincodeStubInterface, args []string) sc.Response { if len(args) != 2 { return shim.Error("Incorrect number of arguments. Expecting 2") } //Get by ID drugAsBytes, _ := APIstub.GetState(args[0]) drug := Drug{} json.Unmarshal(drugAsBytes, &drug) drug.DeliveryOwner = args[1] // drug.UpdatedDate = time.Now().Format("Mon Jan 2 15:04:05 -0700 MST 2006") drugAsBytes, _ = json.Marshal(drug) APIstub.PutState(args[0], drugAsBytes) return shim.Success(nil) } // The main function is only relevant in unit test mode. Only included here for completeness. func main() { // Create a new Smart Contract err := shim.Start(new(SmartContract)) if err != nil { fmt.Printf("Error creating new Smart Contract: %s", err) } }
package protos import ( "math" "testing" "github.com/qlcchain/go-qlc/common/types" ) var ( HeaderBlockHash = "D2F6F6A6422000C60C0CB2708B10C8CA664C874EB8501D2E109CB4830EA41D41" OpenBlockHash = "D2F6F6A6422000C60C0CB2708B10C8CA664C874EB8501D2E109CB4830EA41D47" ) func TestFrontierReq(t *testing.T) { address := types.Address{} Req := NewFrontierReq(address, math.MaxUint32, math.MaxUint32) frBytes, err := FrontierReqToProto(Req) if err != nil { t.Fatal("FrontierReqToProto error") } t.Log(frBytes) frStruct, err := FrontierReqFromProto(frBytes) if err != nil { t.Fatal("FrontierReqFromProto error") } if frStruct.StartAddress != address { t.Fatal("Address error") } if frStruct.Count != math.MaxUint32 { t.Fatal("Count error") } if frStruct.Age != math.MaxUint32 { t.Fatal("Age error") } } func TestFrontierRsp(t *testing.T) { Frontier := new(types.Frontier) err := Frontier.HeaderBlock.Of(HeaderBlockHash) if err != nil { t.Fatal("string to headerhash error") } err = Frontier.OpenBlock.Of(OpenBlockHash) if err != nil { t.Fatal("string to openblockhash error") } fr := NewFrontierRsp(Frontier, 5) frBytes, err := FrontierResponseToProto(fr) if err != nil { t.Fatal("FrontierResponseToProto error") } frontierRsp, err := FrontierResponseFromProto(frBytes) if err != nil { t.Fatal("FrontierResponseFromProto error") } if frontierRsp.Frontier.HeaderBlock != Frontier.HeaderBlock { t.Fatal("parse Headerblock error") } if frontierRsp.Frontier.OpenBlock != Frontier.OpenBlock { t.Fatal("parse Openblock error") } if frontierRsp.TotalFrontierNum != fr.TotalFrontierNum { t.Fatal("parse TotalFrontierNum error") } }
package main import ( "fmt" ) func main() { mainloop: for { fmt.Println("Menu") fmt.Println("====") fmt.Printf("1. Add New Contact\n2. List Contacts\n3. Get Contact by ID\n4. Exit\n\n") fmt.Print("Your choice: ") var choice int fmt.Scanf("%d", &choice) switch choice { case 1: addcontact() case 2: getallcontacts() case 3: getcontactbyid() case 4: break mainloop default: fmt.Println("Invalid choice!") } } }
package ztimer import ( "log" "testing" "time" ) //定义一个超时函数 func myFunc(v ...interface{}) { log.Println("No.", v[0].(int), " function called delay ", v[1].(int), " second") } //go test -v -run TestTimer func TestTimer(t *testing.T) { for i := 0; i < 5; i++ { go func(i int) { NewTimerAfter(NewDelayFunc(myFunc, []interface{}{i, 2 * i}), time.Duration(2*i)*time.Second).Run() }(i) } //主进程等待其它go,由于run方法是用另一个go承载,这里不能使用waitGroup time.Sleep(1 * time.Minute) }
package lwwset import ( "errors" "time" ) // package lwwset implements the LWWSet (Last Writer Wins Set) CRDT data type along with the functionality // to append, remove, list & lookup values in a LWWSet. It also provides the functionality to merge multiple // LWWSets together and a utility function to clear a LWWSet used in tests // LWWSet is the LWWSet CRDT data type // It is implemented by combining two LWWNodes, // One to store the values added & another // to store the values removed type LWWSet struct { // Add is a LWWNodeSlice to store the values added Add LWWNodeSlice `json:"add"` // Remove is a LWWNodeSlice to store the values removed Remove LWWNodeSlice `json:"remove"` } // LWWNode stores a given value // along with a timestamp of // when it was added type LWWNode struct { Value string Timestamp time.Time } // LWWNodeSlice is a // collection of LWWNodes type LWWNodeSlice []LWWNode // Initialize returns a new empty LWWSet func Initialize() LWWSet { return LWWSet{ Add: LWWNodeSlice{}, Remove: LWWNodeSlice{}, } } // Addition adds a new unique value to the Add LWWSet func (lwwset LWWSet) Addition(value string) (LWWSet, error) { // Return an error if the value passed is nil if value == "" { return lwwset, errors.New("empty value provided") } // Order the LWWSet according // to the timestamps lwwset = lwwset.orderList() // Set = Set U value if !isPresent(value, lwwset.Add) { lwwset.Add = append(lwwset.Add, LWWNode{Value: value, Timestamp: time.Now()}) } // Return the new LWWSet // followed by nil error return lwwset, nil } // Removal adds a new unique value to the Remove LWWSet func (lwwset LWWSet) Removal(value string) (LWWSet, error) { // Return an error if the value passed is nil if value == "" { return lwwset, errors.New("empty value provided") } // Order the LWWSet according // to the timestamps lwwset = lwwset.orderList() // Set = Set U value if !isPresent(value, lwwset.Remove) { lwwset.Remove = append(lwwset.Remove, LWWNode{Value: value, Timestamp: time.Now()}) } // Return the new LWWSet // followed by nil error return lwwset, nil } // GetValues extracts all the values // present in the LWWNode slice func (list LWWNodeSlice) GetValues() []string { if len(list) == 0 { return []string{} } values := make([]string, 0) for _, lwwnode := range list { values = append(values, lwwnode.Value) } return values } // List returns all the elements present in the LWWSet func (lwwset LWWSet) List() (LWWSet, []string) { lwwset = lwwset.orderList() return lwwset, lwwset.Add.GetValues() } // orderList iterates over the list and does // a look up if an element is present or not func (lwwset LWWSet) orderList() LWWSet { // An element is a member of the LWW-Element-Set if it is in the add set, and either not in the remove // set, or in the remove set but with an earlier timestamp than the latest timestamp in the add set. for _, lwwNode := range lwwset.Add { if !isPresent(lwwNode.Value, lwwset.Remove) || latestValue(lwwNode.Value, lwwset.Remove).Timestamp.UnixNano() < lwwNode.Timestamp.UnixNano() { continue } lwwset.Add = Delete(lwwset.Add, lwwNode.Value) lwwset.Remove = Delete(lwwset.Remove, lwwNode.Value) } return lwwset } // isPresent checks if a given value // is present in the list or not func isPresent(value string, list LWWNodeSlice) bool { for _, element := range list { if element.Value == value { return true } } return false } // latestValue returns the latest value in a // LWWNodeSlice according to the timestamp func latestValue(value string, list LWWNodeSlice) LWWNode { maxNode := LWWNode{Value: value} for _, element := range list { if element.Value == maxNode.Value && element.Timestamp.UnixNano() > maxNode.Timestamp.UnixNano() { maxNode = element } } return maxNode } // Delete removes an entry from the LWWNodeSlice list func Delete(list LWWNodeSlice, value string) LWWNodeSlice { newList := LWWNodeSlice{} for _, node := range list { if node.Value != value { newList = append(newList, node) } } return newList } // Lookup returns either boolean true/false indicating // if a given value is present in the LWWSet or not func (lwwset LWWSet) Lookup(value string) (bool, error) { // Return an error if the value passed is nil if value == "" { return false, errors.New("empty value provided") } lwwset, list := lwwset.List() // Iterative over the LWWSet and check if the // value is the one we're searching // return true if the value exists for _, element := range list { if element == value { return true, nil } } // If the value isn't found after iterating // over the entire LWWSet we return false return false, nil } // Merge conbines multiple LWWSets together using Union // and returns a single merged LWWSet func Merge(LWWSets ...LWWSet) LWWSet { var LWWSetMerged LWWSet // LWWSetMerged = LWWSetMerged U LWWSetToMergeWith for _, lwwset := range LWWSets { for _, lwwnode := range lwwset.Add { if lwwnode.Value == "" { continue } LWWSetMerged, _ = LWWSetMerged.Addition(lwwnode.Value) } for _, lwwnode := range lwwset.Remove { if lwwnode.Value == "" { continue } LWWSetMerged, _ = LWWSetMerged.Removal(lwwnode.Value) } } // Return the merged LWWSet followed by nil error return LWWSetMerged } // Clear is utility function used only for tests // to empty the contents of a given LWWSet func Clear() LWWSet { lwwset := Initialize() return lwwset }
package model import ( "database/sql" "fmt" "log" "os" _ "github.com/lib/pq" ) var con *sql.DB func Connect() *sql.DB { dbUrl := os.Getenv("DATABASE_URL") ///"postgres://postgres@localhost:5432/test?sslmode=disable" log.Println("DB_URL: " + dbUrl) db, err := sql.Open("postgres", dbUrl) if err != nil { log.Fatal(err) } fmt.Println(db.Ping()) fmt.Println("Connected to the database") con = db return db }
package helpers import ( "encoding/json" "encoding/xml" "net/http" ) func toJson(p interface{}) ([]byte, error) { b, err := json.MarshalIndent(p, "", "\t") if err != nil { return nil, err } return b, nil } func toXML(p interface{}) ([]byte, error) { b, err := xml.Marshal(p) if err != nil { return nil, err } return b, nil } func RenderJSON(p interface{}, w http.ResponseWriter) { js, _ := toJson(p) w.Header().Set("Content-Type", "application/json") w.Write(js) } func RenderXML(p interface{}, w http.ResponseWriter) { xml, _ := toXML(p) w.Header().Set("Content-Type", "application/xml") w.Write(xml) }
package astutil import ( "go/ast" "testing" ) func TestExprString(t *testing.T) { exprs, err := Find(astFile, []interface{}{new(ast.Expr)}) if err != nil { t.Error(err) } for _, exp := range exprs { t.Log(SrcOf(exp), ExprString(exp.(ast.Expr))) } }
package LinkedList import "fmt" type CircularLinkedList struct { tail *Node length int } func NewCirurcularLinkedList() *CircularLinkedList { return &CircularLinkedList{length: 0} } func (cll *CircularLinkedList) Front() *Node { return cll.tail.next } func (cll *CircularLinkedList) Append(n *Node) { if cll.tail == nil { cll.tail = n cll.tail.next = cll.tail } else { n.next = cll.tail.next cll.tail.next = n cll.tail = n } cll.length++ } func (cll *CircularLinkedList) Prepend(n *Node) { if cll.tail == nil { cll.tail = n cll.tail.next = cll.tail } else { n.next = cll.tail.next cll.tail.next = n } cll.length++ } func (cll *CircularLinkedList) Display() { if cll.tail == nil { return } curr := cll.tail.next for { fmt.Print(curr.data) curr = curr.next if curr == cll.tail { break } } } func (cll *CircularLinkedList) Length() int { return cll.length }
package main import ( "bufio" "fmt" "os" "strconv" "strings" ) type password struct { min int max int char rune pwd []rune } // readLines reads a whole file into memory // and returns a slice of its lines. func readLines(path string) ([]password, error) { file, err := os.Open(path) if err != nil { return nil, err } defer file.Close() var lines []password scanner := bufio.NewScanner(file) for scanner.Scan() { line := scanner.Text() parts := strings.Split(line, " ") limits := strings.Split(parts[0], "-") min, err := strconv.Atoi(limits[0]) if err != nil { panic(err) } max, err := strconv.Atoi(limits[1]) if err != nil { panic(err) } lines = append(lines, password{min: min, max: max, char: []rune(parts[1])[0], pwd: []rune(parts[2])}) } return lines, scanner.Err() } func main() { data, err := readLines("input.txt") if err != nil { panic(err) } correctPwds := 0 for _, x := range data { count := 0 for _, c := range x.pwd { if c == x.char { count++ } } if count >= x.min && count <= x.max { correctPwds++ } } fmt.Printf("Old job correct passwords = %d\n", correctPwds) newCorrectPwds := 0 for _, x := range data { first := x.pwd[x.min-1] second := x.pwd[x.max-1] if (first == x.char && second != x.char) || (first != x.char && second == x.char) { newCorrectPwds++ } } fmt.Printf("New job correct passwords = %d\n", newCorrectPwds) }
package controller // //import ( // "../basic" // "math" //) // //type face struct { // p0 *basic.Point // p1 *basic.Point // depth float64 //} // //func (f *face) detectCollision(p *basic.Point) (*basic.Point, float64) { // t := p.Sub(f.p0).Dot(f.p1.Sub(f.p0))/(f.p1.Sub(f.p0).Length2()) // // if t < 0 || t > 1{ // return nil, 0 // } // // x := f.p0.Mult(1-t).Add(f.p1.Mult(t)) // d := x.Sub(p).Dot(f.normal()) // // if d < 0 || d > f.depth { // return nil, 0 // } // // return x, d //} // //func (f *face) detectSinkV2(p *basic.Point) (*basic.Point, float64) { // t := p.Sub(f.p0).Dot(f.p1.Sub(f.p0))/(f.p1.Sub(f.p0).Length2()) // // t = math.Min(t, 1) // t = math.Max(t, 0) // // x := f.p0.Mult(1-t).Add(f.p1.Mult(t)) // d := x.Sub(p).Dot(f.normal()) // // if d < 0 || d > f.depth { // return nil, 0 // } // // return x, d //} // // //func (f *face) detectCollisionV2(q0, q1 *basic.Point) (u0 *basic.Point, u1 *basic.Point, d float64) { // u0, d = f.detectSinkV2(q0) // if u0 == nil { // u0, d = f.detectSinkV2(q1) // if u0 == nil { // return nil, nil, 0 // } // } // // aX := f.p0.X - f.p1.X // aY := f.p0.Y - f.p1.Y // // bX := -(q0.X - q1.X) // bY := -(q0.Y - q1.Y) // // cX := q1.X - f.p1.X // cY := q1.Y - f.p1.Y // // det := aX*bY-bX*aY // if det == 0 { // return nil, nil, 0 // } // // s, t := (bY*cX - bX*cY)/det, (-aY*cX + aX*cY)/det // // if !(s >= 0 && s <= 1 && t >= 0 && t <=1) { // return nil, nil, 0 // } // // u1 = f.p0.Mult(s).Add(f.p1.Mult(1-s)) // // return //} // //func (f *face) normal() *basic.Point { // return f.p1.Sub(f.p0).Rotation2D(math.Pi/2).Normalized() //}
package p2 import ( "bufio" "fmt" "os" ) func checkIfTree(c rune) int { if c == '#' { return 1 } return 0 } func walkThroughGrid(grid [][]rune, x int, y int, xLimit int, yLimit int, xMovement int, yMovement int) int { treesFound := 0 if y >= yLimit { return treesFound } return treesFound + checkIfTree(grid[y][x]) + walkThroughGrid(grid, (x+xMovement)%xLimit, y+yMovement, xLimit, yLimit, xMovement, yMovement) } func driver() int { filename := fmt.Sprintf("p2.input") fp, fpe := os.Open(filename) if fpe != nil { panic(fpe) } defer fp.Close() var grid [][]rune bufReader := bufio.NewScanner(fp) for bufReader.Scan() { inputLine := bufReader.Text() grid = append(grid, []rune(inputLine)) } if grid == nil { return 0 } xLimit := len(grid[0]) yLimit := len(grid) paths := [][]int{ {1, 1}, {3, 1}, {5, 1}, {7, 1}, {1, 2}, } productOfTrees := 1 for _, path := range paths { productOfTrees *= walkThroughGrid(grid, 0, 0, xLimit, yLimit, path[0], path[1]) } return productOfTrees }
package sheet_logic import ( "hub/framework" "hub/sheet_logic/sheet_logic_types" ) type IntGreater IntComparator func NewIntGreater(name string) *IntGreater { tmp := NewIntComparator( name, sheet_logic_types.IntGreater, func(a int64, b int64) bool { return a > b }) return (*IntGreater)(tmp) } type FloatGreater FloatComparator func NewFloatGreater(name string) *FloatGreater { tmp := NewFloatComparator( name, sheet_logic_types.FloatGreater, framework.FloatGt) return (*FloatGreater)(tmp) } type StringGreater StringComparator func NewStringGreater(name string) *StringGreater { tmp := NewStringComparator( name, sheet_logic_types.StringGreater, func(a string, b string) bool { return a > b }) return (*StringGreater)(tmp) }
package swift import ( corev1 "k8s.io/api/core/v1" opapi "github.com/openshift/cluster-image-registry-operator/pkg/apis/imageregistry/v1alpha1" ) type driver struct { Name string Namespace string Config *opapi.ImageRegistryConfigStorageSwift } func NewDriver(crname string, crnamespace string, c *opapi.ImageRegistryConfigStorageSwift) *driver { return &driver{ Name: crname, Namespace: crnamespace, Config: c, } } func (d *driver) GetName() string { return "swift" } func (d *driver) ConfigEnv() (envs []corev1.EnvVar, err error) { envs = append(envs, corev1.EnvVar{Name: "REGISTRY_STORAGE", Value: d.GetName()}, corev1.EnvVar{Name: "REGISTRY_STORAGE_SWIFT_AUTHURL", Value: d.Config.AuthURL}, corev1.EnvVar{Name: "REGISTRY_STORAGE_SWIFT_CONTAINER", Value: d.Config.Container}, corev1.EnvVar{ Name: "REGISTRY_STORAGE_SWIFT_USERNAME", ValueFrom: &corev1.EnvVarSource{ SecretKeyRef: &corev1.SecretKeySelector{ LocalObjectReference: corev1.LocalObjectReference{ Name: d.Name + "-private-configuration", }, Key: "REGISTRY_STORAGE_SWIFT_USERNAME", }, }, }, corev1.EnvVar{ Name: "REGISTRY_STORAGE_SWIFT_PASSWORD", ValueFrom: &corev1.EnvVarSource{ SecretKeyRef: &corev1.SecretKeySelector{ LocalObjectReference: corev1.LocalObjectReference{ Name: d.Name + "-private-configuration", }, Key: "REGISTRY_STORAGE_SWIFT_PASSWORD", }, }, }, ) return } func (d *driver) Volumes() ([]corev1.Volume, []corev1.VolumeMount, error) { return nil, nil, nil } func (d *driver) CompleteConfiguration(customResourceStatus *opapi.ImageRegistryStatus) error { return nil }
package nsq import ( "time" n "github.com/nsqio/go-nsq" "github.com/raintank/fakemetrics/out" "github.com/raintank/met" "gopkg.in/raintank/schema.v1" "gopkg.in/raintank/schema.v1/msg" ) const NSQMaxMpubSize = 5 * 1024 * 1024 // nsq errors if more. not sure if can be changed const NSQMaxMetricPerMsg = 1000 // empirically found through benchmarks (should result in 64~128k messages) type NSQ struct { out.OutStats topic string producer *n.Producer } func New(topic, addr string, stats met.Backend) (*NSQ, error) { cfg := n.NewConfig() cfg.UserAgent = "fake_metrics" producer, err := n.NewProducer(addr, cfg) if err != nil { return nil, err } err = producer.Ping() if err != nil { return nil, err } return &NSQ{ OutStats: out.NewStats(stats, "nsq"), topic: topic, producer: producer, }, nil } func (n *NSQ) Close() error { n.producer.Stop() return nil } func (n *NSQ) Flush(metrics []*schema.MetricData) error { if len(metrics) == 0 { n.FlushDuration.Value(0) return nil } preFlush := time.Now() // typical metrics seem to be around 300B // nsqd allows <= 10MiB messages. // we ideally have 64kB ~ 1MiB messages (see benchmark https://gist.github.com/Dieterbe/604232d35494eae73f15) // at 300B, about 3500 msg fit in 1MiB // in worst case, this allows messages up to 2871B // this could be made more robust of course // real world findings in dev-stack with env-load: // 159569B msg /795 metrics per msg = 200B per msg // so peak message size is about 3500*200 = 700k (seen 711k) subslices := schema.Reslice(metrics, 3500) for _, subslice := range subslices { id := time.Now().UnixNano() data, err := msg.CreateMsg(subslice, id, msg.FormatMetricDataArrayMsgp) if err != nil { return err } n.MessageBytes.Value(int64(len(data))) n.MessageMetrics.Value(int64(len(subslice))) prePub := time.Now() err = n.producer.Publish(n.topic, data) if err != nil { n.PublishErrors.Inc(1) return err } n.PublishedMetrics.Inc(int64(len(subslice))) n.PublishedMessages.Inc(1) n.PublishDuration.Value(time.Since(prePub)) } n.FlushDuration.Value(time.Since(preFlush)) return nil }
package checkpoint import ( "TruckMonitor-Backend/controller/authentication" "TruckMonitor-Backend/model" "errors" "gopkg.in/gin-gonic/gin.v1" "log" "net/http" "strconv" "time" ) func (c *controller) CreateFactTimestamp(context *gin.Context) { checkPointId, err := strconv.Atoi(context.Param("checkpoint")) if err != nil { context.AbortWithStatus(http.StatusBadRequest) log.Println(err) return } employeeId := context.MustGet(authentication.PARAM_EMPLOYEE_ID).(int) dataCarriages, err := c.carriageDao.FindByDriveAndStatus(employeeId, model.CURRENT) if err != nil { context.AbortWithStatus(http.StatusBadRequest) log.Println(err) return } if len(dataCarriages) == 0 { // Если активных рейсов нет context.AbortWithStatus(http.StatusBadRequest) return } else if len(dataCarriages) > 1 { // Если активных рейсов более 1 context.AbortWithStatus(http.StatusInternalServerError) log.Println(errors.New("len(carriages) > 1")) return } // Если активный рейс 1 currentCarriage := dataCarriages[0] c.carriageDao.CreateFactTimestamp(currentCarriage.Id, checkPointId, time.Now()) context.AbortWithStatus(http.StatusOK) }
package game import ( "battleship/game" "battleship/scoreboard" "fmt" "strconv" "testing" "github.com/corbym/gocrest/is" "github.com/corbym/gocrest/then" ) func TestGetScoreBoardWithOneCellLongShip(t *testing.T) { // Given one 1 cell long ship // on a 3x3 grid ship := game.Ship{1, []game.Cell{}} grid := game.NewGrid(3) cells := [][]int{ {2, 2, 2}, {2, 2, 2}, {2, 2, 2}, } expected := &scoreboard.ScoreBoard{3, cells} // When computing its possible positions actual := scoreboard.GetScoreBoard(grid, ship) // adresse récupérée // Then it should equals this score board then.AssertThat(t, actual, is.EqualTo(expected).Reason("1 cell long ship on 3x3 grid")) displayScoreBoard(actual, ship, grid) } func TestGetScoreBoardWithTwoCellsLongShip(t *testing.T) { // Given one 2 cells long ship ship := game.Ship{2, []game.Cell{}} grid := game.NewGrid(3) cells := [][]int{ {2, 3, 2}, {3, 4, 3}, {2, 3, 2}, } expected := &scoreboard.ScoreBoard{3, cells} // When computing its possible positions // on a 3x3 grid actual := scoreboard.GetScoreBoard(grid, ship) // Then it should equals this score board then.AssertThat(t, actual, is.EqualTo(expected).Reason("2 cells long ship on 3x3 grid")) displayScoreBoard(actual, ship, grid) } func TestGetScoreBoardWithTooLongShip(t *testing.T) { // Given one 4 cells long ship // on a 3x3 grid ship := game.Ship{4, []game.Cell{}} grid := game.NewGrid(3) cells := [][]int{ {0, 0, 0}, {0, 0, 0}, {0, 0, 0}, } expected := &scoreboard.ScoreBoard{3, cells} // When computing its possible positions actual := scoreboard.GetScoreBoard(grid, ship) // Then it should not be computed then.AssertThat(t, actual, is.EqualTo(expected).Reason("Too long ship on 3x3 grid")) displayScoreBoard(actual, ship, grid) } func TestGetScoreBoardWithObstacle(t *testing.T) { // Given a grid with an obstacle // and considering a 2 cells long ship grid := game.NewGrid(3) grid = game.AddShot(grid, game.Shot{game.Cell{1, 2}, game.HIT}) ship := game.Ship{2, []game.Cell{}} cells := [][]int{ {2, 3, 1}, {3, 3, 0}, {2, 3, 1}, } expected := &scoreboard.ScoreBoard{3, cells} // When computing possible positions of the ship actual := scoreboard.GetScoreBoard(grid, ship) // Then the resulting score board should equals the expected one then.AssertThat(t, actual, is.EqualTo(expected).Reason("There is an obstacle on cell 1:2")) displayScoreBoard(actual, ship, grid) } func TestGetScoreBoardWithBiggerGridWithoutObstacle(t *testing.T) { grid := game.NewGrid(10) computedShip := game.Ship{2, []game.Cell{}} cells := [][]int{ {2, 3, 3, 3, 3, 3, 3, 3, 3, 2}, {3, 4, 4, 4, 4, 4, 4, 4, 4, 3}, {3, 4, 4, 4, 4, 4, 4, 4, 4, 3}, {3, 4, 4, 4, 4, 4, 4, 4, 4, 3}, {3, 4, 4, 4, 4, 4, 4, 4, 4, 3}, {3, 4, 4, 4, 4, 4, 4, 4, 4, 3}, {3, 4, 4, 4, 4, 4, 4, 4, 4, 3}, {3, 4, 4, 4, 4, 4, 4, 4, 4, 3}, {3, 4, 4, 4, 4, 4, 4, 4, 4, 3}, {2, 3, 3, 3, 3, 3, 3, 3, 3, 2}, } expected := &scoreboard.ScoreBoard{10, cells} actual := scoreboard.GetScoreBoard(grid, computedShip) then.AssertThat(t, actual, is.EqualTo(expected).Reason("Bigger grid without obstacle")) displayScoreBoard(actual, computedShip, grid) } func TestGetScoreBoardWithBiggerGridAndOneObstacle(t *testing.T) { grid := game.NewGrid(10) grid = game.AddShot(grid, game.Shot{game.Cell{1, 2}, game.HIT}) computedShip := game.Ship{2, []game.Cell{}} cells := [][]int{ {2, 3, 2, 3, 3, 3, 3, 3, 3, 2}, {3, 3, 0, 3, 4, 4, 4, 4, 4, 3}, {3, 4, 3, 4, 4, 4, 4, 4, 4, 3}, {3, 4, 4, 4, 4, 4, 4, 4, 4, 3}, {3, 4, 4, 4, 4, 4, 4, 4, 4, 3}, {3, 4, 4, 4, 4, 4, 4, 4, 4, 3}, {3, 4, 4, 4, 4, 4, 4, 4, 4, 3}, {3, 4, 4, 4, 4, 4, 4, 4, 4, 3}, {3, 4, 4, 4, 4, 4, 4, 4, 4, 3}, {2, 3, 3, 3, 3, 3, 3, 3, 3, 2}, } expected := &scoreboard.ScoreBoard{10, cells} actual := scoreboard.GetScoreBoard(grid, computedShip) then.AssertThat(t, actual, is.EqualTo(expected).Reason("Bigger grid with one obstacle")) displayScoreBoard(actual, computedShip, grid) } func TestGetScoreBoardWithBiggerGridAndMultipleObstacles(t *testing.T) { grid := game.NewGrid(10) grid = game.AddShot(grid, game.Shot{game.Cell{1, 2}, game.HIT}) grid = game.AddShot(grid, game.Shot{game.Cell{5, 6}, game.HIT}) grid = game.AddShot(grid, game.Shot{game.Cell{8, 4}, game.HIT}) computedShip := game.Ship{2, []game.Cell{}} cells := [][]int{ {2, 3, 2, 3, 3, 3, 3, 3, 3, 2}, {3, 3, 0, 3, 4, 4, 4, 4, 4, 3}, {3, 4, 3, 4, 4, 4, 4, 4, 4, 3}, {3, 4, 4, 4, 4, 4, 4, 4, 4, 3}, {3, 4, 4, 4, 4, 4, 3, 4, 4, 3}, {3, 4, 4, 4, 4, 3, 0, 3, 4, 3}, {3, 4, 4, 4, 4, 4, 3, 4, 4, 3}, {3, 4, 4, 4, 3, 4, 4, 4, 4, 3}, {3, 4, 4, 3, 0, 3, 4, 4, 4, 3}, {2, 3, 3, 3, 2, 3, 3, 3, 3, 2}, } expected := &scoreboard.ScoreBoard{10, cells} actual := scoreboard.GetScoreBoard(grid, computedShip) then.AssertThat(t, actual, is.EqualTo(expected).Reason("Bigger grid with multiple obstacles")) displayScoreBoard(actual, computedShip, grid) } func displayScoreBoard(scoreBoard *scoreboard.ScoreBoard, ship game.Ship, grid game.Grid) { message := scoreboard.ToString(scoreBoard) message += " " message += strconv.Itoa(ship.Length) + " long ship on " + strconv.Itoa(grid.Size) + "x" + strconv.Itoa(grid.Size) + " grid" obstaclesCount := len(grid.Ships) if obstaclesCount > 0 { message += " with " + strconv.Itoa(obstaclesCount) + " obstacle" } fmt.Println(message) }
package main import ( "fmt" "strings" ) var s = "Hi He Lied Because Boron Could Not Oxidize Fluorine. New Nations Might Also Sign Peace Security Clause. Arthur King Can." var list = []int{1, 5, 6, 7, 8, 9, 15, 16, 19} func contains(i []int, e int) bool { for _, v := range i { if e == v-1 { return true } } return false } func main() { result := make(map[int]string) for i, v := range strings.Split(s, " ") { if contains(list, i) { result[i] = v[0:1] } else { result[i] = v[0:2] } } fmt.Println(result) }
package main import ( "encoding/json" "errors" "flag" "fmt" "io/ioutil" "log" "net/http" "path/filepath" "regexp" ) var ( reName = regexp.MustCompile(`([a-zA-Z0-9_]+).json`) ) type FileInfo struct { Name string Path string Route string } func fileInfo(filepath string) (FileInfo, error) { var fi FileInfo sm := reName.FindStringSubmatch(filepath) if len(sm) < 2 { return fi, errors.New("can't extract name from file") } fi.Name = sm[1] fi.Path = filepath fi.Route = fmt.Sprintf("/%s", sm[1]) return fi, nil } func main() { // cli args port := flag.String("port", "8001", "port to run server on") dbDir := flag.String("dir", "db", "folder containing json models") // all model file names ms, err := filepath.Glob(fmt.Sprintf("%s/*.json", *dbDir)) if err != nil { log.Fatal(err) } var ps []string for _, m := range ms { var p json.RawMessage // json.RawMessage validates json a a side effect f, err := ioutil.ReadFile(m) if err != nil { log.Fatal(err) } if err := json.Unmarshal(f, &p); err != nil { log.Fatal(err) } fi, err := fileInfo(m) if err != nil { log.Fatal(err) } log.Printf(fi.Route) // generating route for each model http.HandleFunc(fi.Route, func(w http.ResponseWriter, r *http.Request) { if err != nil { w.WriteHeader(http.StatusNotFound) } w.Header().Add("Content-Type", "application/json") w.Write(p) }) ps = append(ps, fi.Name) } log.Println("running server with following paths") log.Fatal(http.ListenAndServe(fmt.Sprintf(":%s", *port), nil)) }
package processor import ( "github.com/stretchr/testify/assert" "testing" ) func TestScoreboard(t *testing.T) { assert.False(t, IsInScoreboard(0, "1234")) AddToScoreboard(0, "1234") assert.True(t, IsInScoreboard(0, "1234")) assert.False(t, IsInScoreboard(1, "1234")) assert.False(t, IsInScoreboard(0, "5678")) RemoveFromScoreboard(0, "1234") assert.False(t, IsInScoreboard(0, "1234")) }
package main import ( "github.com/google/uuid" "time" ) type User struct { _id uuid.UUID name string email string password string } type Project struct { _id uuid.UUID user_id uuid.UUID name string dateCompleted time.Time password string } type Task struct { _id uuid.UUID project_id uuid.UUID name string dateCompleted time.Time lastAssigned time.Time } type WorkLog struct { _id uuid.UUID task_id uuid.UUID startTime time.Time endTime time.Time } type UserStore interface { User(_id uuid.UUID) (User, error) CreateUser(t *User) error UpdateUser(t *User) error DeleteUser(t *User) error } type ProjectStore interface { Project(_id uuid.UUID) (Project, error) ProjectsByUser(user_id uuid.UUID) ([]Project, error) CreateProject(t *Project) error UpdateProject(t *Project) error DeleteProject(t *Project) error } type TaskStore interface { Task(_id uuid.UUID) (Task, error) TasksByProject(project_id uuid.UUID) ([]Task, error) CreateTask(t *Task) error UpdateTask(t *Task) error DeleteTask(t *Task) error } type WorkLogStore interface { WorkLog(_id uuid.UUID) (WorkLog, error) WorkLogsByTask(task_id uuid.UUID) ([]WorkLog, error) CreateWorkLog(t *WorkLog) error }
package arb import ( "finrgo/exhanges" "testing" ) type ( ExchangeTest struct { oneExchange exhanges.IExhanged exchanges *exhanges.Exchanges } ) func NewExhcnageTest() IExchange { ex := &ExchangeTest{} // ex.exchanges = exhanges.InitExhanges() // exchanges.AddExhange(BittrexExchange, &bittrex.Bittrex{}) // ex.exchanges.AddExhange(PoloniexExchange, &poloniex.Poloniex{}) // ex.oneExchange = ex.exchanges.GetInstanceExchange(PoloniexExchange) return ex } func (ex *ExchangeTest) GetDataArb(cycles *Cycle) { cycles.Trade[0].AmountInExhange = 0.1 cycles.Trade[0].Price = 0.00007300 cycles.Trade[1].AmountInExhange = 0.1 cycles.Trade[1].Price = 0.52839300 cycles.Trade[2].AmountInExhange = 0.1 cycles.Trade[2].Price = 7285 } func (ex *ExchangeTest) SendOrders(cycles *Cycle) { } func (ex *ExchangeTest) GetCountOpenOrders() { } func (ex *ExchangeTest) GetOneExchage() exhanges.IExhanged { return ex.oneExchange } func TestProfit(t *testing.T) { exchange := NewExhcnageTest() cyclesXMR_BTC_USD := &Cycle{IsTradeOn: false, IsDebugCalc: true, IsVerifyAmountInExchange: false, IsNoLoop: true} cyclesXMR_BTC_USD.Trade = make([]TradeParam, 3) cyclesXMR_BTC_USD.Init_BTCXRPUSD() cyclesXMR_BTC_USD.Trade[0].StartAmount = 0.0050 cyclesXMR_BTC_USD.CalculateTrade(exchange) }
/* * EVE Swagger Interface * * An OpenAPI for EVE Online * * OpenAPI spec version: 0.4.1.dev1 * * Generated by: https://github.com/swagger-api/swagger-codegen.git */ package swagger // dogma_attribute object type GetUniverseTypesTypeIdDogmaAttribute struct { // attribute_id integer AttributeId int32 `json:"attribute_id,omitempty"` // value number Value float32 `json:"value,omitempty"` }
package services // PeriodicSymbols is a map of the symbols of the available metals in the periodic table. var PeriodicSymbols = map[string]string{ "au": "gold", "ag": "silver", "pt": "platinum", "pd": "palladium", "cu": "copper", "rh": "rhodium", }
package quacktorstreams import "github.com/Azer0s/quacktors" //NewConsumer creates a new ConsumerActor by a consumer implementation //and returns both a pointer to the ConsumerActor itself and the PID //of the consumer. The pointer to the ConsumerActor can be used to subscribe //to topics of the stream. func NewConsumer(consumer Consumer) (*ConsumerActor, *quacktors.Pid) { actor := &ConsumerActor{ Consumer: consumer, } pid := quacktors.SpawnStateful(actor) return actor, pid } //NewProducer creates a new producer actor by a consumer implementation //and returns the PID of the ProducerActor. When a message is sent to //the ProducerActor, it is automatically forwarded (i.e. published) //to the provided topic in the stream. func NewProducer(producer Producer, topic string) *quacktors.Pid { actor := &ProducerActor{ producer, } pid := quacktors.SpawnStateful(actor) actor.SetTopic(topic) return pid }
package aws import "github.com/lann/builder" type Options struct { AccessKeyId string `config:"id"` SecretAccessKey string `config:"key"` DefaultRegion string `config:"region"` SessionToken string `config:"token"` } type optionsBuilder builder.Builder func (b optionsBuilder) AccessKeyId(value string) optionsBuilder { return builder.Set(b, "AccessKeyId", value).(optionsBuilder) } func (b optionsBuilder) SecretAccessKey(value string) optionsBuilder { return builder.Set(b, "SecretAccessKey", value).(optionsBuilder) } func (b optionsBuilder) DefaultRegion(value string) optionsBuilder { return builder.Set(b, "DefaultRegion", value).(optionsBuilder) } func (b optionsBuilder) SessionToken(value string) optionsBuilder { return builder.Set(b, "SessionToken", value).(optionsBuilder) } func (b optionsBuilder) Build() Options { return builder.GetStruct(b).(Options) } var OptionsBuilder = builder.Register(optionsBuilder{}, Options{}).(optionsBuilder)
package crawl import ( "sync" "sync/atomic" . "./base" "./robot" "./store" "github.com/golang/glog" ) func (p *Stock) Days_fix(store store.Store) { c := Day_collection_name(p.Id) p.Days.Data, _ = store.LoadTDatas(c, Market_begin_day) l := len(p.Days.Data) if l < 1 { return } t := p.Days.Data[0].Time inds, _ := p.days_download(t) store.SaveTDatas(c, p.Days.Data, inds) } func (p *Stock) Ticks_fix(store store.Store) { daylen := len(p.Days.Data) if daylen < 1 { return } c := Tick_collection_name(p.Id) for i := daylen - 1; i > -1; i-- { if daylen-i > 60 { break } t := p.Days.Data[i].Time if store.HasTickData(c, t) { glog.V(LogV).Infoln(t, "already in db, skip") continue } p.Ticks.Data = []Tick{} if _, err := p.ticks_download(t); err != nil { glog.Warningln("fix ticks err", err) } if len(p.Ticks.Data) < 1 { glog.Warningln("got empty ticks") continue } store.SaveTicks(c, p.Ticks.Data) } } func FixData(storestr string) { store := store.Get(storestr) data, err := store.LoadCategories() if err != nil { glog.Infoln("load categories err", err) } if len(data) < 1 { glog.Infoln("load categories empty") return } for i, _ := range data { data[i].Factor = 0 } robot.Work() stocks := Stocks{store: store} var wg sync.WaitGroup for i, _ := range data { if !data[i].Leaf { continue } _, s, ok := stocks.Insert(data[i].Name) if !ok { continue } wg.Add(1) go func(s *Stock, i int) { defer wg.Done() s.Days_fix(store) s.loaded = int32(i) + 2 }(s, i) } glog.Infoln("wait all fix done") wg.Wait() glog.Infoln("all fix done") stocks.rwmutex.RLock() for i, l := 0, len(stocks.stocks); i < l; i++ { s := stocks.stocks[i] if atomic.LoadInt32(&s.loaded) < 2 { continue } s.Ticks_fix(store) } stocks.rwmutex.RUnlock() }
package acmt import ( "encoding/xml" "github.com/thought-machine/finance-messaging/iso20022" ) type Document01300101 struct { XMLName xml.Name `xml:"urn:iso:std:iso:20022:tech:xsd:acmt.013.001.01 Document"` Message *AccountReportRequestV01 `xml:"AcctRptReq"` } func (d *Document01300101) AddMessage() *AccountReportRequestV01 { d.Message = new(AccountReportRequestV01) return d.Message } // Scope // The AccountReportRequest message is sent from an organisation to a financial institution for reporting purposes. It is a request for an account report. // Usage // This message can be sent at any time outside of account opening, maintenance or closing processes. type AccountReportRequestV01 struct { // Set of elements for the identification of the message and related references. References *iso20022.References4 `xml:"Refs"` // Unique and unambiguous identification of the account between the account owner and the account servicer. AccountIdentification *iso20022.AccountForAction1 `xml:"AcctId"` // Unique and unambiguous identifier of a financial institution, as assigned under an internationally recognised or proprietary identification scheme. // AccountServicerIdentification *iso20022.BranchAndFinancialInstitutionIdentification4 `xml:"AcctSvcrId"` // Identification of the organisation requesting the report. OrganisationIdentification []*iso20022.OrganisationIdentification6 `xml:"OrgId"` // Specifies target and/or actual dates. ContractDates *iso20022.AccountContract2 `xml:"CtrctDts,omitempty"` // Contains the signature with its components, namely signed info, signature value, key info and the object. DigitalSignature []*iso20022.PartyAndSignature1 `xml:"DgtlSgntr,omitempty"` } func (a *AccountReportRequestV01) AddReferences() *iso20022.References4 { a.References = new(iso20022.References4) return a.References } func (a *AccountReportRequestV01) AddAccountIdentification() *iso20022.AccountForAction1 { a.AccountIdentification = new(iso20022.AccountForAction1) return a.AccountIdentification } func (a *AccountReportRequestV01) AddAccountServicerIdentification() *iso20022.BranchAndFinancialInstitutionIdentification4 { a.AccountServicerIdentification = new(iso20022.BranchAndFinancialInstitutionIdentification4) return a.AccountServicerIdentification } func (a *AccountReportRequestV01) AddOrganisationIdentification() *iso20022.OrganisationIdentification6 { newValue := new(iso20022.OrganisationIdentification6) a.OrganisationIdentification = append(a.OrganisationIdentification, newValue) return newValue } func (a *AccountReportRequestV01) AddContractDates() *iso20022.AccountContract2 { a.ContractDates = new(iso20022.AccountContract2) return a.ContractDates } func (a *AccountReportRequestV01) AddDigitalSignature() *iso20022.PartyAndSignature1 { newValue := new(iso20022.PartyAndSignature1) a.DigitalSignature = append(a.DigitalSignature, newValue) return newValue }
package main import ( "fmt" "time" ) func main() { // Classic for loop for i := 0; i < 10; i++ { if i == 0 { continue } fmt.Println("Inside classic for loop, value of i is:", i) } fmt.Println("\n\n") // Single condition for loop j := -20 for j != 0 { fmt.Println("Inside single condition loop, value of j is:", j) j++ } fmt.Println("\n\n") loopTimer := time.NewTimer(time.Second * 9) // An infinite loop, don't worry we'll break out of it in 9 seconds for { fmt.Println("Inside the infinite loop!") <-loopTimer.C break } }
package gosseract import ( "errors" "os" ) func (o *options) init() *options { o.UseFile = false o.FilePath = "" o.Digest = make(map[string]string) return o } func (s *Servant) OptionWithFile(path string) error { _, e := os.Open(path) if e != nil { return errors.New("No such option file `" + path + "` is found.") } s.options.UseFile = true s.options.FilePath = path return nil } func (s *Servant) AllowChars(charAllowed string) { if charAllowed == "" { return } s.options.Digest["tessedit_char_whitelist"] = charAllowed return }
package pkg import ( "errors" "testing" "time" "github.com/calvinmclean/automated-garden/garden-app/pkg/influxdb" "github.com/stretchr/testify/mock" ) func TestHealth(t *testing.T) { tests := []struct { name string lastContactTime time.Time err error expectedStatus string }{ { "GardenIsUp", time.Now(), nil, "UP", }, { "GardenIsDown", time.Now().Add(-5 * time.Minute), nil, "DOWN", }, { "InfluxDBError", time.Time{}, errors.New("influxdb error"), "N/A", }, { "ZeroTime", time.Time{}, nil, "DOWN", }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { influxdbClient := new(influxdb.MockClient) influxdbClient.On("GetLastContact", mock.Anything, "garden").Return(tt.lastContactTime, tt.err) g := Garden{Name: "garden"} gardenHealth := g.Health(influxdbClient) if gardenHealth.Status != tt.expectedStatus { t.Errorf("Unexpected GardenHealth.Status: expected = %s, actual = %s", tt.expectedStatus, gardenHealth.Status) } }) } }
package share const ( S2C_ERROR = 10000 + iota S2C_LOGININFO S2C_LOGINSUCCEED S2C_ENTERBASEERR S2C_ROLEINFO S2C_RPC ) const ( ERROR_SUCCESS = iota ERROR_MSG_ILLEGAL ERROR_NOBASE ERROR_LOGIN_FAILED //登录失败 ERROR_LOGIN_TRY_MAX //登录失败超过最大次数 ERROR_SYSTEMERROR //系统错误 ERROR_BASE_KEY_EXPIRED //密钥过期 ERROR_SELECT_ROLE_ERROR //选择角色出错 ERROR_CREATE_ROLE_ERROR //创建角色出错 ERROR_ROLE_USED //角色正在使用中 ERROR_ROLE_ENTERAREA_ERROR //进入场景失败 ERROR_NAME_CONFLIT //名字冲突 ERROR_ROLE_LIMIT //超出人物个数限制 ERROR_ROLE_REPLACE //已经被顶替 ERROR_CONTAINER_FULL //背包满了 ERROR_NOLOGIN //没有登录服务器 ) //错误消息起始编号 const ( ERROR_BATTLE = 10000 ERROR_PLAYER = 11000 ERROR_MALL = 12000 ERROR_COMPOSE = 13000 ERROR_LETTER = 14000 ) type S2CMsg struct { Sender string To int64 Method string Data []byte } type S2CBrocast struct { Sender string To []int64 Method string Data []byte } type S2SBrocast struct { To []int64 Method string Args interface{} }
package cart import ( "context" "github.com/gingerxman/eel" m_cart "github.com/gingerxman/ginger-product/models/cart" ) type CartService struct { eel.ServiceBase } func NewCartService(ctx context.Context) *CartService { service := new(CartService) service.Ctx = ctx return service } func (this *CartService) DeleteShoppingCartItems(ids[] int) { o := eel.GetOrmFromContext(this.Ctx) db := o.Model(&m_cart.CartItem{}).Where("id__in", ids).Delete(&m_cart.CartItem{}) if db.Error != nil { eel.Logger.Error(db.Error) } } func init() { }
package buildah_test import ( "context" "io" "io/ioutil" "os" "testing" "github.com/werf/werf/pkg/util" "github.com/werf/werf/pkg/docker" "github.com/werf/werf/pkg/werf" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" "github.com/werf/werf/pkg/buildah" ) func TestBuildah(t *testing.T) { RegisterFailHandler(Fail) RunSpecs(t, "Buildah suite") } var _ = BeforeSuite(func() { Expect(werf.Init("", "")).To(Succeed()) Expect(docker.Init(context.Background(), "", false, false, "")).To(Succeed()) }) var _ = Describe("Buildah client", func() { var b buildah.Buildah BeforeEach(func() { Skip("not working inside go test yet") var err error b, err = buildah.NewBuildah(buildah.ModeDockerWithFuse, buildah.BuildahOpts{}) Expect(err).To(Succeed()) }) It("Builds projects using Dockerfile", func() { for _, desc := range []struct { DockerfilePath string ContextPath string }{ {"./buildah_test/Dockerfile.ghost", ""}, {"./buildah_test/Dockerfile.neovim", ""}, {"./buildah_test/app1/Dockerfile", "./buildah_test/app1"}, {"./buildah_test/app2/Dockerfile", "./buildah_test/app2"}, {"./buildah_test/app3/Dockerfile", "./buildah_test/app3"}, } { d, c := loadDockerfileAndContext(desc.DockerfilePath, desc.ContextPath) _, err := b.BuildFromDockerfile(context.Background(), d, buildah.BuildFromDockerfileOpts{ CommonOpts: buildah.CommonOpts{LogWriter: os.Stdout}, ContextTar: c, }) Expect(err).To(Succeed()) } }) }) func loadDockerfileAndContext(dockerfilePath string, contextPath string) ([]byte, io.Reader) { data, err := ioutil.ReadFile(dockerfilePath) Expect(err).To(Succeed()) if contextPath == "" { return data, nil } reader := util.ReadDirAsTar(contextPath) return data, reader }
package main import ( "fmt" "testing" ) func TestIsGm(t *testing.T) { command1 := "/help" command2 := "help" if !IsGm(command1) { t.Fatal("error1") } if IsGm(command2) { t.Fatal("error2") } } func TestLoadSensitiveWords(t *testing.T) { strList := LoadSensitiveWords() if len(strList) != 451 { t.Fatal("load error") } } func TestSecondsToDayStr(t *testing.T) { var d, h, m, s int64 = 100, 3, 32, 18 seconds := d*24*60*60 + h*3600 + m*60 + s timeStr := SecondsToDayStr(seconds) if timeStr != "100d 03h 32m 18s" { t.Fatal("error", timeStr) } else { fmt.Println(timeStr) } }
package main import ( "bufio" "os" "fmt" "io/ioutil" "path" "strings" "os/exec" "io" ) const ExtStrs string =""; var ExtMaps map[string]interface{}; func init(){ GetExtLists() } func GetExtLists(){ ExtMaps=make(map[string] interface{}) if(ExtStrs !=""){ list:=strings.Split(ExtStrs,","); for _,value:=range list{ ExtMaps[value] = struct{}{} }; } } func IsAllows(key string) (b bool){ if(len(ExtMaps)==0){ b =true; return ; } _,b=ExtMaps[key]; return; } func main(){ fmt.Println("place input the source file"); reader := bufio.NewReader(os.Stdin) var file string; for{ tmp, err := reader.ReadString('\n'); if(err!=nil){ fmt.Println("with err file",err); } file=strings.TrimSpace(tmp); _, e:= os.Stat(file); if(e==nil){ break; }else{ fmt.Println("FILE:",file,"does not exist") } } fmt.Println("place input the destination"); var destination string; for { tmp,err:= reader.ReadString('\n'); if(err!=nil){ fmt.Println("width err destination",err); } destination=strings.TrimSpace(tmp) _, err = os.Stat(destination); if(err!=nil){ ce:=os.Mkdir(destination,os.ModeDir); if(ce==nil){ break; }else{ fmt.Println("width err destination",ce); } }else{ break; } } dir, err := ioutil.ReadDir(file) if err != nil { fmt.Println("faild to read:",file) return; } for _, fi := range dir { //判断是否是目录 fileName:=file+string(os.PathSeparator)+fi.Name(); if(fi.IsDir()){ continue; } //判断文件后缀名 ext:=path.Ext(fileName); ext=strings.Trim(strings.ToLower(ext),".") if(!IsAllows(ext)){ continue; } ch:=make(chan int); dName:=destination+string(os.PathSeparator)+fi.Name(); go CommonExecs(fileName,dName,ch); <-ch } } func CommonExecs(file string,name string,ch chan<- int){ cmd := exec.Command("ffmpeg", "-i",file,"-acodec","aac","-ab","64k","-vcodec","libx264","-vb","1000k","-preset","superfast","-threads","16","-r","25",name); stdout,err:=cmd.StderrPipe(); if(err!=nil){ fmt.Println("Fail to execute start:",err,file) return; } err=cmd.Start(); //实时循环读取输出流中的一行内容 reader := bufio.NewReader(stdout) for { line, err2 := reader.ReadString('\r') line = strings.TrimSpace(line) if err2 != nil || io.EOF == err2 { break } fmt.Println(line); } if(err==nil){ fmt.Println("Success:",cmd.Args) }else{ fmt.Println("Fail:",err,cmd.Args) } cmd.Wait() ch<-1 }
package _316_Remove_Duplicate_Letters import ( "strings" "testing" ) type testCase struct { input string output string } func TestRemoveDuplicateLetters(t *testing.T) { cases := []testCase{ { input: "bcabc", output: "abc", }, { input: "cbacdcbc", output: "acdb", }, } for _, c := range cases { if x := removeDuplicateLetters(c.input); !strings.EqualFold(x, c.output) { t.Errorf("output should be \"%s\" instead of \"%s\" with input=\"%s\"", c.output, x, c.input) } } }
// +build cgo /* Copyright (c) 2016 Jason Ish * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package sqlite import ( "database/sql" "fmt" "github.com/jasonish/evebox/appcontext" "github.com/jasonish/evebox/log" "github.com/jasonish/evebox/sqlite/common" _ "github.com/mattn/go-sqlite3" "github.com/pkg/errors" "github.com/spf13/viper" "os" "path" "strings" "time" ) const OLD_DB_FILENAME = "evebox.sqlite" const DB_FILENAME = "events.sqlite" func init() { viper.SetDefault("database.sqlite.disable-fsync", false) viper.BindEnv("database.sqlite.disable-fsync", "DISABLE_FSYNC") } type SqliteService struct { *sql.DB } func NewSqliteService(filename string) (*SqliteService, error) { log.Debug("Opening SQLite database %s", filename) dsn := fmt.Sprintf("file:%s?cache=shared&mode=rwc&_txlock=immediate", filename) db, err := sql.Open("sqlite3", dsn) if err != nil { return nil, err } service := &SqliteService{ DB: db, } return service, nil } func (s *SqliteService) GetTx() (tx *sql.Tx, err error) { for i := 0; i < 100; i++ { tx, err = s.DB.Begin() if err == nil { return tx, nil } else { time.Sleep(10 * time.Millisecond) } } return nil, err } func (s *SqliteService) Migrate() error { migrator := common.NewSqlMigrator(s.DB, "sqlite") return migrator.Migrate() } func InitPurger(db *SqliteService) { retentionPeriod := viper.GetInt("database.retention-period") log.Info("Retention period: %d days", retentionPeriod) // Start the purge runner. go (&SqlitePurger{ db: db, period: retentionPeriod, }).Run() } func getFilename() (string, error) { basename := viper.GetString("database.sqlite.filename") // In memory database. if basename == ":memory:" { return basename, nil } // Database file has absolute filename, use as-is. if strings.HasPrefix(basename, "/") { return basename, nil } datadir := viper.GetString("data-directory") if datadir == "" { return "", errors.New("data-directory required") } // If set, and not an absolute filename, return a full path relative // to the data directory. if basename != "" { return path.Join(datadir, basename), nil } // Check for the old filename. filename := path.Join(datadir, OLD_DB_FILENAME) _, err := os.Stat(filename) if err == nil { return filename, nil } // Return the new filename. return path.Join(datadir, DB_FILENAME), nil } func InitSqlite(appContext *appcontext.AppContext) (err error) { log.Info("Configuring SQLite datastore") filename, err := getFilename() if err != nil { return err } log.Info("SQLite event store using file %s", filename) db, err := NewSqliteService(filename) if err != nil { return err } if err := db.Migrate(); err != nil { return err } if viper.GetBool("database.sqlite.disable-fsync") { log.Info("Disabling fsync") db.Exec("PRAGMA synchronous = OFF") } appContext.DataStore = NewDataStore(db) InitPurger(db) return nil }
/* Write the shortest program that will attempt to connect to open ports on a remote computer and check if they are open. (It's called a Port Scanner) Take input from command line arguments. your-port-scanner host_ip startPort endPort Assume, startPort < endPort (and endPort - startPort < 1000) Output: All the open ports between that range should space or comma seperated. */ package main import ( "fmt" "net" ) func main() { scan("127.0.0.1", 1, 65536) } func scan(host string, start, end int) error { if start > end { start, end = end, start } fmt.Println("Scanning", host) fmt.Println() fmt.Println("PORT") for port := start; port <= end; port++ { addr := fmt.Sprintf("%v:%v", host, port) conn, err := net.Dial("tcp", addr) if err != nil { continue } fmt.Println(port) conn.Close() } return nil }
package main type ListNode struct { Val int Next *ListNode } func mergeKLists(lists []*ListNode) *ListNode { var res *ListNode for i := 0; i < len(lists); i++ { res = merge(res, lists[i]) } return res } func merge(left, right *ListNode) *ListNode { dummy := new(ListNode) pre := dummy for left != nil && right != nil { if left.Val <= right.Val { pre.Next = left left = left.Next } else { pre.Next = right right = right.Next } pre = pre.Next } if left == nil { pre.Next = right } else { pre.Next = left } return dummy.Next }
// DRUNKWATER TEMPLATE(add description and prototypes) // Question Title and Description on leetcode.com // Function Declaration and Function Prototypes on leetcode.com //100. Same Tree //Given two binary trees, write a function to check if they are the same or not. //Two binary trees are considered the same if they are structurally identical and the nodes have the same value. //Example 1: //Input: 1 1 // / \ / \ // 2 3 2 3 // [1,2,3], [1,2,3] //Output: true //Example 2: //Input: 1 1 // / \ // 2 2 // [1,2], [1,null,2] //Output: false //Example 3: //Input: 1 1 // / \ / \ // 2 1 1 2 // [1,2,1], [1,1,2] //Output: false ///** // * Definition for a binary tree node. // * type TreeNode struct { // * Val int // * Left *TreeNode // * Right *TreeNode // * } // */ //func isSameTree(p *TreeNode, q *TreeNode) bool { //} // Time Is Money
package jarviscore import ( "testing" ) func TestIsValidNodeName(t *testing.T) { arrOK := []string{ "zhs007", "jarviscore", "jarvis_dt", "j123_456dt", } for _, v := range arrOK { if !IsValidNodeName(v) { t.Fatalf("IsValidNodeName(%v): got false", v) } } arrFalse := []string{ "007zhs", "", "a b c", "_aa456dt", "aa456dt_", "aa456dt ", } for _, v := range arrFalse { if IsValidNodeName(v) { t.Fatalf("IsValidNodeName(%v): got true", v) } } t.Log("success IsValidNodeName()") } func TestIsMyServAddr(t *testing.T) { type data struct { destaddr string srcaddr string ret bool } lst := []data{ data{"192.168.0.1:7788", "192.168.0.1:7788", true}, data{"192.168.0.1:7788", "127.0.0.1:7788", false}, data{"127.0.0.1:7788", "192.168.0.1:7788", true}, data{"192.168.0.1:7788", "127.0.0.1:7789", false}, data{"127.0.0.1:7789", "192.168.0.1:7788", false}, } for i := 0; i < len(lst); i++ { cr := IsMyServAddr(lst[i].destaddr, lst[i].srcaddr) if cr != lst[i].ret { t.Fatalf("TestIsMyServAddr fail %v %v", lst[i].destaddr, lst[i].srcaddr) } } t.Logf("TestIsMyServAddr OK") } func TestIsValidServAddr(t *testing.T) { type data struct { servaddr string ret bool } lst := []data{ data{"192.168.0.1:7788", true}, data{"192.168.0.1:", false}, data{":7788", false}, data{"a.b.c:7788", true}, } for i := 0; i < len(lst); i++ { cr := IsValidServAddr(lst[i].servaddr) if cr != lst[i].ret { t.Fatalf("TestIsValidServAddr fail %v", lst[i].servaddr) } } t.Logf("TestIsValidServAddr OK") } func TestIsLocalHostAddr(t *testing.T) { type data struct { servaddr string ret bool } lst := []data{ data{"192.168.0.1:7788", false}, data{"192.168.0.1:", false}, data{":7788", false}, data{"localhost:7788", true}, data{"localhost:", true}, data{"127.0.0.1:7788", true}, data{"127.0.0.1:", true}, } for i := 0; i < len(lst); i++ { cr := IsLocalHostAddr(lst[i].servaddr) if cr != lst[i].ret { t.Fatalf("TestIsLocalHostAddr fail %v", lst[i].servaddr) } } t.Logf("TestIsLocalHostAddr OK") } func TestAppendString(t *testing.T) { type data struct { params []string ret string } lst := []data{ data{[]string{"192.168.0.1", ":", "7788"}, "192.168.0.1:7788"}, data{[]string{"192.168.0.1"}, "192.168.0.1"}, data{[]string{"", "", "192.168.0.1"}, "192.168.0.1"}, data{[]string{"", "", "192.168.0.1", "", ""}, "192.168.0.1"}, data{[]string{"192.168.0.1", "", ""}, "192.168.0.1"}, } for i := 0; i < len(lst); i++ { cr := AppendString(lst[i].params...) if cr != lst[i].ret { t.Fatalf("TestAppendString(%v) fail %v", lst[i], cr) } } t.Logf("TestAppendString OK") }
package events type UserConnected struct { ClientID int32 Name string Key string }
// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package swarming import ( "errors" "net/http" "strings" "time" "github.com/luci/luci-go/client/internal/lhttp" "github.com/luci/luci-go/client/internal/retry" ) // TaskID is a unique reference to a Swarming task. type TaskID string // Swarming defines a Swarming client. type Swarming struct { host string } func (s *Swarming) getJSON(resource string, v interface{}) error { if len(resource) == 0 || resource[0] != '/' { return errors.New("resource must start with '/'") } _, err := lhttp.GetJSON(retry.Default, http.DefaultClient, s.host+resource, v) return err } // NewSwarming returns a new Swarming client. func New(host string) (*Swarming, error) { host = strings.TrimRight(host, "/") return &Swarming{host}, nil } // FetchRequest returns the TaskRequest. func (s *Swarming) FetchRequest(id TaskID) (*TaskRequest, error) { out := &TaskRequest{} err := s.getJSON("/swarming/api/v1/client/task/"+string(id)+"/request", out) return out, err } // TaskRequestProperties describes the idempotent properties of a task. type TaskRequestProperties struct { Commands [][]string `json:"commands"` Data [][]string `json:"data"` Dimensions map[string]string `json:"dimensions"` Env map[string]string `json:"env"` ExecutionTimeoutSecs int `json:"execution_timeout_secs"` Idempotent bool `json:"idempotent"` IoTimeoutSecs int `json:"io_timeout_secs"` } // TaskRequest describes a complete request. type TaskRequest struct { //"created_ts": "2014-10-24 00:00:00", //"expiration_ts": "2014-10-24 00:00:00", Name string `json:"name"` Priority int `json:"priority"` Properties TaskRequestProperties `json:"properties"` PropertiesHash string `json:"properties_hash"` Tags []string `json:"tags"` User string `json:"user"` } // TaskResult describes the results of a task. type TaskResult struct { TaskRequest TaskRequest `json:"request"` //"abandoned_ts": "2014-10-24 00:00:00", BotID string `json:"bot_id"` BotVersion string `json:"bot_version"` //"completed_ts": "2014-10-24 00:00:00", //"created_ts": "2014-10-24 00:00:00", DedupedFrom string `json:"deduped_from"` Durations []float64 `json:"durations"` ExitCodes []int `json:"exit_codes"` Failure bool `json:"failure"` ID TaskID `json:"id"` InternalFailure bool `json:"internal_failure"` //"modified_ts": "2014-10-24 00:00:00", Name string `json:"name"` PropertiesHash string `json:"properties_hash"` ServerVersions []string `json:"server_versions"` // "started_ts": "2014-10-24 00:00:00", State int `json:"state"` TryNumber int `json:"try_number"` User string `json:"user"` } // Duration returns the total duration of a task. func (s *TaskResult) Duration() (out time.Duration) { for _, d := range s.Durations { out += time.Duration(d) * time.Second } return }
package main import ( "fmt" ) func isUnique(s string) bool { if len(s) > 128 { return false } arr := [128]bool{} for _, j := range s { v := int(j) if arr[v] == true { return false } arr[v] = true } return true } func main() { s := "abced" r := isUnique(s) fmt.Print(r) }
// Copyright (c) 2016, David Url // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package main import ( "bufio" "errors" "io" "math/rand" "strings" ) // lookback specifies how many words are used for a prefix. const lookback = 2 const loopSize = 6 // Suffix represents the occurences of a following word in a markov chain. type Suffix struct { Suffix string Occurences int Probability float32 } // MarkovMap represents a markov chain with a multi word prefix as key, // and a list of suffixes as value of the map. type MarkovMap map[string][]Suffix // BuildMarkovChain reads titles separated by newlines from a given input, // and builds a markov chain, aswell as a list of normalized (no unecessary // whitespace) original titles. This list can be used to discard generated // titles which closely resemble original ones. func BuildMarkovChain(input io.Reader) (MarkovMap, []string) { markov := make(MarkovMap) originals := make([]string, 0) scanner := bufio.NewScanner(input) for scanner.Scan() { title := scanner.Text() orig := markov.addTitle(title) originals = append(originals, orig) } markov.calculateProbabilities() return markov, originals } func (m MarkovMap) addTitle(title string) string { words := strings.Fields(title) if len(words) <= lookback { // ignore titles which are too short return join(words) } for i, word := range words { prefix := join(words[max(0, i-lookback):i]) var suffixes []Suffix if existingSuffixes, ok := m[prefix]; ok { suffixes = existingSuffixes } else { suffixes = make([]Suffix, 0) } var suffix Suffix suffix.Suffix = word new := true for j, existingSuffix := range suffixes { if existingSuffix.Suffix == suffix.Suffix { new = false suffixes[j].Occurences++ break } } if new { suffix.Occurences++ suffixes = append(suffixes, suffix) m[prefix] = suffixes } } // return normalized original title return join(words) } func join(words []string) string { return strings.Join(words, " ") } func max(a, b int) int { if a > b { return a } return b } func (m MarkovMap) calculateProbabilities() { for _, suffixes := range m { var total int for _, suffix := range suffixes { total += suffix.Occurences } for i, suffix := range suffixes { suffix.Probability = float32(suffix.Occurences) / float32(total) suffixes[i] = suffix } } } func sample(suffixes []Suffix, rnd *rand.Rand) Suffix { for { i := rnd.Intn(len(suffixes)) if rnd.Float32() < suffixes[i].Probability { return suffixes[i] } } } // GenerateTitle generates a title based on a markov chain. // An error is returned if the title contains a loop of a certain length. func (m MarkovMap) GenerateTitle(rnd *rand.Rand) (string, error) { title := make([]string, 0) next := sample(m[""], rnd) for next.Suffix != "" { title = append(title, next.Suffix) candidates, ok := m[join(title[max(len(title)-lookback, 0):])] if !ok { break } next = sample(candidates, rnd) if hasLoop(title) { return join(title), errors.New("loop detected") } } return join(title), nil } func hasLoop(words []string) bool { if len(words) <= loopSize { return false } loopStr := join(words[len(words)-loopSize:]) if strings.Contains(join(words[:len(words)-loopSize]), loopStr) { return true } return false }
package common import ( "strings" ) type firstPermission struct { id string `json:"id"` descrip string `json:"descrip"` sep string `json:"sep"` } func NewFirstP(id, descrip string) *firstPermission { return &firstPermission{id, descrip, FirstSep} } func (p *firstPermission) getDes() string { return p.descrip } func (p *firstPermission) getId() string { return p.id } func (p *firstPermission) setDes(descrip string) { p.descrip = descrip } func (p *firstPermission) match(a Permission) bool { if p.id == a.getId() || p.descrip == a.getDes() { return true } q, ok := a.(*firstPermission) if !ok { return false } players := strings.Split(p.descrip, p.sep) qlayers := strings.Split(q.descrip, q.sep) // 可以包含 if len(players) > len(qlayers) { return false } for k, pv := range players { if pv != qlayers[k] { return false } } return true }
package main import ( "fmt" ) func main(){ mySlice := []int {10,11,12,13,14,15} mySliceStr := []string {"hendrawan","sueng","maneh"} fmt.Println(mySlice[0]) for i, v := range mySlice { fmt.Println(i, v) } mySliceStr = append(mySliceStr, "ratih") //ADD DATA for _,v := range mySliceStr{ fmt.Println(v) } }
/* Copyright 2021 The KubeVela 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 env import ( "context" "encoding/json" "fmt" "os" "path/filepath" "github.com/AlecAivazis/survey/v2" "github.com/kubevela/pkg/util/singleton" "github.com/pkg/errors" v1 "k8s.io/api/core/v1" apierrors "k8s.io/apimachinery/pkg/api/errors" "k8s.io/apimachinery/pkg/labels" "sigs.k8s.io/controller-runtime/pkg/client" "github.com/oam-dev/kubevela/apis/core.oam.dev/v1beta1" "github.com/oam-dev/kubevela/apis/types" "github.com/oam-dev/kubevela/pkg/oam" "github.com/oam-dev/kubevela/pkg/oam/util" "github.com/oam-dev/kubevela/pkg/utils" "github.com/oam-dev/kubevela/pkg/utils/common" "github.com/oam-dev/kubevela/pkg/utils/system" ) const ( // DefaultEnvNamespace is namespace of default env DefaultEnvNamespace = "default" ) // following functions are CRUD of env // CreateEnv will create e env. // Because Env equals to namespace, one env should not be updated func CreateEnv(envArgs *types.EnvMeta) (err error) { c := singleton.KubeClient.Get() if envArgs.Namespace == "" { err = common.AskToChooseOneNamespace(c, envArgs) if err != nil { return err } } if envArgs.Name == "" { prompt := &survey.Input{ Message: "Please name your new env:", } err = survey.AskOne(prompt, &envArgs.Name) if err != nil { return err } } ctx := context.TODO() var nsList v1.NamespaceList err = c.List(ctx, &nsList, client.MatchingLabels{oam.LabelControlPlaneNamespaceUsage: oam.VelaNamespaceUsageEnv, oam.LabelNamespaceOfEnvName: envArgs.Name}) if err != nil { return err } if len(nsList.Items) > 0 { return fmt.Errorf("env name %s already exists", envArgs.Name) } namespace, err := utils.GetNamespace(ctx, c, envArgs.Namespace) if err != nil && !apierrors.IsNotFound(err) { return err } if namespace != nil { existedEnv := namespace.GetLabels()[oam.LabelNamespaceOfEnvName] if existedEnv != "" && existedEnv != envArgs.Name { return fmt.Errorf("the namespace %s was already assigned to env %s", envArgs.Namespace, existedEnv) } } err = utils.CreateOrUpdateNamespace(ctx, c, envArgs.Namespace, utils.MergeOverrideLabels(map[string]string{ oam.LabelControlPlaneNamespaceUsage: oam.VelaNamespaceUsageEnv, }), utils.MergeNoConflictLabels(map[string]string{ oam.LabelNamespaceOfEnvName: envArgs.Name, })) if err != nil { return err } return nil } // GetEnvByName will get env info by name func GetEnvByName(name string) (*types.EnvMeta, error) { if name == DefaultEnvNamespace { return &types.EnvMeta{Name: DefaultEnvNamespace, Namespace: DefaultEnvNamespace}, nil } namespace, err := getEnvNamespaceByName(name) if err != nil { return nil, err } return &types.EnvMeta{ Name: name, Namespace: namespace.Name, }, nil } // ListEnvs will list all envs // if envName specified, return list that only contains one env func ListEnvs(envName string) ([]*types.EnvMeta, error) { var envList []*types.EnvMeta if envName != "" { env, err := GetEnvByName(envName) if err != nil { if os.IsNotExist(err) { err = fmt.Errorf("env %s not exist", envName) } return envList, err } envList = append(envList, env) return envList, err } clt := singleton.KubeClient.Get() ctx := context.Background() var nsList v1.NamespaceList err := clt.List(ctx, &nsList, client.MatchingLabels{oam.LabelControlPlaneNamespaceUsage: oam.VelaNamespaceUsageEnv}) if err != nil { return nil, err } for _, it := range nsList.Items { envList = append(envList, &types.EnvMeta{ Name: it.Labels[oam.LabelNamespaceOfEnvName], Namespace: it.Name, }) } if len(envList) < 1 { return envList, nil } cur, err := GetCurrentEnv() if err != nil { _ = SetCurrentEnv(envList[0]) envList[0].Current = "*" // we set a current env if not exist // nolint:nilerr return envList, nil } for i := range envList { if envList[i].Name == cur.Name { envList[i].Current = "*" } } return envList, nil } // DeleteEnv will delete env and its application func DeleteEnv(envName string) (string, error) { var message string var err error envMeta, err := GetEnvByName(envName) if err != nil { return "", err } clt := singleton.KubeClient.Get() var appList v1beta1.ApplicationList err = clt.List(context.TODO(), &appList, client.InNamespace(envMeta.Namespace)) if err != nil { return "", err } if len(appList.Items) > 0 { err = fmt.Errorf("you can't delete this environment(namespace=%s) that has %d application inside", envMeta.Namespace, len(appList.Items)) return message, err } // reset the labels err = utils.UpdateNamespace(context.TODO(), clt, envMeta.Namespace, utils.MergeOverrideLabels(map[string]string{ oam.LabelNamespaceOfEnvName: "", oam.LabelControlPlaneNamespaceUsage: "", })) if err != nil { return "", err } message = "env " + envName + " deleted" return message, err } // GetCurrentEnv will get current env func GetCurrentEnv() (*types.EnvMeta, error) { currentEnvPath, err := system.GetCurrentEnvPath() if err != nil { return nil, err } data, err := os.ReadFile(filepath.Clean(currentEnvPath)) if err != nil { return nil, err } var envMeta types.EnvMeta err = json.Unmarshal(data, &envMeta) if err != nil { em, err := GetEnvByName(string(data)) if err != nil { return nil, err } _ = SetCurrentEnv(em) return em, nil } return &envMeta, nil } // SetCurrentEnv will set the current env to the specified one func SetCurrentEnv(meta *types.EnvMeta) error { currentEnvPath, err := system.GetCurrentEnvPath() if err != nil { return err } data, err := json.Marshal(meta) if err != nil { return err } //nolint:gosec if err = os.WriteFile(currentEnvPath, data, 0644); err != nil { return err } return nil } // getEnvNamespaceByName get v1.Namespace object by env name func getEnvNamespaceByName(name string) (*v1.Namespace, error) { ctx := context.Background() var nsList v1.NamespaceList err := singleton.KubeClient.Get().List(ctx, &nsList, client.MatchingLabels{oam.LabelNamespaceOfEnvName: name}) if err != nil { return nil, err } if len(nsList.Items) < 1 { return nil, errors.Errorf("Env %s not exist", name) } return &nsList.Items[0], nil } // SetEnvLabels set labels for namespace func SetEnvLabels(envArgs *types.EnvMeta) error { namespace, err := getEnvNamespaceByName(envArgs.Name) if err != nil { return err } labelsMap, err := labels.ConvertSelectorToLabelsMap(envArgs.Labels) if err != nil { return err } namespace.Labels = util.MergeMapOverrideWithDst(namespace.GetLabels(), labelsMap) err = singleton.KubeClient.Get().Update(context.Background(), namespace) if err != nil { return errors.Wrapf(err, "fail to set env labelsMap") } return nil }
package main import ( "fmt" "math" "sort" ) func main() { // //fmt.Println(successfulPairs([]int{ // 15, 8, 19, //}, []int{ // 38, 36, 23, //}, 328)) // //fmt.Println(successfulPairs([]int{ // 5, 1, 3, //}, []int{ // 1, 2, 3, 4, 5, //}, 7)) fmt.Println(successfulPairs([]int{ 4, 1, 3, }, []int{ 1, 2, 3, 4, 5, }, 8)) } func successfulPairs(spells []int, potions []int, success int64) []int { sort.Ints(potions) ln := len(potions) var ans []int for _, v := range spells { idx := sort.SearchInts(potions, int(math.Ceil(float64(success)/float64(v)))) // 避免对数组中每个数进行乘法 ans = append(ans, ln-idx) } return ans } func successfulPairs2(spells []int, potions []int, success int64) []int { sort.Ints(potions) suc := int(success) ln := len(potions) newPotions := make([]int, len(potions)) type item struct { idx int val int } spellList := make([]item, len(spells)) for i, v := range spells { spellList[i] = item{ idx: i, val: v, } } sort.Slice(spellList, func(i, j int) bool { return spellList[i].val < spellList[j].val }) ans := make([]int, len(spells)) idx := 0 for i, v := range spellList { idx = i for i, p := range potions { newPotions[i] = v.val * p } idx := sort.SearchInts(newPotions, suc) ans[v.idx] = ln - idx if ans[v.idx] == ln { break } } if spellList[idx].idx == ln { for i := idx + 1; i < len(spellList); i++ { ans[spellList[i].idx] = ln } } return ans }
package main import ( "flag" "fmt" "os/exec" "regexp" "strconv" "strings" "time" ) type CmusStatus struct { status string artist string album string title string duration int position int } var api_key *string var api_secret *string var session_key *string var token *string var queue CmusStatus func cmus_remote_status(ch chan CmusStatus) { output, err := exec.Command("cmus-remote", "-Q").Output() if err != nil { fmt.Println("Exec: failed to run command", "cmus-remote") return } var status CmusStatus items := strings.Split(string(output), "\n") for _, v := range items { if m, _ := regexp.MatchString("status", v); m == true { re, _ := regexp.Compile("^status ") status.status = string(re.ReplaceAll([]byte(v), []byte(""))) } else if m, _ := regexp.MatchString("tag artist", v); m == true { re, _ := regexp.Compile("^tag artist ") status.artist = string(re.ReplaceAll([]byte(v), []byte(""))) } else if m, _ := regexp.MatchString("tag album", v); m == true { re, _ := regexp.Compile("^tag album ") status.album = string(re.ReplaceAll([]byte(v), []byte(""))) } else if m, _ := regexp.MatchString("tag title", v); m == true { re, _ := regexp.Compile("^tag title ") status.title = string(re.ReplaceAll([]byte(v), []byte(""))) } else if m, _ := regexp.MatchString("duration", v); m == true { re, _ := regexp.Compile("^duration ") status.duration, _ = strconv.Atoi(string(re.ReplaceAll([]byte(v), []byte("")))) } else if m, _ := regexp.MatchString("position", v); m == true { re, _ := regexp.Compile("^position ") status.position, _ = strconv.Atoi(string(re.ReplaceAll([]byte(v), []byte("")))) } } ch <- status } func main() { api_key = flag.String("api_key", "", "API Key") api_secret = flag.String("api_secret", "", "API Secret") session_key = flag.String("session", "", "Session") token = flag.String("token", "", "Token") flag.Parse() ch := make(chan CmusStatus) for { go cmus_remote_status(ch) time.Sleep(time.Duration(1) * time.Second) select { case s := <-ch: if s.status == "playing" && queue.artist != s.artist && queue.album != s.album && queue.title != s.title && s.duration > 20 && (float64(s.position)/float64(s.duration) > 0.3) { fmt.Println("Scrobbling:", s.artist, " - ", s.album, " - ", s.title, " (", s.position, "/", s.duration, ")") c := exec.Command("goscrobble", "-artist", s.artist, "-album", s.album, "-title", s.title, "-api_key", *api_key, "-api_secret", *api_secret, "-session", *session_key, "-token", *token) err := c.Start() if err != nil { fmt.Println("Exec: failed to run command goscrobble") } c.Wait() queue = s } } } }
package githubfetch import ( "archive/tar" "compress/gzip" "context" "fmt" "io" "io/ioutil" "log" "net/http" "net/url" "path" "strings" "time" "github.com/docker/docker/builder/dockerignore" "github.com/docker/docker/pkg/fileutils" "github.com/google/go-github/github" "golang.org/x/oauth2" "gopkg.in/DataDog/dd-trace-go.v1/ddtrace/tracer" ) const ( githubDownloadTimeoutSecs = 300 dockerIgnorePath = ".dockerignore" ) // CodeFetcher represents an object capable of fetching code and returning a // gzip-compressed tarball io.Reader type CodeFetcher interface { GetCommitSHA(tracer.Span, string, string, string) (string, error) Get(tracer.Span, string, string, string) (io.Reader, error) } // GitHubFetcher represents a github data fetcher type GitHubFetcher struct { c *github.Client } // NewGitHubFetcher returns a new github fetcher func NewGitHubFetcher(token string) *GitHubFetcher { ts := oauth2.StaticTokenSource(&oauth2.Token{AccessToken: token}) tc := oauth2.NewClient(oauth2.NoContext, ts) gf := &GitHubFetcher{ c: github.NewClient(tc), } return gf } // GetCommitSHA returns the commit SHA for a reference func (gf *GitHubFetcher) GetCommitSHA(parentSpan tracer.Span, owner string, repo string, ref string) (csha string, err error) { span := tracer.StartSpan("github_fetcher.get_commit_sha", tracer.ChildOf(parentSpan.Context())) defer func() { span.Finish(tracer.WithError(err)) }() ctx, cf := context.WithTimeout(context.Background(), githubDownloadTimeoutSecs*time.Second) defer cf() csha, _, err = gf.c.Repositories.GetCommitSHA1(ctx, owner, repo, ref, "") return csha, err } // Get fetches contents of GitHub repo and returns the processed contents as // an in-memory io.Reader. func (gf *GitHubFetcher) Get(parentSpan tracer.Span, owner string, repo string, ref string) (tarball io.Reader, err error) { span := tracer.StartSpan("github_fetcher.get", tracer.ChildOf(parentSpan.Context())) defer func() { span.Finish(tracer.WithError(err)) }() opt := &github.RepositoryContentGetOptions{ Ref: ref, } ctx, cf := context.WithTimeout(context.Background(), githubDownloadTimeoutSecs*time.Second) defer cf() excludes, err := gf.parseDockerIgnoreIfExists(ctx, owner, repo, opt) if err != nil { return nil, fmt.Errorf("error parsing %v file: %v", dockerIgnorePath, err) } url, resp, err := gf.c.Repositories.GetArchiveLink(ctx, owner, repo, github.Tarball, opt) if err != nil { return nil, fmt.Errorf("error getting archive link: %v", err) } if resp.StatusCode > 399 { return nil, fmt.Errorf("error status when getting archive link: %v", resp.Status) } if url == nil { return nil, fmt.Errorf("url is nil") } return gf.getArchive(url, excludes) } // parseDockerIgnoreIfExists will parse the docker ignore file if it exists in order to determine which patterns should be excluded. // The excluded patterns are intended to be used with a pattern matcher. func (gf *GitHubFetcher) parseDockerIgnoreIfExists(ctx context.Context, owner, repo string, opt *github.RepositoryContentGetOptions) ([]string, error) { fc, _, resp, err := gf.c.Repositories.GetContents(ctx, owner, repo, dockerIgnorePath, opt) if err != nil { if resp.StatusCode == 404 { // Not all repos will have dockerignore, just move along return []string{}, nil } return nil, fmt.Errorf("error getting .dockerignore: %v", err) } content, err := fc.GetContent() if err != nil { return nil, fmt.Errorf("error getting content from %v, %v", dockerIgnorePath, err) } excludes, err := dockerignore.ReadAll(strings.NewReader(content)) if err != nil { return nil, fmt.Errorf("error parsing %v, %v", dockerIgnorePath, err) } return excludes, nil } func (gf *GitHubFetcher) getArchive(archiveURL *url.URL, excludes []string) (io.Reader, error) { hc := http.Client{ Timeout: githubDownloadTimeoutSecs * time.Second, } hr, err := http.NewRequest("GET", archiveURL.String(), nil) if err != nil { return nil, fmt.Errorf("error creating http request: %v", err) } resp, err := hc.Do(hr) if err != nil { return nil, fmt.Errorf("error performing archive http request: %v", err) } if resp == nil { return nil, fmt.Errorf("error getting archive: response is nil") } if resp.StatusCode > 299 { return nil, fmt.Errorf("archive http request failed: %v", resp.StatusCode) } return newTarPrefixStripper(resp.Body, excludes), nil } func (gf *GitHubFetcher) debugWriteTar(contents []byte) { f, err := ioutil.TempFile("", "output-tar") if err != nil { log.Printf("debug: error creating TempFile: %v", err) } defer f.Close() log.Printf("debug: saving tar output to %v", f.Name()) _, err = f.Write(contents) if err != nil { log.Printf("debug: error writing tar output: %v", err) } } // tarPrefixStripper removes a random path that Github prefixes its // archives with. type tarPrefixStripper struct { tarball io.ReadCloser pipeReader *io.PipeReader pipeWriter *io.PipeWriter strippingStarted bool excludes []string } func newTarPrefixStripper(tarball io.ReadCloser, excludes []string) io.Reader { reader, writer := io.Pipe() return &tarPrefixStripper{ tarball: tarball, pipeReader: reader, pipeWriter: writer, excludes: excludes, } } func (t *tarPrefixStripper) Read(p []byte) (n int, err error) { if !t.strippingStarted { go t.startStrippingPipe() t.strippingStarted = true } return t.pipeReader.Read(p) } func (t *tarPrefixStripper) shouldSkipDockerIgnoredFile(h *tar.Header) (bool, error) { match, err := fileutils.Matches(h.Name, t.excludes) if err != nil { return false, fmt.Errorf("error matching file name to docker ignored files: %v", h.Name) } return match, nil } func (t *tarPrefixStripper) processHeader(h *tar.Header) (bool, error) { // metadata file, ignore if h.Name == "pax_global_header" { return true, nil } if path.IsAbs(h.Name) { return true, fmt.Errorf("archive contains absolute path: %v", h.Name) } // top-level directory entry spath := strings.Split(h.Name, "/") if len(spath) == 2 && spath[1] == "" { return true, nil } h.Name = strings.Join(spath[1:len(spath)], "/") return t.shouldSkipDockerIgnoredFile(h) } func (t *tarPrefixStripper) startStrippingPipe() { gzr, err := gzip.NewReader(t.tarball) if err != nil { t.pipeWriter.CloseWithError(err) return } tarball := tar.NewReader(gzr) outTarball := tar.NewWriter(t.pipeWriter) closeFunc := func(e error) { outTarball.Close() t.pipeWriter.CloseWithError(e) t.tarball.Close() } for { header, err := tarball.Next() if err == io.EOF { closeFunc(nil) return } if err != nil { closeFunc(err) return } skip, err := t.processHeader(header) if err != nil { closeFunc(err) return } if skip { continue } if err := outTarball.WriteHeader(header); err != nil { closeFunc(err) return } if _, err := io.Copy(outTarball, tarball); err != nil { closeFunc(err) return } if err := outTarball.Flush(); err != nil { closeFunc(err) return } } }
package controller import ( "bytes" "encoding/json" "fmt" "io" "io/ioutil" "net/http" "net/http/httptest" "net/url" "strings" "testing" "text/template" "github.com/ksw95/GoIndustrialProject/Client/session" "github.com/labstack/echo" "github.com/stretchr/testify/assert" ) var ( // GetDoFunc fetches the mock client's `Do` func Client HTTPClient ) func (t *Template) Render(w io.Writer, name string, data interface{}, c echo.Context) error { return t.templates.ExecuteTemplate(w, name, data) } type ( // Custom type that allows setting the func that our Mock Do func will run instead MockDoFunc func(req *http.Request) (*http.Response, error) // MockClient is the mock client MockClient struct { MockDo MockDoFunc } Template struct { templates *template.Template } HTTPClient interface { Do(req *http.Request) (*http.Response, error) } ) // Overriding what the Do function should "do" in our MockClient func (m *MockClient) Do(req *http.Request) (*http.Response, error) { return m.MockDo(req) } // provides the wrapper required by handlers func getDependency(address string, encode io.Reader) (*session.Session, *httptest.ResponseRecorder, *http.Request, *session.SessionStruct, *echo.Echo, echo.Context) { mapSession := make(map[string]*session.SessionStruct) sessionMgr := &session.Session{ MapSession: &mapSession, ApiKey: "key", Client: &http.Client{}, } //mock form values to function post rec := httptest.NewRecorder() req := httptest.NewRequest(http.MethodPost, address, encode) req.Header.Set(echo.HeaderContentType, echo.MIMEApplicationForm) e := echo.New() c := e.NewContext(req, rec) sessionStruct, uuid := sessionMgr.NewEmptySession(c) req.AddCookie(&http.Cookie{ Name: "foodiepandaCookie", Value: uuid, MaxAge: 300, }) c = e.NewContext(req, rec) tem := &Template{ templates: template.Must(template.ParseGlob("templates/*.gohtml")), } e.Renderer = tem return sessionMgr, rec, req, sessionStruct, e, c } func TestIndex_GET(t *testing.T) { client := &MockClient{ MockDo: func(req *http.Request) (*http.Response, error) { return &http.Response{ StatusCode: 202, }, nil }, } // get dependencies sessionMgr, rec, _, _, _, c := getDependency("/", nil) sessionMgr.Client = client // fmt.Println(rec.Body) if assert.NoError(t, Index_GET(c, sessionMgr)) { assert.Equal(t, http.StatusOK, rec.Code) } } func TestIndex_POST(t *testing.T) { client := &MockClient{ MockDo: func(req *http.Request) (*http.Response, error) { return &http.Response{ StatusCode: 202, }, nil }, } //insert form value f := make(url.Values) f.Set("cat", "Food") f.Set("query", "item") // get dependencies sessionMgr, rec, _, _, _, c := getDependency("/", strings.NewReader(f.Encode())) sessionMgr.Client = client // fmt.Println(rec.Body) if assert.NoError(t, Index_POST(c, sessionMgr)) { assert.Equal(t, http.StatusSeeOther, rec.Code) fmt.Println(c.Request().URL) } } func TestSearchPage_GET_Food(t *testing.T) { // create dependencies // mock client Do for handler // build our response JSON // create a new reader with that JSON client := &MockClient{ MockDo: func(req *http.Request) (*http.Response, error) { querySearch := req.URL.Query().Get("search") queryType := req.URL.Query().Get("type") assert.Equal(t, "item", querySearch) assert.Equal(t, "Food", queryType) dataResponse := []interface{}{getDummyData("Food", 1), getDummyData("Food", 2), getDummyData("Food", 3), } searchResult := struct { Msg string ResBool string Data []interface{} }{ "ok", "true", dataResponse, } jsonResponse, _ := json.Marshal(searchResult) r := ioutil.NopCloser(bytes.NewReader([]byte(jsonResponse))) return &http.Response{ StatusCode: 202, Body: r, }, nil }, } //insert form value q := make(url.Values) q.Set("cat", "Food") q.Set("query", "item") sessionMgr, rec, _, _, _, c := getDependency("/search?"+q.Encode(), nil) sessionMgr.Client = client // fmt.Println(rec.Body) if assert.NoError(t, SearchPage_GET(c, sessionMgr)) { assert.Equal(t, http.StatusOK, rec.Code) fmt.Println(c.Request().URL) } } func TestSearchPage_GET_Restaurant(t *testing.T) { // create dependencies // mock client Do for handler // build our response JSON // create a new reader with that JSON client := &MockClient{ MockDo: func(req *http.Request) (*http.Response, error) { querySearch := req.URL.Query().Get("search") queryType := req.URL.Query().Get("type") assert.Equal(t, "item", querySearch) assert.Equal(t, "Restaurant", queryType) dataResponse := []interface{}{getDummyData("Restaurant", 1), getDummyData("Restaurant", 2), getDummyData("Restaurant", 3), } searchResult := struct { Msg string ResBool string Data []interface{} }{ "ok", "true", dataResponse, } jsonResponse, _ := json.Marshal(searchResult) r := ioutil.NopCloser(bytes.NewReader([]byte(jsonResponse))) return &http.Response{ StatusCode: 202, Body: r, }, nil }, } //insert form value q := make(url.Values) q.Set("cat", "Restaurant") q.Set("query", "item") sessionMgr, rec, _, _, _, c := getDependency("/search?"+q.Encode(), nil) sessionMgr.Client = client // fmt.Println(rec.Body) if assert.NoError(t, SearchPage_GET(c, sessionMgr)) { assert.Equal(t, http.StatusOK, rec.Code) fmt.Println(c.Request().URL) } } func getDummyData(db string, id int) (newMap map[string]interface{}) { newMap = make(map[string]interface{}) switch db { case "UserCond": newMap["Username"] = id newMap["LastLogin"] = "20-7-2021" newMap["MaxCalories"] = 2500 newMap["Diabetic"] = "Not Diabetic" newMap["Halal"] = "Not Halal" newMap["Vegan"] = "Not Vegan" case "Food": newMap["ID"] = id newMap["Name"] = "Name" newMap["ShopID"] = 1 newMap["Calories"] = 800 newMap["Description"] = "Description" newMap["Sugary"] = "Not Sugary" newMap["Halal"] = "Not Halal" newMap["Vegan"] = "Not Vegan" case "History": newMap["ID"] = id newMap["Username"] = "username" newMap["FoodPurchase"] = "20-7-2021" newMap["Price"] = 3.7 newMap["DeliveryMode"] = "Walking" newMap["Distance"] = 2.2 newMap["CaloriesBurned"] = 120 case "Account": newMap["Username"] = "Username" newMap["Password"] = "Password" } return }
package main import "errors" var errNotDir = errors.New("Not a directory") var errNotGoFile = errors.New("Not a go file") var errNotIsGoTestFile = errors.New("Is a go test file") var errNotIsNotGoTestFile = errors.New("Is not a go test file") var errNotImplemented = errors.New("Not implemented") var errMalFormedFunctionDef = errors.New("Malformed function definition string array") // Ignoreable ... type Ignoreable interface { Ignore() bool } // IgnoreableError ... type IgnoreableError struct { CanIgnore bool Message string } // Error ... func (e IgnoreableError) Error() string { return e.Message } // Ignore ... func (e IgnoreableError) Ignore() bool { return e.CanIgnore }
package KMP import ( "testing" "fmt" ) func TestCalNext(t *testing.T) { s := "ababaca" fmt.Println(calNext(s)) s = "abababa" fmt.Println(calNext(s)) } func TestGetNext(t *testing.T) { s := "ababaca" fmt.Println(getNext(s)) s = "abababa" fmt.Println(getNext(s)) } func TestKMP(t *testing.T) { src, desc := "测abcdefg", "bcde" startIndex := KMP(src, desc) startIndexB := KMP_BASIC(src, desc) if 4 != startIndex || startIndex != startIndexB { t.Error("KMP error: result: ", startIndex, startIndexB) } }
// Copyright 2018 The OpenSDS 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 l package oceanstor import "time" // default value for driver const ( defaultConfPath = "/etc/opensds/driver/huawei_oceanstor_block.yaml" defaultAZ = "default" ) // metadata keys const ( KLunId = "huaweiLunId" KSnapId = "huaweiSnapId" KPairId = "huaweiReplicaPairId" // replication pair ) // name prefix const ( PrefixMappingView = "OpenSDSMappingView" PrefixLunGroup = "OpenSDSLunGroup" PrefixHostGroup = "OpenSDSHostGroup" ) // object type id const ( ObjectTypeLun = "11" ObjectTypeHost = "21" ObjectTypeSnapshot = "27" ObjectTypeHostGroup = "14" ObjectTypeController = "207" ObjectTypePool = "216" ObjectTypeLunCopy = 219 // not string, should be integer ObjectTypeIscsiInitiator = "222" ObjectTypeFcInitiator = "223" ObjectTypeMappingView = "245" ObjectTypeLunGroup = "256" ObjectTypeReplicationPair = "263" ) // Error Code const ( ErrorConnectToServer = -403 ErrorUnauthorizedToServer = -401 ErrorObjectUnavailable = 1077948996 ErrorHostGroupNotExist = 1077937500 ErrorObjectNameAlreadyExist = 1077948993 ErrorHostAlreadyInHostGroup = 1077937501 ErrorObjectIDNotUnique = 1077948997 ErrorHostGroupAlreadyInMappingView = 1073804556 ErrorLunGroupAlreadyInMappingView = 1073804560 ErrorLunNotExist = 1077936859 ) // misc const ( ThickLunType = 0 ThinLunType = 1 MaxNameLength = 31 MaxDescriptionLength = 170 PortNumPerContr = 2 PwdExpired = 3 PwdReset = 4 ) // lun copy const ( LunCopySpeedLow = "1" LunCopySpeedMedium = "2" LunCopySpeedHigh = "3" LunCopySpeedHighest = "4" ) var LunCopySpeedTypes = []string{LunCopySpeedLow, LunCopySpeedMedium, LunCopySpeedHigh, LunCopySpeedHighest} const ( LunReadyWaitInterval = 2 * time.Second LunReadyWaitTimeout = 20 * time.Second LunCopyWaitInterval = 2 * time.Second LunCopyWaitTimeout = 200 * time.Second ) // Object status key id const ( StatusHealth = "1" StatusQosActive = "2" StatusRunning = "10" StatusVolumeReady = "27" StatusLunCoping = "39" StatusLunCopyStop = "38" StatusLunCopyQueue = "37" StatusLunCopyNotStart = "36" StatusLunCopyReady = "40" StatusActive = "43" StatusQosInactive = "45" ) // Array type const ( ArrayTypeReplication = "1" ArrayTypeHeterogeneity = "2" ArrayTypeUnknown = "3" ) // Health status const ( HealthStatusNormal = "1" HealthStatusFault = "2" HealthStatusPreFail = "3" HealthStatusPartiallyBroken = "4" HealthStatusDegraded = "5" HealthStatusBadSectorsFound = "6" HealthStatusBitErrorsFound = "7" HealthStatusConsistent = "8" HealthStatusInconsistent = "9" HealthStatusBusy = "10" HealthStatusNoInput = "11" HealthStatusLowBattery = "12" HealthStatusSingleLinkFault = "13" HealthStatusInvalid = "14" HealthStatusWriteProtect = "15" ) // Running status const ( RunningStatusNormal = "1" RunningStatusLinkUp = "10" RunningStatusLinkDown = "11" RunningStatusOnline = "27" RunningStatusDisabled = "31" RunningStatusInitialSync = "21" RunningStatusSync = "23" RunningStatusSynced = "24" RunningStatusSplit = "26" RunningStatusInterrupted = "34" RunningStatusInvalid = "35" RunningStatusConnecting = "101" ) const ( DefaultReplicaWaitInterval = 1 * time.Second DefaultReplicaWaitTimeout = 20 * time.Second ReplicaSyncMode = "1" ReplicaAsyncMode = "2" ReplicaSpeed = "2" ReplicaPeriod = "3600" ReplicaSecondRo = "2" ReplicaSecondRw = "3" ReplicaRunningStatusKey = "RUNNINGSTATUS" ReplicaHealthStatusKey = "HEALTHSTATUS" ReplicaHealthStatusNormal = "1" ReplicaLocalDataStatusKey = "PRIRESDATASTATUS" ReplicaRemoteDataStatusKey = "SECRESDATASTATUS" ReplicaDataSyncKey = "ISDATASYNC" ReplicaDataStatusSynced = "1" ReplicaDataStatusComplete = "2" ReplicaDataStatusIncomplete = "3" ) // performance key ids const ( PerfUtilizationPercent = "18" // usage ratioPerf PerfBandwidth = "21" // mbs PerfIOPS = "22" // tps PerfServiceTime = "29" // excluding queue time(ms) PerfCpuUsage = "68" // % PerfCacheHitRatio = "303" // % PerfLatency = "370" // ms )
// Copyright (c) 2016, Ben Morgan. All rights reserved. // Use of this source code is governed by an MIT license // that can be found in the LICENSE file. package stat import ( "math" "testing" "github.com/stretchr/testify/assert" ) func TestRunSeries(z *testing.T) { assert := assert.New(z) var assertFloat = func(a, b float64) { if math.IsNaN(a) && math.IsNaN(b) { return // ok } assert.Equal(a, b) } tests := []Series{ {1, 2, 3, 4, 5}, {0.38809179, 0.94113008, 0.15350705, 0.03311646, 0.68168087, 0.21719990}, {0.32123922, 0.57085251, 0.53576882, 0.38965630, 0.27487263, 0.90783122}, {0, 0, 0, 0, 0}, {-1, -2, -3}, {}, } for _, t := range tests { var r Run for _, f := range t { r.Add(f) } assertFloat(t.Min(), r.Min()) assertFloat(t.Max(), r.Max()) assertFloat(t.Mean(), r.Mean()) assertFloat(t.Var(), r.Var()) assertFloat(t.Std(), r.Std()) assertFloat(t.VarP(), r.VarP()) assertFloat(t.StdP(), r.StdP()) } }
package dependencies import ( "sync" "testing" "github.com/Juniper/contrail/pkg/models" "github.com/stretchr/testify/assert" ) func TestReturnsRefs(t *testing.T) { ObjsCache := make(map[string]map[string]interface{}) ObjsCache["virtual_network"] = make(map[string]interface{}) Vn1 := models.VirtualNetwork{} Vn1.UUID = "Virtual-Network-1" ObjsCache["virtual_network"][Vn1.UUID] = &Vn1 Vn2 := models.VirtualNetwork{} Vn2.UUID = "Virtual-Network-2" ObjsCache["virtual_network"][Vn2.UUID] = &Vn2 ObjsCache["NetworkPolicy"] = make(map[string]interface{}) Np1 := models.NetworkPolicy{} Np1.UUID = "Network-policy-1" ObjsCache["NetworkPolicy"][Np1.UUID] = &Np1 Np2 := models.NetworkPolicy{} Np2.UUID = "Network-policy-2" ObjsCache["NetworkPolicy"][Np2.UUID] = &Np2 Np1Ref := models.VirtualNetworkNetworkPolicyRef{} Np1Ref.UUID = Np1.UUID Np1Ref.To = []string{"default-domain", "default-project", "Network-Policy-1"} Vn1.NetworkPolicyRefs = append(Vn1.NetworkPolicyRefs, &Np1Ref) Np2Ref := models.VirtualNetworkNetworkPolicyRef{} Np2Ref.UUID = Np2.UUID Np2Ref.To = []string{"default-domain", "default-project", "Network-Policy-2"} Vn1.NetworkPolicyRefs = append(Vn1.NetworkPolicyRefs, &Np2Ref) Vn2.NetworkPolicyRefs = append(Vn2.NetworkPolicyRefs, &Np2Ref) Np1.VirtualNetworkBackRefs = append(Np1.VirtualNetworkBackRefs, &Vn1) Np2.VirtualNetworkBackRefs = append(Np1.VirtualNetworkBackRefs, &Vn1) Np2.VirtualNetworkBackRefs = append(Np1.VirtualNetworkBackRefs, &Vn2) d := NewDependencyProcessor(ObjsCache) d.Evaluate(Vn1, "VirtualNetwork", "Self") resources := d.GetResources() networks := mustLoad(t, resources, "VirtualNetwork") mustLoad(t, networks, Vn1.UUID) mustLoad(t, networks, Vn2.UUID) policies := mustLoad(t, resources, "NetworkPolicy") mustLoad(t, policies, Np1.UUID) mustLoad(t, policies, Np2.UUID) } func TestReturnsSelf(t *testing.T) { ObjsCache := make(map[string]map[string]interface{}) ObjsCache["virtual_network"] = make(map[string]interface{}) Vn1 := models.VirtualNetwork{ UUID: "Virtual-Network-1", } ObjsCache["virtual_network"][Vn1.UUID] = &Vn1 d := NewDependencyProcessor(ObjsCache) d.Evaluate(Vn1, "VirtualNetwork", "Self") resources := d.GetResources() networks := mustLoad(t, resources, "VirtualNetwork") mustLoad(t, networks, Vn1.UUID) } func mustLoad(t *testing.T, rawSyncMap interface{}, key string) interface{} { syncMap, ok := rawSyncMap.(*sync.Map) assert.Truef(t, ok, "%v should be a sync.Map", rawSyncMap) value, ok := syncMap.Load(key) assert.Truef(t, ok, "The map should have a '%s' key", key) return value }
package main import "fmt" var quit chan int func foo(id int) { fmt.Println(id) quit <- id } func main() { count := 100 // quit = make(chan int) quit = make(chan int, 1000) for i := 0; i < count; i++ { go foo(i) } for i := 0; i < count; i ++ { fmt.Printf(">>> %d", <- quit) } }
package camt import ( "encoding/xml" "github.com/thought-machine/finance-messaging/iso20022" ) type Document03000104 struct { XMLName xml.Name `xml:"urn:iso:std:iso:20022:tech:xsd:camt.030.001.04 Document"` Message *NotificationOfCaseAssignmentV04 `xml:"NtfctnOfCaseAssgnmt"` } func (d *Document03000104) AddMessage() *NotificationOfCaseAssignmentV04 { d.Message = new(NotificationOfCaseAssignmentV04) return d.Message } // Scope // The Notification Of Case Assignment message is sent by a case assignee to a case creator/case assigner. // This message is used to inform the case assigner that: // - the assignee is reassigning the case to the next agent in the transaction processing chain for further action // - the assignee will work on the case himself, without re-assigning it to another party, and therefore indicating that the re-assignment has reached its end-point // Usage // The Notification Of Case Assignment message is used to notify the case creator or case assigner of further action undertaken by the case assignee in a: // - request to cancel payment case // - request to modify payment case // - unable to apply case // - claim non receipt case // The Notification Of Case Assignment message // - covers one and only one case at a time. If the case assignee needs to inform a case creator or case assigner about several cases, then multiple Notification Of Case Assignment messages must be sent // - except in the case where it is used to indicate that an agent is doing the correction himself, this message must be forwarded by all subsequent case assigner(s) until it reaches the case creator // - must not be used in place of a Resolution Of Investigation or a Case Status Report message // When the assignee does not reassign the case to another party (that is responding with a Notification Of Case Assignment message with notification MINE - The case is processed by the assignee), the case assignment should contain the case assignment elements as received in the original query. type NotificationOfCaseAssignmentV04 struct { // Specifies generic information about the notification. // The receiver of a notification must be the party which assigned the case to the sender. Header *iso20022.ReportHeader4 `xml:"Hdr"` // Identifies the investigation case. Case *iso20022.Case3 `xml:"Case"` // Identifies the assignment of an investigation case from an assigner to an assignee. // Usage: The Assigner must be the sender of this confirmation and the Assignee must be the receiver. Assignment *iso20022.CaseAssignment3 `xml:"Assgnmt"` // Information about the type of action taken. Notification *iso20022.CaseForwardingNotification3 `xml:"Ntfctn"` // Additional information that cannot be captured in the structured elements and/or any other specific block. SupplementaryData []*iso20022.SupplementaryData1 `xml:"SplmtryData,omitempty"` } func (n *NotificationOfCaseAssignmentV04) AddHeader() *iso20022.ReportHeader4 { n.Header = new(iso20022.ReportHeader4) return n.Header } func (n *NotificationOfCaseAssignmentV04) AddCase() *iso20022.Case3 { n.Case = new(iso20022.Case3) return n.Case } func (n *NotificationOfCaseAssignmentV04) AddAssignment() *iso20022.CaseAssignment3 { n.Assignment = new(iso20022.CaseAssignment3) return n.Assignment } func (n *NotificationOfCaseAssignmentV04) AddNotification() *iso20022.CaseForwardingNotification3 { n.Notification = new(iso20022.CaseForwardingNotification3) return n.Notification } func (n *NotificationOfCaseAssignmentV04) AddSupplementaryData() *iso20022.SupplementaryData1 { newValue := new(iso20022.SupplementaryData1) n.SupplementaryData = append(n.SupplementaryData, newValue) return newValue }
package client import ( "context" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/types" k8scontrollerclient "sigs.k8s.io/controller-runtime/pkg/client" fakecontrollerclient "sigs.k8s.io/controller-runtime/pkg/client/fake" ) // FakeApplier provides a wrapper around the fake k8s controller client to convert the unsupported apply-type patches to merge patches. func NewFakeApplier(scheme *runtime.Scheme, owner string, objs ...runtime.Object) *ServerSideApplier { return &ServerSideApplier{ client: &fakeApplier{fakecontrollerclient.NewFakeClientWithScheme(scheme, objs...)}, Scheme: scheme, Owner: k8scontrollerclient.FieldOwner(owner), } } type fakeApplier struct { k8scontrollerclient.Client } func (c *fakeApplier) Patch(ctx context.Context, obj k8scontrollerclient.Object, patch k8scontrollerclient.Patch, opts ...k8scontrollerclient.PatchOption) error { patch, opts = convertApplyToMergePatch(patch, opts...) return c.Client.Patch(ctx, obj, patch, opts...) } func (c *fakeApplier) Status() k8scontrollerclient.StatusWriter { return fakeStatusWriter{c.Client.Status()} } type fakeStatusWriter struct { k8scontrollerclient.StatusWriter } func (c fakeStatusWriter) Patch(ctx context.Context, obj k8scontrollerclient.Object, patch k8scontrollerclient.Patch, opts ...k8scontrollerclient.SubResourcePatchOption) error { return c.StatusWriter.Patch(ctx, obj, patch, opts...) } func convertApplyToMergePatch(patch k8scontrollerclient.Patch, opts ...k8scontrollerclient.PatchOption) (k8scontrollerclient.Patch, []k8scontrollerclient.PatchOption) { // Apply patch type is not supported on the fake controller if patch.Type() == types.ApplyPatchType { patch = k8scontrollerclient.Merge patchOptions := make([]k8scontrollerclient.PatchOption, 0, len(opts)) for _, opt := range opts { if opt == k8scontrollerclient.ForceOwnership { continue } patchOptions = append(patchOptions, opt) } opts = patchOptions } return patch, opts }
package main import "net/http" // NewNpkgdServer returns an http.ServeMux that handles all the requests. func NewNpkgdServer(upstream string) *http.ServeMux { mux := http.NewServeMux() proxy := NewUpstreamProxy(upstream) mux.Handle("/", proxy) return mux }
package main import ( "errors" "regexp" "strconv" "strings" ) // CustomSort is implementation of custom sort logic type CustomSort struct { reverse bool ignoreCase bool numerical bool columnNum int strings []string } func (c CustomSort) Len() int { return len(c.strings) } func (c CustomSort) Swap(i, j int) { c.strings[i], c.strings[j] = c.strings[j], c.strings[i] } func getColumn(str string, n int) string { words := strings.Split(str, " ") if n >= len(words) { return "" } return words[n] } // ErrorParse is error displaying that string has no leading number var ErrorParse = errors.New("val: can not parse leading number") var numRegexp = regexp.MustCompile(`^-?[0-9]+`) func parseNum(str string) (int, error) { num := numRegexp.FindString(str) if num == "" { return 0, ErrorParse } integer, err := strconv.Atoi(num) // This check could be skipped because of regexp if err != nil { return 0, ErrorParse } return integer, nil } func lessNum(left, right string) bool { leftNum, _ := parseNum(left) rightNum, _ := parseNum(right) return leftNum < rightNum } func (c CustomSort) Less(i, j int) bool { var isLess bool left := c.strings[i] right := c.strings[j] if c.columnNum != 0 { left = getColumn(left, c.columnNum) right = getColumn(right, c.columnNum) } if c.ignoreCase { left = strings.ToLower(left) right = strings.ToLower(right) } if c.numerical { isLess = lessNum(left, right) } else { isLess = left < right } if c.reverse { isLess = !isLess } return isLess }
package order import ( "context" "time" "tpay_backend/merchantapi/internal/common" "tpay_backend/model" "tpay_backend/utils" "tpay_backend/merchantapi/internal/svc" "tpay_backend/merchantapi/internal/types" "github.com/tal-tech/go-zero/core/logx" ) type PayOrderNotifyLogic struct { logx.Logger ctx context.Context svcCtx *svc.ServiceContext } func NewPayOrderNotifyLogic(ctx context.Context, svcCtx *svc.ServiceContext) PayOrderNotifyLogic { return PayOrderNotifyLogic{ Logger: logx.WithContext(ctx), ctx: ctx, svcCtx: svcCtx, } } func (l *PayOrderNotifyLogic) PayOrderNotify(merchantId int64, req types.PayOrderNotifyRequest) (*types.PayOrderNotifyResponse, error) { order, err := model.NewPayOrderModel(l.svcCtx.DbEngine).FindOrderByMerchantId(merchantId, req.OrderNo) if err != nil { if err == model.ErrRecordNotFound { l.Errorf("代收订单[%v]不存在", req.OrderNo) return nil, common.NewCodeError(common.OrderNotExist) } else { l.Errorf("查询代收订单[%]失败, err=%v", req.OrderNo, err) return nil, common.NewCodeError(common.SystemInternalErr) } } if order.OrderNo == "" { l.Errorf("代收订单[%v]不存在", req.OrderNo) return nil, common.NewCodeError(common.OrderNotExist) } //检查订单状态 //只有支付成功和支付失败的订单才可以通知 if order.OrderStatus != model.PayOrderStatusPaid && order.OrderStatus != model.PayOrderStatusFail { l.Errorf("代收订单[%v]当前支付状态[%v]不能进行通知", order.OrderNo, order.OrderStatus) return nil, common.NewCodeError(common.OrderNotOp) } // 检查订单是否有异步通知URL if order.NotifyUrl == "" { l.Errorf("代收订单[%v]缺少异步通知地址", order.OrderNo) return nil, common.NewCodeError(common.OrderMissingNotifyUrl) } merchant, err := model.NewMerchantModel(l.svcCtx.DbEngine).FindOneById(merchantId) if err != nil { l.Errorf("查询商户失败, MerchantNo=%v, err=%v", order.MerchantNo, err) return nil, common.NewCodeError(common.SystemInternalErr) } postData := &utils.PackPayNotifyParamsRequest{ MerchantNo: merchant.MerchantNo, Timestamp: time.Now().Unix(), NotifyType: utils.PayNotifyType, OrderNo: order.OrderNo, MerchantOrderNo: order.MerchantOrderNo, ReqAmount: order.ReqAmount, Currency: order.Currency, OrderStatus: order.OrderStatus, PayTime: order.UpdateTime, Subject: order.Subject, PaymentAmount: order.PaymentAmount, } param, err := utils.PackPayNotifyParams(postData, merchant.Md5Key) if err != nil { l.Errorf("打包参数失败, data=%v, err=%v", order.MerchantNo, err) return nil, common.NewCodeError(common.SystemInternalErr) } body, err := utils.PostForm(order.NotifyUrl, param) if err != nil { l.Errorf("发送数据失败, url=%v, param=%v, err=%v", order.NotifyUrl, param, err) return nil, common.NewCodeError(common.OrderNotifyFail) } bodyStr := string(body) if bodyStr != "success" { l.Errorf("通知失败, body=%v", bodyStr) } l.Infof("代收订单[%v]通知成功, body:%v", order.OrderNo, bodyStr) return &types.PayOrderNotifyResponse{ NotifyResponse: bodyStr, }, nil }
package logic import ( "context" "github.com/just-coding-0/learn_example/micro_service/zero/rpc/history/internal/svc" history "github.com/just-coding-0/learn_example/micro_service/zero/rpc/history/pb" "github.com/tal-tech/go-zero/core/logx" ) type GetLogic struct { ctx context.Context svcCtx *svc.ServiceContext logx.Logger } func NewGetLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetLogic { return &GetLogic{ ctx: ctx, svcCtx: svcCtx, Logger: logx.WithContext(ctx), } } func (l *GetLogic) Get(in *history.GetRequest) (*history.GetResponse, error) { resp, err := l.svcCtx.Model.FindOne(in.Msg) if err != nil { return nil, err } return &history.GetResponse{ Msg: resp.Msg, Times: resp.Times, LastEcho: resp.LastEcho.Format(`2006-01-02 15:04:05`), }, nil }
package vote import "github.com/google/uuid" type Vote struct { ID uuid.UUID Email string TalkName string `json:"talk_name"` Score int `json:"score,string"` }
package account import ( "time" "github.com/jinzhu/gorm" "mingchuan.me/api" ) // NewService - new service func NewService(db *gorm.DB, secret string) *AccountService { jwtDuration, _ := time.ParseDuration("24h") return &AccountService{ DB: db, Version: AccountServiceVersion, JWTConfig: &AccountJWTConfig{ ExpireIn: time.Duration(jwtDuration), Issuer: Issuer, Secret: secret, }, } } // Init - do initialization on the service func (srv *AccountService) Init() error { if err1 := srv.DB.AutoMigrate(&Account{}).Error; err1 != nil { return err1 } return nil } // RegisterAPI - func (srv *AccountService) RegisterAPI(api *api.API) { c := CreateController(api, srv) // bind routes c.RegisterAdmin() c.Login() }
package _125_Valid_Palindrome import "strings" func isPalindrome(s string) bool { if len(s) == 0 || len(s) == 1 { return true } var ( i, j = 0, len(s) - 1 ) for i <= j { if !isWord(s[i]) { i++ continue } if !isWord(s[j]) { j-- continue } if strings.ToLower(string(s[i])) != strings.ToLower(string(s[j])) { return false } i++ j-- } return true } func isWord(b byte) bool { if (b >= 'A' && b <= 'Z') || (b >= 'a' && b <= 'z') || (b >= '0' && b <= '9') { return true } return false }
// Copyright 2023 Google LLC. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package cloudscheduler import ( "bytes" "context" "encoding/json" "fmt" "io/ioutil" "strings" "github.com/GoogleCloudPlatform/declarative-resource-client-library/dcl" ) func (r *Job) validate() error { if err := dcl.ValidateAtMostOneOfFieldsSet([]string{"PubsubTarget", "AppEngineHttpTarget", "HttpTarget"}, r.PubsubTarget, r.AppEngineHttpTarget, r.HttpTarget); err != nil { return err } if err := dcl.Required(r, "name"); err != nil { return err } if err := dcl.RequiredParameter(r.Project, "Project"); err != nil { return err } if err := dcl.RequiredParameter(r.Location, "Location"); err != nil { return err } if !dcl.IsEmptyValueIndirect(r.PubsubTarget) { if err := r.PubsubTarget.validate(); err != nil { return err } } if !dcl.IsEmptyValueIndirect(r.AppEngineHttpTarget) { if err := r.AppEngineHttpTarget.validate(); err != nil { return err } } if !dcl.IsEmptyValueIndirect(r.HttpTarget) { if err := r.HttpTarget.validate(); err != nil { return err } } if !dcl.IsEmptyValueIndirect(r.Status) { if err := r.Status.validate(); err != nil { return err } } if !dcl.IsEmptyValueIndirect(r.RetryConfig) { if err := r.RetryConfig.validate(); err != nil { return err } } return nil } func (r *JobPubsubTarget) validate() error { if err := dcl.Required(r, "topicName"); err != nil { return err } return nil } func (r *JobAppEngineHttpTarget) validate() error { if !dcl.IsEmptyValueIndirect(r.AppEngineRouting) { if err := r.AppEngineRouting.validate(); err != nil { return err } } return nil } func (r *JobAppEngineHttpTargetAppEngineRouting) validate() error { return nil } func (r *JobHttpTarget) validate() error { if err := dcl.Required(r, "uri"); err != nil { return err } if !dcl.IsEmptyValueIndirect(r.OAuthToken) { if err := r.OAuthToken.validate(); err != nil { return err } } if !dcl.IsEmptyValueIndirect(r.OidcToken) { if err := r.OidcToken.validate(); err != nil { return err } } return nil } func (r *JobHttpTargetOAuthToken) validate() error { return nil } func (r *JobHttpTargetOidcToken) validate() error { return nil } func (r *JobStatus) validate() error { return nil } func (r *JobStatusDetails) validate() error { return nil } func (r *JobRetryConfig) validate() error { return nil } func (r *Job) basePath() string { params := map[string]interface{}{} return dcl.Nprintf("https://cloudscheduler.googleapis.com/v1/", params) } func (r *Job) getURL(userBasePath string) (string, error) { nr := r.urlNormalized() params := map[string]interface{}{ "project": dcl.ValueOrEmptyString(nr.Project), "location": dcl.ValueOrEmptyString(nr.Location), "name": dcl.ValueOrEmptyString(nr.Name), } return dcl.URL("projects/{{project}}/locations/{{location}}/jobs/{{name}}", nr.basePath(), userBasePath, params), nil } func (r *Job) listURL(userBasePath string) (string, error) { nr := r.urlNormalized() params := map[string]interface{}{ "project": dcl.ValueOrEmptyString(nr.Project), "location": dcl.ValueOrEmptyString(nr.Location), } return dcl.URL("projects/{{project}}/locations/{{location}}/jobs", nr.basePath(), userBasePath, params), nil } func (r *Job) createURL(userBasePath string) (string, error) { nr := r.urlNormalized() params := map[string]interface{}{ "project": dcl.ValueOrEmptyString(nr.Project), "location": dcl.ValueOrEmptyString(nr.Location), } return dcl.URL("projects/{{project}}/locations/{{location}}/jobs", nr.basePath(), userBasePath, params), nil } func (r *Job) deleteURL(userBasePath string) (string, error) { nr := r.urlNormalized() params := map[string]interface{}{ "project": dcl.ValueOrEmptyString(nr.Project), "location": dcl.ValueOrEmptyString(nr.Location), "name": dcl.ValueOrEmptyString(nr.Name), } return dcl.URL("projects/{{project}}/locations/{{location}}/jobs/{{name}}", nr.basePath(), userBasePath, params), nil } // jobApiOperation represents a mutable operation in the underlying REST // API such as Create, Update, or Delete. type jobApiOperation interface { do(context.Context, *Job, *Client) error } // newUpdateJobUpdateJobRequest creates a request for an // Job resource's UpdateJob update type by filling in the update // fields based on the intended state of the resource. func newUpdateJobUpdateJobRequest(ctx context.Context, f *Job, c *Client) (map[string]interface{}, error) { req := map[string]interface{}{} res := f _ = res if v, err := dcl.DeriveField("projects/%s/locations/%s/jobs/%s", f.Name, dcl.SelfLinkToName(f.Project), dcl.SelfLinkToName(f.Location), dcl.SelfLinkToName(f.Name)); err != nil { return nil, fmt.Errorf("error expanding Name into name: %w", err) } else if !dcl.IsEmptyValueIndirect(v) { req["name"] = v } if v := f.Description; !dcl.IsEmptyValueIndirect(v) { req["description"] = v } if v, err := expandJobPubsubTarget(c, f.PubsubTarget, res); err != nil { return nil, fmt.Errorf("error expanding PubsubTarget into pubsubTarget: %w", err) } else if !dcl.IsEmptyValueIndirect(v) { req["pubsubTarget"] = v } if v, err := expandJobAppEngineHttpTarget(c, f.AppEngineHttpTarget, res); err != nil { return nil, fmt.Errorf("error expanding AppEngineHttpTarget into appEngineHttpTarget: %w", err) } else if !dcl.IsEmptyValueIndirect(v) { req["appEngineHttpTarget"] = v } if v, err := expandJobHttpTarget(c, f.HttpTarget, res); err != nil { return nil, fmt.Errorf("error expanding HttpTarget into httpTarget: %w", err) } else if !dcl.IsEmptyValueIndirect(v) { req["httpTarget"] = v } if v := f.Schedule; !dcl.IsEmptyValueIndirect(v) { req["schedule"] = v } if v := f.TimeZone; !dcl.IsEmptyValueIndirect(v) { req["timeZone"] = v } if v, err := expandJobRetryConfig(c, f.RetryConfig, res); err != nil { return nil, fmt.Errorf("error expanding RetryConfig into retryConfig: %w", err) } else if !dcl.IsEmptyValueIndirect(v) { req["retryConfig"] = v } if v := f.AttemptDeadline; !dcl.IsEmptyValueIndirect(v) { req["attemptDeadline"] = v } return req, nil } // marshalUpdateJobUpdateJobRequest converts the update into // the final JSON request body. func marshalUpdateJobUpdateJobRequest(c *Client, m map[string]interface{}) ([]byte, error) { return json.Marshal(m) } type updateJobUpdateJobOperation struct { // If the update operation has the REQUIRES_APPLY_OPTIONS trait, this will be populated. // Usually it will be nil - this is to prevent us from accidentally depending on apply // options, which should usually be unnecessary. ApplyOptions []dcl.ApplyOption FieldDiffs []*dcl.FieldDiff } // do creates a request and sends it to the appropriate URL. In most operations, // do will transcribe a subset of the resource into a request object and send a // PUT request to a single URL. func (op *updateJobUpdateJobOperation) do(ctx context.Context, r *Job, c *Client) error { _, err := c.GetJob(ctx, r) if err != nil { return err } u, err := r.updateURL(c.Config.BasePath, "UpdateJob") if err != nil { return err } req, err := newUpdateJobUpdateJobRequest(ctx, r, c) if err != nil { return err } c.Config.Logger.InfoWithContextf(ctx, "Created update: %#v", req) body, err := marshalUpdateJobUpdateJobRequest(c, req) if err != nil { return err } _, err = dcl.SendRequest(ctx, c.Config, "PATCH", u, bytes.NewBuffer(body), c.Config.RetryProvider) if err != nil { return err } return nil } func (c *Client) listJobRaw(ctx context.Context, r *Job, pageToken string, pageSize int32) ([]byte, error) { u, err := r.urlNormalized().listURL(c.Config.BasePath) if err != nil { return nil, err } m := make(map[string]string) if pageToken != "" { m["pageToken"] = pageToken } if pageSize != JobMaxPage { m["pageSize"] = fmt.Sprintf("%v", pageSize) } u, err = dcl.AddQueryParams(u, m) if err != nil { return nil, err } resp, err := dcl.SendRequest(ctx, c.Config, "GET", u, &bytes.Buffer{}, c.Config.RetryProvider) if err != nil { return nil, err } defer resp.Response.Body.Close() return ioutil.ReadAll(resp.Response.Body) } type listJobOperation struct { Jobs []map[string]interface{} `json:"jobs"` Token string `json:"nextPageToken"` } func (c *Client) listJob(ctx context.Context, r *Job, pageToken string, pageSize int32) ([]*Job, string, error) { b, err := c.listJobRaw(ctx, r, pageToken, pageSize) if err != nil { return nil, "", err } var m listJobOperation if err := json.Unmarshal(b, &m); err != nil { return nil, "", err } var l []*Job for _, v := range m.Jobs { res, err := unmarshalMapJob(v, c, r) if err != nil { return nil, m.Token, err } res.Project = r.Project res.Location = r.Location l = append(l, res) } return l, m.Token, nil } func (c *Client) deleteAllJob(ctx context.Context, f func(*Job) bool, resources []*Job) error { var errors []string for _, res := range resources { if f(res) { // We do not want deleteAll to fail on a deletion or else it will stop deleting other resources. err := c.DeleteJob(ctx, res) if err != nil { errors = append(errors, err.Error()) } } } if len(errors) > 0 { return fmt.Errorf("%v", strings.Join(errors, "\n")) } else { return nil } } type deleteJobOperation struct{} func (op *deleteJobOperation) do(ctx context.Context, r *Job, c *Client) error { r, err := c.GetJob(ctx, r) if err != nil { if dcl.IsNotFound(err) { c.Config.Logger.InfoWithContextf(ctx, "Job not found, returning. Original error: %v", err) return nil } c.Config.Logger.WarningWithContextf(ctx, "GetJob checking for existence. error: %v", err) return err } u, err := r.deleteURL(c.Config.BasePath) if err != nil { return err } // Delete should never have a body body := &bytes.Buffer{} _, err = dcl.SendRequest(ctx, c.Config, "DELETE", u, body, c.Config.RetryProvider) if err != nil { return fmt.Errorf("failed to delete Job: %w", err) } // We saw a race condition where for some successful delete operation, the Get calls returned resources for a short duration. // This is the reason we are adding retry to handle that case. retriesRemaining := 10 dcl.Do(ctx, func(ctx context.Context) (*dcl.RetryDetails, error) { _, err := c.GetJob(ctx, r) if dcl.IsNotFound(err) { return nil, nil } if retriesRemaining > 0 { retriesRemaining-- return &dcl.RetryDetails{}, dcl.OperationNotDone{} } return nil, dcl.NotDeletedError{ExistingResource: r} }, c.Config.RetryProvider) return nil } // Create operations are similar to Update operations, although they do not have // specific request objects. The Create request object is the json encoding of // the resource, which is modified by res.marshal to form the base request body. type createJobOperation struct { response map[string]interface{} } func (op *createJobOperation) FirstResponse() (map[string]interface{}, bool) { return op.response, len(op.response) > 0 } func (op *createJobOperation) do(ctx context.Context, r *Job, c *Client) error { c.Config.Logger.InfoWithContextf(ctx, "Attempting to create %v", r) u, err := r.createURL(c.Config.BasePath) if err != nil { return err } req, err := r.marshal(c) if err != nil { return err } resp, err := dcl.SendRequest(ctx, c.Config, "POST", u, bytes.NewBuffer(req), c.Config.RetryProvider) if err != nil { return err } o, err := dcl.ResponseBodyAsJSON(resp) if err != nil { return fmt.Errorf("error decoding response body into JSON: %w", err) } op.response = o if _, err := c.GetJob(ctx, r); err != nil { c.Config.Logger.WarningWithContextf(ctx, "get returned error: %v", err) return err } return nil } func (c *Client) getJobRaw(ctx context.Context, r *Job) ([]byte, error) { u, err := r.getURL(c.Config.BasePath) if err != nil { return nil, err } resp, err := dcl.SendRequest(ctx, c.Config, "GET", u, &bytes.Buffer{}, c.Config.RetryProvider) if err != nil { return nil, err } defer resp.Response.Body.Close() b, err := ioutil.ReadAll(resp.Response.Body) if err != nil { return nil, err } return b, nil } func (c *Client) jobDiffsForRawDesired(ctx context.Context, rawDesired *Job, opts ...dcl.ApplyOption) (initial, desired *Job, diffs []*dcl.FieldDiff, err error) { c.Config.Logger.InfoWithContext(ctx, "Fetching initial state...") // First, let us see if the user provided a state hint. If they did, we will start fetching based on that. var fetchState *Job if sh := dcl.FetchStateHint(opts); sh != nil { if r, ok := sh.(*Job); !ok { c.Config.Logger.WarningWithContextf(ctx, "Initial state hint was of the wrong type; expected Job, got %T", sh) } else { fetchState = r } } if fetchState == nil { fetchState = rawDesired } // 1.2: Retrieval of raw initial state from API rawInitial, err := c.GetJob(ctx, fetchState) if rawInitial == nil { if !dcl.IsNotFound(err) { c.Config.Logger.WarningWithContextf(ctx, "Failed to retrieve whether a Job resource already exists: %s", err) return nil, nil, nil, fmt.Errorf("failed to retrieve Job resource: %v", err) } c.Config.Logger.InfoWithContext(ctx, "Found that Job resource did not exist.") // Perform canonicalization to pick up defaults. desired, err = canonicalizeJobDesiredState(rawDesired, rawInitial) return nil, desired, nil, err } c.Config.Logger.InfoWithContextf(ctx, "Found initial state for Job: %v", rawInitial) c.Config.Logger.InfoWithContextf(ctx, "Initial desired state for Job: %v", rawDesired) // The Get call applies postReadExtract and so the result may contain fields that are not part of API version. if err := extractJobFields(rawInitial); err != nil { return nil, nil, nil, err } // 1.3: Canonicalize raw initial state into initial state. initial, err = canonicalizeJobInitialState(rawInitial, rawDesired) if err != nil { return nil, nil, nil, err } c.Config.Logger.InfoWithContextf(ctx, "Canonicalized initial state for Job: %v", initial) // 1.4: Canonicalize raw desired state into desired state. desired, err = canonicalizeJobDesiredState(rawDesired, rawInitial, opts...) if err != nil { return nil, nil, nil, err } c.Config.Logger.InfoWithContextf(ctx, "Canonicalized desired state for Job: %v", desired) // 2.1: Comparison of initial and desired state. diffs, err = diffJob(c, desired, initial, opts...) return initial, desired, diffs, err } func canonicalizeJobInitialState(rawInitial, rawDesired *Job) (*Job, error) { // TODO(magic-modules-eng): write canonicalizer once relevant traits are added. if !dcl.IsZeroValue(rawInitial.PubsubTarget) { // Check if anything else is set. if dcl.AnySet(rawInitial.AppEngineHttpTarget, rawInitial.HttpTarget) { rawInitial.PubsubTarget = EmptyJobPubsubTarget } } if !dcl.IsZeroValue(rawInitial.AppEngineHttpTarget) { // Check if anything else is set. if dcl.AnySet(rawInitial.PubsubTarget, rawInitial.HttpTarget) { rawInitial.AppEngineHttpTarget = EmptyJobAppEngineHttpTarget } } if !dcl.IsZeroValue(rawInitial.HttpTarget) { // Check if anything else is set. if dcl.AnySet(rawInitial.PubsubTarget, rawInitial.AppEngineHttpTarget) { rawInitial.HttpTarget = EmptyJobHttpTarget } } return rawInitial, nil } /* * Canonicalizers * * These are responsible for converting either a user-specified config or a * GCP API response to a standard format that can be used for difference checking. * */ func canonicalizeJobDesiredState(rawDesired, rawInitial *Job, opts ...dcl.ApplyOption) (*Job, error) { if rawInitial == nil { // Since the initial state is empty, the desired state is all we have. // We canonicalize the remaining nested objects with nil to pick up defaults. rawDesired.PubsubTarget = canonicalizeJobPubsubTarget(rawDesired.PubsubTarget, nil, opts...) rawDesired.AppEngineHttpTarget = canonicalizeJobAppEngineHttpTarget(rawDesired.AppEngineHttpTarget, nil, opts...) rawDesired.HttpTarget = canonicalizeJobHttpTarget(rawDesired.HttpTarget, nil, opts...) rawDesired.Status = canonicalizeJobStatus(rawDesired.Status, nil, opts...) rawDesired.RetryConfig = canonicalizeJobRetryConfig(rawDesired.RetryConfig, nil, opts...) return rawDesired, nil } canonicalDesired := &Job{} if dcl.PartialSelfLinkToSelfLink(rawDesired.Name, rawInitial.Name) { canonicalDesired.Name = rawInitial.Name } else { canonicalDesired.Name = rawDesired.Name } if dcl.StringCanonicalize(rawDesired.Description, rawInitial.Description) { canonicalDesired.Description = rawInitial.Description } else { canonicalDesired.Description = rawDesired.Description } canonicalDesired.PubsubTarget = canonicalizeJobPubsubTarget(rawDesired.PubsubTarget, rawInitial.PubsubTarget, opts...) canonicalDesired.AppEngineHttpTarget = canonicalizeJobAppEngineHttpTarget(rawDesired.AppEngineHttpTarget, rawInitial.AppEngineHttpTarget, opts...) canonicalDesired.HttpTarget = canonicalizeJobHttpTarget(rawDesired.HttpTarget, rawInitial.HttpTarget, opts...) if dcl.StringCanonicalize(rawDesired.Schedule, rawInitial.Schedule) { canonicalDesired.Schedule = rawInitial.Schedule } else { canonicalDesired.Schedule = rawDesired.Schedule } if dcl.StringCanonicalize(rawDesired.TimeZone, rawInitial.TimeZone) { canonicalDesired.TimeZone = rawInitial.TimeZone } else { canonicalDesired.TimeZone = rawDesired.TimeZone } canonicalDesired.RetryConfig = canonicalizeJobRetryConfig(rawDesired.RetryConfig, rawInitial.RetryConfig, opts...) if dcl.StringCanonicalize(rawDesired.AttemptDeadline, rawInitial.AttemptDeadline) { canonicalDesired.AttemptDeadline = rawInitial.AttemptDeadline } else { canonicalDesired.AttemptDeadline = rawDesired.AttemptDeadline } if dcl.NameToSelfLink(rawDesired.Project, rawInitial.Project) { canonicalDesired.Project = rawInitial.Project } else { canonicalDesired.Project = rawDesired.Project } if dcl.NameToSelfLink(rawDesired.Location, rawInitial.Location) { canonicalDesired.Location = rawInitial.Location } else { canonicalDesired.Location = rawDesired.Location } if canonicalDesired.PubsubTarget != nil { // Check if anything else is set. if dcl.AnySet(rawDesired.AppEngineHttpTarget, rawDesired.HttpTarget) { canonicalDesired.PubsubTarget = EmptyJobPubsubTarget } } if canonicalDesired.AppEngineHttpTarget != nil { // Check if anything else is set. if dcl.AnySet(rawDesired.PubsubTarget, rawDesired.HttpTarget) { canonicalDesired.AppEngineHttpTarget = EmptyJobAppEngineHttpTarget } } if canonicalDesired.HttpTarget != nil { // Check if anything else is set. if dcl.AnySet(rawDesired.PubsubTarget, rawDesired.AppEngineHttpTarget) { canonicalDesired.HttpTarget = EmptyJobHttpTarget } } return canonicalDesired, nil } func canonicalizeJobNewState(c *Client, rawNew, rawDesired *Job) (*Job, error) { if dcl.IsEmptyValueIndirect(rawNew.Name) && dcl.IsEmptyValueIndirect(rawDesired.Name) { rawNew.Name = rawDesired.Name } else { if dcl.PartialSelfLinkToSelfLink(rawDesired.Name, rawNew.Name) { rawNew.Name = rawDesired.Name } } if dcl.IsEmptyValueIndirect(rawNew.Description) && dcl.IsEmptyValueIndirect(rawDesired.Description) { rawNew.Description = rawDesired.Description } else { if dcl.StringCanonicalize(rawDesired.Description, rawNew.Description) { rawNew.Description = rawDesired.Description } } if dcl.IsEmptyValueIndirect(rawNew.PubsubTarget) && dcl.IsEmptyValueIndirect(rawDesired.PubsubTarget) { rawNew.PubsubTarget = rawDesired.PubsubTarget } else { rawNew.PubsubTarget = canonicalizeNewJobPubsubTarget(c, rawDesired.PubsubTarget, rawNew.PubsubTarget) } if dcl.IsEmptyValueIndirect(rawNew.AppEngineHttpTarget) && dcl.IsEmptyValueIndirect(rawDesired.AppEngineHttpTarget) { rawNew.AppEngineHttpTarget = rawDesired.AppEngineHttpTarget } else { rawNew.AppEngineHttpTarget = canonicalizeNewJobAppEngineHttpTarget(c, rawDesired.AppEngineHttpTarget, rawNew.AppEngineHttpTarget) } if dcl.IsEmptyValueIndirect(rawNew.HttpTarget) && dcl.IsEmptyValueIndirect(rawDesired.HttpTarget) { rawNew.HttpTarget = rawDesired.HttpTarget } else { rawNew.HttpTarget = canonicalizeNewJobHttpTarget(c, rawDesired.HttpTarget, rawNew.HttpTarget) } if dcl.IsEmptyValueIndirect(rawNew.Schedule) && dcl.IsEmptyValueIndirect(rawDesired.Schedule) { rawNew.Schedule = rawDesired.Schedule } else { if dcl.StringCanonicalize(rawDesired.Schedule, rawNew.Schedule) { rawNew.Schedule = rawDesired.Schedule } } if dcl.IsEmptyValueIndirect(rawNew.TimeZone) && dcl.IsEmptyValueIndirect(rawDesired.TimeZone) { rawNew.TimeZone = rawDesired.TimeZone } else { if dcl.StringCanonicalize(rawDesired.TimeZone, rawNew.TimeZone) { rawNew.TimeZone = rawDesired.TimeZone } } if dcl.IsEmptyValueIndirect(rawNew.UserUpdateTime) && dcl.IsEmptyValueIndirect(rawDesired.UserUpdateTime) { rawNew.UserUpdateTime = rawDesired.UserUpdateTime } else { } if dcl.IsEmptyValueIndirect(rawNew.State) && dcl.IsEmptyValueIndirect(rawDesired.State) { rawNew.State = rawDesired.State } else { } if dcl.IsEmptyValueIndirect(rawNew.Status) && dcl.IsEmptyValueIndirect(rawDesired.Status) { rawNew.Status = rawDesired.Status } else { rawNew.Status = canonicalizeNewJobStatus(c, rawDesired.Status, rawNew.Status) } if dcl.IsEmptyValueIndirect(rawNew.ScheduleTime) && dcl.IsEmptyValueIndirect(rawDesired.ScheduleTime) { rawNew.ScheduleTime = rawDesired.ScheduleTime } else { } if dcl.IsEmptyValueIndirect(rawNew.LastAttemptTime) && dcl.IsEmptyValueIndirect(rawDesired.LastAttemptTime) { rawNew.LastAttemptTime = rawDesired.LastAttemptTime } else { } if dcl.IsEmptyValueIndirect(rawNew.RetryConfig) && dcl.IsEmptyValueIndirect(rawDesired.RetryConfig) { rawNew.RetryConfig = rawDesired.RetryConfig } else { rawNew.RetryConfig = canonicalizeNewJobRetryConfig(c, rawDesired.RetryConfig, rawNew.RetryConfig) } if dcl.IsEmptyValueIndirect(rawNew.AttemptDeadline) && dcl.IsEmptyValueIndirect(rawDesired.AttemptDeadline) { rawNew.AttemptDeadline = rawDesired.AttemptDeadline } else { if dcl.StringCanonicalize(rawDesired.AttemptDeadline, rawNew.AttemptDeadline) { rawNew.AttemptDeadline = rawDesired.AttemptDeadline } } rawNew.Project = rawDesired.Project rawNew.Location = rawDesired.Location return rawNew, nil } func canonicalizeJobPubsubTarget(des, initial *JobPubsubTarget, opts ...dcl.ApplyOption) *JobPubsubTarget { if des == nil { return initial } if des.empty { return des } if initial == nil { return des } cDes := &JobPubsubTarget{} if dcl.IsZeroValue(des.TopicName) || (dcl.IsEmptyValueIndirect(des.TopicName) && dcl.IsEmptyValueIndirect(initial.TopicName)) { // Desired and initial values are equivalent, so set canonical desired value to initial value. cDes.TopicName = initial.TopicName } else { cDes.TopicName = des.TopicName } if dcl.StringCanonicalize(des.Data, initial.Data) || dcl.IsZeroValue(des.Data) { cDes.Data = initial.Data } else { cDes.Data = des.Data } if dcl.IsZeroValue(des.Attributes) || (dcl.IsEmptyValueIndirect(des.Attributes) && dcl.IsEmptyValueIndirect(initial.Attributes)) { // Desired and initial values are equivalent, so set canonical desired value to initial value. cDes.Attributes = initial.Attributes } else { cDes.Attributes = des.Attributes } return cDes } func canonicalizeJobPubsubTargetSlice(des, initial []JobPubsubTarget, opts ...dcl.ApplyOption) []JobPubsubTarget { if dcl.IsEmptyValueIndirect(des) { return initial } if len(des) != len(initial) { items := make([]JobPubsubTarget, 0, len(des)) for _, d := range des { cd := canonicalizeJobPubsubTarget(&d, nil, opts...) if cd != nil { items = append(items, *cd) } } return items } items := make([]JobPubsubTarget, 0, len(des)) for i, d := range des { cd := canonicalizeJobPubsubTarget(&d, &initial[i], opts...) if cd != nil { items = append(items, *cd) } } return items } func canonicalizeNewJobPubsubTarget(c *Client, des, nw *JobPubsubTarget) *JobPubsubTarget { if des == nil { return nw } if nw == nil { if dcl.IsEmptyValueIndirect(des) { c.Config.Logger.Info("Found explicitly empty value for JobPubsubTarget while comparing non-nil desired to nil actual. Returning desired object.") return des } return nil } if dcl.StringCanonicalize(des.Data, nw.Data) { nw.Data = des.Data } return nw } func canonicalizeNewJobPubsubTargetSet(c *Client, des, nw []JobPubsubTarget) []JobPubsubTarget { if des == nil { return nw } // Find the elements in des that are also in nw and canonicalize them. Remove matched elements from nw. var items []JobPubsubTarget for _, d := range des { matchedIndex := -1 for i, n := range nw { if diffs, _ := compareJobPubsubTargetNewStyle(&d, &n, dcl.FieldName{}); len(diffs) == 0 { matchedIndex = i break } } if matchedIndex != -1 { items = append(items, *canonicalizeNewJobPubsubTarget(c, &d, &nw[matchedIndex])) nw = append(nw[:matchedIndex], nw[matchedIndex+1:]...) } } // Also include elements in nw that are not matched in des. items = append(items, nw...) return items } func canonicalizeNewJobPubsubTargetSlice(c *Client, des, nw []JobPubsubTarget) []JobPubsubTarget { if des == nil { return nw } // Lengths are unequal. A diff will occur later, so we shouldn't canonicalize. // Return the original array. if len(des) != len(nw) { return nw } var items []JobPubsubTarget for i, d := range des { n := nw[i] items = append(items, *canonicalizeNewJobPubsubTarget(c, &d, &n)) } return items } func canonicalizeJobAppEngineHttpTarget(des, initial *JobAppEngineHttpTarget, opts ...dcl.ApplyOption) *JobAppEngineHttpTarget { if des == nil { return initial } if des.empty { return des } if initial == nil { return des } cDes := &JobAppEngineHttpTarget{} if dcl.IsZeroValue(des.HttpMethod) || (dcl.IsEmptyValueIndirect(des.HttpMethod) && dcl.IsEmptyValueIndirect(initial.HttpMethod)) { // Desired and initial values are equivalent, so set canonical desired value to initial value. cDes.HttpMethod = initial.HttpMethod } else { cDes.HttpMethod = des.HttpMethod } cDes.AppEngineRouting = canonicalizeJobAppEngineHttpTargetAppEngineRouting(des.AppEngineRouting, initial.AppEngineRouting, opts...) if dcl.StringCanonicalize(des.RelativeUri, initial.RelativeUri) || dcl.IsZeroValue(des.RelativeUri) { cDes.RelativeUri = initial.RelativeUri } else { cDes.RelativeUri = des.RelativeUri } if dcl.IsZeroValue(des.Headers) || (dcl.IsEmptyValueIndirect(des.Headers) && dcl.IsEmptyValueIndirect(initial.Headers)) { // Desired and initial values are equivalent, so set canonical desired value to initial value. cDes.Headers = initial.Headers } else { cDes.Headers = des.Headers } if dcl.StringCanonicalize(des.Body, initial.Body) || dcl.IsZeroValue(des.Body) { cDes.Body = initial.Body } else { cDes.Body = des.Body } return cDes } func canonicalizeJobAppEngineHttpTargetSlice(des, initial []JobAppEngineHttpTarget, opts ...dcl.ApplyOption) []JobAppEngineHttpTarget { if dcl.IsEmptyValueIndirect(des) { return initial } if len(des) != len(initial) { items := make([]JobAppEngineHttpTarget, 0, len(des)) for _, d := range des { cd := canonicalizeJobAppEngineHttpTarget(&d, nil, opts...) if cd != nil { items = append(items, *cd) } } return items } items := make([]JobAppEngineHttpTarget, 0, len(des)) for i, d := range des { cd := canonicalizeJobAppEngineHttpTarget(&d, &initial[i], opts...) if cd != nil { items = append(items, *cd) } } return items } func canonicalizeNewJobAppEngineHttpTarget(c *Client, des, nw *JobAppEngineHttpTarget) *JobAppEngineHttpTarget { if des == nil { return nw } if nw == nil { if dcl.IsEmptyValueIndirect(des) { c.Config.Logger.Info("Found explicitly empty value for JobAppEngineHttpTarget while comparing non-nil desired to nil actual. Returning desired object.") return des } return nil } nw.AppEngineRouting = canonicalizeNewJobAppEngineHttpTargetAppEngineRouting(c, des.AppEngineRouting, nw.AppEngineRouting) if dcl.StringCanonicalize(des.RelativeUri, nw.RelativeUri) { nw.RelativeUri = des.RelativeUri } if dcl.StringCanonicalize(des.Body, nw.Body) { nw.Body = des.Body } return nw } func canonicalizeNewJobAppEngineHttpTargetSet(c *Client, des, nw []JobAppEngineHttpTarget) []JobAppEngineHttpTarget { if des == nil { return nw } // Find the elements in des that are also in nw and canonicalize them. Remove matched elements from nw. var items []JobAppEngineHttpTarget for _, d := range des { matchedIndex := -1 for i, n := range nw { if diffs, _ := compareJobAppEngineHttpTargetNewStyle(&d, &n, dcl.FieldName{}); len(diffs) == 0 { matchedIndex = i break } } if matchedIndex != -1 { items = append(items, *canonicalizeNewJobAppEngineHttpTarget(c, &d, &nw[matchedIndex])) nw = append(nw[:matchedIndex], nw[matchedIndex+1:]...) } } // Also include elements in nw that are not matched in des. items = append(items, nw...) return items } func canonicalizeNewJobAppEngineHttpTargetSlice(c *Client, des, nw []JobAppEngineHttpTarget) []JobAppEngineHttpTarget { if des == nil { return nw } // Lengths are unequal. A diff will occur later, so we shouldn't canonicalize. // Return the original array. if len(des) != len(nw) { return nw } var items []JobAppEngineHttpTarget for i, d := range des { n := nw[i] items = append(items, *canonicalizeNewJobAppEngineHttpTarget(c, &d, &n)) } return items } func canonicalizeJobAppEngineHttpTargetAppEngineRouting(des, initial *JobAppEngineHttpTargetAppEngineRouting, opts ...dcl.ApplyOption) *JobAppEngineHttpTargetAppEngineRouting { if des == nil { return initial } if des.empty { return des } if initial == nil { return des } cDes := &JobAppEngineHttpTargetAppEngineRouting{} if dcl.StringCanonicalize(des.Service, initial.Service) || dcl.IsZeroValue(des.Service) { cDes.Service = initial.Service } else { cDes.Service = des.Service } if dcl.StringCanonicalize(des.Version, initial.Version) || dcl.IsZeroValue(des.Version) { cDes.Version = initial.Version } else { cDes.Version = des.Version } if dcl.StringCanonicalize(des.Instance, initial.Instance) || dcl.IsZeroValue(des.Instance) { cDes.Instance = initial.Instance } else { cDes.Instance = des.Instance } return cDes } func canonicalizeJobAppEngineHttpTargetAppEngineRoutingSlice(des, initial []JobAppEngineHttpTargetAppEngineRouting, opts ...dcl.ApplyOption) []JobAppEngineHttpTargetAppEngineRouting { if dcl.IsEmptyValueIndirect(des) { return initial } if len(des) != len(initial) { items := make([]JobAppEngineHttpTargetAppEngineRouting, 0, len(des)) for _, d := range des { cd := canonicalizeJobAppEngineHttpTargetAppEngineRouting(&d, nil, opts...) if cd != nil { items = append(items, *cd) } } return items } items := make([]JobAppEngineHttpTargetAppEngineRouting, 0, len(des)) for i, d := range des { cd := canonicalizeJobAppEngineHttpTargetAppEngineRouting(&d, &initial[i], opts...) if cd != nil { items = append(items, *cd) } } return items } func canonicalizeNewJobAppEngineHttpTargetAppEngineRouting(c *Client, des, nw *JobAppEngineHttpTargetAppEngineRouting) *JobAppEngineHttpTargetAppEngineRouting { if des == nil { return nw } if nw == nil { if dcl.IsEmptyValueIndirect(des) { c.Config.Logger.Info("Found explicitly empty value for JobAppEngineHttpTargetAppEngineRouting while comparing non-nil desired to nil actual. Returning desired object.") return des } return nil } if dcl.StringCanonicalize(des.Service, nw.Service) { nw.Service = des.Service } if dcl.StringCanonicalize(des.Version, nw.Version) { nw.Version = des.Version } if dcl.StringCanonicalize(des.Instance, nw.Instance) { nw.Instance = des.Instance } if dcl.StringCanonicalize(des.Host, nw.Host) { nw.Host = des.Host } return nw } func canonicalizeNewJobAppEngineHttpTargetAppEngineRoutingSet(c *Client, des, nw []JobAppEngineHttpTargetAppEngineRouting) []JobAppEngineHttpTargetAppEngineRouting { if des == nil { return nw } // Find the elements in des that are also in nw and canonicalize them. Remove matched elements from nw. var items []JobAppEngineHttpTargetAppEngineRouting for _, d := range des { matchedIndex := -1 for i, n := range nw { if diffs, _ := compareJobAppEngineHttpTargetAppEngineRoutingNewStyle(&d, &n, dcl.FieldName{}); len(diffs) == 0 { matchedIndex = i break } } if matchedIndex != -1 { items = append(items, *canonicalizeNewJobAppEngineHttpTargetAppEngineRouting(c, &d, &nw[matchedIndex])) nw = append(nw[:matchedIndex], nw[matchedIndex+1:]...) } } // Also include elements in nw that are not matched in des. items = append(items, nw...) return items } func canonicalizeNewJobAppEngineHttpTargetAppEngineRoutingSlice(c *Client, des, nw []JobAppEngineHttpTargetAppEngineRouting) []JobAppEngineHttpTargetAppEngineRouting { if des == nil { return nw } // Lengths are unequal. A diff will occur later, so we shouldn't canonicalize. // Return the original array. if len(des) != len(nw) { return nw } var items []JobAppEngineHttpTargetAppEngineRouting for i, d := range des { n := nw[i] items = append(items, *canonicalizeNewJobAppEngineHttpTargetAppEngineRouting(c, &d, &n)) } return items } func canonicalizeJobHttpTarget(des, initial *JobHttpTarget, opts ...dcl.ApplyOption) *JobHttpTarget { if des == nil { return initial } if des.empty { return des } if initial == nil { return des } cDes := &JobHttpTarget{} if dcl.StringCanonicalize(des.Uri, initial.Uri) || dcl.IsZeroValue(des.Uri) { cDes.Uri = initial.Uri } else { cDes.Uri = des.Uri } if dcl.IsZeroValue(des.HttpMethod) || (dcl.IsEmptyValueIndirect(des.HttpMethod) && dcl.IsEmptyValueIndirect(initial.HttpMethod)) { // Desired and initial values are equivalent, so set canonical desired value to initial value. cDes.HttpMethod = initial.HttpMethod } else { cDes.HttpMethod = des.HttpMethod } if dcl.IsZeroValue(des.Headers) || (dcl.IsEmptyValueIndirect(des.Headers) && dcl.IsEmptyValueIndirect(initial.Headers)) { // Desired and initial values are equivalent, so set canonical desired value to initial value. cDes.Headers = initial.Headers } else { cDes.Headers = des.Headers } if dcl.StringCanonicalize(des.Body, initial.Body) || dcl.IsZeroValue(des.Body) { cDes.Body = initial.Body } else { cDes.Body = des.Body } cDes.OAuthToken = canonicalizeJobHttpTargetOAuthToken(des.OAuthToken, initial.OAuthToken, opts...) cDes.OidcToken = canonicalizeJobHttpTargetOidcToken(des.OidcToken, initial.OidcToken, opts...) return cDes } func canonicalizeJobHttpTargetSlice(des, initial []JobHttpTarget, opts ...dcl.ApplyOption) []JobHttpTarget { if dcl.IsEmptyValueIndirect(des) { return initial } if len(des) != len(initial) { items := make([]JobHttpTarget, 0, len(des)) for _, d := range des { cd := canonicalizeJobHttpTarget(&d, nil, opts...) if cd != nil { items = append(items, *cd) } } return items } items := make([]JobHttpTarget, 0, len(des)) for i, d := range des { cd := canonicalizeJobHttpTarget(&d, &initial[i], opts...) if cd != nil { items = append(items, *cd) } } return items } func canonicalizeNewJobHttpTarget(c *Client, des, nw *JobHttpTarget) *JobHttpTarget { if des == nil { return nw } if nw == nil { if dcl.IsEmptyValueIndirect(des) { c.Config.Logger.Info("Found explicitly empty value for JobHttpTarget while comparing non-nil desired to nil actual. Returning desired object.") return des } return nil } if dcl.StringCanonicalize(des.Uri, nw.Uri) { nw.Uri = des.Uri } if dcl.StringCanonicalize(des.Body, nw.Body) { nw.Body = des.Body } nw.OAuthToken = canonicalizeNewJobHttpTargetOAuthToken(c, des.OAuthToken, nw.OAuthToken) nw.OidcToken = canonicalizeNewJobHttpTargetOidcToken(c, des.OidcToken, nw.OidcToken) return nw } func canonicalizeNewJobHttpTargetSet(c *Client, des, nw []JobHttpTarget) []JobHttpTarget { if des == nil { return nw } // Find the elements in des that are also in nw and canonicalize them. Remove matched elements from nw. var items []JobHttpTarget for _, d := range des { matchedIndex := -1 for i, n := range nw { if diffs, _ := compareJobHttpTargetNewStyle(&d, &n, dcl.FieldName{}); len(diffs) == 0 { matchedIndex = i break } } if matchedIndex != -1 { items = append(items, *canonicalizeNewJobHttpTarget(c, &d, &nw[matchedIndex])) nw = append(nw[:matchedIndex], nw[matchedIndex+1:]...) } } // Also include elements in nw that are not matched in des. items = append(items, nw...) return items } func canonicalizeNewJobHttpTargetSlice(c *Client, des, nw []JobHttpTarget) []JobHttpTarget { if des == nil { return nw } // Lengths are unequal. A diff will occur later, so we shouldn't canonicalize. // Return the original array. if len(des) != len(nw) { return nw } var items []JobHttpTarget for i, d := range des { n := nw[i] items = append(items, *canonicalizeNewJobHttpTarget(c, &d, &n)) } return items } func canonicalizeJobHttpTargetOAuthToken(des, initial *JobHttpTargetOAuthToken, opts ...dcl.ApplyOption) *JobHttpTargetOAuthToken { if des == nil { return initial } if des.empty { return des } if initial == nil { return des } cDes := &JobHttpTargetOAuthToken{} if dcl.IsZeroValue(des.ServiceAccountEmail) || (dcl.IsEmptyValueIndirect(des.ServiceAccountEmail) && dcl.IsEmptyValueIndirect(initial.ServiceAccountEmail)) { // Desired and initial values are equivalent, so set canonical desired value to initial value. cDes.ServiceAccountEmail = initial.ServiceAccountEmail } else { cDes.ServiceAccountEmail = des.ServiceAccountEmail } if dcl.StringCanonicalize(des.Scope, initial.Scope) || dcl.IsZeroValue(des.Scope) { cDes.Scope = initial.Scope } else { cDes.Scope = des.Scope } return cDes } func canonicalizeJobHttpTargetOAuthTokenSlice(des, initial []JobHttpTargetOAuthToken, opts ...dcl.ApplyOption) []JobHttpTargetOAuthToken { if dcl.IsEmptyValueIndirect(des) { return initial } if len(des) != len(initial) { items := make([]JobHttpTargetOAuthToken, 0, len(des)) for _, d := range des { cd := canonicalizeJobHttpTargetOAuthToken(&d, nil, opts...) if cd != nil { items = append(items, *cd) } } return items } items := make([]JobHttpTargetOAuthToken, 0, len(des)) for i, d := range des { cd := canonicalizeJobHttpTargetOAuthToken(&d, &initial[i], opts...) if cd != nil { items = append(items, *cd) } } return items } func canonicalizeNewJobHttpTargetOAuthToken(c *Client, des, nw *JobHttpTargetOAuthToken) *JobHttpTargetOAuthToken { if des == nil { return nw } if nw == nil { if dcl.IsEmptyValueIndirect(des) { c.Config.Logger.Info("Found explicitly empty value for JobHttpTargetOAuthToken while comparing non-nil desired to nil actual. Returning desired object.") return des } return nil } if dcl.StringCanonicalize(des.Scope, nw.Scope) { nw.Scope = des.Scope } return nw } func canonicalizeNewJobHttpTargetOAuthTokenSet(c *Client, des, nw []JobHttpTargetOAuthToken) []JobHttpTargetOAuthToken { if des == nil { return nw } // Find the elements in des that are also in nw and canonicalize them. Remove matched elements from nw. var items []JobHttpTargetOAuthToken for _, d := range des { matchedIndex := -1 for i, n := range nw { if diffs, _ := compareJobHttpTargetOAuthTokenNewStyle(&d, &n, dcl.FieldName{}); len(diffs) == 0 { matchedIndex = i break } } if matchedIndex != -1 { items = append(items, *canonicalizeNewJobHttpTargetOAuthToken(c, &d, &nw[matchedIndex])) nw = append(nw[:matchedIndex], nw[matchedIndex+1:]...) } } // Also include elements in nw that are not matched in des. items = append(items, nw...) return items } func canonicalizeNewJobHttpTargetOAuthTokenSlice(c *Client, des, nw []JobHttpTargetOAuthToken) []JobHttpTargetOAuthToken { if des == nil { return nw } // Lengths are unequal. A diff will occur later, so we shouldn't canonicalize. // Return the original array. if len(des) != len(nw) { return nw } var items []JobHttpTargetOAuthToken for i, d := range des { n := nw[i] items = append(items, *canonicalizeNewJobHttpTargetOAuthToken(c, &d, &n)) } return items } func canonicalizeJobHttpTargetOidcToken(des, initial *JobHttpTargetOidcToken, opts ...dcl.ApplyOption) *JobHttpTargetOidcToken { if des == nil { return initial } if des.empty { return des } if initial == nil { return des } cDes := &JobHttpTargetOidcToken{} if dcl.IsZeroValue(des.ServiceAccountEmail) || (dcl.IsEmptyValueIndirect(des.ServiceAccountEmail) && dcl.IsEmptyValueIndirect(initial.ServiceAccountEmail)) { // Desired and initial values are equivalent, so set canonical desired value to initial value. cDes.ServiceAccountEmail = initial.ServiceAccountEmail } else { cDes.ServiceAccountEmail = des.ServiceAccountEmail } if dcl.StringCanonicalize(des.Audience, initial.Audience) || dcl.IsZeroValue(des.Audience) { cDes.Audience = initial.Audience } else { cDes.Audience = des.Audience } return cDes } func canonicalizeJobHttpTargetOidcTokenSlice(des, initial []JobHttpTargetOidcToken, opts ...dcl.ApplyOption) []JobHttpTargetOidcToken { if dcl.IsEmptyValueIndirect(des) { return initial } if len(des) != len(initial) { items := make([]JobHttpTargetOidcToken, 0, len(des)) for _, d := range des { cd := canonicalizeJobHttpTargetOidcToken(&d, nil, opts...) if cd != nil { items = append(items, *cd) } } return items } items := make([]JobHttpTargetOidcToken, 0, len(des)) for i, d := range des { cd := canonicalizeJobHttpTargetOidcToken(&d, &initial[i], opts...) if cd != nil { items = append(items, *cd) } } return items } func canonicalizeNewJobHttpTargetOidcToken(c *Client, des, nw *JobHttpTargetOidcToken) *JobHttpTargetOidcToken { if des == nil { return nw } if nw == nil { if dcl.IsEmptyValueIndirect(des) { c.Config.Logger.Info("Found explicitly empty value for JobHttpTargetOidcToken while comparing non-nil desired to nil actual. Returning desired object.") return des } return nil } if dcl.StringCanonicalize(des.Audience, nw.Audience) { nw.Audience = des.Audience } return nw } func canonicalizeNewJobHttpTargetOidcTokenSet(c *Client, des, nw []JobHttpTargetOidcToken) []JobHttpTargetOidcToken { if des == nil { return nw } // Find the elements in des that are also in nw and canonicalize them. Remove matched elements from nw. var items []JobHttpTargetOidcToken for _, d := range des { matchedIndex := -1 for i, n := range nw { if diffs, _ := compareJobHttpTargetOidcTokenNewStyle(&d, &n, dcl.FieldName{}); len(diffs) == 0 { matchedIndex = i break } } if matchedIndex != -1 { items = append(items, *canonicalizeNewJobHttpTargetOidcToken(c, &d, &nw[matchedIndex])) nw = append(nw[:matchedIndex], nw[matchedIndex+1:]...) } } // Also include elements in nw that are not matched in des. items = append(items, nw...) return items } func canonicalizeNewJobHttpTargetOidcTokenSlice(c *Client, des, nw []JobHttpTargetOidcToken) []JobHttpTargetOidcToken { if des == nil { return nw } // Lengths are unequal. A diff will occur later, so we shouldn't canonicalize. // Return the original array. if len(des) != len(nw) { return nw } var items []JobHttpTargetOidcToken for i, d := range des { n := nw[i] items = append(items, *canonicalizeNewJobHttpTargetOidcToken(c, &d, &n)) } return items } func canonicalizeJobStatus(des, initial *JobStatus, opts ...dcl.ApplyOption) *JobStatus { if des == nil { return initial } if des.empty { return des } if initial == nil { return des } cDes := &JobStatus{} if dcl.IsZeroValue(des.Code) || (dcl.IsEmptyValueIndirect(des.Code) && dcl.IsEmptyValueIndirect(initial.Code)) { // Desired and initial values are equivalent, so set canonical desired value to initial value. cDes.Code = initial.Code } else { cDes.Code = des.Code } if dcl.StringCanonicalize(des.Message, initial.Message) || dcl.IsZeroValue(des.Message) { cDes.Message = initial.Message } else { cDes.Message = des.Message } cDes.Details = canonicalizeJobStatusDetailsSlice(des.Details, initial.Details, opts...) return cDes } func canonicalizeJobStatusSlice(des, initial []JobStatus, opts ...dcl.ApplyOption) []JobStatus { if dcl.IsEmptyValueIndirect(des) { return initial } if len(des) != len(initial) { items := make([]JobStatus, 0, len(des)) for _, d := range des { cd := canonicalizeJobStatus(&d, nil, opts...) if cd != nil { items = append(items, *cd) } } return items } items := make([]JobStatus, 0, len(des)) for i, d := range des { cd := canonicalizeJobStatus(&d, &initial[i], opts...) if cd != nil { items = append(items, *cd) } } return items } func canonicalizeNewJobStatus(c *Client, des, nw *JobStatus) *JobStatus { if des == nil { return nw } if nw == nil { if dcl.IsEmptyValueIndirect(des) { c.Config.Logger.Info("Found explicitly empty value for JobStatus while comparing non-nil desired to nil actual. Returning desired object.") return des } return nil } if dcl.StringCanonicalize(des.Message, nw.Message) { nw.Message = des.Message } nw.Details = canonicalizeNewJobStatusDetailsSlice(c, des.Details, nw.Details) return nw } func canonicalizeNewJobStatusSet(c *Client, des, nw []JobStatus) []JobStatus { if des == nil { return nw } // Find the elements in des that are also in nw and canonicalize them. Remove matched elements from nw. var items []JobStatus for _, d := range des { matchedIndex := -1 for i, n := range nw { if diffs, _ := compareJobStatusNewStyle(&d, &n, dcl.FieldName{}); len(diffs) == 0 { matchedIndex = i break } } if matchedIndex != -1 { items = append(items, *canonicalizeNewJobStatus(c, &d, &nw[matchedIndex])) nw = append(nw[:matchedIndex], nw[matchedIndex+1:]...) } } // Also include elements in nw that are not matched in des. items = append(items, nw...) return items } func canonicalizeNewJobStatusSlice(c *Client, des, nw []JobStatus) []JobStatus { if des == nil { return nw } // Lengths are unequal. A diff will occur later, so we shouldn't canonicalize. // Return the original array. if len(des) != len(nw) { return nw } var items []JobStatus for i, d := range des { n := nw[i] items = append(items, *canonicalizeNewJobStatus(c, &d, &n)) } return items } func canonicalizeJobStatusDetails(des, initial *JobStatusDetails, opts ...dcl.ApplyOption) *JobStatusDetails { if des == nil { return initial } if des.empty { return des } if initial == nil { return des } cDes := &JobStatusDetails{} if dcl.StringCanonicalize(des.TypeUrl, initial.TypeUrl) || dcl.IsZeroValue(des.TypeUrl) { cDes.TypeUrl = initial.TypeUrl } else { cDes.TypeUrl = des.TypeUrl } if dcl.StringCanonicalize(des.Value, initial.Value) || dcl.IsZeroValue(des.Value) { cDes.Value = initial.Value } else { cDes.Value = des.Value } return cDes } func canonicalizeJobStatusDetailsSlice(des, initial []JobStatusDetails, opts ...dcl.ApplyOption) []JobStatusDetails { if des == nil { return initial } if len(des) != len(initial) { items := make([]JobStatusDetails, 0, len(des)) for _, d := range des { cd := canonicalizeJobStatusDetails(&d, nil, opts...) if cd != nil { items = append(items, *cd) } } return items } items := make([]JobStatusDetails, 0, len(des)) for i, d := range des { cd := canonicalizeJobStatusDetails(&d, &initial[i], opts...) if cd != nil { items = append(items, *cd) } } return items } func canonicalizeNewJobStatusDetails(c *Client, des, nw *JobStatusDetails) *JobStatusDetails { if des == nil { return nw } if nw == nil { if dcl.IsEmptyValueIndirect(des) { c.Config.Logger.Info("Found explicitly empty value for JobStatusDetails while comparing non-nil desired to nil actual. Returning desired object.") return des } return nil } if dcl.StringCanonicalize(des.TypeUrl, nw.TypeUrl) { nw.TypeUrl = des.TypeUrl } if dcl.StringCanonicalize(des.Value, nw.Value) { nw.Value = des.Value } return nw } func canonicalizeNewJobStatusDetailsSet(c *Client, des, nw []JobStatusDetails) []JobStatusDetails { if des == nil { return nw } // Find the elements in des that are also in nw and canonicalize them. Remove matched elements from nw. var items []JobStatusDetails for _, d := range des { matchedIndex := -1 for i, n := range nw { if diffs, _ := compareJobStatusDetailsNewStyle(&d, &n, dcl.FieldName{}); len(diffs) == 0 { matchedIndex = i break } } if matchedIndex != -1 { items = append(items, *canonicalizeNewJobStatusDetails(c, &d, &nw[matchedIndex])) nw = append(nw[:matchedIndex], nw[matchedIndex+1:]...) } } // Also include elements in nw that are not matched in des. items = append(items, nw...) return items } func canonicalizeNewJobStatusDetailsSlice(c *Client, des, nw []JobStatusDetails) []JobStatusDetails { if des == nil { return nw } // Lengths are unequal. A diff will occur later, so we shouldn't canonicalize. // Return the original array. if len(des) != len(nw) { return nw } var items []JobStatusDetails for i, d := range des { n := nw[i] items = append(items, *canonicalizeNewJobStatusDetails(c, &d, &n)) } return items } func canonicalizeJobRetryConfig(des, initial *JobRetryConfig, opts ...dcl.ApplyOption) *JobRetryConfig { if des == nil { return initial } if des.empty { return des } if initial == nil { return des } cDes := &JobRetryConfig{} if dcl.IsZeroValue(des.RetryCount) || (dcl.IsEmptyValueIndirect(des.RetryCount) && dcl.IsEmptyValueIndirect(initial.RetryCount)) { // Desired and initial values are equivalent, so set canonical desired value to initial value. cDes.RetryCount = initial.RetryCount } else { cDes.RetryCount = des.RetryCount } if dcl.StringCanonicalize(des.MaxRetryDuration, initial.MaxRetryDuration) || dcl.IsZeroValue(des.MaxRetryDuration) { cDes.MaxRetryDuration = initial.MaxRetryDuration } else { cDes.MaxRetryDuration = des.MaxRetryDuration } if dcl.StringCanonicalize(des.MinBackoffDuration, initial.MinBackoffDuration) || dcl.IsZeroValue(des.MinBackoffDuration) { cDes.MinBackoffDuration = initial.MinBackoffDuration } else { cDes.MinBackoffDuration = des.MinBackoffDuration } if dcl.StringCanonicalize(des.MaxBackoffDuration, initial.MaxBackoffDuration) || dcl.IsZeroValue(des.MaxBackoffDuration) { cDes.MaxBackoffDuration = initial.MaxBackoffDuration } else { cDes.MaxBackoffDuration = des.MaxBackoffDuration } if dcl.IsZeroValue(des.MaxDoublings) || (dcl.IsEmptyValueIndirect(des.MaxDoublings) && dcl.IsEmptyValueIndirect(initial.MaxDoublings)) { // Desired and initial values are equivalent, so set canonical desired value to initial value. cDes.MaxDoublings = initial.MaxDoublings } else { cDes.MaxDoublings = des.MaxDoublings } return cDes } func canonicalizeJobRetryConfigSlice(des, initial []JobRetryConfig, opts ...dcl.ApplyOption) []JobRetryConfig { if dcl.IsEmptyValueIndirect(des) { return initial } if len(des) != len(initial) { items := make([]JobRetryConfig, 0, len(des)) for _, d := range des { cd := canonicalizeJobRetryConfig(&d, nil, opts...) if cd != nil { items = append(items, *cd) } } return items } items := make([]JobRetryConfig, 0, len(des)) for i, d := range des { cd := canonicalizeJobRetryConfig(&d, &initial[i], opts...) if cd != nil { items = append(items, *cd) } } return items } func canonicalizeNewJobRetryConfig(c *Client, des, nw *JobRetryConfig) *JobRetryConfig { if des == nil { return nw } if nw == nil { if dcl.IsEmptyValueIndirect(des) { c.Config.Logger.Info("Found explicitly empty value for JobRetryConfig while comparing non-nil desired to nil actual. Returning desired object.") return des } return nil } if dcl.StringCanonicalize(des.MaxRetryDuration, nw.MaxRetryDuration) { nw.MaxRetryDuration = des.MaxRetryDuration } if dcl.StringCanonicalize(des.MinBackoffDuration, nw.MinBackoffDuration) { nw.MinBackoffDuration = des.MinBackoffDuration } if dcl.StringCanonicalize(des.MaxBackoffDuration, nw.MaxBackoffDuration) { nw.MaxBackoffDuration = des.MaxBackoffDuration } return nw } func canonicalizeNewJobRetryConfigSet(c *Client, des, nw []JobRetryConfig) []JobRetryConfig { if des == nil { return nw } // Find the elements in des that are also in nw and canonicalize them. Remove matched elements from nw. var items []JobRetryConfig for _, d := range des { matchedIndex := -1 for i, n := range nw { if diffs, _ := compareJobRetryConfigNewStyle(&d, &n, dcl.FieldName{}); len(diffs) == 0 { matchedIndex = i break } } if matchedIndex != -1 { items = append(items, *canonicalizeNewJobRetryConfig(c, &d, &nw[matchedIndex])) nw = append(nw[:matchedIndex], nw[matchedIndex+1:]...) } } // Also include elements in nw that are not matched in des. items = append(items, nw...) return items } func canonicalizeNewJobRetryConfigSlice(c *Client, des, nw []JobRetryConfig) []JobRetryConfig { if des == nil { return nw } // Lengths are unequal. A diff will occur later, so we shouldn't canonicalize. // Return the original array. if len(des) != len(nw) { return nw } var items []JobRetryConfig for i, d := range des { n := nw[i] items = append(items, *canonicalizeNewJobRetryConfig(c, &d, &n)) } return items } // The differ returns a list of diffs, along with a list of operations that should be taken // to remedy them. Right now, it does not attempt to consolidate operations - if several // fields can be fixed with a patch update, it will perform the patch several times. // Diffs on some fields will be ignored if the `desired` state has an empty (nil) // value. This empty value indicates that the user does not care about the state for // the field. Empty fields on the actual object will cause diffs. // TODO(magic-modules-eng): for efficiency in some resources, add batching. func diffJob(c *Client, desired, actual *Job, opts ...dcl.ApplyOption) ([]*dcl.FieldDiff, error) { if desired == nil || actual == nil { return nil, fmt.Errorf("nil resource passed to diff - always a programming error: %#v, %#v", desired, actual) } c.Config.Logger.Infof("Diff function called with desired state: %v", desired) c.Config.Logger.Infof("Diff function called with actual state: %v", actual) var fn dcl.FieldName var newDiffs []*dcl.FieldDiff // New style diffs. if ds, err := dcl.Diff(desired.Name, actual.Name, dcl.DiffInfo{OperationSelector: dcl.TriggersOperation("updateJobUpdateJobOperation")}, fn.AddNest("Name")); len(ds) != 0 || err != nil { if err != nil { return nil, err } newDiffs = append(newDiffs, ds...) } if ds, err := dcl.Diff(desired.Description, actual.Description, dcl.DiffInfo{OperationSelector: dcl.TriggersOperation("updateJobUpdateJobOperation")}, fn.AddNest("Description")); len(ds) != 0 || err != nil { if err != nil { return nil, err } newDiffs = append(newDiffs, ds...) } if ds, err := dcl.Diff(desired.PubsubTarget, actual.PubsubTarget, dcl.DiffInfo{ObjectFunction: compareJobPubsubTargetNewStyle, EmptyObject: EmptyJobPubsubTarget, OperationSelector: dcl.TriggersOperation("updateJobUpdateJobOperation")}, fn.AddNest("PubsubTarget")); len(ds) != 0 || err != nil { if err != nil { return nil, err } newDiffs = append(newDiffs, ds...) } if ds, err := dcl.Diff(desired.AppEngineHttpTarget, actual.AppEngineHttpTarget, dcl.DiffInfo{ObjectFunction: compareJobAppEngineHttpTargetNewStyle, EmptyObject: EmptyJobAppEngineHttpTarget, OperationSelector: dcl.TriggersOperation("updateJobUpdateJobOperation")}, fn.AddNest("AppEngineHttpTarget")); len(ds) != 0 || err != nil { if err != nil { return nil, err } newDiffs = append(newDiffs, ds...) } if ds, err := dcl.Diff(desired.HttpTarget, actual.HttpTarget, dcl.DiffInfo{ObjectFunction: compareJobHttpTargetNewStyle, EmptyObject: EmptyJobHttpTarget, OperationSelector: dcl.TriggersOperation("updateJobUpdateJobOperation")}, fn.AddNest("HttpTarget")); len(ds) != 0 || err != nil { if err != nil { return nil, err } newDiffs = append(newDiffs, ds...) } if ds, err := dcl.Diff(desired.Schedule, actual.Schedule, dcl.DiffInfo{OperationSelector: dcl.TriggersOperation("updateJobUpdateJobOperation")}, fn.AddNest("Schedule")); len(ds) != 0 || err != nil { if err != nil { return nil, err } newDiffs = append(newDiffs, ds...) } if ds, err := dcl.Diff(desired.TimeZone, actual.TimeZone, dcl.DiffInfo{ServerDefault: true, OperationSelector: dcl.TriggersOperation("updateJobUpdateJobOperation")}, fn.AddNest("TimeZone")); len(ds) != 0 || err != nil { if err != nil { return nil, err } newDiffs = append(newDiffs, ds...) } if ds, err := dcl.Diff(desired.UserUpdateTime, actual.UserUpdateTime, dcl.DiffInfo{OutputOnly: true, OperationSelector: dcl.RequiresRecreate()}, fn.AddNest("UserUpdateTime")); len(ds) != 0 || err != nil { if err != nil { return nil, err } newDiffs = append(newDiffs, ds...) } if ds, err := dcl.Diff(desired.State, actual.State, dcl.DiffInfo{OutputOnly: true, Type: "EnumType", OperationSelector: dcl.RequiresRecreate()}, fn.AddNest("State")); len(ds) != 0 || err != nil { if err != nil { return nil, err } newDiffs = append(newDiffs, ds...) } if ds, err := dcl.Diff(desired.Status, actual.Status, dcl.DiffInfo{OutputOnly: true, ObjectFunction: compareJobStatusNewStyle, EmptyObject: EmptyJobStatus, OperationSelector: dcl.RequiresRecreate()}, fn.AddNest("Status")); len(ds) != 0 || err != nil { if err != nil { return nil, err } newDiffs = append(newDiffs, ds...) } if ds, err := dcl.Diff(desired.ScheduleTime, actual.ScheduleTime, dcl.DiffInfo{OutputOnly: true, OperationSelector: dcl.RequiresRecreate()}, fn.AddNest("ScheduleTime")); len(ds) != 0 || err != nil { if err != nil { return nil, err } newDiffs = append(newDiffs, ds...) } if ds, err := dcl.Diff(desired.LastAttemptTime, actual.LastAttemptTime, dcl.DiffInfo{OutputOnly: true, OperationSelector: dcl.RequiresRecreate()}, fn.AddNest("LastAttemptTime")); len(ds) != 0 || err != nil { if err != nil { return nil, err } newDiffs = append(newDiffs, ds...) } if ds, err := dcl.Diff(desired.RetryConfig, actual.RetryConfig, dcl.DiffInfo{ObjectFunction: compareJobRetryConfigNewStyle, EmptyObject: EmptyJobRetryConfig, OperationSelector: dcl.TriggersOperation("updateJobUpdateJobOperation")}, fn.AddNest("RetryConfig")); len(ds) != 0 || err != nil { if err != nil { return nil, err } newDiffs = append(newDiffs, ds...) } if ds, err := dcl.Diff(desired.AttemptDeadline, actual.AttemptDeadline, dcl.DiffInfo{OperationSelector: dcl.TriggersOperation("updateJobUpdateJobOperation")}, fn.AddNest("AttemptDeadline")); len(ds) != 0 || err != nil { if err != nil { return nil, err } newDiffs = append(newDiffs, ds...) } if ds, err := dcl.Diff(desired.Project, actual.Project, dcl.DiffInfo{Type: "ReferenceType", OperationSelector: dcl.RequiresRecreate()}, fn.AddNest("Project")); len(ds) != 0 || err != nil { if err != nil { return nil, err } newDiffs = append(newDiffs, ds...) } if ds, err := dcl.Diff(desired.Location, actual.Location, dcl.DiffInfo{OperationSelector: dcl.RequiresRecreate()}, fn.AddNest("Location")); len(ds) != 0 || err != nil { if err != nil { return nil, err } newDiffs = append(newDiffs, ds...) } if len(newDiffs) > 0 { c.Config.Logger.Infof("Diff function found diffs: %v", newDiffs) } return newDiffs, nil } func compareJobPubsubTargetNewStyle(d, a interface{}, fn dcl.FieldName) ([]*dcl.FieldDiff, error) { var diffs []*dcl.FieldDiff desired, ok := d.(*JobPubsubTarget) if !ok { desiredNotPointer, ok := d.(JobPubsubTarget) if !ok { return nil, fmt.Errorf("obj %v is not a JobPubsubTarget or *JobPubsubTarget", d) } desired = &desiredNotPointer } actual, ok := a.(*JobPubsubTarget) if !ok { actualNotPointer, ok := a.(JobPubsubTarget) if !ok { return nil, fmt.Errorf("obj %v is not a JobPubsubTarget", a) } actual = &actualNotPointer } if ds, err := dcl.Diff(desired.TopicName, actual.TopicName, dcl.DiffInfo{Type: "ReferenceType", OperationSelector: dcl.TriggersOperation("updateJobUpdateJobOperation")}, fn.AddNest("TopicName")); len(ds) != 0 || err != nil { if err != nil { return nil, err } diffs = append(diffs, ds...) } if ds, err := dcl.Diff(desired.Data, actual.Data, dcl.DiffInfo{OperationSelector: dcl.TriggersOperation("updateJobUpdateJobOperation")}, fn.AddNest("Data")); len(ds) != 0 || err != nil { if err != nil { return nil, err } diffs = append(diffs, ds...) } if ds, err := dcl.Diff(desired.Attributes, actual.Attributes, dcl.DiffInfo{OperationSelector: dcl.TriggersOperation("updateJobUpdateJobOperation")}, fn.AddNest("Attributes")); len(ds) != 0 || err != nil { if err != nil { return nil, err } diffs = append(diffs, ds...) } return diffs, nil } func compareJobAppEngineHttpTargetNewStyle(d, a interface{}, fn dcl.FieldName) ([]*dcl.FieldDiff, error) { var diffs []*dcl.FieldDiff desired, ok := d.(*JobAppEngineHttpTarget) if !ok { desiredNotPointer, ok := d.(JobAppEngineHttpTarget) if !ok { return nil, fmt.Errorf("obj %v is not a JobAppEngineHttpTarget or *JobAppEngineHttpTarget", d) } desired = &desiredNotPointer } actual, ok := a.(*JobAppEngineHttpTarget) if !ok { actualNotPointer, ok := a.(JobAppEngineHttpTarget) if !ok { return nil, fmt.Errorf("obj %v is not a JobAppEngineHttpTarget", a) } actual = &actualNotPointer } if ds, err := dcl.Diff(desired.HttpMethod, actual.HttpMethod, dcl.DiffInfo{Type: "EnumType", OperationSelector: dcl.TriggersOperation("updateJobUpdateJobOperation")}, fn.AddNest("HttpMethod")); len(ds) != 0 || err != nil { if err != nil { return nil, err } diffs = append(diffs, ds...) } if ds, err := dcl.Diff(desired.AppEngineRouting, actual.AppEngineRouting, dcl.DiffInfo{ObjectFunction: compareJobAppEngineHttpTargetAppEngineRoutingNewStyle, EmptyObject: EmptyJobAppEngineHttpTargetAppEngineRouting, OperationSelector: dcl.TriggersOperation("updateJobUpdateJobOperation")}, fn.AddNest("AppEngineRouting")); len(ds) != 0 || err != nil { if err != nil { return nil, err } diffs = append(diffs, ds...) } if ds, err := dcl.Diff(desired.RelativeUri, actual.RelativeUri, dcl.DiffInfo{OperationSelector: dcl.TriggersOperation("updateJobUpdateJobOperation")}, fn.AddNest("RelativeUri")); len(ds) != 0 || err != nil { if err != nil { return nil, err } diffs = append(diffs, ds...) } if ds, err := dcl.Diff(desired.Headers, actual.Headers, dcl.DiffInfo{OperationSelector: dcl.TriggersOperation("updateJobUpdateJobOperation")}, fn.AddNest("Headers")); len(ds) != 0 || err != nil { if err != nil { return nil, err } diffs = append(diffs, ds...) } if ds, err := dcl.Diff(desired.Body, actual.Body, dcl.DiffInfo{OperationSelector: dcl.TriggersOperation("updateJobUpdateJobOperation")}, fn.AddNest("Body")); len(ds) != 0 || err != nil { if err != nil { return nil, err } diffs = append(diffs, ds...) } return diffs, nil } func compareJobAppEngineHttpTargetAppEngineRoutingNewStyle(d, a interface{}, fn dcl.FieldName) ([]*dcl.FieldDiff, error) { var diffs []*dcl.FieldDiff desired, ok := d.(*JobAppEngineHttpTargetAppEngineRouting) if !ok { desiredNotPointer, ok := d.(JobAppEngineHttpTargetAppEngineRouting) if !ok { return nil, fmt.Errorf("obj %v is not a JobAppEngineHttpTargetAppEngineRouting or *JobAppEngineHttpTargetAppEngineRouting", d) } desired = &desiredNotPointer } actual, ok := a.(*JobAppEngineHttpTargetAppEngineRouting) if !ok { actualNotPointer, ok := a.(JobAppEngineHttpTargetAppEngineRouting) if !ok { return nil, fmt.Errorf("obj %v is not a JobAppEngineHttpTargetAppEngineRouting", a) } actual = &actualNotPointer } if ds, err := dcl.Diff(desired.Service, actual.Service, dcl.DiffInfo{OperationSelector: dcl.TriggersOperation("updateJobUpdateJobOperation")}, fn.AddNest("Service")); len(ds) != 0 || err != nil { if err != nil { return nil, err } diffs = append(diffs, ds...) } if ds, err := dcl.Diff(desired.Version, actual.Version, dcl.DiffInfo{OperationSelector: dcl.TriggersOperation("updateJobUpdateJobOperation")}, fn.AddNest("Version")); len(ds) != 0 || err != nil { if err != nil { return nil, err } diffs = append(diffs, ds...) } if ds, err := dcl.Diff(desired.Instance, actual.Instance, dcl.DiffInfo{OperationSelector: dcl.TriggersOperation("updateJobUpdateJobOperation")}, fn.AddNest("Instance")); len(ds) != 0 || err != nil { if err != nil { return nil, err } diffs = append(diffs, ds...) } if ds, err := dcl.Diff(desired.Host, actual.Host, dcl.DiffInfo{OutputOnly: true, OperationSelector: dcl.RequiresRecreate()}, fn.AddNest("Host")); len(ds) != 0 || err != nil { if err != nil { return nil, err } diffs = append(diffs, ds...) } return diffs, nil } func compareJobHttpTargetNewStyle(d, a interface{}, fn dcl.FieldName) ([]*dcl.FieldDiff, error) { var diffs []*dcl.FieldDiff desired, ok := d.(*JobHttpTarget) if !ok { desiredNotPointer, ok := d.(JobHttpTarget) if !ok { return nil, fmt.Errorf("obj %v is not a JobHttpTarget or *JobHttpTarget", d) } desired = &desiredNotPointer } actual, ok := a.(*JobHttpTarget) if !ok { actualNotPointer, ok := a.(JobHttpTarget) if !ok { return nil, fmt.Errorf("obj %v is not a JobHttpTarget", a) } actual = &actualNotPointer } if ds, err := dcl.Diff(desired.Uri, actual.Uri, dcl.DiffInfo{OperationSelector: dcl.TriggersOperation("updateJobUpdateJobOperation")}, fn.AddNest("Uri")); len(ds) != 0 || err != nil { if err != nil { return nil, err } diffs = append(diffs, ds...) } if ds, err := dcl.Diff(desired.HttpMethod, actual.HttpMethod, dcl.DiffInfo{Type: "EnumType", OperationSelector: dcl.TriggersOperation("updateJobUpdateJobOperation")}, fn.AddNest("HttpMethod")); len(ds) != 0 || err != nil { if err != nil { return nil, err } diffs = append(diffs, ds...) } if ds, err := dcl.Diff(desired.Headers, actual.Headers, dcl.DiffInfo{OperationSelector: dcl.TriggersOperation("updateJobUpdateJobOperation")}, fn.AddNest("Headers")); len(ds) != 0 || err != nil { if err != nil { return nil, err } diffs = append(diffs, ds...) } if ds, err := dcl.Diff(desired.Body, actual.Body, dcl.DiffInfo{OperationSelector: dcl.TriggersOperation("updateJobUpdateJobOperation")}, fn.AddNest("Body")); len(ds) != 0 || err != nil { if err != nil { return nil, err } diffs = append(diffs, ds...) } if ds, err := dcl.Diff(desired.OAuthToken, actual.OAuthToken, dcl.DiffInfo{ObjectFunction: compareJobHttpTargetOAuthTokenNewStyle, EmptyObject: EmptyJobHttpTargetOAuthToken, OperationSelector: dcl.TriggersOperation("updateJobUpdateJobOperation")}, fn.AddNest("OauthToken")); len(ds) != 0 || err != nil { if err != nil { return nil, err } diffs = append(diffs, ds...) } if ds, err := dcl.Diff(desired.OidcToken, actual.OidcToken, dcl.DiffInfo{ObjectFunction: compareJobHttpTargetOidcTokenNewStyle, EmptyObject: EmptyJobHttpTargetOidcToken, OperationSelector: dcl.TriggersOperation("updateJobUpdateJobOperation")}, fn.AddNest("OidcToken")); len(ds) != 0 || err != nil { if err != nil { return nil, err } diffs = append(diffs, ds...) } return diffs, nil } func compareJobHttpTargetOAuthTokenNewStyle(d, a interface{}, fn dcl.FieldName) ([]*dcl.FieldDiff, error) { var diffs []*dcl.FieldDiff desired, ok := d.(*JobHttpTargetOAuthToken) if !ok { desiredNotPointer, ok := d.(JobHttpTargetOAuthToken) if !ok { return nil, fmt.Errorf("obj %v is not a JobHttpTargetOAuthToken or *JobHttpTargetOAuthToken", d) } desired = &desiredNotPointer } actual, ok := a.(*JobHttpTargetOAuthToken) if !ok { actualNotPointer, ok := a.(JobHttpTargetOAuthToken) if !ok { return nil, fmt.Errorf("obj %v is not a JobHttpTargetOAuthToken", a) } actual = &actualNotPointer } if ds, err := dcl.Diff(desired.ServiceAccountEmail, actual.ServiceAccountEmail, dcl.DiffInfo{Type: "ReferenceType", OperationSelector: dcl.TriggersOperation("updateJobUpdateJobOperation")}, fn.AddNest("ServiceAccountEmail")); len(ds) != 0 || err != nil { if err != nil { return nil, err } diffs = append(diffs, ds...) } if ds, err := dcl.Diff(desired.Scope, actual.Scope, dcl.DiffInfo{OperationSelector: dcl.TriggersOperation("updateJobUpdateJobOperation")}, fn.AddNest("Scope")); len(ds) != 0 || err != nil { if err != nil { return nil, err } diffs = append(diffs, ds...) } return diffs, nil } func compareJobHttpTargetOidcTokenNewStyle(d, a interface{}, fn dcl.FieldName) ([]*dcl.FieldDiff, error) { var diffs []*dcl.FieldDiff desired, ok := d.(*JobHttpTargetOidcToken) if !ok { desiredNotPointer, ok := d.(JobHttpTargetOidcToken) if !ok { return nil, fmt.Errorf("obj %v is not a JobHttpTargetOidcToken or *JobHttpTargetOidcToken", d) } desired = &desiredNotPointer } actual, ok := a.(*JobHttpTargetOidcToken) if !ok { actualNotPointer, ok := a.(JobHttpTargetOidcToken) if !ok { return nil, fmt.Errorf("obj %v is not a JobHttpTargetOidcToken", a) } actual = &actualNotPointer } if ds, err := dcl.Diff(desired.ServiceAccountEmail, actual.ServiceAccountEmail, dcl.DiffInfo{Type: "ReferenceType", OperationSelector: dcl.TriggersOperation("updateJobUpdateJobOperation")}, fn.AddNest("ServiceAccountEmail")); len(ds) != 0 || err != nil { if err != nil { return nil, err } diffs = append(diffs, ds...) } if ds, err := dcl.Diff(desired.Audience, actual.Audience, dcl.DiffInfo{OperationSelector: dcl.TriggersOperation("updateJobUpdateJobOperation")}, fn.AddNest("Audience")); len(ds) != 0 || err != nil { if err != nil { return nil, err } diffs = append(diffs, ds...) } return diffs, nil } func compareJobStatusNewStyle(d, a interface{}, fn dcl.FieldName) ([]*dcl.FieldDiff, error) { var diffs []*dcl.FieldDiff desired, ok := d.(*JobStatus) if !ok { desiredNotPointer, ok := d.(JobStatus) if !ok { return nil, fmt.Errorf("obj %v is not a JobStatus or *JobStatus", d) } desired = &desiredNotPointer } actual, ok := a.(*JobStatus) if !ok { actualNotPointer, ok := a.(JobStatus) if !ok { return nil, fmt.Errorf("obj %v is not a JobStatus", a) } actual = &actualNotPointer } if ds, err := dcl.Diff(desired.Code, actual.Code, dcl.DiffInfo{OperationSelector: dcl.RequiresRecreate()}, fn.AddNest("Code")); len(ds) != 0 || err != nil { if err != nil { return nil, err } diffs = append(diffs, ds...) } if ds, err := dcl.Diff(desired.Message, actual.Message, dcl.DiffInfo{OperationSelector: dcl.RequiresRecreate()}, fn.AddNest("Message")); len(ds) != 0 || err != nil { if err != nil { return nil, err } diffs = append(diffs, ds...) } if ds, err := dcl.Diff(desired.Details, actual.Details, dcl.DiffInfo{ObjectFunction: compareJobStatusDetailsNewStyle, EmptyObject: EmptyJobStatusDetails, OperationSelector: dcl.RequiresRecreate()}, fn.AddNest("Details")); len(ds) != 0 || err != nil { if err != nil { return nil, err } diffs = append(diffs, ds...) } return diffs, nil } func compareJobStatusDetailsNewStyle(d, a interface{}, fn dcl.FieldName) ([]*dcl.FieldDiff, error) { var diffs []*dcl.FieldDiff desired, ok := d.(*JobStatusDetails) if !ok { desiredNotPointer, ok := d.(JobStatusDetails) if !ok { return nil, fmt.Errorf("obj %v is not a JobStatusDetails or *JobStatusDetails", d) } desired = &desiredNotPointer } actual, ok := a.(*JobStatusDetails) if !ok { actualNotPointer, ok := a.(JobStatusDetails) if !ok { return nil, fmt.Errorf("obj %v is not a JobStatusDetails", a) } actual = &actualNotPointer } if ds, err := dcl.Diff(desired.TypeUrl, actual.TypeUrl, dcl.DiffInfo{OperationSelector: dcl.RequiresRecreate()}, fn.AddNest("TypeUrl")); len(ds) != 0 || err != nil { if err != nil { return nil, err } diffs = append(diffs, ds...) } if ds, err := dcl.Diff(desired.Value, actual.Value, dcl.DiffInfo{OperationSelector: dcl.RequiresRecreate()}, fn.AddNest("Value")); len(ds) != 0 || err != nil { if err != nil { return nil, err } diffs = append(diffs, ds...) } return diffs, nil } func compareJobRetryConfigNewStyle(d, a interface{}, fn dcl.FieldName) ([]*dcl.FieldDiff, error) { var diffs []*dcl.FieldDiff desired, ok := d.(*JobRetryConfig) if !ok { desiredNotPointer, ok := d.(JobRetryConfig) if !ok { return nil, fmt.Errorf("obj %v is not a JobRetryConfig or *JobRetryConfig", d) } desired = &desiredNotPointer } actual, ok := a.(*JobRetryConfig) if !ok { actualNotPointer, ok := a.(JobRetryConfig) if !ok { return nil, fmt.Errorf("obj %v is not a JobRetryConfig", a) } actual = &actualNotPointer } if ds, err := dcl.Diff(desired.RetryCount, actual.RetryCount, dcl.DiffInfo{OperationSelector: dcl.TriggersOperation("updateJobUpdateJobOperation")}, fn.AddNest("RetryCount")); len(ds) != 0 || err != nil { if err != nil { return nil, err } diffs = append(diffs, ds...) } if ds, err := dcl.Diff(desired.MaxRetryDuration, actual.MaxRetryDuration, dcl.DiffInfo{OperationSelector: dcl.TriggersOperation("updateJobUpdateJobOperation")}, fn.AddNest("MaxRetryDuration")); len(ds) != 0 || err != nil { if err != nil { return nil, err } diffs = append(diffs, ds...) } if ds, err := dcl.Diff(desired.MinBackoffDuration, actual.MinBackoffDuration, dcl.DiffInfo{OperationSelector: dcl.TriggersOperation("updateJobUpdateJobOperation")}, fn.AddNest("MinBackoffDuration")); len(ds) != 0 || err != nil { if err != nil { return nil, err } diffs = append(diffs, ds...) } if ds, err := dcl.Diff(desired.MaxBackoffDuration, actual.MaxBackoffDuration, dcl.DiffInfo{OperationSelector: dcl.TriggersOperation("updateJobUpdateJobOperation")}, fn.AddNest("MaxBackoffDuration")); len(ds) != 0 || err != nil { if err != nil { return nil, err } diffs = append(diffs, ds...) } if ds, err := dcl.Diff(desired.MaxDoublings, actual.MaxDoublings, dcl.DiffInfo{OperationSelector: dcl.TriggersOperation("updateJobUpdateJobOperation")}, fn.AddNest("MaxDoublings")); len(ds) != 0 || err != nil { if err != nil { return nil, err } diffs = append(diffs, ds...) } return diffs, nil } // urlNormalized returns a copy of the resource struct with values normalized // for URL substitutions. For instance, it converts long-form self-links to // short-form so they can be substituted in. func (r *Job) urlNormalized() *Job { normalized := dcl.Copy(*r).(Job) normalized.Name = dcl.SelfLinkToName(r.Name) normalized.Description = dcl.SelfLinkToName(r.Description) normalized.Schedule = dcl.SelfLinkToName(r.Schedule) normalized.TimeZone = dcl.SelfLinkToName(r.TimeZone) normalized.AttemptDeadline = dcl.SelfLinkToName(r.AttemptDeadline) normalized.Project = dcl.SelfLinkToName(r.Project) normalized.Location = dcl.SelfLinkToName(r.Location) return &normalized } func (r *Job) updateURL(userBasePath, updateName string) (string, error) { nr := r.urlNormalized() if updateName == "UpdateJob" { fields := map[string]interface{}{ "project": dcl.ValueOrEmptyString(nr.Project), "location": dcl.ValueOrEmptyString(nr.Location), "name": dcl.ValueOrEmptyString(nr.Name), } return dcl.URL("projects/{{project}}/locations/{{location}}/jobs/{{name}}", nr.basePath(), userBasePath, fields), nil } return "", fmt.Errorf("unknown update name: %s", updateName) } // marshal encodes the Job resource into JSON for a Create request, and // performs transformations from the resource schema to the API schema if // necessary. func (r *Job) marshal(c *Client) ([]byte, error) { m, err := expandJob(c, r) if err != nil { return nil, fmt.Errorf("error marshalling Job: %w", err) } return json.Marshal(m) } // unmarshalJob decodes JSON responses into the Job resource schema. func unmarshalJob(b []byte, c *Client, res *Job) (*Job, error) { var m map[string]interface{} if err := json.Unmarshal(b, &m); err != nil { return nil, err } return unmarshalMapJob(m, c, res) } func unmarshalMapJob(m map[string]interface{}, c *Client, res *Job) (*Job, error) { flattened := flattenJob(c, m, res) if flattened == nil { return nil, fmt.Errorf("attempted to flatten empty json object") } return flattened, nil } // expandJob expands Job into a JSON request object. func expandJob(c *Client, f *Job) (map[string]interface{}, error) { m := make(map[string]interface{}) res := f _ = res if v, err := dcl.DeriveField("projects/%s/locations/%s/jobs/%s", f.Name, dcl.SelfLinkToName(f.Project), dcl.SelfLinkToName(f.Location), dcl.SelfLinkToName(f.Name)); err != nil { return nil, fmt.Errorf("error expanding Name into name: %w", err) } else if !dcl.IsEmptyValueIndirect(v) { m["name"] = v } if v := f.Description; dcl.ValueShouldBeSent(v) { m["description"] = v } if v, err := expandJobPubsubTarget(c, f.PubsubTarget, res); err != nil { return nil, fmt.Errorf("error expanding PubsubTarget into pubsubTarget: %w", err) } else if !dcl.IsEmptyValueIndirect(v) { m["pubsubTarget"] = v } if v, err := expandJobAppEngineHttpTarget(c, f.AppEngineHttpTarget, res); err != nil { return nil, fmt.Errorf("error expanding AppEngineHttpTarget into appEngineHttpTarget: %w", err) } else if !dcl.IsEmptyValueIndirect(v) { m["appEngineHttpTarget"] = v } if v, err := expandJobHttpTarget(c, f.HttpTarget, res); err != nil { return nil, fmt.Errorf("error expanding HttpTarget into httpTarget: %w", err) } else if !dcl.IsEmptyValueIndirect(v) { m["httpTarget"] = v } if v := f.Schedule; dcl.ValueShouldBeSent(v) { m["schedule"] = v } if v := f.TimeZone; dcl.ValueShouldBeSent(v) { m["timeZone"] = v } if v, err := expandJobRetryConfig(c, f.RetryConfig, res); err != nil { return nil, fmt.Errorf("error expanding RetryConfig into retryConfig: %w", err) } else if !dcl.IsEmptyValueIndirect(v) { m["retryConfig"] = v } if v := f.AttemptDeadline; dcl.ValueShouldBeSent(v) { m["attemptDeadline"] = v } if v, err := dcl.EmptyValue(); err != nil { return nil, fmt.Errorf("error expanding Project into project: %w", err) } else if !dcl.IsEmptyValueIndirect(v) { m["project"] = v } if v, err := dcl.EmptyValue(); err != nil { return nil, fmt.Errorf("error expanding Location into location: %w", err) } else if !dcl.IsEmptyValueIndirect(v) { m["location"] = v } return m, nil } // flattenJob flattens Job from a JSON request object into the // Job type. func flattenJob(c *Client, i interface{}, res *Job) *Job { m, ok := i.(map[string]interface{}) if !ok { return nil } if len(m) == 0 { return nil } resultRes := &Job{} resultRes.Name = dcl.FlattenString(m["name"]) resultRes.Description = dcl.FlattenString(m["description"]) resultRes.PubsubTarget = flattenJobPubsubTarget(c, m["pubsubTarget"], res) resultRes.AppEngineHttpTarget = flattenJobAppEngineHttpTarget(c, m["appEngineHttpTarget"], res) resultRes.HttpTarget = flattenJobHttpTarget(c, m["httpTarget"], res) resultRes.Schedule = dcl.FlattenString(m["schedule"]) resultRes.TimeZone = dcl.FlattenString(m["timeZone"]) resultRes.UserUpdateTime = dcl.FlattenString(m["userUpdateTime"]) resultRes.State = flattenJobStateEnum(m["state"]) resultRes.Status = flattenJobStatus(c, m["status"], res) resultRes.ScheduleTime = dcl.FlattenString(m["scheduleTime"]) resultRes.LastAttemptTime = dcl.FlattenString(m["lastAttemptTime"]) resultRes.RetryConfig = flattenJobRetryConfig(c, m["retryConfig"], res) resultRes.AttemptDeadline = dcl.FlattenString(m["attemptDeadline"]) resultRes.Project = dcl.FlattenString(m["project"]) resultRes.Location = dcl.FlattenString(m["location"]) return resultRes } // expandJobPubsubTargetMap expands the contents of JobPubsubTarget into a JSON // request object. func expandJobPubsubTargetMap(c *Client, f map[string]JobPubsubTarget, res *Job) (map[string]interface{}, error) { if f == nil { return nil, nil } items := make(map[string]interface{}) for k, item := range f { i, err := expandJobPubsubTarget(c, &item, res) if err != nil { return nil, err } if i != nil { items[k] = i } } return items, nil } // expandJobPubsubTargetSlice expands the contents of JobPubsubTarget into a JSON // request object. func expandJobPubsubTargetSlice(c *Client, f []JobPubsubTarget, res *Job) ([]map[string]interface{}, error) { if f == nil { return nil, nil } items := []map[string]interface{}{} for _, item := range f { i, err := expandJobPubsubTarget(c, &item, res) if err != nil { return nil, err } items = append(items, i) } return items, nil } // flattenJobPubsubTargetMap flattens the contents of JobPubsubTarget from a JSON // response object. func flattenJobPubsubTargetMap(c *Client, i interface{}, res *Job) map[string]JobPubsubTarget { a, ok := i.(map[string]interface{}) if !ok { return map[string]JobPubsubTarget{} } if len(a) == 0 { return map[string]JobPubsubTarget{} } items := make(map[string]JobPubsubTarget) for k, item := range a { items[k] = *flattenJobPubsubTarget(c, item.(map[string]interface{}), res) } return items } // flattenJobPubsubTargetSlice flattens the contents of JobPubsubTarget from a JSON // response object. func flattenJobPubsubTargetSlice(c *Client, i interface{}, res *Job) []JobPubsubTarget { a, ok := i.([]interface{}) if !ok { return []JobPubsubTarget{} } if len(a) == 0 { return []JobPubsubTarget{} } items := make([]JobPubsubTarget, 0, len(a)) for _, item := range a { items = append(items, *flattenJobPubsubTarget(c, item.(map[string]interface{}), res)) } return items } // expandJobPubsubTarget expands an instance of JobPubsubTarget into a JSON // request object. func expandJobPubsubTarget(c *Client, f *JobPubsubTarget, res *Job) (map[string]interface{}, error) { if dcl.IsEmptyValueIndirect(f) { return nil, nil } m := make(map[string]interface{}) if v := f.TopicName; !dcl.IsEmptyValueIndirect(v) { m["topicName"] = v } if v := f.Data; !dcl.IsEmptyValueIndirect(v) { m["data"] = v } if v := f.Attributes; !dcl.IsEmptyValueIndirect(v) { m["attributes"] = v } return m, nil } // flattenJobPubsubTarget flattens an instance of JobPubsubTarget from a JSON // response object. func flattenJobPubsubTarget(c *Client, i interface{}, res *Job) *JobPubsubTarget { m, ok := i.(map[string]interface{}) if !ok { return nil } r := &JobPubsubTarget{} if dcl.IsEmptyValueIndirect(i) { return EmptyJobPubsubTarget } r.TopicName = dcl.FlattenString(m["topicName"]) r.Data = dcl.FlattenString(m["data"]) r.Attributes = dcl.FlattenKeyValuePairs(m["attributes"]) return r } // expandJobAppEngineHttpTargetMap expands the contents of JobAppEngineHttpTarget into a JSON // request object. func expandJobAppEngineHttpTargetMap(c *Client, f map[string]JobAppEngineHttpTarget, res *Job) (map[string]interface{}, error) { if f == nil { return nil, nil } items := make(map[string]interface{}) for k, item := range f { i, err := expandJobAppEngineHttpTarget(c, &item, res) if err != nil { return nil, err } if i != nil { items[k] = i } } return items, nil } // expandJobAppEngineHttpTargetSlice expands the contents of JobAppEngineHttpTarget into a JSON // request object. func expandJobAppEngineHttpTargetSlice(c *Client, f []JobAppEngineHttpTarget, res *Job) ([]map[string]interface{}, error) { if f == nil { return nil, nil } items := []map[string]interface{}{} for _, item := range f { i, err := expandJobAppEngineHttpTarget(c, &item, res) if err != nil { return nil, err } items = append(items, i) } return items, nil } // flattenJobAppEngineHttpTargetMap flattens the contents of JobAppEngineHttpTarget from a JSON // response object. func flattenJobAppEngineHttpTargetMap(c *Client, i interface{}, res *Job) map[string]JobAppEngineHttpTarget { a, ok := i.(map[string]interface{}) if !ok { return map[string]JobAppEngineHttpTarget{} } if len(a) == 0 { return map[string]JobAppEngineHttpTarget{} } items := make(map[string]JobAppEngineHttpTarget) for k, item := range a { items[k] = *flattenJobAppEngineHttpTarget(c, item.(map[string]interface{}), res) } return items } // flattenJobAppEngineHttpTargetSlice flattens the contents of JobAppEngineHttpTarget from a JSON // response object. func flattenJobAppEngineHttpTargetSlice(c *Client, i interface{}, res *Job) []JobAppEngineHttpTarget { a, ok := i.([]interface{}) if !ok { return []JobAppEngineHttpTarget{} } if len(a) == 0 { return []JobAppEngineHttpTarget{} } items := make([]JobAppEngineHttpTarget, 0, len(a)) for _, item := range a { items = append(items, *flattenJobAppEngineHttpTarget(c, item.(map[string]interface{}), res)) } return items } // expandJobAppEngineHttpTarget expands an instance of JobAppEngineHttpTarget into a JSON // request object. func expandJobAppEngineHttpTarget(c *Client, f *JobAppEngineHttpTarget, res *Job) (map[string]interface{}, error) { if dcl.IsEmptyValueIndirect(f) { return nil, nil } m := make(map[string]interface{}) if v := f.HttpMethod; !dcl.IsEmptyValueIndirect(v) { m["httpMethod"] = v } if v, err := expandJobAppEngineHttpTargetAppEngineRouting(c, f.AppEngineRouting, res); err != nil { return nil, fmt.Errorf("error expanding AppEngineRouting into appEngineRouting: %w", err) } else if !dcl.IsEmptyValueIndirect(v) { m["appEngineRouting"] = v } if v := f.RelativeUri; !dcl.IsEmptyValueIndirect(v) { m["relativeUri"] = v } if v := f.Headers; !dcl.IsEmptyValueIndirect(v) { m["headers"] = v } if v := f.Body; !dcl.IsEmptyValueIndirect(v) { m["body"] = v } return m, nil } // flattenJobAppEngineHttpTarget flattens an instance of JobAppEngineHttpTarget from a JSON // response object. func flattenJobAppEngineHttpTarget(c *Client, i interface{}, res *Job) *JobAppEngineHttpTarget { m, ok := i.(map[string]interface{}) if !ok { return nil } r := &JobAppEngineHttpTarget{} if dcl.IsEmptyValueIndirect(i) { return EmptyJobAppEngineHttpTarget } r.HttpMethod = flattenJobAppEngineHttpTargetHttpMethodEnum(m["httpMethod"]) r.AppEngineRouting = flattenJobAppEngineHttpTargetAppEngineRouting(c, m["appEngineRouting"], res) r.RelativeUri = dcl.FlattenString(m["relativeUri"]) r.Headers = dcl.FlattenKeyValuePairs(m["headers"]) r.Body = dcl.FlattenString(m["body"]) return r } // expandJobAppEngineHttpTargetAppEngineRoutingMap expands the contents of JobAppEngineHttpTargetAppEngineRouting into a JSON // request object. func expandJobAppEngineHttpTargetAppEngineRoutingMap(c *Client, f map[string]JobAppEngineHttpTargetAppEngineRouting, res *Job) (map[string]interface{}, error) { if f == nil { return nil, nil } items := make(map[string]interface{}) for k, item := range f { i, err := expandJobAppEngineHttpTargetAppEngineRouting(c, &item, res) if err != nil { return nil, err } if i != nil { items[k] = i } } return items, nil } // expandJobAppEngineHttpTargetAppEngineRoutingSlice expands the contents of JobAppEngineHttpTargetAppEngineRouting into a JSON // request object. func expandJobAppEngineHttpTargetAppEngineRoutingSlice(c *Client, f []JobAppEngineHttpTargetAppEngineRouting, res *Job) ([]map[string]interface{}, error) { if f == nil { return nil, nil } items := []map[string]interface{}{} for _, item := range f { i, err := expandJobAppEngineHttpTargetAppEngineRouting(c, &item, res) if err != nil { return nil, err } items = append(items, i) } return items, nil } // flattenJobAppEngineHttpTargetAppEngineRoutingMap flattens the contents of JobAppEngineHttpTargetAppEngineRouting from a JSON // response object. func flattenJobAppEngineHttpTargetAppEngineRoutingMap(c *Client, i interface{}, res *Job) map[string]JobAppEngineHttpTargetAppEngineRouting { a, ok := i.(map[string]interface{}) if !ok { return map[string]JobAppEngineHttpTargetAppEngineRouting{} } if len(a) == 0 { return map[string]JobAppEngineHttpTargetAppEngineRouting{} } items := make(map[string]JobAppEngineHttpTargetAppEngineRouting) for k, item := range a { items[k] = *flattenJobAppEngineHttpTargetAppEngineRouting(c, item.(map[string]interface{}), res) } return items } // flattenJobAppEngineHttpTargetAppEngineRoutingSlice flattens the contents of JobAppEngineHttpTargetAppEngineRouting from a JSON // response object. func flattenJobAppEngineHttpTargetAppEngineRoutingSlice(c *Client, i interface{}, res *Job) []JobAppEngineHttpTargetAppEngineRouting { a, ok := i.([]interface{}) if !ok { return []JobAppEngineHttpTargetAppEngineRouting{} } if len(a) == 0 { return []JobAppEngineHttpTargetAppEngineRouting{} } items := make([]JobAppEngineHttpTargetAppEngineRouting, 0, len(a)) for _, item := range a { items = append(items, *flattenJobAppEngineHttpTargetAppEngineRouting(c, item.(map[string]interface{}), res)) } return items } // expandJobAppEngineHttpTargetAppEngineRouting expands an instance of JobAppEngineHttpTargetAppEngineRouting into a JSON // request object. func expandJobAppEngineHttpTargetAppEngineRouting(c *Client, f *JobAppEngineHttpTargetAppEngineRouting, res *Job) (map[string]interface{}, error) { if dcl.IsEmptyValueIndirect(f) { return nil, nil } m := make(map[string]interface{}) if v := f.Service; !dcl.IsEmptyValueIndirect(v) { m["service"] = v } if v := f.Version; !dcl.IsEmptyValueIndirect(v) { m["version"] = v } if v := f.Instance; !dcl.IsEmptyValueIndirect(v) { m["instance"] = v } return m, nil } // flattenJobAppEngineHttpTargetAppEngineRouting flattens an instance of JobAppEngineHttpTargetAppEngineRouting from a JSON // response object. func flattenJobAppEngineHttpTargetAppEngineRouting(c *Client, i interface{}, res *Job) *JobAppEngineHttpTargetAppEngineRouting { m, ok := i.(map[string]interface{}) if !ok { return nil } r := &JobAppEngineHttpTargetAppEngineRouting{} if dcl.IsEmptyValueIndirect(i) { return EmptyJobAppEngineHttpTargetAppEngineRouting } r.Service = dcl.FlattenString(m["service"]) r.Version = dcl.FlattenString(m["version"]) r.Instance = dcl.FlattenString(m["instance"]) r.Host = dcl.FlattenString(m["host"]) return r } // expandJobHttpTargetMap expands the contents of JobHttpTarget into a JSON // request object. func expandJobHttpTargetMap(c *Client, f map[string]JobHttpTarget, res *Job) (map[string]interface{}, error) { if f == nil { return nil, nil } items := make(map[string]interface{}) for k, item := range f { i, err := expandJobHttpTarget(c, &item, res) if err != nil { return nil, err } if i != nil { items[k] = i } } return items, nil } // expandJobHttpTargetSlice expands the contents of JobHttpTarget into a JSON // request object. func expandJobHttpTargetSlice(c *Client, f []JobHttpTarget, res *Job) ([]map[string]interface{}, error) { if f == nil { return nil, nil } items := []map[string]interface{}{} for _, item := range f { i, err := expandJobHttpTarget(c, &item, res) if err != nil { return nil, err } items = append(items, i) } return items, nil } // flattenJobHttpTargetMap flattens the contents of JobHttpTarget from a JSON // response object. func flattenJobHttpTargetMap(c *Client, i interface{}, res *Job) map[string]JobHttpTarget { a, ok := i.(map[string]interface{}) if !ok { return map[string]JobHttpTarget{} } if len(a) == 0 { return map[string]JobHttpTarget{} } items := make(map[string]JobHttpTarget) for k, item := range a { items[k] = *flattenJobHttpTarget(c, item.(map[string]interface{}), res) } return items } // flattenJobHttpTargetSlice flattens the contents of JobHttpTarget from a JSON // response object. func flattenJobHttpTargetSlice(c *Client, i interface{}, res *Job) []JobHttpTarget { a, ok := i.([]interface{}) if !ok { return []JobHttpTarget{} } if len(a) == 0 { return []JobHttpTarget{} } items := make([]JobHttpTarget, 0, len(a)) for _, item := range a { items = append(items, *flattenJobHttpTarget(c, item.(map[string]interface{}), res)) } return items } // expandJobHttpTarget expands an instance of JobHttpTarget into a JSON // request object. func expandJobHttpTarget(c *Client, f *JobHttpTarget, res *Job) (map[string]interface{}, error) { if dcl.IsEmptyValueIndirect(f) { return nil, nil } m := make(map[string]interface{}) if v := f.Uri; !dcl.IsEmptyValueIndirect(v) { m["uri"] = v } if v := f.HttpMethod; !dcl.IsEmptyValueIndirect(v) { m["httpMethod"] = v } if v := f.Headers; !dcl.IsEmptyValueIndirect(v) { m["headers"] = v } if v := f.Body; !dcl.IsEmptyValueIndirect(v) { m["body"] = v } if v, err := expandJobHttpTargetOAuthToken(c, f.OAuthToken, res); err != nil { return nil, fmt.Errorf("error expanding OAuthToken into oauthToken: %w", err) } else if !dcl.IsEmptyValueIndirect(v) { m["oauthToken"] = v } if v, err := expandJobHttpTargetOidcToken(c, f.OidcToken, res); err != nil { return nil, fmt.Errorf("error expanding OidcToken into oidcToken: %w", err) } else if !dcl.IsEmptyValueIndirect(v) { m["oidcToken"] = v } return m, nil } // flattenJobHttpTarget flattens an instance of JobHttpTarget from a JSON // response object. func flattenJobHttpTarget(c *Client, i interface{}, res *Job) *JobHttpTarget { m, ok := i.(map[string]interface{}) if !ok { return nil } r := &JobHttpTarget{} if dcl.IsEmptyValueIndirect(i) { return EmptyJobHttpTarget } r.Uri = dcl.FlattenString(m["uri"]) r.HttpMethod = flattenJobHttpTargetHttpMethodEnum(m["httpMethod"]) r.Headers = dcl.FlattenKeyValuePairs(m["headers"]) r.Body = dcl.FlattenString(m["body"]) r.OAuthToken = flattenJobHttpTargetOAuthToken(c, m["oauthToken"], res) r.OidcToken = flattenJobHttpTargetOidcToken(c, m["oidcToken"], res) return r } // expandJobHttpTargetOAuthTokenMap expands the contents of JobHttpTargetOAuthToken into a JSON // request object. func expandJobHttpTargetOAuthTokenMap(c *Client, f map[string]JobHttpTargetOAuthToken, res *Job) (map[string]interface{}, error) { if f == nil { return nil, nil } items := make(map[string]interface{}) for k, item := range f { i, err := expandJobHttpTargetOAuthToken(c, &item, res) if err != nil { return nil, err } if i != nil { items[k] = i } } return items, nil } // expandJobHttpTargetOAuthTokenSlice expands the contents of JobHttpTargetOAuthToken into a JSON // request object. func expandJobHttpTargetOAuthTokenSlice(c *Client, f []JobHttpTargetOAuthToken, res *Job) ([]map[string]interface{}, error) { if f == nil { return nil, nil } items := []map[string]interface{}{} for _, item := range f { i, err := expandJobHttpTargetOAuthToken(c, &item, res) if err != nil { return nil, err } items = append(items, i) } return items, nil } // flattenJobHttpTargetOAuthTokenMap flattens the contents of JobHttpTargetOAuthToken from a JSON // response object. func flattenJobHttpTargetOAuthTokenMap(c *Client, i interface{}, res *Job) map[string]JobHttpTargetOAuthToken { a, ok := i.(map[string]interface{}) if !ok { return map[string]JobHttpTargetOAuthToken{} } if len(a) == 0 { return map[string]JobHttpTargetOAuthToken{} } items := make(map[string]JobHttpTargetOAuthToken) for k, item := range a { items[k] = *flattenJobHttpTargetOAuthToken(c, item.(map[string]interface{}), res) } return items } // flattenJobHttpTargetOAuthTokenSlice flattens the contents of JobHttpTargetOAuthToken from a JSON // response object. func flattenJobHttpTargetOAuthTokenSlice(c *Client, i interface{}, res *Job) []JobHttpTargetOAuthToken { a, ok := i.([]interface{}) if !ok { return []JobHttpTargetOAuthToken{} } if len(a) == 0 { return []JobHttpTargetOAuthToken{} } items := make([]JobHttpTargetOAuthToken, 0, len(a)) for _, item := range a { items = append(items, *flattenJobHttpTargetOAuthToken(c, item.(map[string]interface{}), res)) } return items } // expandJobHttpTargetOAuthToken expands an instance of JobHttpTargetOAuthToken into a JSON // request object. func expandJobHttpTargetOAuthToken(c *Client, f *JobHttpTargetOAuthToken, res *Job) (map[string]interface{}, error) { if dcl.IsEmptyValueIndirect(f) { return nil, nil } m := make(map[string]interface{}) if v := f.ServiceAccountEmail; !dcl.IsEmptyValueIndirect(v) { m["serviceAccountEmail"] = v } if v := f.Scope; !dcl.IsEmptyValueIndirect(v) { m["scope"] = v } return m, nil } // flattenJobHttpTargetOAuthToken flattens an instance of JobHttpTargetOAuthToken from a JSON // response object. func flattenJobHttpTargetOAuthToken(c *Client, i interface{}, res *Job) *JobHttpTargetOAuthToken { m, ok := i.(map[string]interface{}) if !ok { return nil } r := &JobHttpTargetOAuthToken{} if dcl.IsEmptyValueIndirect(i) { return EmptyJobHttpTargetOAuthToken } r.ServiceAccountEmail = dcl.FlattenString(m["serviceAccountEmail"]) r.Scope = dcl.FlattenString(m["scope"]) return r } // expandJobHttpTargetOidcTokenMap expands the contents of JobHttpTargetOidcToken into a JSON // request object. func expandJobHttpTargetOidcTokenMap(c *Client, f map[string]JobHttpTargetOidcToken, res *Job) (map[string]interface{}, error) { if f == nil { return nil, nil } items := make(map[string]interface{}) for k, item := range f { i, err := expandJobHttpTargetOidcToken(c, &item, res) if err != nil { return nil, err } if i != nil { items[k] = i } } return items, nil } // expandJobHttpTargetOidcTokenSlice expands the contents of JobHttpTargetOidcToken into a JSON // request object. func expandJobHttpTargetOidcTokenSlice(c *Client, f []JobHttpTargetOidcToken, res *Job) ([]map[string]interface{}, error) { if f == nil { return nil, nil } items := []map[string]interface{}{} for _, item := range f { i, err := expandJobHttpTargetOidcToken(c, &item, res) if err != nil { return nil, err } items = append(items, i) } return items, nil } // flattenJobHttpTargetOidcTokenMap flattens the contents of JobHttpTargetOidcToken from a JSON // response object. func flattenJobHttpTargetOidcTokenMap(c *Client, i interface{}, res *Job) map[string]JobHttpTargetOidcToken { a, ok := i.(map[string]interface{}) if !ok { return map[string]JobHttpTargetOidcToken{} } if len(a) == 0 { return map[string]JobHttpTargetOidcToken{} } items := make(map[string]JobHttpTargetOidcToken) for k, item := range a { items[k] = *flattenJobHttpTargetOidcToken(c, item.(map[string]interface{}), res) } return items } // flattenJobHttpTargetOidcTokenSlice flattens the contents of JobHttpTargetOidcToken from a JSON // response object. func flattenJobHttpTargetOidcTokenSlice(c *Client, i interface{}, res *Job) []JobHttpTargetOidcToken { a, ok := i.([]interface{}) if !ok { return []JobHttpTargetOidcToken{} } if len(a) == 0 { return []JobHttpTargetOidcToken{} } items := make([]JobHttpTargetOidcToken, 0, len(a)) for _, item := range a { items = append(items, *flattenJobHttpTargetOidcToken(c, item.(map[string]interface{}), res)) } return items } // expandJobHttpTargetOidcToken expands an instance of JobHttpTargetOidcToken into a JSON // request object. func expandJobHttpTargetOidcToken(c *Client, f *JobHttpTargetOidcToken, res *Job) (map[string]interface{}, error) { if dcl.IsEmptyValueIndirect(f) { return nil, nil } m := make(map[string]interface{}) if v := f.ServiceAccountEmail; !dcl.IsEmptyValueIndirect(v) { m["serviceAccountEmail"] = v } if v := f.Audience; !dcl.IsEmptyValueIndirect(v) { m["audience"] = v } return m, nil } // flattenJobHttpTargetOidcToken flattens an instance of JobHttpTargetOidcToken from a JSON // response object. func flattenJobHttpTargetOidcToken(c *Client, i interface{}, res *Job) *JobHttpTargetOidcToken { m, ok := i.(map[string]interface{}) if !ok { return nil } r := &JobHttpTargetOidcToken{} if dcl.IsEmptyValueIndirect(i) { return EmptyJobHttpTargetOidcToken } r.ServiceAccountEmail = dcl.FlattenString(m["serviceAccountEmail"]) r.Audience = dcl.FlattenString(m["audience"]) return r } // expandJobStatusMap expands the contents of JobStatus into a JSON // request object. func expandJobStatusMap(c *Client, f map[string]JobStatus, res *Job) (map[string]interface{}, error) { if f == nil { return nil, nil } items := make(map[string]interface{}) for k, item := range f { i, err := expandJobStatus(c, &item, res) if err != nil { return nil, err } if i != nil { items[k] = i } } return items, nil } // expandJobStatusSlice expands the contents of JobStatus into a JSON // request object. func expandJobStatusSlice(c *Client, f []JobStatus, res *Job) ([]map[string]interface{}, error) { if f == nil { return nil, nil } items := []map[string]interface{}{} for _, item := range f { i, err := expandJobStatus(c, &item, res) if err != nil { return nil, err } items = append(items, i) } return items, nil } // flattenJobStatusMap flattens the contents of JobStatus from a JSON // response object. func flattenJobStatusMap(c *Client, i interface{}, res *Job) map[string]JobStatus { a, ok := i.(map[string]interface{}) if !ok { return map[string]JobStatus{} } if len(a) == 0 { return map[string]JobStatus{} } items := make(map[string]JobStatus) for k, item := range a { items[k] = *flattenJobStatus(c, item.(map[string]interface{}), res) } return items } // flattenJobStatusSlice flattens the contents of JobStatus from a JSON // response object. func flattenJobStatusSlice(c *Client, i interface{}, res *Job) []JobStatus { a, ok := i.([]interface{}) if !ok { return []JobStatus{} } if len(a) == 0 { return []JobStatus{} } items := make([]JobStatus, 0, len(a)) for _, item := range a { items = append(items, *flattenJobStatus(c, item.(map[string]interface{}), res)) } return items } // expandJobStatus expands an instance of JobStatus into a JSON // request object. func expandJobStatus(c *Client, f *JobStatus, res *Job) (map[string]interface{}, error) { if dcl.IsEmptyValueIndirect(f) { return nil, nil } m := make(map[string]interface{}) if v := f.Code; !dcl.IsEmptyValueIndirect(v) { m["code"] = v } if v := f.Message; !dcl.IsEmptyValueIndirect(v) { m["message"] = v } if v, err := expandJobStatusDetailsSlice(c, f.Details, res); err != nil { return nil, fmt.Errorf("error expanding Details into details: %w", err) } else if v != nil { m["details"] = v } return m, nil } // flattenJobStatus flattens an instance of JobStatus from a JSON // response object. func flattenJobStatus(c *Client, i interface{}, res *Job) *JobStatus { m, ok := i.(map[string]interface{}) if !ok { return nil } r := &JobStatus{} if dcl.IsEmptyValueIndirect(i) { return EmptyJobStatus } r.Code = dcl.FlattenInteger(m["code"]) r.Message = dcl.FlattenString(m["message"]) r.Details = flattenJobStatusDetailsSlice(c, m["details"], res) return r } // expandJobStatusDetailsMap expands the contents of JobStatusDetails into a JSON // request object. func expandJobStatusDetailsMap(c *Client, f map[string]JobStatusDetails, res *Job) (map[string]interface{}, error) { if f == nil { return nil, nil } items := make(map[string]interface{}) for k, item := range f { i, err := expandJobStatusDetails(c, &item, res) if err != nil { return nil, err } if i != nil { items[k] = i } } return items, nil } // expandJobStatusDetailsSlice expands the contents of JobStatusDetails into a JSON // request object. func expandJobStatusDetailsSlice(c *Client, f []JobStatusDetails, res *Job) ([]map[string]interface{}, error) { if f == nil { return nil, nil } items := []map[string]interface{}{} for _, item := range f { i, err := expandJobStatusDetails(c, &item, res) if err != nil { return nil, err } items = append(items, i) } return items, nil } // flattenJobStatusDetailsMap flattens the contents of JobStatusDetails from a JSON // response object. func flattenJobStatusDetailsMap(c *Client, i interface{}, res *Job) map[string]JobStatusDetails { a, ok := i.(map[string]interface{}) if !ok { return map[string]JobStatusDetails{} } if len(a) == 0 { return map[string]JobStatusDetails{} } items := make(map[string]JobStatusDetails) for k, item := range a { items[k] = *flattenJobStatusDetails(c, item.(map[string]interface{}), res) } return items } // flattenJobStatusDetailsSlice flattens the contents of JobStatusDetails from a JSON // response object. func flattenJobStatusDetailsSlice(c *Client, i interface{}, res *Job) []JobStatusDetails { a, ok := i.([]interface{}) if !ok { return []JobStatusDetails{} } if len(a) == 0 { return []JobStatusDetails{} } items := make([]JobStatusDetails, 0, len(a)) for _, item := range a { items = append(items, *flattenJobStatusDetails(c, item.(map[string]interface{}), res)) } return items } // expandJobStatusDetails expands an instance of JobStatusDetails into a JSON // request object. func expandJobStatusDetails(c *Client, f *JobStatusDetails, res *Job) (map[string]interface{}, error) { if f == nil { return nil, nil } m := make(map[string]interface{}) if v := f.TypeUrl; !dcl.IsEmptyValueIndirect(v) { m["typeUrl"] = v } if v := f.Value; !dcl.IsEmptyValueIndirect(v) { m["value"] = v } return m, nil } // flattenJobStatusDetails flattens an instance of JobStatusDetails from a JSON // response object. func flattenJobStatusDetails(c *Client, i interface{}, res *Job) *JobStatusDetails { m, ok := i.(map[string]interface{}) if !ok { return nil } r := &JobStatusDetails{} if dcl.IsEmptyValueIndirect(i) { return EmptyJobStatusDetails } r.TypeUrl = dcl.FlattenString(m["typeUrl"]) r.Value = dcl.FlattenString(m["value"]) return r } // expandJobRetryConfigMap expands the contents of JobRetryConfig into a JSON // request object. func expandJobRetryConfigMap(c *Client, f map[string]JobRetryConfig, res *Job) (map[string]interface{}, error) { if f == nil { return nil, nil } items := make(map[string]interface{}) for k, item := range f { i, err := expandJobRetryConfig(c, &item, res) if err != nil { return nil, err } if i != nil { items[k] = i } } return items, nil } // expandJobRetryConfigSlice expands the contents of JobRetryConfig into a JSON // request object. func expandJobRetryConfigSlice(c *Client, f []JobRetryConfig, res *Job) ([]map[string]interface{}, error) { if f == nil { return nil, nil } items := []map[string]interface{}{} for _, item := range f { i, err := expandJobRetryConfig(c, &item, res) if err != nil { return nil, err } items = append(items, i) } return items, nil } // flattenJobRetryConfigMap flattens the contents of JobRetryConfig from a JSON // response object. func flattenJobRetryConfigMap(c *Client, i interface{}, res *Job) map[string]JobRetryConfig { a, ok := i.(map[string]interface{}) if !ok { return map[string]JobRetryConfig{} } if len(a) == 0 { return map[string]JobRetryConfig{} } items := make(map[string]JobRetryConfig) for k, item := range a { items[k] = *flattenJobRetryConfig(c, item.(map[string]interface{}), res) } return items } // flattenJobRetryConfigSlice flattens the contents of JobRetryConfig from a JSON // response object. func flattenJobRetryConfigSlice(c *Client, i interface{}, res *Job) []JobRetryConfig { a, ok := i.([]interface{}) if !ok { return []JobRetryConfig{} } if len(a) == 0 { return []JobRetryConfig{} } items := make([]JobRetryConfig, 0, len(a)) for _, item := range a { items = append(items, *flattenJobRetryConfig(c, item.(map[string]interface{}), res)) } return items } // expandJobRetryConfig expands an instance of JobRetryConfig into a JSON // request object. func expandJobRetryConfig(c *Client, f *JobRetryConfig, res *Job) (map[string]interface{}, error) { if dcl.IsEmptyValueIndirect(f) { return nil, nil } m := make(map[string]interface{}) if v := f.RetryCount; !dcl.IsEmptyValueIndirect(v) { m["retryCount"] = v } if v := f.MaxRetryDuration; !dcl.IsEmptyValueIndirect(v) { m["maxRetryDuration"] = v } if v := f.MinBackoffDuration; !dcl.IsEmptyValueIndirect(v) { m["minBackoffDuration"] = v } if v := f.MaxBackoffDuration; !dcl.IsEmptyValueIndirect(v) { m["maxBackoffDuration"] = v } if v := f.MaxDoublings; !dcl.IsEmptyValueIndirect(v) { m["maxDoublings"] = v } return m, nil } // flattenJobRetryConfig flattens an instance of JobRetryConfig from a JSON // response object. func flattenJobRetryConfig(c *Client, i interface{}, res *Job) *JobRetryConfig { m, ok := i.(map[string]interface{}) if !ok { return nil } r := &JobRetryConfig{} if dcl.IsEmptyValueIndirect(i) { return EmptyJobRetryConfig } r.RetryCount = dcl.FlattenInteger(m["retryCount"]) r.MaxRetryDuration = dcl.FlattenString(m["maxRetryDuration"]) r.MinBackoffDuration = dcl.FlattenString(m["minBackoffDuration"]) r.MaxBackoffDuration = dcl.FlattenString(m["maxBackoffDuration"]) r.MaxDoublings = dcl.FlattenInteger(m["maxDoublings"]) return r } // flattenJobAppEngineHttpTargetHttpMethodEnumMap flattens the contents of JobAppEngineHttpTargetHttpMethodEnum from a JSON // response object. func flattenJobAppEngineHttpTargetHttpMethodEnumMap(c *Client, i interface{}, res *Job) map[string]JobAppEngineHttpTargetHttpMethodEnum { a, ok := i.(map[string]interface{}) if !ok { return map[string]JobAppEngineHttpTargetHttpMethodEnum{} } if len(a) == 0 { return map[string]JobAppEngineHttpTargetHttpMethodEnum{} } items := make(map[string]JobAppEngineHttpTargetHttpMethodEnum) for k, item := range a { items[k] = *flattenJobAppEngineHttpTargetHttpMethodEnum(item.(interface{})) } return items } // flattenJobAppEngineHttpTargetHttpMethodEnumSlice flattens the contents of JobAppEngineHttpTargetHttpMethodEnum from a JSON // response object. func flattenJobAppEngineHttpTargetHttpMethodEnumSlice(c *Client, i interface{}, res *Job) []JobAppEngineHttpTargetHttpMethodEnum { a, ok := i.([]interface{}) if !ok { return []JobAppEngineHttpTargetHttpMethodEnum{} } if len(a) == 0 { return []JobAppEngineHttpTargetHttpMethodEnum{} } items := make([]JobAppEngineHttpTargetHttpMethodEnum, 0, len(a)) for _, item := range a { items = append(items, *flattenJobAppEngineHttpTargetHttpMethodEnum(item.(interface{}))) } return items } // flattenJobAppEngineHttpTargetHttpMethodEnum asserts that an interface is a string, and returns a // pointer to a *JobAppEngineHttpTargetHttpMethodEnum with the same value as that string. func flattenJobAppEngineHttpTargetHttpMethodEnum(i interface{}) *JobAppEngineHttpTargetHttpMethodEnum { s, ok := i.(string) if !ok { return nil } return JobAppEngineHttpTargetHttpMethodEnumRef(s) } // flattenJobHttpTargetHttpMethodEnumMap flattens the contents of JobHttpTargetHttpMethodEnum from a JSON // response object. func flattenJobHttpTargetHttpMethodEnumMap(c *Client, i interface{}, res *Job) map[string]JobHttpTargetHttpMethodEnum { a, ok := i.(map[string]interface{}) if !ok { return map[string]JobHttpTargetHttpMethodEnum{} } if len(a) == 0 { return map[string]JobHttpTargetHttpMethodEnum{} } items := make(map[string]JobHttpTargetHttpMethodEnum) for k, item := range a { items[k] = *flattenJobHttpTargetHttpMethodEnum(item.(interface{})) } return items } // flattenJobHttpTargetHttpMethodEnumSlice flattens the contents of JobHttpTargetHttpMethodEnum from a JSON // response object. func flattenJobHttpTargetHttpMethodEnumSlice(c *Client, i interface{}, res *Job) []JobHttpTargetHttpMethodEnum { a, ok := i.([]interface{}) if !ok { return []JobHttpTargetHttpMethodEnum{} } if len(a) == 0 { return []JobHttpTargetHttpMethodEnum{} } items := make([]JobHttpTargetHttpMethodEnum, 0, len(a)) for _, item := range a { items = append(items, *flattenJobHttpTargetHttpMethodEnum(item.(interface{}))) } return items } // flattenJobHttpTargetHttpMethodEnum asserts that an interface is a string, and returns a // pointer to a *JobHttpTargetHttpMethodEnum with the same value as that string. func flattenJobHttpTargetHttpMethodEnum(i interface{}) *JobHttpTargetHttpMethodEnum { s, ok := i.(string) if !ok { return nil } return JobHttpTargetHttpMethodEnumRef(s) } // flattenJobStateEnumMap flattens the contents of JobStateEnum from a JSON // response object. func flattenJobStateEnumMap(c *Client, i interface{}, res *Job) map[string]JobStateEnum { a, ok := i.(map[string]interface{}) if !ok { return map[string]JobStateEnum{} } if len(a) == 0 { return map[string]JobStateEnum{} } items := make(map[string]JobStateEnum) for k, item := range a { items[k] = *flattenJobStateEnum(item.(interface{})) } return items } // flattenJobStateEnumSlice flattens the contents of JobStateEnum from a JSON // response object. func flattenJobStateEnumSlice(c *Client, i interface{}, res *Job) []JobStateEnum { a, ok := i.([]interface{}) if !ok { return []JobStateEnum{} } if len(a) == 0 { return []JobStateEnum{} } items := make([]JobStateEnum, 0, len(a)) for _, item := range a { items = append(items, *flattenJobStateEnum(item.(interface{}))) } return items } // flattenJobStateEnum asserts that an interface is a string, and returns a // pointer to a *JobStateEnum with the same value as that string. func flattenJobStateEnum(i interface{}) *JobStateEnum { s, ok := i.(string) if !ok { return nil } return JobStateEnumRef(s) } // This function returns a matcher that checks whether a serialized resource matches this resource // in its parameters (as defined by the fields in a Get, which definitionally define resource // identity). This is useful in extracting the element from a List call. func (r *Job) matcher(c *Client) func([]byte) bool { return func(b []byte) bool { cr, err := unmarshalJob(b, c, r) if err != nil { c.Config.Logger.Warning("failed to unmarshal provided resource in matcher.") return false } nr := r.urlNormalized() ncr := cr.urlNormalized() c.Config.Logger.Infof("looking for %v\nin %v", nr, ncr) if nr.Project == nil && ncr.Project == nil { c.Config.Logger.Info("Both Project fields null - considering equal.") } else if nr.Project == nil || ncr.Project == nil { c.Config.Logger.Info("Only one Project field is null - considering unequal.") return false } else if *nr.Project != *ncr.Project { return false } if nr.Location == nil && ncr.Location == nil { c.Config.Logger.Info("Both Location fields null - considering equal.") } else if nr.Location == nil || ncr.Location == nil { c.Config.Logger.Info("Only one Location field is null - considering unequal.") return false } else if *nr.Location != *ncr.Location { return false } if nr.Name == nil && ncr.Name == nil { c.Config.Logger.Info("Both Name fields null - considering equal.") } else if nr.Name == nil || ncr.Name == nil { c.Config.Logger.Info("Only one Name field is null - considering unequal.") return false } else if *nr.Name != *ncr.Name { return false } return true } } type jobDiff struct { // The diff should include one or the other of RequiresRecreate or UpdateOp. RequiresRecreate bool UpdateOp jobApiOperation FieldName string // used for error logging } func convertFieldDiffsToJobDiffs(config *dcl.Config, fds []*dcl.FieldDiff, opts []dcl.ApplyOption) ([]jobDiff, error) { opNamesToFieldDiffs := make(map[string][]*dcl.FieldDiff) // Map each operation name to the field diffs associated with it. for _, fd := range fds { for _, ro := range fd.ResultingOperation { if fieldDiffs, ok := opNamesToFieldDiffs[ro]; ok { fieldDiffs = append(fieldDiffs, fd) opNamesToFieldDiffs[ro] = fieldDiffs } else { config.Logger.Infof("%s required due to diff: %v", ro, fd) opNamesToFieldDiffs[ro] = []*dcl.FieldDiff{fd} } } } var diffs []jobDiff // For each operation name, create a jobDiff which contains the operation. for opName, fieldDiffs := range opNamesToFieldDiffs { // Use the first field diff's field name for logging required recreate error. diff := jobDiff{FieldName: fieldDiffs[0].FieldName} if opName == "Recreate" { diff.RequiresRecreate = true } else { apiOp, err := convertOpNameToJobApiOperation(opName, fieldDiffs, opts...) if err != nil { return diffs, err } diff.UpdateOp = apiOp } diffs = append(diffs, diff) } return diffs, nil } func convertOpNameToJobApiOperation(opName string, fieldDiffs []*dcl.FieldDiff, opts ...dcl.ApplyOption) (jobApiOperation, error) { switch opName { case "updateJobUpdateJobOperation": return &updateJobUpdateJobOperation{FieldDiffs: fieldDiffs}, nil default: return nil, fmt.Errorf("no such operation with name: %v", opName) } } func extractJobFields(r *Job) error { vPubsubTarget := r.PubsubTarget if vPubsubTarget == nil { // note: explicitly not the empty object. vPubsubTarget = &JobPubsubTarget{} } if err := extractJobPubsubTargetFields(r, vPubsubTarget); err != nil { return err } if !dcl.IsEmptyValueIndirect(vPubsubTarget) { r.PubsubTarget = vPubsubTarget } vAppEngineHttpTarget := r.AppEngineHttpTarget if vAppEngineHttpTarget == nil { // note: explicitly not the empty object. vAppEngineHttpTarget = &JobAppEngineHttpTarget{} } if err := extractJobAppEngineHttpTargetFields(r, vAppEngineHttpTarget); err != nil { return err } if !dcl.IsEmptyValueIndirect(vAppEngineHttpTarget) { r.AppEngineHttpTarget = vAppEngineHttpTarget } vHttpTarget := r.HttpTarget if vHttpTarget == nil { // note: explicitly not the empty object. vHttpTarget = &JobHttpTarget{} } if err := extractJobHttpTargetFields(r, vHttpTarget); err != nil { return err } if !dcl.IsEmptyValueIndirect(vHttpTarget) { r.HttpTarget = vHttpTarget } vStatus := r.Status if vStatus == nil { // note: explicitly not the empty object. vStatus = &JobStatus{} } if err := extractJobStatusFields(r, vStatus); err != nil { return err } if !dcl.IsEmptyValueIndirect(vStatus) { r.Status = vStatus } vRetryConfig := r.RetryConfig if vRetryConfig == nil { // note: explicitly not the empty object. vRetryConfig = &JobRetryConfig{} } if err := extractJobRetryConfigFields(r, vRetryConfig); err != nil { return err } if !dcl.IsEmptyValueIndirect(vRetryConfig) { r.RetryConfig = vRetryConfig } return nil } func extractJobPubsubTargetFields(r *Job, o *JobPubsubTarget) error { return nil } func extractJobAppEngineHttpTargetFields(r *Job, o *JobAppEngineHttpTarget) error { vAppEngineRouting := o.AppEngineRouting if vAppEngineRouting == nil { // note: explicitly not the empty object. vAppEngineRouting = &JobAppEngineHttpTargetAppEngineRouting{} } if err := extractJobAppEngineHttpTargetAppEngineRoutingFields(r, vAppEngineRouting); err != nil { return err } if !dcl.IsEmptyValueIndirect(vAppEngineRouting) { o.AppEngineRouting = vAppEngineRouting } return nil } func extractJobAppEngineHttpTargetAppEngineRoutingFields(r *Job, o *JobAppEngineHttpTargetAppEngineRouting) error { return nil } func extractJobHttpTargetFields(r *Job, o *JobHttpTarget) error { vOAuthToken := o.OAuthToken if vOAuthToken == nil { // note: explicitly not the empty object. vOAuthToken = &JobHttpTargetOAuthToken{} } if err := extractJobHttpTargetOAuthTokenFields(r, vOAuthToken); err != nil { return err } if !dcl.IsEmptyValueIndirect(vOAuthToken) { o.OAuthToken = vOAuthToken } vOidcToken := o.OidcToken if vOidcToken == nil { // note: explicitly not the empty object. vOidcToken = &JobHttpTargetOidcToken{} } if err := extractJobHttpTargetOidcTokenFields(r, vOidcToken); err != nil { return err } if !dcl.IsEmptyValueIndirect(vOidcToken) { o.OidcToken = vOidcToken } return nil } func extractJobHttpTargetOAuthTokenFields(r *Job, o *JobHttpTargetOAuthToken) error { return nil } func extractJobHttpTargetOidcTokenFields(r *Job, o *JobHttpTargetOidcToken) error { return nil } func extractJobStatusFields(r *Job, o *JobStatus) error { return nil } func extractJobStatusDetailsFields(r *Job, o *JobStatusDetails) error { return nil } func extractJobRetryConfigFields(r *Job, o *JobRetryConfig) error { return nil } func postReadExtractJobFields(r *Job) error { vPubsubTarget := r.PubsubTarget if vPubsubTarget == nil { // note: explicitly not the empty object. vPubsubTarget = &JobPubsubTarget{} } if err := postReadExtractJobPubsubTargetFields(r, vPubsubTarget); err != nil { return err } if !dcl.IsEmptyValueIndirect(vPubsubTarget) { r.PubsubTarget = vPubsubTarget } vAppEngineHttpTarget := r.AppEngineHttpTarget if vAppEngineHttpTarget == nil { // note: explicitly not the empty object. vAppEngineHttpTarget = &JobAppEngineHttpTarget{} } if err := postReadExtractJobAppEngineHttpTargetFields(r, vAppEngineHttpTarget); err != nil { return err } if !dcl.IsEmptyValueIndirect(vAppEngineHttpTarget) { r.AppEngineHttpTarget = vAppEngineHttpTarget } vHttpTarget := r.HttpTarget if vHttpTarget == nil { // note: explicitly not the empty object. vHttpTarget = &JobHttpTarget{} } if err := postReadExtractJobHttpTargetFields(r, vHttpTarget); err != nil { return err } if !dcl.IsEmptyValueIndirect(vHttpTarget) { r.HttpTarget = vHttpTarget } vStatus := r.Status if vStatus == nil { // note: explicitly not the empty object. vStatus = &JobStatus{} } if err := postReadExtractJobStatusFields(r, vStatus); err != nil { return err } if !dcl.IsEmptyValueIndirect(vStatus) { r.Status = vStatus } vRetryConfig := r.RetryConfig if vRetryConfig == nil { // note: explicitly not the empty object. vRetryConfig = &JobRetryConfig{} } if err := postReadExtractJobRetryConfigFields(r, vRetryConfig); err != nil { return err } if !dcl.IsEmptyValueIndirect(vRetryConfig) { r.RetryConfig = vRetryConfig } return nil } func postReadExtractJobPubsubTargetFields(r *Job, o *JobPubsubTarget) error { return nil } func postReadExtractJobAppEngineHttpTargetFields(r *Job, o *JobAppEngineHttpTarget) error { vAppEngineRouting := o.AppEngineRouting if vAppEngineRouting == nil { // note: explicitly not the empty object. vAppEngineRouting = &JobAppEngineHttpTargetAppEngineRouting{} } if err := extractJobAppEngineHttpTargetAppEngineRoutingFields(r, vAppEngineRouting); err != nil { return err } if !dcl.IsEmptyValueIndirect(vAppEngineRouting) { o.AppEngineRouting = vAppEngineRouting } return nil } func postReadExtractJobAppEngineHttpTargetAppEngineRoutingFields(r *Job, o *JobAppEngineHttpTargetAppEngineRouting) error { return nil } func postReadExtractJobHttpTargetFields(r *Job, o *JobHttpTarget) error { vOAuthToken := o.OAuthToken if vOAuthToken == nil { // note: explicitly not the empty object. vOAuthToken = &JobHttpTargetOAuthToken{} } if err := extractJobHttpTargetOAuthTokenFields(r, vOAuthToken); err != nil { return err } if !dcl.IsEmptyValueIndirect(vOAuthToken) { o.OAuthToken = vOAuthToken } vOidcToken := o.OidcToken if vOidcToken == nil { // note: explicitly not the empty object. vOidcToken = &JobHttpTargetOidcToken{} } if err := extractJobHttpTargetOidcTokenFields(r, vOidcToken); err != nil { return err } if !dcl.IsEmptyValueIndirect(vOidcToken) { o.OidcToken = vOidcToken } return nil } func postReadExtractJobHttpTargetOAuthTokenFields(r *Job, o *JobHttpTargetOAuthToken) error { return nil } func postReadExtractJobHttpTargetOidcTokenFields(r *Job, o *JobHttpTargetOidcToken) error { return nil } func postReadExtractJobStatusFields(r *Job, o *JobStatus) error { return nil } func postReadExtractJobStatusDetailsFields(r *Job, o *JobStatusDetails) error { return nil } func postReadExtractJobRetryConfigFields(r *Job, o *JobRetryConfig) error { return nil }
/* * Copyright 2017 StreamSets 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 common import ( "github.com/satori/go.uuid" log "github.com/sirupsen/logrus" "io/ioutil" "os" ) const ( EDGE_ID_FILE = "/data/edge.id" ) type RuntimeInfo struct { ID string BaseDir string HttpUrl string DPMEnabled bool AppAuthToken string } func (r *RuntimeInfo) init() error { r.ID = r.getSdeId() return nil } func (r *RuntimeInfo) getSdeId() string { var edgeId string if _, err := os.Stat(r.getSdeIdFilePath()); os.IsNotExist(err) { f, err := os.Create(r.getSdeIdFilePath()) check(err) defer f.Close() edgeId = uuid.NewV4().String() f.WriteString(edgeId) } else { buf, err := ioutil.ReadFile(r.getSdeIdFilePath()) if err != nil { log.Fatal(err) } edgeId = string(buf) } return edgeId } func (r *RuntimeInfo) getSdeIdFilePath() string { return r.BaseDir + EDGE_ID_FILE } func check(e error) { if e != nil { panic(e) } } func NewRuntimeInfo(httpUrl string, baseDir string) (*RuntimeInfo, error) { runtimeInfo := RuntimeInfo{ HttpUrl: httpUrl, BaseDir: baseDir, } err := runtimeInfo.init() if err != nil { return nil, err } return &runtimeInfo, nil }
//////////////////////////////////////////////////////////////////////////////// // // // Copyright 2020 Broadcom. The term Broadcom refers to Broadcom Inc. and/or // // its subsidiaries. // // // // 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 translib import ( "path/filepath" "reflect" "strings" "sync" "time" "github.com/Azure/sonic-mgmt-common/translib/db" "github.com/Azure/sonic-mgmt-common/translib/ocbinds" "github.com/Azure/sonic-mgmt-common/translib/tlerr" "github.com/Azure/sonic-mgmt-common/translib/transformer" "github.com/golang/glog" "github.com/openconfig/goyang/pkg/yang" ) // yanglibApp implements app interface for the // ietf-yang-library module type yanglibApp struct { pathInfo *PathInfo ygotRoot *ocbinds.Device ygotTarget *interface{} } // theYanglibMutex synchronizes all cache loads var theYanglibMutex sync.Mutex // theYanglibCache holds parsed yanglib info. Populated on first // request. var theYanglibCache *ocbinds.IETFYangLibrary_ModulesState // theSchemaRootURL is the base URL for the yang file download URL. // Main program must set the value through SetSchemaRootURL() API. // Individual file URL is obtained by appending file name to it. var theSchemaRootURL string func init() { err := register("/ietf-yang-library:modules-state", &appInfo{ appType: reflect.TypeOf(yanglibApp{}), ygotRootType: reflect.TypeOf(ocbinds.IETFYangLibrary_ModulesState{}), isNative: false, }) if err != nil { glog.Fatal("register() failed for yanglibApp;", err) } err = addModel(&ModelData{ Name: "ietf-yang-library", Org: "IETF NETCONF (Network Configuration) Working Group", Ver: "2016-06-21", }) if err != nil { glog.Fatal("addModel() failed for yanglibApp;", err) } } /* * App interface functions */ func (app *yanglibApp) initialize(data appData) { app.pathInfo = NewPathInfo(data.path) app.ygotRoot = (*data.ygotRoot).(*ocbinds.Device) app.ygotTarget = data.ygotTarget } func (app *yanglibApp) translateCreate(d *db.DB) ([]db.WatchKeys, error) { return nil, tlerr.NotSupported("Unsupported") } func (app *yanglibApp) translateUpdate(d *db.DB) ([]db.WatchKeys, error) { return nil, tlerr.NotSupported("Unsupported") } func (app *yanglibApp) translateReplace(d *db.DB) ([]db.WatchKeys, error) { return nil, tlerr.NotSupported("Unsupported") } func (app *yanglibApp) translateDelete(d *db.DB) ([]db.WatchKeys, error) { return nil, tlerr.NotSupported("Unsupported") } func (app *yanglibApp) translateGet(dbs [db.MaxDB]*db.DB) error { return nil // NOOP! everyting is in processGet } func (app *yanglibApp) translateAction(dbs [db.MaxDB]*db.DB) error { return tlerr.NotSupported("Unsupported") } func (app *yanglibApp) translateSubscribe(req translateSubRequest) (translateSubResponse, error) { return emptySubscribeResponse(req.path) } func (app *yanglibApp) processSubscribe(req processSubRequest) (processSubResponse, error) { return processSubResponse{}, tlerr.New("not implemented") } func (app *yanglibApp) processCreate(d *db.DB) (SetResponse, error) { return SetResponse{}, tlerr.NotSupported("Unsupported") } func (app *yanglibApp) processUpdate(d *db.DB) (SetResponse, error) { return SetResponse{}, tlerr.NotSupported("Unsupported") } func (app *yanglibApp) processReplace(d *db.DB) (SetResponse, error) { return SetResponse{}, tlerr.NotSupported("Unsupported") } func (app *yanglibApp) processDelete(d *db.DB) (SetResponse, error) { return SetResponse{}, tlerr.NotSupported("Unsupported") } func (app *yanglibApp) processAction(dbs [db.MaxDB]*db.DB) (ActionResponse, error) { return ActionResponse{}, tlerr.NotSupported("Unsupported") } func (app *yanglibApp) processGet(dbs [db.MaxDB]*db.DB) (GetResponse, error) { glog.Infof("path = %s", app.pathInfo.Template) glog.Infof("vars = %s", app.pathInfo.Vars) var resp GetResponse ylib, err := getYanglibInfo() if err != nil { return resp, err } switch { case app.pathInfo.HasSuffix("/module-set-id"): // only module-set-id app.ygotRoot.ModulesState.ModuleSetId = ylib.ModuleSetId case app.pathInfo.HasVar("name"): // only one module err = app.copyOneModuleInfo(ylib) default: // all modules app.ygotRoot.ModulesState = ylib } if err == nil { resp.Payload, err = generateGetResponsePayload( app.pathInfo.Path, app.ygotRoot, app.ygotTarget) } return resp, err } // copyOneModuleInfo fills one module from given ygot IETFYangLibrary_ModulesState // object into app.ygotRoot. func (app *yanglibApp) copyOneModuleInfo(fromMods *ocbinds.IETFYangLibrary_ModulesState) error { key := ocbinds.IETFYangLibrary_ModulesState_Module_Key{ Name: app.pathInfo.Var("name"), Revision: app.pathInfo.Var("revision")} glog.Infof("Copying module %s@%s", key.Name, key.Revision) to := app.ygotRoot.ModulesState.Module[key] from := fromMods.Module[key] if from == nil { glog.Errorf("No module %s in yanglib", key) return tlerr.NotFound("Module %s@%s not found", key.Name, key.Revision) } switch pt := app.pathInfo.Template; { case strings.HasSuffix(pt, "/deviation"): // Copy only deviations. if len(from.Deviation) != 0 { to.Deviation = from.Deviation } else { return tlerr.NotFound("Module %s@%s has no deviations", key.Name, key.Revision) } case strings.Contains(pt, "/deviation{}{}"): // Copy only one deviation info devkey := ocbinds.IETFYangLibrary_ModulesState_Module_Deviation_Key{ Name: app.pathInfo.Var("name#2"), Revision: app.pathInfo.Var("revision#2")} if devmod := from.Deviation[devkey]; devmod != nil { *to.Deviation[devkey] = *devmod } else { return tlerr.NotFound("Module %s@%s has no deviation %s@%s", key.Name, key.Revision, devkey.Name, devkey.Revision) } case strings.HasSuffix(pt, "/submodule"): // Copy only submodules.. if len(from.Submodule) != 0 { to.Submodule = from.Submodule } else { return tlerr.NotFound("Module %s@%s has no submodules", key.Name, key.Revision) } case strings.Contains(pt, "/submodule{}{}"): // Copy only one submodule info subkey := ocbinds.IETFYangLibrary_ModulesState_Module_Submodule_Key{ Name: app.pathInfo.Var("name#2"), Revision: app.pathInfo.Var("revision#2")} if submod := from.Submodule[subkey]; submod != nil { *to.Submodule[subkey] = *submod } else { return tlerr.NotFound("Module %s@%s has no submodule %s@%s", key.Name, key.Revision, subkey.Name, subkey.Revision) } default: // Copy full module app.ygotRoot.ModulesState.Module[key] = from } return nil } /* * Yang parsing utilities */ // yanglibBuilder is the utility for parsing and loading yang files into // ygot IETFYangLibrary_ModulesState object. type yanglibBuilder struct { // yangDir is the directory with all yang files yangDir string // implModules contains top level yang module names implemented // by this system. Values are discovered from translib.getModels() API implModules map[string]bool // yangModules is the temporary cache of all parsed yang modules. // Populated by loadYangs() function. yangModules *yang.Modules // ygotModules is the output ygot object tree containing all // yang module info ygotModules *ocbinds.IETFYangLibrary_ModulesState } // getYanglibInfo returns the ygot IETFYangLibrary_ModulesState object // with all yang library information. func getYanglibInfo() (ylib *ocbinds.IETFYangLibrary_ModulesState, err error) { theYanglibMutex.Lock() if theYanglibCache == nil { glog.Infof("Building yanglib cache") theYanglibCache, err = newYanglibInfo() glog.Infof("Yanglib cache ready; err=%v", err) } ylib = theYanglibCache theYanglibMutex.Unlock() return } // newYanglibInfo loads all eligible yangs and fills yanglib info into the // ygot IETFYangLibrary_ModulesState object func newYanglibInfo() (*ocbinds.IETFYangLibrary_ModulesState, error) { var yb yanglibBuilder if err := yb.prepare(); err != nil { return nil, err } if err := yb.loadYangs(); err != nil { return nil, err } if err := yb.translate(); err != nil { return nil, err } return yb.ygotModules, nil } // prepare function initializes the yanglibBuilder object for // parsing yangs and translating into ygot. func (yb *yanglibBuilder) prepare() error { yb.yangDir = GetYangPath() glog.Infof("yanglibBuilder.prepare: yangDir = %s", yb.yangDir) glog.Infof("yanglibBuilder.prepare: baseURL = %s", theSchemaRootURL) // Load supported model information yb.implModules = make(map[string]bool) for _, m := range getModels() { yb.implModules[m.Name] = true } yb.ygotModules = &ocbinds.IETFYangLibrary_ModulesState{} return nil } // loadYangs reads eligible yang files into yang.Modules object. // Skips transformer annotation yangs. func (yb *yanglibBuilder) loadYangs() error { glog.Infof("Loading yangs from %s directory", yb.yangDir) var parsed, ignored uint32 mods := yang.NewModules() start := time.Now() files, _ := filepath.Glob(filepath.Join(yb.yangDir, "*.yang")) for _, f := range files { // ignore transformer annotation yangs if strings.HasSuffix(filepath.Base(f), "-annot.yang") { ignored++ continue } if err := mods.Read(f); err != nil { glog.Errorf("Failed to parse %s; err=%v", f, err) return tlerr.New("System error") } parsed++ } glog.Infof("%d yang files loaded in %s; %d ignored", parsed, time.Since(start), ignored) yb.yangModules = mods return nil } // translate function fills parsed yang.Modules info into the // ygot IETFYangLibrary_ModulesState object. func (yb *yanglibBuilder) translate() error { var modsWithDeviation []*yang.Module // First iteration -- create ygot module entry for each yang.Module for _, mod := range yb.yangModules.Modules { m, _ := yb.ygotModules.NewModule(mod.Name, mod.Current()) if m == nil { // ignore; yang.Modules map contains dupicate entries - one for name and // other for name@rev. NewModule() will return nil if entry exists. continue } // Fill basic properties into ygot module yb.fillModuleInfo(m, mod) // Mark the yang.Module with "deviation" statements for 2nd iteration. We need reverse // mapping of deviation target -> current module in ygot. Hence 2nd iteration.. if len(mod.Deviation) != 0 { modsWithDeviation = append(modsWithDeviation, mod) } } // 2nd iteration -- fill deviations. for _, mod := range modsWithDeviation { yb.translateDeviations(mod) } // 3rd iteration -- fill conformance type for _, m := range yb.ygotModules.Module { if yb.implModules[*m.Name] { m.ConformanceType = ocbinds.IETFYangLibrary_ModulesState_Module_ConformanceType_implement } else { m.ConformanceType = ocbinds.IETFYangLibrary_ModulesState_Module_ConformanceType_import } } // Use yang bundle version as module-set-id msetID := GetYangModuleSetID() yb.ygotModules.ModuleSetId = &msetID return nil } // fillModuleInfo yang module info from yang.Module to ygot IETFYangLibrary_ModulesState_Module // object.. Deviation information is not filled. func (yb *yanglibBuilder) fillModuleInfo(to *ocbinds.IETFYangLibrary_ModulesState_Module, from *yang.Module) { to.Namespace = &from.Namespace.Name to.Schema = yb.getSchemaURL(from) // Fill the "feature" info from yang even though we dont have full // support for yang features. for _, f := range from.Feature { to.Feature = append(to.Feature, f.Name) } // Iterate thru "include" statements to resolve submodules for _, inc := range from.Include { submod := yb.yangModules.FindModule(inc) if submod == nil { // should not happen glog.Errorf("No sub-module %s; @%s", inc.Name, inc.Statement().Location()) continue } // NewSubmodule() returns nil if submodule entry already exists.. Ignore it. if sm, _ := to.NewSubmodule(submod.Name, submod.Current()); sm != nil { sm.Schema = yb.getSchemaURL(submod) } } } // fillModuleDeviation creates a deviation module info in the ygot structure // for a given main module. func (yb *yanglibBuilder) fillModuleDeviation(main *yang.Module, deviation *yang.Module) { key := ocbinds.IETFYangLibrary_ModulesState_Module_Key{ Name: main.Name, Revision: main.Current()} if m, ok := yb.ygotModules.Module[key]; ok { m.NewDeviation(deviation.Name, deviation.Current()) // Mark the deviation module as "implemented" if main module is also "implemented" if yb.implModules[main.Name] { yb.implModules[deviation.Name] = true } } else { glog.Errorf("Ygot module entry %s not found", key) } } // translateDeviations function will process all "devaiation" statements of // a yang.Module and fill deviation info into corresponding ygot module objects. func (yb *yanglibBuilder) translateDeviations(mod *yang.Module) error { deviationTargets := make(map[string]bool) // Loop thru deviation statements and find modules deviated by current module for _, d := range mod.Deviation { if !strings.HasPrefix(d.Name, "/") { glog.Errorf("Deviation path \"%s\" is not absolute! @%s", d.Name, d.Statement().Location()) continue } // Get prefix of root node from the deviation path. First split the path // by "/" char and then split 1st part by ":". // Eg, find "acl" from "/acl:scl-sets/config/something" root := strings.SplitN(strings.SplitN(d.Name, "/", 3)[1], ":", 2) if len(root) != 2 { glog.Errorf("Deviation path \"%s\" has no prefix for root element! @%s", d.Name, d.Statement().Location()) } else { deviationTargets[root[0]] = true } } glog.V(2).Infof("Module %s has deviations for %d modules", mod.FullName(), len(deviationTargets)) // Deviation target prefixes must be in the import list.. Find the target // modules by matching the prefix in imports. for _, imp := range mod.Import { prefix := imp.Name if imp.Prefix != nil { prefix = imp.Prefix.Name } if !deviationTargets[prefix] { continue } if m := yb.yangModules.FindModule(imp); m != nil { yb.fillModuleDeviation(m, mod) } else { glog.Errorf("No module for prefix \"%s\"", prefix) } } return nil } // getSchemaURL resolves the URL for downloading yang file from current // device. Returns nil if yang URL could not be prepared. func (yb *yanglibBuilder) getSchemaURL(m *yang.Module) *string { if len(theSchemaRootURL) == 0 { return nil // Base URL not resolved; hence no yang URL } // Ugly hack to get source file name from yang.Module. See implementation // of yang.Statement.Location() function. // TODO: any better way to get source file path from yang.Module?? toks := strings.Split(m.Source.Location(), ":") if len(toks) != 1 && len(toks) != 3 { glog.Warningf("Could not resolve file path for module %s; location=%s", m.FullName(), m.Source.Location()) return nil } uri := theSchemaRootURL + filepath.Base(toks[0]) return &uri } // SetSchemaRootURL sets root URL for yang file download URLs. func SetSchemaRootURL(url string) { theYanglibMutex.Lock() defer theYanglibMutex.Unlock() newURL := url if len(url) != 0 && !strings.HasSuffix(url, "/") { newURL += "/" } if theSchemaRootURL != newURL { theSchemaRootURL = newURL theYanglibCache = nil // reset cache } } // GetYangPath returns directory containing yang files. Use // transformer.YangPath for now. func GetYangPath() string { return transformer.YangPath } // GetYangModuleSetID returns the ietf-yang-library's module-set-id value. func GetYangModuleSetID() string { return GetYangBundleVersion().String() }
package main import ( "encoding/json" "fmt" "github.com/hyperledger/fabric-contract-api-go/contractapi" ) // Read returns the value at id in the world state func (rc *ResourceTypesContract) Read(ctx contractapi.TransactionContextInterface, id string) (ret *ResourceType, err error) { resultsIterator, _, err := ctx.GetStub().GetQueryResultWithPagination(`{"selector": {"id":"`+id+`"}}`, 0, "") if err != nil { return } defer resultsIterator.Close() if resultsIterator.HasNext() { ret = new(ResourceType) queryResponse, err2 := resultsIterator.Next() if err2 != nil { return nil, err2 } if err = json.Unmarshal(queryResponse.Value, ret); err != nil { return } } else { return nil, fmt.Errorf("Unable to find item in world state") } mspID, err := ctx.GetClientIdentity().GetMSPID() if err != nil { return nil, err } valAsBytes, err := ctx.GetStub().GetPrivateData( mspID+"ResourceTypesPrivateData", id, ) if err == nil && len(valAsBytes) > 0 { ret.PrivateName = string(valAsBytes) } return }
package pg import ( "github.com/kyleconroy/sqlc/internal/sql/ast" ) type CollateExpr struct { Xpr ast.Node Arg ast.Node CollOid Oid Location int } func (n *CollateExpr) Pos() int { return n.Location }
package c2 import ( "fmt" "x-tool/m" ) var model m.M func (mo *model) control() { var z = m.get("c1") z.control() fmt.Print("c2 !") } func init() { m.reject(model) }
//Copyright (c) 2017 Phil package apollo import ( "io/ioutil" "os" "testing" "github.com/stretchr/testify/suite" ) type CacheTestSuite struct { suite.Suite } func (s *CacheTestSuite) TestCache() { cache := newCache() cache.set("key", []byte("val")) val, ok := cache.get("key") s.True(ok) s.Equal("val", string(val)) cache.set("key", []byte("val2")) val1, ok1 := cache.get("key") s.True(ok1) s.Equal("val2", string(val1)) kv := cache.dump() s.Equal(1, len(kv)) s.Equal("val2", string(kv["key"])) cache.delete("key") _, ok2 := cache.get("key") s.False(ok2) } func (s *CacheTestSuite) TestCacheDump() { var caches = newNamespaceCache() defer caches.drain() caches.mustGetCache("namespace").set("key", []byte("val")) f, err := ioutil.TempFile(".", "apollo") s.NoError(err) f.Close() defer os.Remove(f.Name()) s.NoError(caches.dump(f.Name())) var restore = newNamespaceCache() defer restore.drain() s.NoError(restore.load(f.Name())) val, _ := restore.mustGetCache("namespace").get("key") s.Equal("val", string(val)) s.Error(restore.load("null")) s.Error(restore.load("./testdata/app.yml")) } func TestRunCacheSuite(t *testing.T) { suite.Run(t, new(CacheTestSuite)) }
package dialect import ( "github.com/jdkato/prose/tokenize" "github.com/c9s/inflect" "regexp" "strings" "fmt" ) // Dialect Detectors must implement a method which returns a corpus and another // which implements the algorithm which categorizes a product into the // appropriate dialect type Detector interface { Corpus () (Corpus) Categorize(p Product) (string) } type NaiveDetector struct { corpus Corpus } func (d NaiveDetector) Corpus () (Corpus) { return d.corpus } // Given a product, santizes the name and description fields, // and searches for the resulting tokens in the corpora func (d NaiveDetector) Categorize(p Product) (string) { hasAmericanWord, hasBritishWord := false, false americanWord, britishWord := "", "" for w, _ := range *words(p) { if !hasAmericanWord { if _, ok := d.Corpus().AmericanWords[w]; ok { hasAmericanWord = true americanWord += w continue } } if !hasBritishWord { if _, ok := d.Corpus().BritishWords[w]; ok { hasBritishWord = true britishWord += w continue } } if hasAmericanWord && hasBritishWord { break } } var output string = "Unknown" if hasAmericanWord && hasBritishWord { output = "Mixed British and American English" americanWord = americanWord + " " } else if hasAmericanWord { output = "American English" } else if hasBritishWord { output = "British English" } return fmt.Sprintf("%-35s %s%s", output, americanWord, britishWord) } func words(p Product) *map[string]bool { words := make(map[string]bool) santize(p.Name, &words) santize(p.Description, &words) return &words; } // tokenizes, singularizes, drops non-words and converts to lower case func santize(s string, words *map[string]bool) { var word = regexp.MustCompile(`^[A-Za-z-]+$`) for _, w := range tokenize.TextToWords(s) { if word.MatchString(w) { (*words)[inflect.Singularize(strings.ToLower(w))] = true } } }
package controller import ( "net/http" "github.com/go-chi/render" ) type ErrorResponse struct { Error string `json:"error"` } var UnableToParseJsonError = ErrorResponse{ Error: "Unable to parse json", } func ErrUnableToParseJson(w http.ResponseWriter, r *http.Request) { render.Status(r, http.StatusBadRequest) render.JSON(w, r, &UnableToParseJsonError) } var InvalidSeedError = ErrorResponse{ Error: "Invalid seed", } func ErrInvalidSeed(w http.ResponseWriter, r *http.Request) { render.Status(r, http.StatusBadRequest) render.JSON(w, r, &InvalidSeedError) } var WalletNotFoundError = ErrorResponse{ Error: "wallet not found", } func ErrWalletNotFound(w http.ResponseWriter, r *http.Request) { render.Status(r, http.StatusBadRequest) render.JSON(w, r, &WalletNotFoundError) } var WalletLockedError = ErrorResponse{ Error: "wallet locked", } func ErrWalletLocked(w http.ResponseWriter, r *http.Request) { render.Status(r, http.StatusBadRequest) render.JSON(w, r, &WalletLockedError) } var WalletNotLockedError = ErrorResponse{ Error: "wallet not locked", } func ErrWalletNotLocked(w http.ResponseWriter, r *http.Request) { render.Status(r, http.StatusBadRequest) render.JSON(w, r, &WalletNotLockedError) } var InvalidKeyError = ErrorResponse{ Error: "Invalid key", } func ErrInvalidKey(w http.ResponseWriter, r *http.Request) { render.Status(r, http.StatusBadRequest) render.JSON(w, r, &InvalidKeyError) } var WalletNoPasswordError = ErrorResponse{ Error: "password not set", } func ErrNoWalletPassword(w http.ResponseWriter, r *http.Request) { render.Status(r, http.StatusBadRequest) render.JSON(w, r, &WalletNoPasswordError) } var InvalidHashError = ErrorResponse{ Error: "Invalid hash", } func ErrInvalidHash(w http.ResponseWriter, r *http.Request) { render.Status(r, http.StatusBadRequest) render.JSON(w, r, &InvalidHashError) } var WorkFailedError = ErrorResponse{ Error: "Failed to generate work", } func ErrWorkFailed(w http.ResponseWriter, r *http.Request) { render.Status(r, http.StatusInternalServerError) render.JSON(w, r, &WorkFailedError) } var InvalidAccountError = ErrorResponse{ Error: "Invalid account", } func ErrInvalidAccount(w http.ResponseWriter, r *http.Request) { render.Status(r, http.StatusBadRequest) render.JSON(w, r, &InvalidAccountError) } func ErrInternalServerError(w http.ResponseWriter, r *http.Request, errorText string) { render.Status(r, http.StatusInternalServerError) render.JSON(w, r, &ErrorResponse{ Error: errorText, }) } func ErrBadRequest(w http.ResponseWriter, r *http.Request, errorText string) { render.Status(r, http.StatusBadRequest) render.JSON(w, r, &ErrorResponse{ Error: errorText, }) }
package model import ( "net/http" ) type ResponseEntity struct { Code int `json:"code"` Message string `json:"message"` Data interface{} `json:"data"` } func SuccessResponse(message string, data interface{}) *ResponseEntity { return &ResponseEntity{ Code: http.StatusOK, Message: message, Data: data, } } func FailResponse(message string, data interface{}) *ResponseEntity { return &ResponseEntity{ Code: http.StatusInternalServerError, Message: message, Data: data, } } func NewResponse(code int, message string, data interface{}) *ResponseEntity { return &ResponseEntity{ Code: code, Message: message, Data: data, } }
package userModel import ( "bytes" "encoding/json" "errors" ) // User Registered User of Client type User struct { // List of client that user registered from Clients []string `json:"clients,omitempty"` // The email that user registered with Email string `json:"email"` // User's Name Name string `json:"name"` // The unique identifier for a user based on provider ProviderID []string `json:"providerID,omitempty"` // The unique identifier for a user in database UserID string `json:"userID"` } func (strct *User) MarshalJSON() ([]byte, error) { buf := bytes.NewBuffer(make([]byte, 0)) buf.WriteString("{") comma := false // "Clients" field is required // only required object types supported for marshal checking (for now) // Marshal the "clients" field if comma { buf.WriteString(",") } buf.WriteString("\"clients\": ") if tmp, err := json.Marshal(strct.Clients); err != nil { return nil, err } else { buf.Write(tmp) } comma = true // "Email" field is required // only required object types supported for marshal checking (for now) // Marshal the "email" field if comma { buf.WriteString(",") } buf.WriteString("\"email\": ") if tmp, err := json.Marshal(strct.Email); err != nil { return nil, err } else { buf.Write(tmp) } comma = true // "Name" field is required // only required object types supported for marshal checking (for now) // Marshal the "name" field if comma { buf.WriteString(",") } buf.WriteString("\"name\": ") if tmp, err := json.Marshal(strct.Name); err != nil { return nil, err } else { buf.Write(tmp) } comma = true // Marshal the "providerID" field if comma { buf.WriteString(",") } buf.WriteString("\"providerID\": ") if tmp, err := json.Marshal(strct.ProviderID); err != nil { return nil, err } else { buf.Write(tmp) } comma = true // "UserID" field is required // only required object types supported for marshal checking (for now) // Marshal the "userID" field if comma { buf.WriteString(",") } buf.WriteString("\"userID\": ") if tmp, err := json.Marshal(strct.UserID); err != nil { return nil, err } else { buf.Write(tmp) } comma = true buf.WriteString("}") rv := buf.Bytes() return rv, nil } func (strct *User) UnmarshalJSON(b []byte) error { emailReceived := false nameReceived := false userIDReceived := false var jsonMap map[string]json.RawMessage if err := json.Unmarshal(b, &jsonMap); err != nil { return err } // parse all the defined properties for k, v := range jsonMap { switch k { case "clients": if err := json.Unmarshal([]byte(v), &strct.Clients); err != nil { return err } case "email": if err := json.Unmarshal([]byte(v), &strct.Email); err != nil { return err } emailReceived = true case "name": if err := json.Unmarshal([]byte(v), &strct.Name); err != nil { return err } nameReceived = true case "providerID": if err := json.Unmarshal([]byte(v), &strct.ProviderID); err != nil { return err } case "userID": if err := json.Unmarshal([]byte(v), &strct.UserID); err != nil { return err } userIDReceived = true } } // check if email (a required property) was received if !emailReceived { return errors.New("\"email\" is required but was not present") } // check if name (a required property) was received if !nameReceived { return errors.New("\"name\" is required but was not present") } // check if userID (a required property) was received if !userIDReceived { return errors.New("\"userID\" is required but was not present") } return nil }
package main import ( "flag" "fmt" "os" ) func main() { var ( cmd string = "website" port int = 8000 log int = 1 ) fs := flag.NewFlagSet("default", flag.ExitOnError) fs.StringVar(&cmd, "cmd", cmd, "the command to run") fs.IntVar(&port, "p", port, "the port to run on") fs.IntVar(&log, "l", log, "the log level") fs.Parse(os.Args[1:]) fmt.Printf("Running %q on port %d with log level %d", cmd, port, log) }
// Copyright 2013 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package htmlx import "testing" type unescapeTest struct { // A short description of the test case. desc string // The HTML text. html string // The unescaped text. unescaped string } var unescapeTests = []unescapeTest{ // Handle no entities. { "copy", "A\ttext\nstring", "A\ttext\nstring", }, // Handle simple named entities. { "simple", "&amp; &gt; &lt;", "& > <", }, // Handle hitting the end of the string. { "stringEnd", "&amp &amp", "& &", }, // Handle entities with two codepoints. { "multiCodepoint", "text &gesl; blah", "text \u22db\ufe00 blah", }, // Handle decimal numeric entities. { "decimalEntity", "Delta = &#916; ", "Delta = Δ ", }, // Handle hexadecimal numeric entities. { "hexadecimalEntity", "Lambda = &#x3bb; = &#X3Bb ", "Lambda = λ = λ ", }, // Handle numeric early termination. { "numericEnds", "&# &#x &#128;43 &copy = &#169f = &#xa9", "&# &#x €43 © = ©f = ©", }, // Handle numeric ISO-8859-1 entity replacements. { "numericReplacements", "Footnote&#x87;", "Footnote‡", }, } func TestUnescape(t *testing.T) { for _, tt := range unescapeTests { unescaped := UnescapeString(tt.html) if unescaped != tt.unescaped { t.Errorf("TestUnescape %s: want %q, got %q", tt.desc, tt.unescaped, unescaped) } } } func TestUnescapeEscape(t *testing.T) { ss := []string{ ``, `abc def`, `a & b`, `a&amp;b`, `a &amp b`, `&quot;`, `"`, `"<&>"`, `&quot;&lt;&amp;&gt;&quot;`, `3&5==1 && 0<1, "0&lt;1", a+acute=&aacute;`, `The special characters are: <, >, &, ' and "`, } for _, s := range ss { if got := UnescapeString(EscapeString(s)); got != s { t.Errorf("got %q want %q", got, s) } } }
package main import ( "bytes" "flag" "io" "net/http" "sync" quic "gx/ipfs/QmU44KWVkSHno7sNDTeUcL4FBgxgoidkFuTUyTXWJPXXFJ/quic-go" "gx/ipfs/QmU44KWVkSHno7sNDTeUcL4FBgxgoidkFuTUyTXWJPXXFJ/quic-go/h2quic" "gx/ipfs/QmU44KWVkSHno7sNDTeUcL4FBgxgoidkFuTUyTXWJPXXFJ/quic-go/internal/protocol" "gx/ipfs/QmU44KWVkSHno7sNDTeUcL4FBgxgoidkFuTUyTXWJPXXFJ/quic-go/internal/utils" ) func main() { verbose := flag.Bool("v", false, "verbose") tls := flag.Bool("tls", false, "activate support for IETF QUIC (work in progress)") flag.Parse() urls := flag.Args() logger := utils.DefaultLogger if *verbose { logger.SetLogLevel(utils.LogLevelDebug) } else { logger.SetLogLevel(utils.LogLevelInfo) } logger.SetLogTimeFormat("") versions := protocol.SupportedVersions if *tls { versions = append([]protocol.VersionNumber{protocol.VersionTLS}, versions...) } roundTripper := &h2quic.RoundTripper{ QuicConfig: &quic.Config{Versions: versions}, } defer roundTripper.Close() hclient := &http.Client{ Transport: roundTripper, } var wg sync.WaitGroup wg.Add(len(urls)) for _, addr := range urls { logger.Infof("GET %s", addr) go func(addr string) { rsp, err := hclient.Get(addr) if err != nil { panic(err) } logger.Infof("Got response for %s: %#v", addr, rsp) body := &bytes.Buffer{} _, err = io.Copy(body, rsp.Body) if err != nil { panic(err) } logger.Infof("Request Body:") logger.Infof("%s", body.Bytes()) wg.Done() }(addr) } wg.Wait() }
package main import "fmt" func main() { p := person{ name: "James", lastname: "Bond", age: 33, } fmt.Println("Original:", p) changeMe(&p, "Jason", "Bourne", 22) fmt.Println("New:", p) } type person struct { name string lastname string age int } func changeMe(p *person, name string, lastname string, age int) { p.name = name p.lastname = lastname p.age = age }
package as_test import ( "fmt" "github.com/lunemec/as" ) func Example() { for _, n := range []int{127, 128} { num, err := as.Int8(n) if err != nil { fmt.Printf("Input invalid: %d, err: %s\n", num, err) } else { fmt.Printf("Input valid: %d\n", num) } } // Output: Input valid: 127 // Input invalid: -128, err: 128 (int) overflows int8 } func ExampleT() { for _, n := range []int{127, 128} { num, err := as.T[int8](n) if err != nil { fmt.Printf("Input invalid: %d, err: %s\n", num, err) } else { fmt.Printf("Input valid: %d\n", num) } } // Output: Input valid: 127 // Input invalid: -128, err: 128 (int) overflows int8 } func ExampleSliceT() { out, err := as.SliceT[int, int8]([]int{127, 128}) fmt.Printf("Output: %+v, error: %+v\n", out, err) // Output: Output: [127 0], error: 1 error occurred: // * at index [1]: 128 (int) overflows int8 } func ExampleSliceTUnchecked() { out := as.SliceTUnchecked[int, int8]([]int{127, 128}) fmt.Printf("Output: %+v\n", out) // Output: Output: [127 -128] }
package tag import ( "github.com/go-jar/goerror" "github.com/go-jar/gohttp/query" "blog/entity" "blog/errno" ) func (tc *TagController) ModifyAction(context *TagContext) { if err := tc.VerifyToken(context.ApiContext); err != nil { context.ApiData.Err = goerror.New(errno.EUserUnauthorized, err.Error()) return } tagEntity, err := tc.parseModifyActionParams(context) if err != nil { context.ApiData.Err = err return } required := map[string]bool{ "tag_name": true, "tag_index": true, } if _, err := context.tagSvc.UpdateById(tagEntity.Id, tagEntity, required); err != nil { context.ApiData.Err = goerror.New(errno.ESysMysqlError, err.Error()) return } context.ApiData.Data = map[string]interface{}{ "RequestId": context.TraceId, } } func (tc *TagController) parseModifyActionParams(context *TagContext) (*entity.TagEntity, *goerror.Error) { tagEntity := &entity.TagEntity{} qs := query.NewQuerySet() qs.Int64Var(&tagEntity.Id, "TagId", true, errno.ECommonInvalidArg, "invalid TagId", query.CheckInt64GreaterEqual0) qs.StringVar(&tagEntity.TagName, "TagName", true, errno.ECommonInvalidArg, "invalid TagName", query.CheckStringNotEmpty) qs.Int64Var(&tagEntity.TagIndex, "TagIndex", false, errno.ECommonInvalidArg, "invalid TagIndex", query.CheckInt64GreaterEqual0) if err := qs.Parse(context.QueryValues); err != nil { context.ErrorLog([]byte("TagController.parseModifyActionParams"), []byte(err.Error())) return nil, err } return tagEntity, nil }
package db type Store interface { Set(key string, value interface{}) Get(key string) interface{} } type keyValueStore struct { store map[string]interface{} locker RWLocker } func newKeyValueStore(locker RWLocker) *keyValueStore { return &keyValueStore{make(map[string]interface{}), locker} } func (ks *keyValueStore) Set(key string, value interface{}) { ks.locker.Lock() ks.store[key] = value ks.locker.Unlock() } func (ks *keyValueStore) Get(key string) interface{} { ks.locker.RLock() defer ks.locker.RUnlock() return ks.store[key] }
/* Copyright 2021 The Knative 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 reconciler import ( "context" "fmt" "github.com/kiegroup/kogito-operator/apis/app/v1beta1" kogitoclient "github.com/kiegroup/kogito-operator/client/clientset/versioned" appsv1 "k8s.io/api/apps/v1" corev1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/api/equality" apierrors "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/labels" "k8s.io/apimachinery/pkg/runtime/schema" "k8s.io/client-go/kubernetes" // knative.dev imports duckv1 "knative.dev/pkg/apis/duck/v1" "knative.dev/pkg/kmeta" "knative.dev/pkg/logging" pkgreconciler "knative.dev/pkg/reconciler" sourcesv1 "knative.dev/eventing/pkg/apis/sources/v1" "go.uber.org/zap" ) // newKogitoRuntimeCreated makes a new reconciler event with event type Normal, and // reason KogitoRuntimeCreated. func newKogitoRuntimeCreated(namespace, name string) pkgreconciler.Event { return pkgreconciler.NewEvent(corev1.EventTypeNormal, "KogitoRuntimeCreated", "created kogitoruntime: \"%s/%s\"", namespace, name) } // newKogitoRuntimeFailed makes a new reconciler event with event type Warning, and // reason KogitoRuntimeFailed. func newKogitoRuntimeFailed(namespace, name string, err error) pkgreconciler.Event { return pkgreconciler.NewEvent(corev1.EventTypeWarning, "KogitoRuntimeFailed", "failed to create kogitoruntime: \"%s/%s\", %w", namespace, name, err) } // newKogitoRuntimeUpdated makes a new reconciler event with event type Normal, and // reason KogitoRuntimeUpdated. func newKogitoRuntimeUpdated(namespace, name string) pkgreconciler.Event { return pkgreconciler.NewEvent(corev1.EventTypeNormal, "KogitoRuntimeUpdated", "updated kogitoruntime: \"%s/%s\"", namespace, name) } // newKogitoRuntimeNotReady makes a new reconciler event with type Normal, and // reason KogitoRuntimeNotReady func newKogitoRuntimeNotReady(namespace, name string) pkgreconciler.Event { return pkgreconciler.NewEvent(corev1.EventTypeNormal, "KogitoRuntimeNotReady", "waiting for kogitoruntime: \"%s/%s\"", namespace, name) } type KogitoRuntimeReconciler struct { KubeClientSet kubernetes.Interface KogitoClientSet kogitoclient.Interface } // ReconcileKogitoRuntime reconciles kogitoruntime resource for KogitoSource func (r *KogitoRuntimeReconciler) ReconcileKogitoRuntime( ctx context.Context, owner kmeta.OwnerRefable, binder *sourcesv1.SinkBinding, expected *v1beta1.KogitoRuntime, ) (*appsv1.Deployment, *sourcesv1.SinkBinding, pkgreconciler.Event) { namespace := owner.GetObjectMeta().GetNamespace() ra, err := r.KogitoClientSet.AppV1beta1().KogitoRuntimes(namespace).Get(ctx, expected.Name, metav1.GetOptions{}) if apierrors.IsNotFound(err) { syncSink(ctx, binder, expected) ra, err = r.KogitoClientSet.AppV1beta1().KogitoRuntimes(namespace).Create(ctx, expected, metav1.CreateOptions{}) if err != nil { return nil, binder, newKogitoRuntimeFailed(expected.Namespace, expected.Name, err) } return nil, binder, newKogitoRuntimeCreated(ra.Namespace, ra.Name) } else if err != nil { return nil, binder, fmt.Errorf("error getting receive adapter %q: %v", expected.Name, err) } else if !metav1.IsControlledBy(ra, owner.GetObjectMeta()) { return nil, binder, fmt.Errorf("kogitoruntime %q is not owned by %s %q", ra.Name, owner.GetGroupVersionKind().Kind, owner.GetObjectMeta().GetName()) } deployment, err := r.getDeployment(ctx, ra) if err != nil { return nil, binder, fmt.Errorf("error getting kogitoruntime %q deployment", ra.Name) } else if deployment == nil { // KogitoRuntime doesn't have a deployment created yet, reconcile return nil, binder, newKogitoRuntimeNotReady(ra.Namespace, ra.Name) } if kogitoRuntimeSpecSync(ctx, binder, expected, ra) { if ra, err = r.KogitoClientSet.AppV1beta1().KogitoRuntimes(namespace).Update(ctx, ra, metav1.UpdateOptions{}); err != nil { return deployment, binder, err } return deployment, binder, newKogitoRuntimeUpdated(ra.Namespace, ra.Name) } logging.FromContext(ctx).Debugw("Reusing existing receive adapter", zap.Any("receiveAdapter", ra)) return deployment, binder, nil } // getDeployment gets the associated Deployment of the given Receive Adapter func (r *KogitoRuntimeReconciler) getDeployment(ctx context.Context, ra *v1beta1.KogitoRuntime) (*appsv1.Deployment, error) { // KogitoRuntime has a associated Deployment with same name and namespace deployment, err := r.KubeClientSet.AppsV1().Deployments(ra.Namespace).Get(ctx, ra.Name, metav1.GetOptions{}) if apierrors.IsNotFound(err) { return nil, nil } else if err != nil { return nil, err } return deployment, nil } func (r *KogitoRuntimeReconciler) FindOwned(ctx context.Context, owner kmeta.OwnerRefable, selector labels.Selector) (*v1beta1.KogitoRuntime, error) { kogitoRuntimeList, err := r.KogitoClientSet.AppV1beta1().KogitoRuntimes(owner.GetObjectMeta().GetNamespace()).List(ctx, metav1.ListOptions{ LabelSelector: selector.String(), }) if err != nil { logging.FromContext(ctx).Error("Unable to list kogitoruntime: %v", zap.Error(err)) return nil, err } for _, kogitoruntime := range kogitoRuntimeList.Items { if metav1.IsControlledBy(&kogitoruntime, owner.GetObjectMeta()) { return &kogitoruntime, nil } } return nil, apierrors.NewNotFound(schema.GroupResource{}, "") } // Returns true if an update is needed. func kogitoRuntimeSpecSync(ctx context.Context, binder *sourcesv1.SinkBinding, expected *v1beta1.KogitoRuntime, now *v1beta1.KogitoRuntime) bool { old := *now.Spec.DeepCopy() now.Spec = expected.Spec syncSink(ctx, binder, now) return !equality.Semantic.DeepEqual(old, now.Spec) } func syncSink(ctx context.Context, binder *sourcesv1.SinkBinding, now *v1beta1.KogitoRuntime) { // call Do() to project sink information. ps := &duckv1.WithPod{} // binder.Do will inject all the env vars with the correct sink URIs in this template ps.Spec.Template.Spec.Containers = append(ps.Spec.Template.Spec.Containers, corev1.Container{}) ps.Spec.Template.Spec.Containers[0].Env = now.Spec.Env binder.Do(ctx, ps) // import the env vars generated by binder to KogitoRuntime Envs, let the Kogito Operator inject them in the inner containers if binder.Status.SinkURI == nil { binder.Status.MarkSink(nil) } else { now.Spec.Env = ps.Spec.Template.Spec.Containers[0].Env } }
package datetime import ( "encoding/json" "time" ) type Date time.Time func (dt Date) Time() time.Time { return time.Time(dt) } func (dt Date) String() string { return time.Time(dt).Format("2006-01-02") } func (dt *Date) parse(v string) error { ts, err := time.ParseInLocation("2006-01-02", v, time.Local) if err != nil { return err } *dt = Date(ts) return nil } func (dt Date) MarshalURL() (string, error) { return dt.String(), nil } func (dt *Date) UnmarshalURL(v string) error { return dt.parse(v) } func (dt Date) MarshalJSON() ([]byte, error) { return json.Marshal(dt.String()) } func (dt *Date) UnmarshalJSON(v []byte) error { var s string if err := json.Unmarshal(v, &s); err != nil { return err } return dt.parse(s) }
package main import "fmt" // go 内置函数 func fb() { defer func() { err := recover() fmt.Println(err) fmt.Println("释放链接数据库") }() fmt.Println("b") panic("出现严重错误!!!") } func main() { fb() }
package defaults import ( "github.com/openshift/installer/pkg/types/ovirt" ) // DefaultNetworkName is the default network name to use in a cluster. const DefaultNetworkName = "ovirtmgmt" // DefaultControlPlaneAffinityGroupName is the default affinity group name for the control plane VMs. const DefaultControlPlaneAffinityGroupName = "controlplane" // DefaultComputeAffinityGroupName is the default affinity group name for the compute VMs. const DefaultComputeAffinityGroupName = "compute" func defaultControlPlaneAffinityGroup() ovirt.AffinityGroup { return ovirt.AffinityGroup{ Name: DefaultControlPlaneAffinityGroupName, Priority: 5, Description: "AffinityGroup for spreading each control plane machine to a different host", Enforcing: true, } } func defaultComputeAffinityGroup() ovirt.AffinityGroup { return ovirt.AffinityGroup{ Name: DefaultComputeAffinityGroupName, Priority: 3, Description: "AffinityGroup for spreading each compute machine to a different host", Enforcing: true, } } // SetPlatformDefaults sets the defaults for the platform. func SetPlatformDefaults(p *ovirt.Platform) { if p.NetworkName == "" { p.NetworkName = DefaultNetworkName } if p.AffinityGroups == nil { // No affinity group field, using the default settings p.AffinityGroups = []ovirt.AffinityGroup{ defaultComputeAffinityGroup(), defaultControlPlaneAffinityGroup()} } }
package bench import "sync/atomic" // AtomicCounter implements an atmoic lock // using the atomic package type AtomicCounter struct { value int64 } // Add increments the counter func (c *AtomicCounter) Add(amount int64) { atomic.AddInt64(&c.value, amount) } // Read returns the current counter amount func (c *AtomicCounter) Read() int64 { var result int64 result = atomic.LoadInt64(&c.value) return result }
package main import ( "flag" "fmt" "log" "strings" "github.com/dgryski/go-farm" "github.com/dgryski/go-shardedkv/choosers/jump" "github.com/pkg/errors" ) func buildHostnames(siteCount int) []string { var hostnames []string for i := 0; i < siteCount; i++ { hostnames = append(hostnames, fmt.Sprintf("%d.example.jp", i)) } return hostnames } func buildBuckets(shardCount int) []string { var buckets []string for i := 0; i < shardCount; i++ { buckets = append(buckets, fmt.Sprintf("met%d", i+1)) } return buckets } func buildJump(buckets []string) (*jump.Jump, error) { jmp := jump.New(farm.Hash64) err := jmp.SetBuckets(buckets) if err != nil { return nil, errors.WithStack(err) } return jmp, nil } func deleteBucket(buckets []string, bucket string) []string { newBuckets := make([]string, 0, len(buckets)-1) for i, b := range buckets { if b == bucket { newBuckets = append(newBuckets, buckets[:i]...) return append(newBuckets, buckets[i+1:]...) } } return buckets } func addBucket(buckets []string, bucket string) []string { newBuckets := make([]string, 0, len(buckets)+1) newBuckets = append(newBuckets, buckets...) return append(newBuckets, bucket) } func containsStrInArray(a []string, s string) bool { for _, ae := range a { if ae == s { return true } } return false } func stringSetMinus(a, b []string) []string { var c []string for _, ae := range a { if !containsStrInArray(b, ae) { c = append(c, ae) } } return c } type copyListKey struct { src string dest string } func (k copyListKey) String() string { return fmt.Sprintf("%s->%s", k.src, k.dest) } func main() { var shardCount int flag.IntVar(&shardCount, "shard-count", 3, "shard count") var siteCount int flag.IntVar(&siteCount, "site-count", 10, "site count") var replicas int flag.IntVar(&replicas, "replicas", 2, "replica count") var op string flag.StringVar(&op, "op", "del", "operation: add or del") var opShard string flag.StringVar(&opShard, "op-shard", "", "operation target shard") flag.Parse() oldBuckets := buildBuckets(shardCount) hostnames := buildHostnames(siteCount) oldJump, err := buildJump(oldBuckets) if err != nil { log.Fatal(err) } oldMapping := make(map[string][]string) for _, h := range hostnames { shards := oldJump.ChooseReplicas(h, replicas) oldMapping[h] = shards } var newBuckets []string switch op { case "add": newBuckets = addBucket(oldBuckets, opShard) case "del": newBuckets = deleteBucket(oldBuckets, opShard) default: log.Fatal("op must be add or del") } fmt.Printf("oldBuckets:%s\tnewBuckets:%s\n", strings.Join(oldBuckets, ","), strings.Join(newBuckets, ","), ) newJump, err := buildJump(newBuckets) if err != nil { log.Fatal(err) } newMapping := make(map[string][]string) for _, h := range hostnames { shards := newJump.ChooseReplicas(h, replicas) newMapping[h] = shards } copyList := make(map[copyListKey][]string) delList := make(map[string][]string) for _, h := range hostnames { oldShards := oldMapping[h] newShards := newMapping[h] inc := stringSetMinus(newShards, oldShards) del := stringSetMinus(oldShards, newShards) if op == "del" { del = stringSetMinus(del, []string{opShard}) } var keys []string for i, d := range inc { var srcCandidates []string if op == "add" { srcCandidates = oldShards } else { // "del" srcCandidates = stringSetMinus(oldShards, []string{opShard}) } src := srcCandidates[i%len(srcCandidates)] key := copyListKey{src: src, dest: d} if hosts, ok := copyList[key]; ok { copyList[key] = append(hosts, h) } else { copyList[key] = []string{h} } keys = append(keys, key.String()) } for _, b := range del { if hosts, ok := delList[b]; ok { delList[b] = append(hosts, h) } else { delList[b] = []string{h} } } fmt.Printf("%s\told=%s\tnew=%s\tinc_shards=%s\tcopykeys=%s\tdel_shards=%s\n", h, strings.Join(oldShards, ","), strings.Join(newShards, ","), strings.Join(inc, ","), strings.Join(keys, ","), strings.Join(del, ","), ) } for _, o := range oldBuckets { for _, n := range newBuckets { key := copyListKey{src: o, dest: n} if hosts, ok := copyList[key]; ok { fmt.Printf("copy sublist %s\n", key.String()) for _, h := range hosts { fmt.Printf("\t%s\n", h) } } } } delKeys := oldBuckets if op == "del" { delKeys = stringSetMinus(delKeys, []string{opShard}) } for _, key := range delKeys { if hosts, ok := delList[key]; ok { fmt.Printf("delete sublist %s\n", key) for _, h := range hosts { fmt.Printf("\t%s\n", h) } } } }
package mongodb import ( "context" "go.mongodb.org/mongo-driver/mongo" "go.mongodb.org/mongo-driver/mongo/options" ) // Collection is an interface for the subset of *mongo.Collection functions that // we actually use. Using this interface in our datastores, instead of using the // *mongo.Collection type directly, allows for the possibility of utilizing a // mock implementation for testing purposes. Adding only the subset of functions // that we actually use limits the effort involved in creating such mocks. type Collection interface { // CountDocuments returns the number of documents in the collection. CountDocuments( ctx context.Context, filter interface{}, opts ...*options.CountOptions, ) (int64, error) // DeleteMany executes a delete command to delete documents from the // collection. DeleteMany( ctx context.Context, filter interface{}, opts ...*options.DeleteOptions, ) (*mongo.DeleteResult, error) // DeleteOne executes a delete command to delete at most one document from the // collection. DeleteOne( ctx context.Context, filter interface{}, opts ...*options.DeleteOptions, ) (*mongo.DeleteResult, error) // Find executes a find command and returns a Cursor over the matching // documents in the collection. Find( ctx context.Context, filter interface{}, opts ...*options.FindOptions, ) (*mongo.Cursor, error) // FindOne executes a find command and returns a SingleResult for one document // in the collection. FindOne( ctx context.Context, filter interface{}, opts ...*options.FindOneOptions, ) *mongo.SingleResult // FindOneAndReplace executes a findAndModify command to replace at most one // document in the collection and returns the document as it appeared before // replacement. FindOneAndReplace( ctx context.Context, filter interface{}, replacement interface{}, opts ...*options.FindOneAndReplaceOptions, ) *mongo.SingleResult // InsertOne executes an insert command to insert a single document into the // collection. InsertOne( ctx context.Context, document interface{}, opts ...*options.InsertOneOptions, ) (*mongo.InsertOneResult, error) // UpdateMany executes an update command to update documents in the // collection. UpdateMany( ctx context.Context, filter interface{}, update interface{}, opts ...*options.UpdateOptions, ) (*mongo.UpdateResult, error) // UpdateOne executes an update command to update at most one document in the // collection. UpdateOne( ctx context.Context, filter interface{}, update interface{}, opts ...*options.UpdateOptions, ) (*mongo.UpdateResult, error) }